From bd3a9d318ed46f13ac4eb5b27578becd4122a3e7 Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Sat, 17 Oct 2026 21:22:19 -0700 Subject: [PATCH 001/114] audit: track clipping paths, form BBox, and color spaces in redaction cover scan Prevent false-positive faux redactions where drawing occurs outside an active clipping path (re W n), outside a form XObject's /BBox, inside a default-off optional content layer (/OC OFF), or through text clipping modes (Tr 4-7). Also track cs, sc, and scn non-stroking color space operators so dark fills following a white g are not missed. Treat non-rectangular clipping paths and unknown color spaces as fail-closed. Refs #3117, refs #3118 --- crates/audit/src/cover.rs | 250 +++++++++++++++++++++++++++++++++++--- crates/audit/src/tests.rs | 209 +++++++++++++++++++++++++++++++ 2 files changed, 440 insertions(+), 19 deletions(-) diff --git a/crates/audit/src/cover.rs b/crates/audit/src/cover.rs index 3df666c190..60852c3123 100644 --- a/crates/audit/src/cover.rs +++ b/crates/audit/src/cover.rs @@ -4,9 +4,12 @@ //! color (`re` + `f`) is the classic way a "redaction" is faked. A single closed `m`/`l` subpath //! whose four corners form an axis-aligned rectangle in user space is the same shape and counts //! too (#1510). Graphics state tracked here is deliberately small: the CTM stack (`q`/`Q`/`cm`), -//! the non-stroking color (`g`/`rg`/`k`) and the non-stroking alpha from ExtGState (`gs` reading -//! `/ca`). Form XObjects are followed read-only with a depth cap. Anything fancier (other filled paths, shadings, patterns) is -//! out of scope and documented as such. +//! the non-stroking color (`g`/`rg`/`k`, `cs`, `sc`, `scn`, defaulting unknown color spaces to +//! black fail-closed), the clipping state (`re W n`, form `/BBox`, and text clipping modes `Tr 4..=7`), +//! optional content layer visibility (`/OC BDC`/`EMC`), and the non-stroking alpha from ExtGState +//! (`gs` reading `/ca`). Form XObjects are followed read-only with a depth cap. Anything fancier +//! (other filled paths, non-axis-aligned rotations, shadings, patterns) is out of scope and +//! documented as such. //! //! Paint order: a page's content streams are one stream in pieces (ISO 32000-2 §7.8.2), so they //! are parsed joined and walked once with a single graphics state — state set in an earlier @@ -15,8 +18,10 @@ //! the joined stream)`; rectangles inside a form XObject carry the `Do` operator's position. //! Positions compare lexicographically in paint order. +use std::collections::HashSet; + use pdfcraft_content::{Matrix, Op, Pieces, parse}; -use pdfcraft_cos::{Dict, Document, Object}; +use pdfcraft_cos::{Dict, Document, ObjRef, Object}; use crate::AuditError; @@ -39,11 +44,41 @@ pub struct FilledRect { pub pos: (usize, usize), } +/// Active clipping state in page user space. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Clip { + /// No clipping has been applied yet. + None, + /// An axis-aligned clipping rectangle in user space. + Rect([f64; 4]), + /// Text glyph clipping active (`Tr 4..=7`). Fills through this clip paint the text glyphs, not a rectangle cover. + Glyphs, + /// Non-rectangular or complex clipping path (fail-closed: do not prune candidate covers). + Unknown, +} + +impl Clip { + fn intersect_rect(self, r: [f64; 4]) -> Clip { + match self { + Clip::None => Clip::Rect(r), + Clip::Rect(c) => match intersect(c, r) { + Some(cr) => Clip::Rect(cr), + None => Clip::Rect([0.0, 0.0, 0.0, 0.0]), + }, + Clip::Glyphs => Clip::Glyphs, + Clip::Unknown => Clip::Unknown, + } + } +} + #[derive(Clone)] struct Gs { ctm: Matrix, fill: [f64; 3], alpha: f64, + clip: Clip, + tr: u32, + space: usize, } /// The path under construction, as far as the audit cares about it. @@ -59,9 +94,9 @@ enum Path { impl Path { /// The rectangle a fill of this path paints, if the path is one. - fn rect(self) -> Option<[f64; 4]> { + fn rect(&self) -> Option<[f64; 4]> { match self { - Path::Rect(r) => Some(r), + Path::Rect(r) => Some(*r), Path::Lines(pts, _) => lines_rect(pts), Path::Empty | Path::Other => None, } @@ -71,14 +106,12 @@ impl Path { /// The bounding box of a closed polygon that is an axis-aligned rectangle, or `None`. A repeated /// start point is dropped first; the remaining four corners must alternate horizontal and /// vertical edges. -fn lines_rect(mut pts: Vec<[f64; 2]>) -> Option<[f64; 4]> { +fn lines_rect(pts: &[[f64; 2]]) -> Option<[f64; 4]> { // CTM products leave rounding noise, so corners compare with a tolerance (in points). const EPS: f64 = 1e-6; let same = |a: f64, b: f64| (a - b).abs() <= EPS; - if pts.len() == 5 && same(pts[0][0], pts[4][0]) && same(pts[0][1], pts[4][1]) { - pts.pop(); - } - let [a, b, c, d] = <[[f64; 2]; 4]>::try_from(pts).ok()?; + let slice = if pts.len() == 5 && same(pts[0][0], pts[4][0]) && same(pts[0][1], pts[4][1]) { pts.get(..4)? } else { pts }; + let [a, b, c, d] = <[[f64; 2]; 4]>::try_from(slice).ok()?; let fits = |first_horizontal: bool| { [(a, b), (b, c), (c, d), (d, a)] .iter() @@ -98,9 +131,19 @@ fn lines_rect(mut pts: Vec<[f64; 2]>) -> Option<[f64; 4]> { (r[2] - r[0] > EPS && r[3] - r[1] > EPS).then_some(r) } +fn axis_aligned(m: &Matrix) -> bool { + let [a, b, c, d, ..] = m.0; + (b.abs() < 1e-9 && c.abs() < 1e-9) || (a.abs() < 1e-9 && d.abs() < 1e-9) +} + +fn intersect(a: [f64; 4], b: [f64; 4]) -> Option<[f64; 4]> { + let r = [a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])]; + (r.iter().all(|v| v.is_finite()) && r[2] > r[0] && r[3] > r[1]).then_some(r) +} + impl Default for Gs { fn default() -> Self { - Gs { ctm: Matrix::IDENTITY, fill: [0.0, 0.0, 0.0], alpha: 1.0 } + Gs { ctm: Matrix::IDENTITY, fill: [0.0, 0.0, 0.0], alpha: 1.0, clip: Clip::None, tr: 0, space: 1 } } } @@ -109,6 +152,8 @@ struct Walker<'a> { pieces: &'a Pieces, out: Vec, ops_seen: usize, + off_layers: HashSet, + oc_hidden_depth: usize, } impl<'a> Walker<'a> { @@ -133,6 +178,7 @@ impl<'a> Walker<'a> { at_do: Option<(usize, usize)>, ) -> Result<(), AuditError> { let mut path = Path::Empty; + let mut clip_next = false; for (i, op) in ops.iter().enumerate() { self.bump()?; // Paint position of this operator: its own `(piece, joined index)` at page level, @@ -148,6 +194,7 @@ impl<'a> Walker<'a> { *gs = g; } path = Path::Empty; + clip_next = false; } b"cm" => { let before = gs.ctm; @@ -163,12 +210,14 @@ impl<'a> Walker<'a> { } } b"g" => { + gs.space = 1; if let Some(v) = op.num(0).filter(|v| v.is_finite()) { let v = v.clamp(0.0, 1.0); gs.fill = [v, v, v]; } } b"rg" => { + gs.space = 3; if let Some([r, g, b]) = op.nums::<3>() && [r, g, b].iter().all(|v| v.is_finite()) { @@ -176,6 +225,7 @@ impl<'a> Walker<'a> { } } b"k" => { + gs.space = 4; if let Some([c, m, y, k]) = op.nums::<4>() && [c, m, y, k].iter().all(|v| v.is_finite()) { @@ -184,6 +234,43 @@ impl<'a> Walker<'a> { gs.fill = [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)]; } } + b"cs" => { + if let Some(name) = op.name(0) { + gs.space = match name { + b"DeviceGray" => 1, + b"DeviceRGB" => 3, + b"DeviceCMYK" => 4, + _ => 0, + }; + gs.fill = [0.0, 0.0, 0.0]; + } + } + b"sc" | b"scn" => match gs.space { + 1 => { + if let Some(v) = op.num(0).filter(|v| v.is_finite()) { + let v = v.clamp(0.0, 1.0); + gs.fill = [v, v, v]; + } + } + 3 => { + if let Some([r, g, b]) = op.nums::<3>() + && [r, g, b].iter().all(|v| v.is_finite()) + { + gs.fill = [r.clamp(0.0, 1.0), g.clamp(0.0, 1.0), b.clamp(0.0, 1.0)]; + } + } + 4 => { + if let Some([c, m, y, k]) = op.nums::<4>() + && [c, m, y, k].iter().all(|v| v.is_finite()) + { + let (c, m, y, k) = (c.clamp(0.0, 1.0), m.clamp(0.0, 1.0), y.clamp(0.0, 1.0), k.clamp(0.0, 1.0)); + gs.fill = [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)]; + } + } + _ => { + gs.fill = [0.0, 0.0, 0.0]; + } + }, b"gs" => { if let Some(name) = op.name(0) { gs.alpha = ext_alpha(self.doc, resources, name); @@ -191,7 +278,7 @@ impl<'a> Walker<'a> { } b"re" => { let rect = op.nums::<4>().and_then(|[x, y, w, h]| { - if [x, y, w, h].iter().all(|v| v.is_finite()) && w != 0.0 && h != 0.0 { + if [x, y, w, h].iter().all(|v| v.is_finite()) && w != 0.0 && h != 0.0 && axis_aligned(&gs.ctm) { let r = gs.ctm.bbox([x.min(x + w), y.min(y + h), x.max(x + w), y.max(y + h)]); (r[2] > r[0] && r[3] > r[1]).then_some(r) } else { @@ -224,16 +311,82 @@ impl<'a> Walker<'a> { _ => Path::Other, }; } + b"W" | b"W*" => clip_next = true, + b"n" => { + if clip_next { + if let Some(r) = path.rect() { + gs.clip = gs.clip.intersect_rect(r); + } else { + gs.clip = Clip::Unknown; + } + clip_next = false; + } + path = Path::Empty; + } // `b`/`b*` close the path before filling it, which the fill does anyway. b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" => { - if let Some(r) = std::mem::replace(&mut path, Path::Empty).rect() + let p = std::mem::replace(&mut path, Path::Empty); + if clip_next { + if let Some(r) = p.rect() { + gs.clip = gs.clip.intersect_rect(r); + } else { + gs.clip = Clip::Unknown; + } + clip_next = false; + } + if self.oc_hidden_depth == 0 && gs.alpha >= 1.0 + && let Some(r) = p.rect() { - self.out.push(FilledRect { rect: r, rgb: gs.fill, pos }); + let visible_r = match gs.clip { + Clip::None | Clip::Unknown => Some(r), + Clip::Rect(c) => intersect(r, c), + Clip::Glyphs => None, + }; + if let Some(r) = visible_r { + self.out.push(FilledRect { rect: r, rgb: gs.fill, pos }); + } + } + } + b"S" | b"s" => { + if clip_next { + if let Some(r) = path.rect() { + gs.clip = gs.clip.intersect_rect(r); + } else { + gs.clip = Clip::Unknown; + } + clip_next = false; + } + path = Path::Empty; + } + b"c" | b"v" | b"y" => path = Path::Other, + b"Tr" => { + if let Some(mode) = op.num(0).and_then(|v| (v.is_finite() && v >= 0.0).then_some(v as u32)) { + gs.tr = mode; + } + } + b"Tj" | b"TJ" | b"'" | b"\"" => { + if (4..=7).contains(&gs.tr) { + gs.clip = Clip::Glyphs; + } + } + b"BDC" => { + let is_off = + if op.name(0) == Some(b"OC") { is_layer_off(self.doc, resources, &self.off_layers, op.operands.get(1)) } else { false }; + if is_off || self.oc_hidden_depth > 0 { + self.oc_hidden_depth += 1; + } + } + b"BMC" => { + if self.oc_hidden_depth > 0 { + self.oc_hidden_depth += 1; + } + } + b"EMC" => { + if self.oc_hidden_depth > 0 { + self.oc_hidden_depth -= 1; } } - b"S" | b"s" | b"n" => path = Path::Empty, - b"c" | b"v" | b"y" | b"W" | b"W*" => path = Path::Other, b"Do" => { if let Some(name) = op.name(0) { if depth >= MAX_DEPTH { @@ -253,6 +406,9 @@ impl<'a> Walker<'a> { /// changes inside never leak out; every rectangle found is stamped with the `Do` /// position `pos`. fn walk_xobject(&mut self, name: &[u8], gs: &Gs, resources: &Dict, depth: usize, pos: (usize, usize)) -> Result<(), AuditError> { + if self.oc_hidden_depth > 0 { + return Ok(()); + } let xobjects = resources.get(b"XObject").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default(); let Some(entry) = xobjects.get(name) else { return Ok(()) }; let resolved = self.doc.resolve(entry); @@ -261,6 +417,11 @@ impl<'a> Walker<'a> { if dict.name(b"Subtype") != Some(b"Form") { return Ok(()); } + if let Some(Object::Ref(r)) = dict.get(b"OC") + && self.off_layers.contains(r) + { + return Ok(()); + } let matrix = dict .get(b"Matrix") .map(|o| self.doc.resolve(o)) @@ -270,6 +431,10 @@ impl<'a> Walker<'a> { (v.len() == 6 && v.iter().all(|x| x.is_finite())).then(|| Matrix([v[0], v[1], v[2], v[3], v[4], v[5]])) }) .unwrap_or(Matrix::IDENTITY); + let bbox = dict.get(b"BBox").map(|o| self.doc.resolve(o)).and_then(|o| o.as_array().map(|a| a.to_vec())).and_then(|a| { + let v: Vec = a.iter().filter_map(|o| self.doc.resolve(o).as_f64()).collect(); + (v.len() == 4 && v.iter().all(|x| x.is_finite())).then(|| [v[0].min(v[2]), v[1].min(v[3]), v[0].max(v[2]), v[1].max(v[3])]) + }); let sub_resources = dict.get(b"Resources").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default(); // A form stream that cannot be decoded fails the audit: it might hide a cover. let data = stream.decoded_strict()?; @@ -277,8 +442,19 @@ impl<'a> Walker<'a> { // The XObject matrix maps form space into the user space active at `Do`. let mut sub_gs = gs.clone(); sub_gs.ctm = matrix.then(&gs.ctm); + if let Some(bbox) = bbox { + if axis_aligned(&sub_gs.ctm) { + let form_box = sub_gs.ctm.bbox(bbox); + sub_gs.clip = sub_gs.clip.intersect_rect(form_box); + } else { + sub_gs.clip = Clip::Unknown; + } + } + let saved_oc_depth = self.oc_hidden_depth; let mut sub_stack = Vec::new(); - self.walk_ops(&ops, &mut sub_gs, &mut sub_stack, &sub_resources, depth + 1, Some(pos)) + let res = self.walk_ops(&ops, &mut sub_gs, &mut sub_stack, &sub_resources, depth + 1, Some(pos)); + self.oc_hidden_depth = saved_oc_depth; + res } } @@ -301,6 +477,41 @@ fn ext_alpha(doc: &Document, resources: &Dict, name: &[u8]) -> f64 { alpha.filter(|a| a.is_finite()).map(|a| a.clamp(0.0, 1.0)).unwrap_or(1.0) } +fn off_layers(doc: &Document) -> HashSet { + let mut off_set = HashSet::new(); + let Some(root) = doc.trailer().get(b"Root").map(|r| doc.resolve(r)) else { return off_set }; + let Some(catalog) = root.as_dict() else { return off_set }; + let Some(oc_props) = catalog.get(b"OCProperties").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()) else { + return off_set; + }; + let Some(d) = oc_props.get(b"D").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()) else { + return off_set; + }; + if let Some(off_arr) = d.get(b"OFF").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()) { + for item in off_arr { + if let Object::Ref(r) = item { + off_set.insert(r); + } + } + } + off_set +} + +fn is_layer_off(doc: &Document, resources: &Dict, off_layers: &HashSet, prop: Option<&Object>) -> bool { + let Some(prop) = prop else { return false }; + match prop { + Object::Ref(r) => off_layers.contains(r), + Object::Name(name) => { + let Some(props) = resources.get(b"Properties").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()) else { + return false; + }; + let Some(entry) = props.get(name) else { return false }; + if let Object::Ref(r) = entry { off_layers.contains(r) } else { false } + } + _ => false, + } +} + /// Every opaque filled rectangle drawn by a page's content (and its form XObjects), with paint /// positions. A page's content streams are walked once, joined, with one graphics state, so /// state set in an earlier stream is still in force in the later ones. Any content stream that @@ -322,7 +533,8 @@ pub fn filled_rects(doc: &Document, page: &Dict) -> Result, Audi } let pieces = Pieces::join(&streams); let parsed = pieces.parse(); - let mut w = Walker { doc, pieces: &pieces, out: Vec::new(), ops_seen: 0 }; + let off = off_layers(doc); + let mut w = Walker { doc, pieces: &pieces, out: Vec::new(), ops_seen: 0, off_layers: off, oc_hidden_depth: 0 }; let mut gs = Gs::default(); let mut stack = Vec::new(); w.walk_ops(&parsed.ops, &mut gs, &mut stack, &resources, 0, None)?; diff --git a/crates/audit/src/tests.rs b/crates/audit/src/tests.rs index 63d9220cca..448c68f74e 100644 --- a/crates/audit/src/tests.rs +++ b/crates/audit/src/tests.rs @@ -529,3 +529,212 @@ fn reading_blocks_respect_stream_comments_and_split_operands() { assert_eq!(text, "Replacement text", "{}", String::from_utf8_lossy(s1)); } } + +#[test] +fn clipping_path_prunes_clipped_out_box() { + // Negative control (#3118): box is drawn outside the active clip, so it hides nothing. + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 0 0 10 10 re W n 0 g 100 688 220 32 re f Q\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert!(findings.is_empty(), "{findings:?}"); + + // Paired positive control: clipping path contains the box, so the cover is detected. + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 90 680 240 50 re W n 0 g 100 688 220 32 re f Q\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "{findings:?}"); + assert_eq!(findings[0].kind, FindingKind::CoveredText); + assert!(findings[0].covered_text.contains("SECRET")); + + // Disjoint clips leave an empty intersection so nothing visible is painted. + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 0 0 10 10 re W n 50 50 10 10 re W n 0 g 100 688 220 32 re f Q\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert!(findings.is_empty(), "disjoint clips leave nothing visible: {findings:?}"); + + // A clip that is not an axis-aligned rectangle fails closed as unknown and keeps the candidate cover. + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 0 0 m 612 0 l 306 792 l h W n 0 g 100 688 220 32 re f Q\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "non-rectangular clip path fails closed: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); +} + +#[test] +fn form_bbox_clips_contained_drawing() { + // Negative control (#3118): form BBox does not reach the text. + let mut b = Builder::new(); + b.add("<< /Type /Catalog /Pages 2 0 R >>"); + b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>"); + b.add("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 6 0 R >> /XObject << /Fm 5 0 R >> >> >>"); + b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/Fm Do\n"); + b.add_stream_with(b"0 g\n100 688 220 32 re f\n", "/Type /XObject /Subtype /Form /BBox [0 0 10 10]"); + b.add(FONT); + let findings = audit_redactions(&open(b.build())).expect("audit must run"); + assert!(findings.is_empty(), "{findings:?}"); + + // Paired positive control: form BBox covers the text. + let mut b = Builder::new(); + b.add("<< /Type /Catalog /Pages 2 0 R >>"); + b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>"); + b.add("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 6 0 R >> /XObject << /Fm 5 0 R >> >> >>"); + b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/Fm Do\n"); + b.add_stream_with(b"0 g\n100 688 220 32 re f\n", "/Type /XObject /Subtype /Form /BBox [0 0 612 792]"); + b.add(FONT); + let findings = audit_redactions(&open(b.build())).expect("audit must run"); + assert_eq!(findings.len(), 1, "{findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); +} + +#[test] +fn optional_content_hidden_layer_is_not_reported() { + // Negative control (#3118): box is drawn inside a layer that is default OFF. + let mut b = Builder::new(); + b.add("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [6 0 R] /D << /OFF [6 0 R] >> >> >>"); + b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>"); + b.add( + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /Properties << /L1 6 0 R >> >> >>", + ); + b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/OC /L1 BDC\n0 g\n100 688 220 32 re f\nEMC\n"); + b.add(FONT); + b.add("<< /Type /OCG /Name (Hidden) >>"); + let findings = audit_redactions(&open(b.build())).expect("audit must run"); + assert!(findings.is_empty(), "{findings:?}"); + + // Paired positive control: box is drawn inside a layer that is visible. + let mut b = Builder::new(); + b.add("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [6 0 R] /D << /Order [6 0 R] >> >> >>"); + b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>"); + b.add( + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /Properties << /L1 6 0 R >> >> >>", + ); + b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/OC /L1 BDC\n0 g\n100 688 220 32 re f\nEMC\n"); + b.add(FONT); + b.add("<< /Type /OCG /Name (Visible) >>"); + let findings = audit_redactions(&open(b.build())).expect("audit must run"); + assert_eq!(findings.len(), 1, "{findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); +} + +#[test] +fn text_clipping_mode_fill_is_not_reported_as_cover() { + // Negative control (#3118): fill through Tr 7 text clip fills the glyphs, not a page cover. + let content = b"q BT /F1 24 Tf 7 Tr 100 700 Td (SECRET DATA 123) Tj ET 0 0 0.5 rg 0 0 612 792 re f Q\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert!(findings.is_empty(), "{findings:?}"); + + // Paired positive control: after Q restores normal clipping (or with 0 Tr), fill is detected. + let content = b"q BT /F1 24 Tf 7 Tr 100 700 Td (SECRET DATA 123) Tj ET Q 0 g 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "{findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); + + // 4 Tr clips like 7 Tr: text clipping modes 4..=7 fill glyphs, not a page cover. + let content = b"q BT /F1 24 Tf 4 Tr 100 700 Td (SECRET DATA 123) Tj ET 0 g 0 0 612 792 re f Q\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert!(findings.is_empty(), "Tr 4 text clip fills glyphs: {findings:?}"); + + // 3 Tr (neither stroke nor fill) does not clip: a black box over invisible, extractable text is still a cover. + let content = b"BT /F1 24 Tf 3 Tr 100 700 Td (SECRET DATA 123) Tj ET\n0 g 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "Tr 3 text does not clip: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); +} + +#[test] +fn color_set_with_cs_sc_and_scn_controls() { + // 1. DeviceGray via cs / sc + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n1 g 0 0 1 1 re f /DeviceGray cs 0 sc 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "DeviceGray cs/sc: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); + + // 2. DeviceRGB via cs / sc + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n1 g 0 0 1 1 re f /DeviceRGB cs 0 0 0 sc 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "DeviceRGB cs/sc: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); + + // 3. DeviceCMYK via cs / sc + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n1 g 0 0 1 1 re f /DeviceCMYK cs 0 0 0 1 sc 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "DeviceCMYK cs/sc: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); + + // 4. scn operator with DeviceRGB + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n1 g 0 0 1 1 re f /DeviceRGB cs 0.05 0.05 0.05 scn 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "scn operator: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); + + // 5. Fail-closed: unknown color space defaults to black + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n1 g 0 0 1 1 re f /CustomSeparation cs 0.5 sc 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "unknown color space fail-closed: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); + + // 6. Negative control: light color set via cs / sc is not reported as cover + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n0 g 0 0 1 1 re f /DeviceGray cs 1 sc 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert!(findings.is_empty(), "light color via cs/sc must not be reported: {findings:?}"); + + // 7. White CMYK fill set through cs / sc is not a cover + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/DeviceCMYK cs 0 0 0 0 sc 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert!(findings.is_empty(), "white CMYK fill via cs/sc is not a cover: {findings:?}"); + + // 8. Unknown color space is treated as black regardless of sc components + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/CS9 cs 1 1 1 sc 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "unknown color space treated as black: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); +} + +#[test] +fn unclosed_oc_in_form_xobject_does_not_leak_to_parent() { + let mut b = Builder::new(); + b.add("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [6 0 R] /D << /OFF [6 0 R] >> >> >>"); + b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>"); + b.add( + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /XObject << /Fm 7 0 R >> /Properties << /L1 6 0 R >> >> >>", + ); + // Page: text, then /Fm Do (which has unclosed /OC /L1 BDC), then genuine cover over text. + b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/Fm Do\n0 g\n100 688 220 32 re f\n"); + b.add(FONT); + b.add("<< /Type /OCG /Name (Hidden) >>"); + // Form Fm leaves /OC /L1 unclosed (no EMC) + b.add_stream_with( + b"/OC /L1 BDC\n0 g\n0 0 10 10 re f\n", + "/Type /XObject /Subtype /Form /BBox [0 0 10 10] /Resources << /Properties << /L1 6 0 R >> >>", + ); + let findings = audit_redactions(&open(b.build())).expect("audit must run"); + assert_eq!(findings.len(), 1, "genuine cover following unclosed form OC must not be suppressed: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); +} + +#[test] +fn rotated_re_cover_detection() { + // 90-degree axis-aligned rotation: (x_user, y_user) = (800 - y, x) + // with rect [688, 480, 32, 220] mapping to user space [100, 688, 320, 720] over the text. + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 0 1 -1 0 800 0 cm 0 g 688 480 32 220 re f Q\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "90-deg rotated axis-aligned rect is detected: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); + + // 45-degree non-axis-aligned rotation: bounding box overlaps text, but non-axis-aligned geometry is excluded. + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 0.7071 0.7071 -0.7071 0.7071 200 550 cm 0 g 10 10 160 160 re f Q\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert!(findings.is_empty(), "non-axis-aligned path is not a rectangular cover: {findings:?}"); +} + +#[test] +fn nested_marked_content_inside_hidden_oc_is_not_reported() { + let mut b = Builder::new(); + b.add("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [6 0 R] /D << /OFF [6 0 R] >> >> >>"); + b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>"); + b.add( + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /Properties << /L1 6 0 R >> >> >>", + ); + // Nested marked content (/Span) inside hidden layer (/OC /L1): box remains on hidden layer after inner EMC. + b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/OC /L1 BDC\n/Span << >> BDC\nEMC\n0 g\n100 688 220 32 re f\nEMC\n"); + b.add(FONT); + b.add("<< /Type /OCG /Name (Hidden) >>"); + let findings = audit_redactions(&open(b.build())).expect("audit must run"); + assert!(findings.is_empty(), "box inside nested marked content on hidden OC layer must not be reported: {findings:?}"); +} From 51edea9894ae54d23e869443fc615ee11e419c3f Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sat, 17 Oct 2026 23:51:25 +0800 Subject: [PATCH 002/114] M7: pick pictures where they show, not across transparent margins A picture with a soft mask, a stencil or colour-key /Mask, or /ImageMask is hit only where it shows: Edit text & images selection and hover, image_hit and Copy Image. Its opacity is read once per document generation onto a grid of at most 256 x 256 cells. Form artwork and pictures that can't be decoded keep their whole box. Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/dispatch.rs | 8 +- crates/automation/src/tools.rs | 2 +- crates/automation/tests/it/automation.rs | 47 ++++++ crates/engine/src/copy_image.rs | 2 +- crates/engine/src/document.rs | 2 + crates/engine/src/image_alpha.rs | 152 ++++++++++++++++++ crates/engine/src/lib.rs | 1 + crates/engine/src/open.rs | 1 + crates/engine/src/tests.rs | 142 +++++++++++++++- crates/ui-egui/src/canvas.rs | 7 +- .../ui-egui/src/tools/edit_text_ui/image.rs | 18 ++- crates/ui-egui/tests/it/editing.rs | 65 ++++++++ docs/editing-images.md | 9 +- parity/acrobat-features.toml | 4 +- 14 files changed, 445 insertions(+), 15 deletions(-) create mode 100644 crates/engine/src/image_alpha.rs diff --git a/crates/automation/src/dispatch.rs b/crates/automation/src/dispatch.rs index 36e0d00454..9066735b1e 100644 --- a/crates/automation/src/dispatch.rs +++ b/crates/automation/src/dispatch.rs @@ -339,7 +339,13 @@ impl Automation { let doc = self.doc(&a)?; let p = &doc.info.pages[page]; let user = p.view_to_user(point[0] as f32, point[1] as f32).map(f64::from); - let images: Vec<_> = doc.page_images(page).iter().enumerate().filter(|(_, im)| im.contains(user)).map(|(i, _)| i + 1).collect(); + let images: Vec<_> = doc + .page_images(page) + .iter() + .enumerate() + .filter(|(_, im)| im.contains(user) && doc.image_shows_at(im, user)) + .map(|(i, _)| i + 1) + .collect(); json!({"page":page+1,"images":images}) } "page_images" => { diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index c6c200cece..696855e0b6 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -1370,7 +1370,7 @@ pub fn tools() -> Vec { .ro() .cmd("edit.edit_text") .with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 } }), &["doc", "page"])), - t("image_hit", "Hit test page artwork", "List image/Form numbers whose placement and all clipping paths contain point [x,y] in top-left-origin points. Bezier curves, even-odd/nonzero fill and holes are respected. Read only.") + t("image_hit", "Hit test page artwork", "List image/Form numbers whose placement and all clipping paths contain point [x,y] in top-left-origin points. Bezier curves, even-odd/nonzero fill and holes are respected; a picture with transparency (soft mask, /Mask, stencil) counts only where it shows. Read only.") .ro() .cmd("edit.edit_text") .with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1},"point":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":2}}), &["doc","page","point"])), diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 6a5765b911..d13191f60d 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -10190,3 +10190,50 @@ fn simple_rule_scan_drawn(content: &[u8]) -> Vec { } write_full(&doc, &SaveOptions::default()).unwrap() } + +/// `image_hit` counts a picture with transparency only where it shows: through a soft-masked +/// picture's transparent margin, only the picture below is hit. +#[test] +fn image_hit_sees_through_transparent_parts_of_pictures() { + let dir = workdir("alpha-hit"); + let stream = |dict: &str, data: &[u8]| { + let mut o = format!("<< {dict} /Length {} >>\nstream\n", data.len()).into_bytes(); + o.extend_from_slice(data); + o.extend_from_slice(b"\nendstream"); + o + }; + let image = "/Type /XObject /Subtype /Image /Width 4 /Height 4 /BitsPerComponent 8"; + // The soft mask shows the top-right quarter only. + let mask: Vec = [[0, 0, 255, 255], [0, 0, 255, 255], [0; 4], [0; 4]].concat(); + let objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 300] >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /XObject << /Low 5 0 R /Top 6 0 R >> >> >>".to_vec(), + stream("", b"q 100 0 0 100 20 20 cm /Low Do Q q 100 0 0 100 60 60 cm /Top Do Q"), + stream(&format!("{image} /ColorSpace /DeviceRGB"), &[0x80; 48]), + stream(&format!("{image} /ColorSpace /DeviceRGB /SMask 7 0 R"), &[0x40; 48]), + stream(&format!("{image} /ColorSpace /DeviceGray"), &mask), + ]; + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(o); + out.extend_from_slice(b"\nendobj\n"); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + std::fs::write(dir.join("overlap.pdf"), out).unwrap(); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({"path":"overlap.pdf"}))["doc"].as_u64().unwrap(); + let hit = |a: &mut Automation, x: i32, y: i32| ok(a, "image_hit", json!({"doc":doc,"page":1,"point":[x, 300 - y]}))["images"].clone(); + assert_eq!(hit(&mut a, 70, 70), json!([1]), "the top picture's transparent margin"); + assert_eq!(hit(&mut a, 115, 115), json!([1, 2]), "where the top picture shows"); + assert_eq!(hit(&mut a, 150, 70), json!([]), "transparent, over nothing"); + assert_eq!(hit(&mut a, 150, 150), json!([2])); +} diff --git a/crates/engine/src/copy_image.rs b/crates/engine/src/copy_image.rs index b377903ee4..8a026bec03 100644 --- a/crates/engine/src/copy_image.rs +++ b/crates/engine/src/copy_image.rs @@ -22,7 +22,7 @@ impl Document { self.page_images(page).iter().rposition(|i| { inside(&i.rect) && match (i.is_form, i.object) { - (false, Some(_)) => true, + (false, Some(_)) => self.image_shows_at(i, at), (true, Some(form)) => picture_in_form(&editor.cos, form).is_some(), _ => false, } diff --git a/crates/engine/src/document.rs b/crates/engine/src/document.rs index fa98a18417..15a98f339a 100644 --- a/crates/engine/src/document.rs +++ b/crates/engine/src/document.rs @@ -63,6 +63,8 @@ pub struct Document { /// [`EditNotice`]): text its fonts can't draw, pages whose own backdrop stays off. The /// interface shows it; tools return it. pub edit_notices: Vec, + /// Which parts of pictures with transparency show, for picking them ([`Document::image_shows_at`]). + pub(crate) alpha: crate::image_alpha::AlphaCache, } /// Something the last successful edit did that the user should hear about, never left silent diff --git a/crates/engine/src/image_alpha.rs b/crates/engine/src/image_alpha.rs new file mode 100644 index 0000000000..9e6b50d181 --- /dev/null +++ b/crates/engine/src/image_alpha.rs @@ -0,0 +1,152 @@ +//! Edit text & images: a picture is picked where it shows, not across its whole box. A PNG +//! signature or a cut-out photo with a transparent margin overlaps its neighbours; clicking a +//! neighbour through that margin picked the transparent picture on top. +//! +//! A picture with transparency (a soft mask, a stencil or colour-key `/Mask`, or a stencil image +//! `/ImageMask`) gets an opacity grid of at most [`MAX_GRID`] cells a side, built once from its +//! pixels and kept until the document changes. A cell counts as opaque if any pixel +//! in it is: thin strokes and the edges of a shape stay easy to pick. Pictures without +//! transparency, Form artwork, and pictures that can't be decoded keep their whole box. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use pdfcraft_cos::{ObjRef, Object}; + +use crate::Document; + +/// The opacity grid's largest side, in cells. +const MAX_GRID: u32 = 256; +/// Grids kept at once (at most 64 KiB each); past this the cache starts over. +const MAX_CACHED: usize = 256; +/// Pictures larger than this many pixels keep their whole box rather than being decoded. +const MAX_DECODE_PIXELS: u64 = 64_000_000; +/// Alpha at or above this (of 255) counts as showing. +const OPAQUE: u8 = 16; + +/// Which cells of a picture show, row 0 at the top of the picture. +#[derive(Debug)] +pub(crate) struct Opacity { + width: u32, + height: u32, + cells: Vec, +} + +/// Opacity grids by picture object, for the document generation they were built at; `None` for +/// a picture that is opaque everywhere or couldn't be read (its whole box counts). The +/// generation, not the picture object alone, says when to rebuild: an edit may change the +/// picture's soft mask without touching the picture. +type Grids = (u64, HashMap>>); + +#[derive(Default)] +pub(crate) struct AlphaCache(Mutex); + +impl Document { + /// Whether `image` shows at user-space `point` (assumed inside its placement): `false` only + /// where a picture with transparency is see-through. Form artwork, pictures without + /// transparency and pictures that can't be read show everywhere in their box. + pub fn image_shows_at(&self, image: &pdfcraft_edit::PageImage, point: [f64; 2]) -> bool { + if image.is_form { + return true; + } + let Some(object) = image.object else { return true }; + let Some(grid) = self.opacity(object) else { return true }; + let Some((x, y)) = unit_point(image.matrix, point) else { return true }; + if !(0.0..=1.0).contains(&x) || !(0.0..=1.0).contains(&y) { + return true; + } + // Image space: row 0 is the top of the unit square (y = 1). + let col = ((x * f64::from(grid.width)) as u32).min(grid.width.saturating_sub(1)); + let row = (((1.0 - y) * f64::from(grid.height)) as u32).min(grid.height.saturating_sub(1)); + let at = usize::try_from(u64::from(row) * u64::from(grid.width) + u64::from(col)).unwrap_or(usize::MAX); + grid.cells.get(at).copied().unwrap_or(true) + } + + /// The opacity grid of picture `object`, built on first use and kept until the document + /// changes. + fn opacity(&self, object: ObjRef) -> Option> { + let editor = self.editor.as_ref()?; + // A poisoned cache is only a cache: build without it. + if let Ok(cache) = self.alpha.0.lock() + && cache.0 == self.generation + && let Some(grid) = cache.1.get(&object) + { + return grid.clone(); + } + let grid = build(&editor.cos, object).map(Arc::new); + if let Ok(mut cache) = self.alpha.0.lock() { + if cache.0 != self.generation || cache.1.len() >= MAX_CACHED { + *cache = (self.generation, HashMap::new()); + } + cache.1.insert(object, grid.clone()); + } + grid + } +} + +/// The picture's opacity grid, or `None` when it is opaque everywhere or can't be read. +fn build(cos: &pdfcraft_cos::Document, object: ObjRef) -> Option { + let current = cos.get(object); + let Object::Stream(s) = &*current else { return None }; + let flag = |key: &[u8]| s.dict.get(key).is_some_and(|v| matches!(&*cos.resolve(v), Object::Bool(true))); + let stencil = flag(b"ImageMask"); + let soft = s.dict.get(b"SMask").is_some_and(|v| cos.resolve(v).as_name() != Some(b"None")); + let in_data = s.dict.int(b"SMaskInData").is_some_and(|v| v != 0); + if !(stencil || soft || in_data || s.dict.get(b"Mask").is_some()) { + return None; + } + let size = |key: &[u8]| u64::try_from(s.dict.int(key).unwrap_or(0)).unwrap_or(0); + if size(b"Width").saturating_mul(size(b"Height")) > MAX_DECODE_PIXELS { + return None; + } + let (_, bytes) = pdfcraft_create::image_file(cos, object).ok()?; + let format = image::guess_format(&bytes).ok()?; + let mut reader = image::ImageReader::with_format(std::io::Cursor::new(bytes.as_slice()), format); + let mut limits = image::Limits::default(); + limits.max_alloc = Some(MAX_DECODE_PIXELS.saturating_mul(4)); + reader.limits(limits); + let picture = reader.decode().ok()?; + let (w, h) = (picture.width(), picture.height()); + if w == 0 || h == 0 { + return None; + } + let shows: Box bool> = if picture.color().has_alpha() { + let rgba = picture.into_rgba8(); + Box::new(move |x, y| rgba.get_pixel_checked(x, y).is_none_or(|p| p.0[3] >= OPAQUE)) + } else if stencil { + // The export draws a stencil image's painted samples white, whatever its `/Decode`. + let luma = picture.into_luma8(); + Box::new(move |x, y| luma.get_pixel_checked(x, y).is_none_or(|p| p.0[0] >= 128)) + } else { + return None; + }; + let (gw, gh) = (w.min(MAX_GRID), h.min(MAX_GRID)); + let mut cells = vec![false; usize::try_from(u64::from(gw) * u64::from(gh)).ok()?]; + for y in 0..h { + let row = u64::from(y) * u64::from(gh) / u64::from(h); + for x in 0..w { + if shows(x, y) { + let col = u64::from(x) * u64::from(gw) / u64::from(w); + if let Some(cell) = usize::try_from(row * u64::from(gw) + col).ok().and_then(|i| cells.get_mut(i)) { + *cell = true; + } + } + } + } + if cells.iter().all(|c| *c) { + return None; + } + Some(Opacity { width: gw, height: gh, cells }) +} + +/// `point` in the placement's unit square: the inverse of `matrix` applied to it. +fn unit_point(m: [f64; 6], point: [f64; 2]) -> Option<(f64, f64)> { + let det = m[0] * m[3] - m[1] * m[2]; + if !det.is_finite() || det.abs() < 1e-12 { + return None; + } + let (dx, dy) = (point[0] - m[4], point[1] - m[5]); + let x = (m[3] * dx - m[2] * dy) / det; + let y = (m[0] * dy - m[1] * dx) / det; + (x.is_finite() && y.is_finite()).then_some((x, y)) +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7cd2f96a96..2e81623cf9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -32,6 +32,7 @@ pub mod export; pub mod field_table; mod fill_sign; mod history; +mod image_alpha; pub mod js; mod layers; pub mod links; diff --git a/crates/engine/src/open.rs b/crates/engine/src/open.rs index 58bc8327e2..ce2a98c201 100644 --- a/crates/engine/src/open.rs +++ b/crates/engine/src/open.rs @@ -352,6 +352,7 @@ impl Session { fonts_stale: false, xfa_warnings: Vec::new(), edit_notices: Vec::new(), + alpha: Default::default(), } } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 833fa16b9f..675bb09404 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8020,7 +8020,9 @@ fn copy_image_finds_the_image_under_a_point_and_decodes_it_at_full_size() { let id = s.open("p.pdf", None, pic, None).unwrap(); let d = s.get(id).unwrap(); let r = d.page_images(0)[0].rect; - assert_eq!(d.page_image_at(0, [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0]), Some(0)); + // On its red top-left pixel; its other pixels but the blue one are transparent. + assert_eq!(d.page_image_at(0, [r[0] + (r[2] - r[0]) / 6.0, r[3] - (r[3] - r[1]) / 4.0]), Some(0)); + assert_eq!(d.page_image_at(0, [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0]), None); assert_eq!(d.page_image_at(0, [r[2] + 10.0, r[3] + 10.0]), None); assert_eq!(d.page_image_at(7, [0.0, 0.0]), None); let (w, h, rgba) = d.page_image_rgba(0, 0).unwrap(); @@ -9335,3 +9337,141 @@ fn repeated_backdrop_artwork_survives_background_undo_redo_and_both_save_modes() s.apply(rewritten, Edit::RemoveMarks { kind: MarkKind::Background }).unwrap(); black(&s, rewritten); } + +/// A one-page 300 × 300 PDF of `objects` (numbered from 5) drawn by `content`; the page's +/// XObjects are `xobjects`. +fn images_pdf(xobjects: &str, content: &[u8], objects: &[(String, Vec)]) -> Vec { + let stream = |dict: &str, data: &[u8]| { + let mut o = format!("<< {dict} /Length {} >>\nstream\n", data.len()).into_bytes(); + o.extend_from_slice(data); + o.extend_from_slice(b"\nendstream"); + o + }; + let mut objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 300] >>".to_vec(), + format!("<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /XObject << {xobjects} >> >> >>").into_bytes(), + stream("", content), + ]; + objs.extend(objects.iter().map(|(dict, data)| stream(dict, data))); + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(o); + out.extend_from_slice(b"\nendobj\n"); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + out +} + +/// Pictures are picked where they show. Overlapping pictures with transparent margins (a PNG +/// signature over a table, cut-out photos side by side) give a click through the margin to the +/// picture below; stencil images and colour-keyed pictures likewise. Pictures that can't be +/// read, or show everywhere, keep their whole box. +#[test] +fn pictures_are_picked_where_they_show() { + let rgb = |n: usize| ("/Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceRGB /BitsPerComponent 8".to_string(), vec![0x80; n]); + let with = |(d, data): (String, Vec), extra: &str| (format!("{d} {extra}"), data); + let gray = |rows: [[u8; 4]; 4]| { + ("/Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceGray /BitsPerComponent 8".to_string(), rows.concat()) + }; + let (a, o) = (255, 0); + let objects = vec![ + rgb(48), // 5: Low, opaque + with(rgb(48), "/SMask 7 0 R"), // 6: Top + gray([[o, o, a, a], [o, o, a, a], [o, o, o, o], [o, o, o, o]]), // 7: its top-right quarter shows + ("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ImageMask true".into(), vec![0x40]), // 8 + ("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ImageMask true /Decode [1 0]".into(), vec![0x40]), // 9 + ( + "/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Mask [250 255 0 5 0 5]".into(), + vec![255, 0, 0, 0, 0, 255], + ), // 10: red keyed out + ( + "/Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /JPXDecode /SMask 7 0 R".into(), + b"not a JPEG 2000 codestream".to_vec(), + ), // 11: can't be read + with(rgb(48), "/SMask 13 0 R"), // 12 + gray([[a; 4]; 4]), // 13: shows everywhere + ]; + let content = b"q 100 0 0 100 20 20 cm /Low Do Q q 100 0 0 100 60 60 cm /Top Do Q \ + q 40 0 0 40 200 20 cm /St Do Q q 40 0 0 40 250 20 cm /StI Do Q q 40 0 0 40 200 100 cm /Key Do Q \ + q 40 0 0 40 200 200 cm /Jpx Do Q q 40 0 0 40 250 200 cm /Full Do Q q -40 0 0 40 140 200 cm /Top Do Q q 0 40 -40 0 300 250 cm /Top Do Q"; + let xobjects = "/Low 5 0 R /Top 6 0 R /St 8 0 R /StI 9 0 R /Key 10 0 R /Jpx 11 0 R /Full 12 0 R"; + let mut s = Session::new(); + let id = s.open("alpha.pdf", None, Arc::new(images_pdf(xobjects, content, &objects)), None).unwrap(); + let d = s.get(id).unwrap(); + assert_eq!(d.page_images(0).len(), 9, "{:?}", d.page_images(0)); + let cases: [([f64; 2], Option); 14] = [ + // Top's transparent lower-left, over Low: Low is picked. + ([70.0, 70.0], Some(0)), + ([100.0, 100.0], Some(0)), + // Top's showing quarter, over Low and beyond it. + ([115.0, 145.0], Some(1)), + ([150.0, 150.0], Some(1)), + // Top's transparent lower-right, over nothing. + ([150.0, 70.0], None), + // A stencil paints its 0 samples; with /Decode [1 0], its 1 samples. + ([210.0, 40.0], Some(2)), + ([230.0, 40.0], None), + ([260.0, 40.0], None), + ([280.0, 40.0], Some(3)), + // The colour-keyed red half doesn't show. + ([210.0, 120.0], None), + ([230.0, 120.0], Some(4)), + // Unreadable, and showing everywhere: the whole box. + ([205.0, 205.0], Some(5)), + ([255.0, 205.0], Some(6)), + // Top mirrored: its showing quarter is on the left. + ([105.0, 235.0], Some(7)), + ]; + for (at, want) in cases { + assert_eq!(d.page_image_at(0, at), want, "at {at:?}"); + } + assert_eq!(d.page_image_at(0, [135.0, 235.0]), None, "the mirrored placement's transparent right"); + // Top turned a quarter: its showing quarter is at the top left. + assert_eq!(d.page_image_at(0, [265.0, 285.0]), Some(8)); + assert_eq!(d.page_image_at(0, [295.0, 285.0]), None); + assert_eq!(d.page_image_at(0, [265.0, 255.0]), None); + let images = d.page_images(0); + assert!(!d.image_shows_at(&images[1], [70.0, 70.0])); + assert!(d.image_shows_at(&images[1], [150.0, 150.0])); + + // An edit changing only Top's soft mask is seen at once: it now shows everywhere. + let doc = s.doc_mut(id).unwrap(); + let editor = doc.editor.as_mut().unwrap(); + let full = editor.cos.get(pdfcraft_cos::ObjRef::new(13, 0)); + editor.cos.set(pdfcraft_cos::ObjRef::new(7, 0), (*full).clone()); + doc.generation += 1; + let d = s.get(id).unwrap(); + assert_eq!(d.page_image_at(0, [70.0, 70.0]), Some(1)); + assert_eq!(d.page_image_at(0, [150.0, 70.0]), Some(1)); +} + +/// A picture larger than the opacity grid is picked where it shows, its pixels scaled onto the +/// grid: a 300 × 300 picture showing only its top-left 150 × 150. +#[test] +fn large_pictures_are_picked_where_they_show() { + let mask: Vec = (0..300).flat_map(|y| (0..300).map(move |x| if x < 150 && y < 150 { 255 } else { 0 })).collect(); + let objects = vec![ + ( + "/Type /XObject /Subtype /Image /Width 300 /Height 300 /ColorSpace /DeviceGray /BitsPerComponent 8 /SMask 6 0 R".to_string(), + vec![0x80; 90_000], + ), + ("/Type /XObject /Subtype /Image /Width 300 /Height 300 /ColorSpace /DeviceGray /BitsPerComponent 8".to_string(), mask), + ]; + let mut s = Session::new(); + let id = s.open("large.pdf", None, Arc::new(images_pdf("/Big 5 0 R", b"q 100 0 0 100 0 0 cm /Big Do Q", &objects)), None).unwrap(); + let d = s.get(id).unwrap(); + // Just inside and just outside the showing quarter, along each axis. + assert_eq!(d.page_image_at(0, [45.0, 55.5]), Some(0)); + assert_eq!(d.page_image_at(0, [45.0, 44.0]), None); + assert_eq!(d.page_image_at(0, [49.0, 80.0]), Some(0)); + assert_eq!(d.page_image_at(0, [56.0, 80.0]), None); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8b280ba75d..37605bc19a 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1158,6 +1158,7 @@ fn page_tool_input(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame< added, lines: &lines, images: &images, + doc, clip: ui.clip_rect(), }; if let Some(o) = ptr.pressed().filter(|o| xf.rect.contains(*o)) { @@ -1324,6 +1325,7 @@ fn page_tool_input(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame< ptr, page: i, info, + doc, allow_interaction: !others_own_pointer && (matches!(view.router.owner(i), Some(crate::page_router::Owner::Picture { .. })) || !text_used), }; let image_used = crate::edit_text_ui::image_input(&image_cx, &images, view, &mut frame.out.image_action); @@ -1396,6 +1398,8 @@ struct PageHits<'a> { added: &'a [pdfcraft_engine::Added], lines: &'a [pdfcraft_engine::TextBlock], images: &'a [pdfcraft_engine::PageImage], + /// Says where a picture with transparency shows, so it is picked only there. + doc: &'a pdfcraft_engine::Document, /// The pages' visible area (the picture's rotate knob stays inside it). clip: Rect, } @@ -1423,6 +1427,7 @@ impl PageHits<'_> { added, lines, images, + doc, clip, } = *self; let fields = if preparing { @@ -1447,7 +1452,7 @@ impl PageHits<'_> { let edit_text = tool == QuickTool::EditText; let on_paragraphs = edit_text || crate::edit_text_ui::over_paragraph(xf, info, page, lines, p); ( - edit_text.then(|| crate::edit_text_ui::picture_hit(xf, page, info, images, view, p)).flatten(), + edit_text.then(|| crate::edit_text_ui::picture_hit(xf, page, info, doc, images, view, p)).flatten(), on_paragraphs.then(|| crate::edit_text_ui::hit(xf, info, page, lines, open.map(|e| e.block), p)).flatten(), edit_text.then(|| crate::object_ui::hit(view, xf, info, page, frame, p)).flatten(), edit_text.then(|| crate::edit_text_ui::picture_handle_hit(clip, xf, page, info, images, view, p)).flatten(), diff --git a/crates/ui-egui/src/tools/edit_text_ui/image.rs b/crates/ui-egui/src/tools/edit_text_ui/image.rs index 6956e656af..04031d719b 100644 --- a/crates/ui-egui/src/tools/edit_text_ui/image.rs +++ b/crates/ui-egui/src/tools/edit_text_ui/image.rs @@ -57,6 +57,8 @@ pub(crate) struct ImageCx<'a> { pub ptr: &'a PagePointer, pub page: usize, pub info: &'a DocInfo, + /// Says where a picture with transparency shows, so it is picked only there. + pub doc: &'a pdfcraft_engine::Document, pub allow_interaction: bool, } @@ -69,7 +71,7 @@ fn crop_handles(k: Rect) -> [Pos2; 8] { /// Crop mode for the selected image `i` whose visible frame is `b` (screen). Returns `true` /// (the pointer and keys are the crop's while it lasts). fn crop_input(cx: &ImageCx<'_>, view: &mut DocView, i: usize, b: Rect) -> bool { - let ImageCx { ui, resp, xf, ptr, page, info, allow_interaction } = *cx; + let ImageCx { ui, resp, xf, ptr, page, info, allow_interaction, .. } = *cx; let painter = ui.painter(); let Some(mode) = view.image_selection.as_mut().and_then(|s| s.crop.as_mut()) else { return false }; let hover_pos = ptr.pos; @@ -254,10 +256,11 @@ pub(crate) fn handle_hit( Some(Hit::new(picture(PicturePart::Corner(corner)), Layer::Handle, icon)) } -/// The picture under `p` (its shape, not only its box): a click selects it, a drag moves the +/// The picture under `p` (its shape and where it shows, not only its box): a click selects it, a +/// drag moves the /// selected one. On the text layer, asked before the paragraphs: editable text on top of a /// picture takes the press. -pub(crate) fn body_hit(xf: &PageXform, page: usize, info: &DocInfo, images: &[pdfcraft_engine::PageImage], view: &DocView, p: Pos2) -> Option { +pub(crate) fn body_hit(xf: &PageXform, page: usize, info: &DocInfo, doc: &pdfcraft_engine::Document, images: &[pdfcraft_engine::PageImage], view: &DocView, p: Pos2) -> Option { if !xf.rect.contains(p) { return None; } @@ -265,7 +268,7 @@ pub(crate) fn body_hit(xf: &PageXform, page: usize, info: &DocInfo, images: &[pd let user = info.pages.get(page)?.view_to_user(x, y).map(f64::from); let index = images .iter() - .rposition(|im| im.visible_rect.is_some_and(|r| xf.user_rect(info, page, r.map(|v| v as f32)).contains(p)) && im.contains(user))?; + .rposition(|im| im.visible_rect.is_some_and(|r| xf.user_rect(info, page, r.map(|v| v as f32)).contains(p)) && im.contains(user) && doc.image_shows_at(im, user))?; let selected = view.image_selection.as_ref().is_some_and(|s| s.page == page && s.index == index); let icon = if selected { egui::CursorIcon::Move } else { egui::CursorIcon::PointingHand }; Some(Hit::new(Owner::Picture { index, part: PicturePart::Body }, Layer::Text, icon)) @@ -483,15 +486,16 @@ fn drag_preview( /// Images on a page: select, move, resize, right-click. Returns `true` when the pointer was used. pub(crate) fn image_input(cx: &ImageCx<'_>, images: &[pdfcraft_engine::PageImage], view: &mut DocView, action: &mut Option) -> bool { - let ImageCx { ui, resp, xf, ptr, page, info, allow_interaction } = *cx; + let ImageCx { ui, resp, xf, ptr, page, info, doc, allow_interaction } = *cx; let boxes: Vec = images.iter().map(|im| im.visible_rect.map_or(Rect::NOTHING, |r| xf.user_rect(info, page, r.map(|v| v as f32)))).collect(); let painter = ui.painter(); let hover_pos = ptr.pos; let image_contains = |index: usize, point: Pos2| { let (x, y) = xf.screen_to_view(point); let Some(p) = info.pages.get(page) else { return false }; - let user = p.view_to_user(x, y); - images.get(index).is_some_and(|im| im.contains(user.map(f64::from))) + let user = p.view_to_user(x, y).map(f64::from); + // A picture is picked where it shows: through its transparent parts, the one below is. + images.get(index).is_some_and(|im| im.contains(user) && doc.image_shows_at(im, user)) }; let selected = view.image_selection.as_ref().filter(|s| s.page == page).map(|s| s.index).filter(|i| *i < boxes.len()); let dragging = view.image_selection.as_ref().is_some_and(|s| s.drag.is_some()); diff --git a/crates/ui-egui/tests/it/editing.rs b/crates/ui-egui/tests/it/editing.rs index bdb0720dde..e87d0b51ce 100644 --- a/crates/ui-egui/tests/it/editing.rs +++ b/crates/ui-egui/tests/it/editing.rs @@ -7554,3 +7554,68 @@ fn escape_in_an_open_paragraph_selects_its_box_for_delete() { assert_eq!(blocks(&h)[0].text, "Page 1"); } } + +/// Edit text & images: a click through the transparent margin of a picture selects the picture +/// below it, and a click where it shows selects it. +#[test] +fn a_click_through_a_pictures_transparent_margin_selects_the_picture_below() { + let stream = |dict: &str, data: &[u8]| { + let mut o = format!("<< {dict} /Length {} >>\nstream\n", data.len()).into_bytes(); + o.extend_from_slice(data); + o.extend_from_slice(b"\nendstream"); + o + }; + let image = "/Type /XObject /Subtype /Image /Width 4 /Height 4 /BitsPerComponent 8"; + // The top picture's soft mask shows its top-right quarter only. + let mask: Vec = [[0, 0, 255, 255], [0, 0, 255, 255], [0; 4], [0; 4]].concat(); + let objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 300] >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /XObject << /Low 5 0 R /Top 6 0 R >> >> >>".to_vec(), + stream("", b"q 100 0 0 100 20 20 cm /Low Do Q q 100 0 0 100 60 60 cm /Top Do Q"), + stream(&format!("{image} /ColorSpace /DeviceRGB"), &[0x80; 48]), + stream(&format!("{image} /ColorSpace /DeviceRGB /SMask 7 0 R"), &[0x40; 48]), + stream(&format!("{image} /ColorSpace /DeviceGray"), &mask), + ]; + let mut bytes = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(bytes.len()); + bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + bytes.extend_from_slice(o); + bytes.extend_from_slice(b"\nendobj\n"); + } + let xref = bytes.len(); + bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + let mut h = Harness::builder().with_size(egui::vec2(900.0, 800.0)).build_eframe(move |_cc| { + let mut app = PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + app.open_bytes("overlap.pdf", None, bytes).unwrap(); + app + }); + h.run_steps(4); + assert!(h.state_mut().execute("edit.edit_text")); + h.state_mut().views[0].fit = pdfcraft_ui_egui::canvas::Fit::Page; + h.run_steps(4); + let id = h.state().views[0].id; + let info = h.state().session.get(id).unwrap().info.pages[0].clone(); + let page = h.state().views[0].page_screen_rect(0).unwrap(); + let at = |x: f32, y: f32| { + let v = info.user_to_view(x, y); + page.min + egui::vec2(v[0], v[1]) * (page.width() / info.width) + }; + for ((x, y), want) in [((70.0, 70.0), 0), ((150.0, 150.0), 1), ((100.0, 100.0), 0), ((115.0, 145.0), 1)] { + let p = at(x, y); + h.hover_at(p); + h.run_steps(1); + h.drag_at(p); + h.run_steps(1); + h.drop_at(p); + h.run_steps(3); + assert_eq!(h.state().views[0].image_selection.as_ref().map(|s| s.index), Some(want), "click at {x}, {y}"); + } +} diff --git a/docs/editing-images.md b/docs/editing-images.md index 4ebafd115f..c2ba11d76f 100644 --- a/docs/editing-images.md +++ b/docs/editing-images.md @@ -42,7 +42,14 @@ with the selected image, also when the picture sits inside a clip it shares with (a report drawing each picture as `q re W n cm Do Q` within a table's clip): the picture's own clip scales with it, and shared clips stay fixed without moving neighbouring text or artwork. -`image_hit` applies the same path and hole checks headlessly. `page_images` retains `rect` as +A picture with transparency (a soft mask, a stencil or colour-key `/Mask`, or a stencil +image) is picked only where it shows: a click through the transparent margin of a PNG +signature or a cut-out photo goes to what is below it. Opacity is read on a grid of at most +256 cells a side, a cell counting as showing if any of its pixels does (alpha ≥ 16 of 255). +Form artwork, pictures without transparency, and pictures that can't be decoded (JPEG 2000, +JBIG2, CCITT) keep their whole box. + +`image_hit` applies the same path, hole and transparency checks headlessly. `page_images` retains `rect` as the full placement rectangle used by `image_edit` and adds `visible_rect` for selection (null when fully clipped). `object_list` reports visible artwork bounds while keeping the original source indexes. A selection frame does not create, remove or enlarge the PDF's clipping path. diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 1404247cd7..262d315b90 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -2153,8 +2153,8 @@ milestone = "M7" status = "shipped" commands = ["edit.edit_text"] tools = ["image_edit", "image_hit"] -evidence = ["crates/edit/src/tests.rs::private_image_crop_with_intervening_state_resizes_across_streams", "crates/automation/tests/it/automation.rs::private_crops_with_nested_state_resize_save_reopen_through_tools", "crates/edit/src/tests.rs::form_artwork_edits_only_the_selected_placement", "crates/ui-egui/tests/it/editing.rs::editing_existing_form_artwork_on_the_page", "crates/automation/tests/it/automation.rs::editing_form_artwork_through_tools", "crates/edit/src/tests.rs::page_images_move_turn_replace_and_delete", "crates/ui-egui/tests/it/editing.rs::editing_existing_images_on_the_page", "crates/automation/tests/it/automation.rs::editing_page_images_through_tools", "crates/edit/src/tests.rs::curved_image_clips_have_analytic_bounds_and_holes_do_not_capture_points", "crates/edit/src/tests.rs::cropped_image_resizing_moves_private_clips_and_keeps_shared_ones", "crates/ui-egui/tests/it/editing.rs::cropped_image_corner_resize_keeps_opposite_corner_and_scales_crop", "crates/edit/src/tests.rs::image_selection_bounds_respect_clips_and_restore_graphics_state", "crates/ui-egui/tests/it/editing.rs::cropped_images_do_not_intercept_text_and_stay_inside_each_page", "crates/automation/tests/it/automation.rs::clipped_image_bounds_and_text_edit_save_reopen_through_tools", "crates/edit/src/tests.rs::resizing_an_image_under_a_shared_clip_moves_its_own_clip"] -notes = "existing raster images and grouped Form artwork: select, drag to move, drag a corner to resize keeping proportions; Delete removes one placement. Forms include their nested content as a group; individual internal elements and inline images are not supported. See docs/editing-images.md; added images too Since #1116: raster images and grouped Forms move/resize/turn as placements; selected grips own the gesture and opposite anchor, with no PDF writes during movement. Curved path frames use analytic Bezier extrema and hit testing evaluates actual nonzero/even-odd fill rules, excluding holes; intersections can retain a loose frame. Selection and resize use the visible (clipped) frame; exclusive image clips move with their pixels across nested states, intervening operators and content streams, also inside a clip the picture shares with other content (its own clip scales, the shared one stays); shared clips stay fixed. Inline images and Form internals remain unsupported; see docs/editing-images.md" +evidence = ["crates/edit/src/tests.rs::private_image_crop_with_intervening_state_resizes_across_streams", "crates/automation/tests/it/automation.rs::private_crops_with_nested_state_resize_save_reopen_through_tools", "crates/edit/src/tests.rs::form_artwork_edits_only_the_selected_placement", "crates/ui-egui/tests/it/editing.rs::editing_existing_form_artwork_on_the_page", "crates/automation/tests/it/automation.rs::editing_form_artwork_through_tools", "crates/edit/src/tests.rs::page_images_move_turn_replace_and_delete", "crates/ui-egui/tests/it/editing.rs::editing_existing_images_on_the_page", "crates/automation/tests/it/automation.rs::editing_page_images_through_tools", "crates/edit/src/tests.rs::curved_image_clips_have_analytic_bounds_and_holes_do_not_capture_points", "crates/edit/src/tests.rs::cropped_image_resizing_moves_private_clips_and_keeps_shared_ones", "crates/ui-egui/tests/it/editing.rs::cropped_image_corner_resize_keeps_opposite_corner_and_scales_crop", "crates/edit/src/tests.rs::image_selection_bounds_respect_clips_and_restore_graphics_state", "crates/ui-egui/tests/it/editing.rs::cropped_images_do_not_intercept_text_and_stay_inside_each_page", "crates/automation/tests/it/automation.rs::clipped_image_bounds_and_text_edit_save_reopen_through_tools", "crates/edit/src/tests.rs::resizing_an_image_under_a_shared_clip_moves_its_own_clip", "crates/engine/src/tests.rs::pictures_are_picked_where_they_show", "crates/engine/src/tests.rs::large_pictures_are_picked_where_they_show", "crates/automation/tests/it/automation.rs::image_hit_sees_through_transparent_parts_of_pictures", "crates/ui-egui/tests/it/editing.rs::a_click_through_a_pictures_transparent_margin_selects_the_picture_below"] +notes = "existing raster images and grouped Form artwork: select, drag to move, drag a corner to resize keeping proportions; Delete removes one placement. Forms include their nested content as a group; individual internal elements and inline images are not supported. See docs/editing-images.md; added images too Since #1116: raster images and grouped Forms move/resize/turn as placements; selected grips own the gesture and opposite anchor, with no PDF writes during movement. Curved path frames use analytic Bezier extrema and hit testing evaluates actual nonzero/even-odd fill rules, excluding holes; intersections can retain a loose frame. Selection and resize use the visible (clipped) frame; exclusive image clips move with their pixels across nested states, intervening operators and content streams, also inside a clip the picture shares with other content (its own clip scales, the shared one stays); shared clips stay fixed. Pictures with transparency (soft mask, /Mask, stencil) are picked only where they show, on an opacity grid of at most 256 cells a side; JPEG 2000/JBIG2/CCITT pictures and Form artwork keep their whole box. Inline images and Form internals remain unsupported; see docs/editing-images.md" [[feature]] id = "edit.image-extract" From 1bdee95bac21891c9692f4efe226ec36591a8883 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Mon, 19 Oct 2026 01:39:44 +0800 Subject: [PATCH 003/114] M2: a picture that shows nowhere keeps its whole box for picking Review follow-up on #3069: an all-transparent grid made a faint watermark or a transparent placeholder impossible to pick. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/image_alpha.rs | 9 ++++++--- crates/engine/src/tests.rs | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/image_alpha.rs b/crates/engine/src/image_alpha.rs index 9e6b50d181..9294c30f0c 100644 --- a/crates/engine/src/image_alpha.rs +++ b/crates/engine/src/image_alpha.rs @@ -6,7 +6,8 @@ //! `/ImageMask`) gets an opacity grid of at most [`MAX_GRID`] cells a side, built once from its //! pixels and kept until the document changes. A cell counts as opaque if any pixel //! in it is: thin strokes and the edges of a shape stay easy to pick. Pictures without -//! transparency, Form artwork, and pictures that can't be decoded keep their whole box. +//! transparency, Form artwork, pictures that show nowhere and pictures that can't be decoded +//! keep their whole box. use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -33,7 +34,7 @@ pub(crate) struct Opacity { } /// Opacity grids by picture object, for the document generation they were built at; `None` for -/// a picture that is opaque everywhere or couldn't be read (its whole box counts). The +/// a picture that is opaque everywhere, shows nowhere or couldn't be read (its whole box counts). The /// generation, not the picture object alone, says when to rebuild: an edit may change the /// picture's soft mask without touching the picture. type Grids = (u64, HashMap>>); @@ -133,7 +134,9 @@ fn build(cos: &pdfcraft_cos::Document, object: ObjRef) -> Option { } } } - if cells.iter().all(|c| *c) { + // A picture that shows everywhere, or nowhere (a faint watermark, a transparent + // placeholder), keeps its whole box: one that showed nowhere couldn't be picked at all. + if cells.iter().all(|c| *c) || !cells.iter().any(|c| *c) { return None; } Some(Opacity { width: gw, height: gh, cells }) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 675bb09404..7661e4cfab 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9371,6 +9371,22 @@ fn images_pdf(xobjects: &str, content: &[u8], objects: &[(String, Vec)]) -> out } +/// #3069 review: a picture that shows nowhere (a soft mask below the opacity threshold +/// everywhere: a faint watermark, a transparent placeholder) keeps its whole box, so it can still +/// be picked to move or delete. +#[test] +fn a_picture_that_shows_nowhere_is_picked_by_its_whole_box() { + let objects = vec![ + ("/Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceRGB /BitsPerComponent 8 /SMask 6 0 R".to_string(), vec![0x80; 48]), + ("/Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceGray /BitsPerComponent 8".to_string(), vec![8; 16]), + ]; + let mut s = Session::new(); + let id = s.open("faint.pdf", None, Arc::new(images_pdf("/Faint 5 0 R", b"q 100 0 0 100 20 20 cm /Faint Do Q", &objects)), None).unwrap(); + let d = s.get(id).unwrap(); + assert_eq!(d.page_image_at(0, [70.0, 70.0]), Some(0)); + assert!(d.image_shows_at(&d.page_images(0)[0], [30.0, 110.0])); +} + /// Pictures are picked where they show. Overlapping pictures with transparent margins (a PNG /// signature over a table, cut-out photos side by side) give a click through the margin to the /// picture below; stencil images and colour-keyed pictures likewise. Pictures that can't be From 89e371125371bd1a4fcc8c7975fc271d9e85a22b Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sat, 31 Oct 2026 08:08:09 +0800 Subject: [PATCH 004/114] M7: format the picture hit test after the rebase onto main Rebasing moved the picking change onto main's page pointer router, where the picture hit test is `body_hit`. This wraps its comment and formats it; no behaviour changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pq7HyCfwzyRXj4VfQAVVdv --- .../ui-egui/src/tools/edit_text_ui/image.rs | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/tools/edit_text_ui/image.rs b/crates/ui-egui/src/tools/edit_text_ui/image.rs index 04031d719b..bde79f94de 100644 --- a/crates/ui-egui/src/tools/edit_text_ui/image.rs +++ b/crates/ui-egui/src/tools/edit_text_ui/image.rs @@ -257,18 +257,27 @@ pub(crate) fn handle_hit( } /// The picture under `p` (its shape and where it shows, not only its box): a click selects it, a -/// drag moves the -/// selected one. On the text layer, asked before the paragraphs: editable text on top of a -/// picture takes the press. -pub(crate) fn body_hit(xf: &PageXform, page: usize, info: &DocInfo, doc: &pdfcraft_engine::Document, images: &[pdfcraft_engine::PageImage], view: &DocView, p: Pos2) -> Option { +/// drag moves the selected one. On the text layer, asked before the paragraphs: editable text on +/// top of a picture takes the press. +pub(crate) fn body_hit( + xf: &PageXform, + page: usize, + info: &DocInfo, + doc: &pdfcraft_engine::Document, + images: &[pdfcraft_engine::PageImage], + view: &DocView, + p: Pos2, +) -> Option { if !xf.rect.contains(p) { return None; } let (x, y) = xf.screen_to_view(p); let user = info.pages.get(page)?.view_to_user(x, y).map(f64::from); - let index = images - .iter() - .rposition(|im| im.visible_rect.is_some_and(|r| xf.user_rect(info, page, r.map(|v| v as f32)).contains(p)) && im.contains(user) && doc.image_shows_at(im, user))?; + let index = images.iter().rposition(|im| { + im.visible_rect.is_some_and(|r| xf.user_rect(info, page, r.map(|v| v as f32)).contains(p)) + && im.contains(user) + && doc.image_shows_at(im, user) + })?; let selected = view.image_selection.as_ref().is_some_and(|s| s.page == page && s.index == index); let icon = if selected { egui::CursorIcon::Move } else { egui::CursorIcon::PointingHand }; Some(Hit::new(Owner::Picture { index, part: PicturePart::Body }, Layer::Text, icon)) From b424c52fb639104388d6b3394d13d2289055ec45 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sat, 31 Oct 2026 08:08:10 +0800 Subject: [PATCH 005/114] M2: bound what the opacity grid decodes, and mark every cell a pixel reaches Review on #3069: - Only the picture's own Width x Height was checked before it was exported for its opacity grid. A soft mask or stencil /Mask is decoded in full before it is scaled to the picture's size, so a small picture with a mask of up to 100 million pixels allocated hundreds of megabytes on the first hover. Each mask stream is now held to the same pixel limit as the picture. - A lossless picture or mask whose stream inflates far past its declared samples was decoded in full (up to 1 GiB) before the declared samples were taken from it. Each is now decoded first within its declared sample bytes, plus a quarter and 64 KiB for padding, through decoded_image_within; past that the picture keeps its whole box. - A showing pixel was stored only in the grid cell its start falls in. When the picture is wider or taller than the grid, a pixel can cross into the next cell, and a point on that part was taken as see-through. Every cell a showing pixel reaches into now shows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pq7HyCfwzyRXj4VfQAVVdv --- crates/engine/src/image_alpha.rs | 109 ++++++++++++++++++++++++++++--- crates/engine/src/tests.rs | 74 +++++++++++++++++++++ 2 files changed, 175 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/image_alpha.rs b/crates/engine/src/image_alpha.rs index 9294c30f0c..3accb79df9 100644 --- a/crates/engine/src/image_alpha.rs +++ b/crates/engine/src/image_alpha.rs @@ -24,6 +24,12 @@ const MAX_CACHED: usize = 256; const MAX_DECODE_PIXELS: u64 = 64_000_000; /// Alpha at or above this (of 255) counts as showing. const OPAQUE: u8 = 16; +/// Colour components assumed for a colour space that can't be read: as many as a DeviceN space +/// may have in practice, so the decoding bound stays generous. +const MAX_COMPONENTS: u64 = 32; +/// Decoded bytes allowed past what a picture's declared size needs (with a quarter more), for +/// padding writers leave after the samples. +const DECODE_SLACK: u64 = 64 << 10; /// Which cells of a picture show, row 0 at the top of the picture. #[derive(Debug)] @@ -89,17 +95,26 @@ impl Document { fn build(cos: &pdfcraft_cos::Document, object: ObjRef) -> Option { let current = cos.get(object); let Object::Stream(s) = &*current else { return None }; - let flag = |key: &[u8]| s.dict.get(key).is_some_and(|v| matches!(&*cos.resolve(v), Object::Bool(true))); - let stencil = flag(b"ImageMask"); + let stencil = flag(cos, s, b"ImageMask"); let soft = s.dict.get(b"SMask").is_some_and(|v| cos.resolve(v).as_name() != Some(b"None")); let in_data = s.dict.int(b"SMaskInData").is_some_and(|v| v != 0); if !(stencil || soft || in_data || s.dict.get(b"Mask").is_some()) { return None; } - let size = |key: &[u8]| u64::try_from(s.dict.int(key).unwrap_or(0)).unwrap_or(0); - if size(b"Width").saturating_mul(size(b"Height")) > MAX_DECODE_PIXELS { + // The picture and the mask images it brings are decoded in full before anything is scaled + // down to the picture's size, so each must be small enough, in pixels and in decoded bytes, + // before any of it is decoded. + let components = if stencil { 1 } else { components(cos, s.dict.get(b"ColorSpace")) }; + if !within_budget(cos, s, components, stencil) { return None; } + for key in [&b"SMask"[..], b"Mask"] { + if let Some(Object::Stream(mask)) = s.dict.get(key).map(|v| cos.resolve(v)).as_deref() + && !within_budget(cos, mask, 1, key == b"Mask" || flag(cos, mask, b"ImageMask")) + { + return None; + } + } let (_, bytes) = pdfcraft_create::image_file(cos, object).ok()?; let format = image::guess_format(&bytes).ok()?; let mut reader = image::ImageReader::with_format(std::io::Cursor::new(bytes.as_slice()), format); @@ -124,12 +139,17 @@ fn build(cos: &pdfcraft_cos::Document, object: ObjRef) -> Option { let (gw, gh) = (w.min(MAX_GRID), h.min(MAX_GRID)); let mut cells = vec![false; usize::try_from(u64::from(gw) * u64::from(gh)).ok()?]; for y in 0..h { - let row = u64::from(y) * u64::from(gh) / u64::from(h); + let rows = cells_covered(y, h, gh); for x in 0..w { if shows(x, y) { - let col = u64::from(x) * u64::from(gw) / u64::from(w); - if let Some(cell) = usize::try_from(row * u64::from(gw) + col).ok().and_then(|i| cells.get_mut(i)) { - *cell = true; + // Every cell the pixel reaches into shows: a point anywhere on a showing pixel + // picks the picture, also where the pixel crosses into the next cell. + for row in rows.clone() { + for col in cells_covered(x, w, gw) { + if let Some(cell) = usize::try_from(row * u64::from(gw) + col).ok().and_then(|i| cells.get_mut(i)) { + *cell = true; + } + } } } } @@ -142,6 +162,79 @@ fn build(cos: &pdfcraft_cos::Document, object: ObjRef) -> Option { Some(Opacity { width: gw, height: gh, cells }) } +/// The grid cells, along an axis of `pixels` pixels and `cells` cells, that pixel `i` reaches +/// into: from the cell its start is in to the cell its end is in. `cells` is at most `pixels`, so +/// a pixel reaches into at most two. +fn cells_covered(i: u32, pixels: u32, cells: u32) -> std::ops::Range { + let (i, pixels, cells) = (u64::from(i), u64::from(pixels).max(1), u64::from(cells)); + let start = i * cells / pixels; + let end = ((i + 1) * cells).div_ceil(pixels).min(cells); + start..end.max(start) +} + +/// Whether the boolean `key` of image stream `s` is `true`. +fn flag(cos: &pdfcraft_cos::Document, s: &pdfcraft_cos::Stream, key: &[u8]) -> bool { + s.dict.get(key).is_some_and(|v| matches!(&*cos.resolve(v), Object::Bool(true))) +} + +/// Whether image stream `s`, of `components` colour components (one bit each for a `stencil`), +/// is small enough to decode for its opacity grid: at most [`MAX_DECODE_PIXELS`] pixels and, when +/// its samples are decoded through its filters, no more decoded bytes than its declared size +/// needs, with room for padding a writer left after the samples. Without that bound a 1 × 1 +/// picture whose stream inflates to a gigabyte would be decoded in full on the first hover. JPEG, +/// JPEG 2000 and JBIG2 data go to their own decoders instead. +fn within_budget(cos: &pdfcraft_cos::Document, s: &pdfcraft_cos::Stream, components: u64, stencil: bool) -> bool { + let size = |key: &[u8]| u64::try_from(s.dict.int(key).unwrap_or(0)).unwrap_or(0); + let (w, h) = (size(b"Width"), size(b"Height")); + if w.saturating_mul(h) > MAX_DECODE_PIXELS { + return false; + } + let codec = match s.dict.get(b"Filter").map(|f| cos.resolve(f)).as_deref() { + Some(Object::Name(n)) => Some(n.clone()), + Some(Object::Array(a)) => a.last().and_then(Object::as_name).map(<[u8]>::to_vec), + _ => None, + }; + if matches!(codec.as_deref(), Some(b"DCTDecode" | b"DCT" | b"JPXDecode" | b"JBIG2Decode")) { + return true; + } + let bpc = if stencil { 1 } else { u64::try_from(s.dict.int(b"BitsPerComponent").unwrap_or(8)).unwrap_or(8).clamp(1, 16) }; + let row = w.checked_mul(components).and_then(|n| n.checked_mul(bpc)).map(|bits| bits.div_ceil(8)); + let budget = row.and_then(|r| r.checked_mul(h)).and_then(|n| n.checked_add(n / 4)).and_then(|n| n.checked_add(DECODE_SLACK)); + let Some(budget) = budget.and_then(|n| usize::try_from(n).ok()) else { return false }; + cos.decoded_image_within(s, budget).is_ok() +} + +/// The colour components of an image in colour space `space` (ISO 32000-2 §8.6): one for an +/// indexed or separation space, the `/N` of an ICC-based one, as many as a DeviceN space names. +/// A space that can't be read counts as [`MAX_COMPONENTS`], which keeps the decoding bound +/// generous rather than refusing the picture. +fn components(cos: &pdfcraft_cos::Document, space: Option<&Object>) -> u64 { + let Some(space) = space.map(|s| cos.resolve(s)) else { return MAX_COMPONENTS }; + let array = space.as_array(); + let family = match (&*space, array.and_then(|a| a.first()).and_then(Object::as_name)) { + (Object::Name(n), _) => n.as_slice(), + (_, Some(n)) => n, + _ => return MAX_COMPONENTS, + }; + let operand = || array.and_then(|a| a.get(1)).map(|o| cos.resolve(o)); + match family { + b"DeviceGray" | b"G" | b"CalGray" | b"Indexed" | b"I" | b"Separation" => 1, + b"DeviceRGB" | b"RGB" | b"CalRGB" | b"Lab" => 3, + b"DeviceCMYK" | b"CMYK" => 4, + b"ICCBased" => match operand().as_deref() { + Some(Object::Stream(icc)) => { + icc.dict.int(b"N").and_then(|n| u64::try_from(n).ok()).filter(|n| (1..=MAX_COMPONENTS).contains(n)).unwrap_or(MAX_COMPONENTS) + } + _ => MAX_COMPONENTS, + }, + b"DeviceN" => match operand().as_deref() { + Some(Object::Array(names)) => u64::try_from(names.len()).unwrap_or(MAX_COMPONENTS).clamp(1, MAX_COMPONENTS), + _ => MAX_COMPONENTS, + }, + _ => MAX_COMPONENTS, + } +} + /// `point` in the placement's unit square: the inverse of `matrix` applied to it. fn unit_point(m: [f64; 6], point: [f64; 2]) -> Option<(f64, f64)> { let det = m[0] * m[3] - m[1] * m[2]; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7661e4cfab..f3b49ed03d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9491,3 +9491,77 @@ fn large_pictures_are_picked_where_they_show() { assert_eq!(d.page_image_at(0, [49.0, 80.0]), Some(0)); assert_eq!(d.page_image_at(0, [56.0, 80.0]), None); } + +/// `data` compressed with Flate, as a stream's bytes. +fn flated(data: &[u8]) -> Vec { + pdfcraft_cos::Stream::flate(pdfcraft_cos::Dict::default(), data).raw.to_vec() +} + +/// #3069 review: a showing pixel that crosses from one grid cell into the next marks both. In a +/// 257-pixel-wide picture on a 256-cell grid, pixel 1 starts in cell 0 and ends in cell 1; a point +/// on its right part, in cell 1, picks the picture. +#[test] +fn a_showing_pixel_marks_every_grid_cell_it_reaches_into() { + let mut mask = vec![0u8; 257]; + mask[1] = 255; + let objects = vec![ + ("/Type /XObject /Subtype /Image /Width 257 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /SMask 6 0 R".to_string(), vec![0x80; 257]), + ("/Type /XObject /Subtype /Image /Width 257 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8".to_string(), mask), + ]; + let mut s = Session::new(); + let id = s.open("wide.pdf", None, Arc::new(images_pdf("/Wide 5 0 R", b"q 257 0 0 10 0 0 cm /Wide Do Q", &objects)), None).unwrap(); + let d = s.get(id).unwrap(); + let image = &d.page_images(0)[0]; + for x in [1.2, 1.5, 1.8] { + assert!(d.image_shows_at(image, [x, 5.0]), "pixel 1 shows at x = {x}"); + } + assert!(!d.image_shows_at(image, [5.5, 5.0]), "pixel 5 is transparent"); +} + +/// #3069 review: a soft mask larger than the opacity grid's decoding limit keeps the picture's +/// whole box, however small the picture: the mask would be decoded in full before being scaled +/// to the picture's size. +#[test] +fn a_picture_whose_soft_mask_is_too_large_keeps_its_whole_box() { + // 8000 × 8001 pixels, just past 64 million; its left quarter shows, so once scaled to the + // picture's two pixels the left one shows and the right one doesn't. + let (w, h) = (8000usize, 8001usize); + let row: Vec = (0..w).map(|x| if x < w / 4 { 255 } else { 0 }).collect(); + let mask = flated(&row.repeat(h)); + let objects = vec![ + ("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /SMask 6 0 R".to_string(), vec![0x80; 2]), + (format!("/Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /FlateDecode"), mask), + ]; + let mut s = Session::new(); + let id = s.open("mask.pdf", None, Arc::new(images_pdf("/Small 5 0 R", b"q 100 0 0 100 0 0 cm /Small Do Q", &objects)), None).unwrap(); + let d = s.get(id).unwrap(); + assert!(d.image_shows_at(&d.page_images(0)[0], [75.0, 50.0]), "the whole box, without decoding the mask"); +} + +/// #3069 review: a picture or soft mask whose stream inflates far past what its declared size +/// needs keeps the picture's whole box, rather than being decoded in full on the first hover. +#[test] +fn picture_streams_that_inflate_past_their_size_keep_the_whole_box() { + let flate = "/Filter /FlateDecode"; + let image = |extra: &str, data: Vec| { + (format!("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 {extra}"), data) + }; + let huge = || flated(&[255u8, 0].repeat(4 << 20)); + let objects = vec![ + image(&format!("{flate} /SMask 7 0 R"), huge()), // 5: its samples inflate to 8 MiB + image("/SMask 9 0 R", vec![0x80; 2]), // 6: its mask inflates to 8 MiB + image("", vec![255, 0]), // 7: the left half shows + image(&format!("{flate} /SMask 7 0 R"), flated(&[9, 9])), // 8: as declared + image(flate, huge()), // 9: 6's mask + ]; + let content = b"q 100 0 0 100 0 0 cm /A Do Q q 100 0 0 100 0 100 cm /B Do Q q 100 0 0 100 0 200 cm /C Do Q"; + let mut s = Session::new(); + let id = s.open("inflate.pdf", None, Arc::new(images_pdf("/A 5 0 R /B 6 0 R /C 8 0 R", content, &objects)), None).unwrap(); + let d = s.get(id).unwrap(); + let images = d.page_images(0); + assert_eq!(images.len(), 3); + assert!(d.image_shows_at(&images[0], [75.0, 50.0]), "the picture's samples are too large: its whole box"); + assert!(d.image_shows_at(&images[1], [75.0, 150.0]), "its soft mask's samples are too large: its whole box"); + assert!(!d.image_shows_at(&images[2], [75.0, 250.0]), "Flate data as large as declared is read"); + assert!(d.image_shows_at(&images[2], [25.0, 250.0])); +} From 8ca0b31dc4dda8e21ee07175693c980a992b4cf8 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:15:16 +0800 Subject: [PATCH 006/114] M6: a value the validate action rejects is dropped and the field keeps its value A text field whose validate action (ISO 32000-2 Table 199 /V) rejects the typed value, by range or by a script setting event.rc false, showed the message but reopened its editor with the rejected text and pulled focus back to it, so the user could not go on filling the form. Other readers (5 of 5) show the message, put the field back to its previous value and let focus move on. - forms: FormError::Rejected for a validate refusal (range or script); a keystroke/format refusal stays Invalid/Format. - engine: EditError::is_rejected_value(). - ui-egui: apply_edit wraps try_apply_edit; a rejected value's draft is dropped instead of reopened, so the editor Tab or a click opened on the next field stays open. Format refusals still reopen (#166). The message is the same notice; Save/Print/Export still stop after it. The engine already applied edits to a copy, so a rejection leaves the document and undo history untouched; the tests pin that too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0175FWj4xFhMhSH3UpMU8DSC --- crates/automation/tests/it/automation.rs | 3 + crates/engine/src/error.rs | 9 ++ crates/forms/src/lib.rs | 6 ++ crates/forms/src/scripting.rs | 7 +- crates/forms/src/tests.rs | 54 +++++++++++- crates/forms/src/values.rs | 2 +- crates/ui-egui/src/editing.rs | 98 ++++++++++++--------- crates/ui-egui/src/tools/forms_ui.rs | 5 +- crates/ui-egui/tests/it/forms.rs | 106 ++++++++++++++++++++--- parity/acrobat-features.toml | 8 +- 10 files changed, 232 insertions(+), 66 deletions(-) diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 6a5765b911..ef0ecf44ba 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -7128,6 +7128,9 @@ fn javascript_through_tools() { assert!(page_text(&mut a, doc)[0].contains("EUR 2.500,00"), "{:?}", page_text(&mut a, doc)); let err = a.call("form_fill", &json!({ "doc": doc, "values": { "Qty": "0" } })).unwrap_err(); assert!(err.to_string().contains("Order at least one"), "{err}"); + let fields = ok(&mut a, "form_fields", json!({ "doc": doc })); + let qty = fields["fields"].as_array().unwrap().iter().find(|x| x["name"] == "Qty").unwrap(); + assert_eq!(qty["value"], "2", "the rejected value is reported, not stored"); let r = ok( &mut a, diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index 5ee915fcdf..75b239cbd2 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -78,3 +78,12 @@ impl From for EditError { EditError::Sign(e.to_string()) } } + +impl EditError { + /// A field's validate action refused the value it was given (ISO 32000-2 Table 199 `/V`). + /// The document is unchanged and the field keeps its value; an interface drops the typing + /// rather than holding the user in the field. + pub fn is_rejected_value(&self) -> bool { + matches!(self, EditError::Form(pdfcraft_forms::FormError::Rejected(_))) + } +} diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rs index 775306d865..3b3a98b71c 100644 --- a/crates/forms/src/lib.rs +++ b/crates/forms/src/lib.rs @@ -73,6 +73,12 @@ pub enum FormError { /// checked before any of the field's scripts run. #[error("{0}")] Format(String), + /// The field's validate action (ISO 32000-2 Table 199 `/V`: it "may check the new value + /// for validity") refused the value: a range it is outside, or a script that set `event.rc` + /// to false. The message is the script's alert, or the range's. Nothing was changed, and + /// the field keeps the value it had. + #[error("{0}")] + Rejected(String), #[error("{0}")] Cos(#[from] pdfcraft_cos::CosError), } diff --git a/crates/forms/src/scripting.rs b/crates/forms/src/scripting.rs index 7dd7bfde6c..cdfd5b3439 100644 --- a/crates/forms/src/scripting.rs +++ b/crates/forms/src/scripting.rs @@ -84,7 +84,12 @@ pub(crate) fn accept(doc: &mut Document, f: &Field, value: &str, scripts: &mut d let r = scripts.run(event, js, f, &v, &all); apply_changes(doc, &r.changes, &f.name)?; if !r.rc { - return Err(FormError::Invalid(r.message.unwrap_or_else(|| format!("{default} [ {} ]", f.name)))); + let message = r.message.unwrap_or_else(|| format!("{default} [ {} ]", f.name)); + // A keystroke refusal is about the typing; a validate refusal is about the value. + return Err(match event { + FieldEvent::Validate => FormError::Rejected(message), + _ => FormError::Invalid(message), + }); } v = r.value; } diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rs index cca4cb4881..004d8f6ef3 100644 --- a/crates/forms/src/tests.rs +++ b/crates/forms/src/tests.rs @@ -1497,7 +1497,7 @@ fn formats_validation_and_calculations_run_like_acrobat() { ); assert_eq!( set_value(&mut doc, "Qty", &FieldValue::Text("120".into())), - Err(FormError::Invalid("Invalid value: must be greater than or equal to 1 and less than or equal to 99.".into())) + Err(FormError::Rejected("Invalid value: must be greater than or equal to 1 and less than or equal to 99.".into())) ); assert_eq!(field(&fields(&doc), "Qty").value, ["2"]); // Dates: stored as typed, shown in the format; impossible dates are refused. @@ -5485,3 +5485,55 @@ fn locked_button_export_edits_leave_the_document_unchanged() { assert_eq!(write_incremental(&doc, &SaveOptions::default()).unwrap(), before); } } + +/// A validate action (ISO 32000-2 Table 199 `/V`) that refuses a value is a rejection the +/// caller can tell apart: the field keeps its value and the interface drops the typing. A +/// keystroke refusal is not one: it is about the typing, which the user may want to fix. +#[test] +fn a_validate_refusal_is_a_rejection_and_a_keystroke_refusal_is_not() { + use crate::af::Validate; + struct Checks; + impl Scripts for Checks { + fn run(&mut self, event: FieldEvent, script: &str, _: &Field, value: &str, _: &[Field]) -> ScriptResult { + let (rc, message) = match (event, script) { + (FieldEvent::Validate, "short") => (value.chars().count() <= 3, Some("At most 3 characters".to_string())), + (FieldEvent::Validate, "never") => (false, None), + (FieldEvent::Keystroke, "digits") => (value.chars().all(|c| c.is_ascii_digit()), Some("Digits only".to_string())), + _ => (true, None), + }; + ScriptResult { rc, value: value.to_string(), changes: Vec::new(), message: if rc { None } else { message } } + } + } + let mut doc = one_page(); + for (i, name) in ["G_range", "H_short", "code", "never"].into_iter().enumerate() { + let y = 10.0 + 30.0 * i as f64; + add_field(&mut doc, 0, [10.0, y, 100.0, y + 20.0], &NewField::Text { multiline: false }, Some(name)).unwrap(); + } + set_props(&mut doc, "G_range", &FieldProps { validate: Some(Validate::Range { min: Some(1.0), max: Some(100.0) }), ..FieldProps::default() }) + .unwrap(); + set_field_script(&mut doc, "H_short", "validate", Some("short")).unwrap(); + set_field_script(&mut doc, "code", "keystroke", Some("digits")).unwrap(); + set_field_script(&mut doc, "never", "validate", Some("never")).unwrap(); + let set = |doc: &mut Document, name: &str, v: &str| set_value_with(doc, name, &FieldValue::Text(v.into()), &mut Checks); + + assert_eq!( + set(&mut doc, "G_range", "150"), + Err(FormError::Rejected("Invalid value: must be greater than or equal to 1 and less than or equal to 100.".into())) + ); + assert!(field(&fields(&doc), "G_range").value.is_empty(), "the field keeps its (blank) value"); + assert_eq!(set(&mut doc, "G_range", "50"), Ok(())); + assert_eq!(field(&fields(&doc), "G_range").value, ["50"], "a value in range commits"); + assert_eq!( + set(&mut doc, "G_range", "0"), + Err(FormError::Rejected("Invalid value: must be greater than or equal to 1 and less than or equal to 100.".into())) + ); + assert_eq!(field(&fields(&doc), "G_range").value, ["50"], "and stays when the next one is refused"); + + assert_eq!(set(&mut doc, "H_short", "abcd"), Err(FormError::Rejected("At most 3 characters".into())), "the script's alert is the message"); + assert!(field(&fields(&doc), "H_short").value.is_empty()); + assert_eq!(set(&mut doc, "H_short", "abc"), Ok(())); + assert_eq!(set(&mut doc, "never", "x"), Err(FormError::Rejected("The value entered is not valid for the field [ never ]".into())), "no alert"); + + assert_eq!(set(&mut doc, "code", "x1"), Err(FormError::Invalid("Digits only".into())), "a keystroke refusal is not a rejected value"); + assert_eq!(set(&mut doc, "code", "12"), Ok(())); +} diff --git a/crates/forms/src/values.rs b/crates/forms/src/values.rs index e8615567b6..e167ffb433 100644 --- a/crates/forms/src/values.rs +++ b/crates/forms/src/values.rs @@ -208,7 +208,7 @@ pub(crate) fn write_value(doc: &mut Document, f: &Field, value: &FieldValue, scr } // Keystroke (on commit) and Validate, as Acrobat runs them before accepting a value. let t = &af::keystroke(&f.actions.format, &f.name, t).map_err(FormError::Format)?; - af::validate(&f.actions.validate, t).map_err(FormError::Invalid)?; + af::validate(&f.actions.validate, t).map_err(FormError::Rejected)?; let t = &scripting::accept(doc, f, t, scripts)?; let shadow = t.is_empty() && crate::author::ancestor_sets(doc, f.obj, b"V"); doc.update_dict(f.obj, |d| { diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs index 8def569f58..94e0c37921 100644 --- a/crates/ui-egui/src/editing.rs +++ b/crates/ui-egui/src/editing.rs @@ -110,7 +110,12 @@ fn form_edit_pages( impl PdfCraftApp { /// Apply an edit to the active document. Returns `true` on success; failures are shown. pub fn apply_edit(&mut self, edit: Edit) -> bool { - let Some((i, id)) = self.active_ids() else { return false }; + self.try_apply_edit(edit).is_ok() + } + + /// [`Self::apply_edit`], returning why it failed (already shown to the user). + fn try_apply_edit(&mut self, edit: Edit) -> Result<(), pdfcraft_engine::EditError> { + let Some((i, id)) = self.active_ids() else { return Err(pdfcraft_engine::EditError::NoDocument) }; let label = edit.label(); let (form_before, page_count_before, had_xfa) = if let Some(d) = self.session.get(id) { (Some(std::sync::Arc::clone(&d.form)), d.info.pages.len(), d.xfa.is_some()) @@ -125,7 +130,7 @@ impl PdfCraftApp { }; match self.session.apply(id, edit.clone()) { Ok(()) => { - let Some(doc) = self.session.get(id) else { return true }; + let Some(doc) = self.session.get(id) else { return Ok(()) }; let info = &doc.info; let view = &mut self.views[i]; view.applied_editor = None; @@ -181,7 +186,7 @@ impl PdfCraftApp { } let out = self.session.take_js_output(id); self.handle_js(id, out); - true + Ok(()) } Err(e) => { if let Some(view) = self.views.get_mut(i) { @@ -199,7 +204,7 @@ impl PdfCraftApp { } let message = if matches!(edit, Edit::MoveObjects { .. }) { crate::object_ui::move_error(&e) } else { e.to_string() }; self.notify_fmt("{label} failed: {e}", &[("label", &crate::i18n::edit_label(&label)), ("e", &message)]); - false + Err(e) } } } @@ -390,7 +395,7 @@ impl PdfCraftApp { } /// Apply any edit a view queued this frame (organize toolbar, keys). - /// Returns false when a field refused the typing queued for it (its editor is open again). + /// Returns false when a field refused the typing queued for it (see [`Self::apply_queued_edit`]). pub(crate) fn process_pending_edits(&mut self) -> bool { let Some(i) = self.active else { return true }; let applied = self.apply_queued_edit(i); @@ -587,9 +592,10 @@ impl PdfCraftApp { /// anything reads the document: Save, Print, Export, Optimize, Sign, Extract, Split, Copy /// pages and button scripts. /// - /// Returns false when the field rejects the value (a validation script or format; the user - /// is told why). The editor stays open with the text, and the caller must stop: nothing is - /// saved, printed or exported without it. + /// Returns false when the field refuses the value (the user is told why), and the caller + /// must stop: nothing is saved, printed or exported behind the refusal. A value the field's + /// format refuses stays in the open editor, to be fixed; one its validate action rejects is + /// dropped and the field keeps its value (see [`Self::apply_queued_edit`]). pub(crate) fn commit_form_typing(&mut self) -> bool { let Some((i, id)) = self.active_ids() else { return true }; if !self.apply_queued_edit(i) { @@ -602,8 +608,11 @@ impl PdfCraftApp { if let Some(view) = self.views.get_mut(i) { view.forms.focus = None; } - if self.apply_edit(edit) { - return true; + match self.try_apply_edit(edit) { + Ok(()) => return true, + // The editor stays closed: the field shows the value it kept. + Err(e) if e.is_rejected_value() => return false, + Err(_) => {} } if let Some(view) = self.views.get_mut(i) { let mut draft = draft; @@ -614,8 +623,11 @@ impl PdfCraftApp { } /// Apply the edit queued on tab `i` (the active one). Returns false only when it was a - /// field's typing and the field refused it (#166): the editor reopens with the text, and the - /// user has been told why, so the typing isn't lost and the caller can stop. + /// field's typing and the field refused it, after telling the user why, so the caller can + /// stop. Typing the field's format refuses reopens in its editor (#166), so it isn't lost. + /// A value the field's validate action rejects (ISO 32000-2 Table 199 `/V`) is dropped + /// instead, as other readers do: the field keeps the value it had, and the editor Tab or a + /// click opened on the next field stays open, so the user can go on filling the form. fn apply_queued_edit(&mut self, i: usize) -> bool { let Some(edit) = self.views.get_mut(i).and_then(|v| v.pending_edit.take()) else { return true }; let signature_page = self.views.get_mut(i).and_then(|v| v.fill_signature_page.take()); @@ -624,43 +636,43 @@ impl PdfCraftApp { (Edit::SetFieldValue { name, .. }, Some(draft)) => *name == draft.name, _ => false, }; - if self.apply_edit(edit) { - // Tab can wrap to the same field (including another widget of that field). - // Its new editor was opened before this edit ran, so it still holds the old - // value. Refresh from the accepted form before Save can commit that stale draft. - if typed - && let Some(view) = self.views.get_mut(i) - && let Some(focus) = view.forms.focus.as_mut() - && focus.request_focus - && committed.as_ref().is_some_and(|draft| draft.name == focus.name) - && let Some(field) = self.session.get(view.id).and_then(|doc| doc.form.iter().find(|field| field.name == focus.name)) - { - focus.text = crate::forms_ui::draft_text(field); - focus.picked = field.value.clone(); + if let Err(e) = self.try_apply_edit(edit) { + if !typed { + return true; } - if let Some(page) = signature_page - && let Some(view) = self.views.get_mut(i) + if !e.is_rejected_value() + && let (Some(mut draft), Some(view)) = (committed, self.views.get_mut(i)) { - // Signature imports are a labeled batch; select their appended stamp just - // as AddAnnotation selects a typed or drawn signature. - let newest = self - .session - .get(view.id) - .and_then(|d| d.info.annotations.iter().filter(|a| a.page == page && !a.is_reply()).map(|a| a.index).max()); - view.comments.selected = newest.map(|index| (page, index)); - view.comments.reveal = true; - self.quick_tool = crate::QuickTool::Select; + draft.request_focus = true; + view.forms.focus = Some(draft); } - return true; + return false; } - if !typed { - return true; + // Tab can wrap to the same field (including another widget of that field). + // Its new editor was opened before this edit ran, so it still holds the old + // value. Refresh from the accepted form before Save can commit that stale draft. + if typed + && let Some(view) = self.views.get_mut(i) + && let Some(focus) = view.forms.focus.as_mut() + && focus.request_focus + && committed.as_ref().is_some_and(|draft| draft.name == focus.name) + && let Some(field) = self.session.get(view.id).and_then(|doc| doc.form.iter().find(|field| field.name == focus.name)) + { + focus.text = crate::forms_ui::draft_text(field); + focus.picked = field.value.clone(); } - if let (Some(mut draft), Some(view)) = (committed, self.views.get_mut(i)) { - draft.request_focus = true; - view.forms.focus = Some(draft); + if let Some(page) = signature_page + && let Some(view) = self.views.get_mut(i) + { + // Signature imports are a labeled batch; select their appended stamp just + // as AddAnnotation selects a typed or drawn signature. + let newest = + self.session.get(view.id).and_then(|d| d.info.annotations.iter().filter(|a| a.page == page && !a.is_reply()).map(|a| a.index).max()); + view.comments.selected = newest.map(|index| (page, index)); + view.comments.reveal = true; + self.quick_tool = crate::QuickTool::Select; } - false + true } /// [`Self::commit_form_typing`] for document `id`, which may not be the active tab (a save diff --git a/crates/ui-egui/src/tools/forms_ui.rs b/crates/ui-egui/src/tools/forms_ui.rs index 7232b1169b..f796b48268 100644 --- a/crates/ui-egui/src/tools/forms_ui.rs +++ b/crates/ui-egui/src/tools/forms_ui.rs @@ -52,8 +52,9 @@ pub struct Focus { #[derive(Clone, Debug, Default)] pub struct FormView { pub focus: Option, - /// The draft whose edit is queued (`DocView::pending_edit`): if the field refuses the value, - /// the editor reopens with it rather than losing the typing. + /// The draft whose edit is queued (`DocView::pending_edit`): if the field's format refuses + /// the value, the editor reopens with it rather than losing the typing. A value the field's + /// validate action rejects is dropped, and the field keeps its value. pub(crate) committed: Option, /// A press on a text field committed the field before it (#2213). Until the button is /// released, that field losing focus to the same gesture must not commit it again: a diff --git a/crates/ui-egui/tests/it/forms.rs b/crates/ui-egui/tests/it/forms.rs index fa828a8f9f..0b294f349b 100644 --- a/crates/ui-egui/tests/it/forms.rs +++ b/crates/ui-egui/tests/it/forms.rs @@ -846,8 +846,10 @@ fn pressing_another_text_field_validates_the_refused_value_once() { h.drop_at(p); h.run_steps(3); assert_eq!(h.state().toast, None, "the release did not validate it again"); - let focus = h.state().views[0].forms.focus.clone().expect("the refused field stays open"); - assert_eq!((focus.name.as_str(), focus.text.as_str()), ("qty", "4500")); + // The rejected value is dropped: qty keeps its value and the pressed field keeps the focus. + assert_eq!(value(&h, "qty"), ["4"]); + let focus = h.state().views[0].forms.focus.clone().expect("the pressed field is open"); + assert_eq!((focus.name.as_str(), focus.text.as_str()), ("note", "")); } /// `validated_form` plus a plain text field, `note`, under `qty`. @@ -862,6 +864,79 @@ fn validated_form_with_note() -> Vec { ]) } +/// Three blank text fields in tab order: `G_range` validates with the range function (1 to +/// 100), `H_short` with a script that alerts and sets `event.rc` false past 3 characters, and +/// `note` takes anything. +fn range_and_script_validated_form() -> Vec { + pdf_from_objects(&[ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 5 0 R 6 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 7 0 R >> >> >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>", + "<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R 6 0 R] >>", + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (G_range) /Rect [20 350 280 372] /P 3 0 R /F 4 /AA << /V << /S /JavaScript /JS (AFRange_Validate\\(true, 1, true, 100\\);) >> >> >>", + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (H_short) /Rect [20 300 280 322] /P 3 0 R /F 4 /AA << /V << /S /JavaScript /JS (if \\(event.value.length > 3\\) { app.alert\\(\"At most 3 characters\"\\); event.rc = false; }) >> >> >>", + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (note) /Rect [20 250 280 272] /P 3 0 R /F 4 >>", + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>", + ]) +} + +/// A value a field's validate action rejects (ISO 32000-2 Table 199 `/V`) is dropped, as other +/// readers do: the message shows, the field keeps its value, nothing is added to undo, and Tab +/// goes on to the next field instead of holding the user in the rejected one. +#[test] +fn a_value_the_validate_action_rejects_reverts_and_tab_moves_on() { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| { + let mut app = PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + app.open_bytes("rows.pdf", None, range_and_script_validated_form()).unwrap(); + app.set_option("left", "closed").unwrap(); + app.set_option("zoom", "150").unwrap(); + app + }); + h.run_steps(6); + let toast = |h: &Harness<'static, PdfCraftApp>| h.state().toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + let unchanged = |h: &Harness<'static, PdfCraftApp>| { + let doc = h.state().session.get(h.state().views[0].id).unwrap(); + !doc.dirty && doc.can_undo().is_none() + }; + let type_and_tab = |h: &mut Harness<'static, PdfCraftApp>, text: &str| { + h.event(egui::Event::Text(text.into())); + h.run_steps(2); + h.key_press(egui::Key::Tab); + h.run_steps(3); + }; + + click_field(&mut h, "G_range", 0); + type_and_tab(&mut h, "150"); + assert!(toast(&h).contains("Invalid value"), "the range's message shows: {:?}", toast(&h)); + assert!(value(&h, "G_range").is_empty(), "G keeps its blank value"); + assert_eq!(focused(&h).map(|(n, _)| n).as_deref(), Some("H_short"), "Tab moved on"); + assert_eq!(h.state().views[0].forms.focus.as_ref().map(|f| f.text.as_str()), Some("")); + assert!(unchanged(&h), "a rejected value is no change and no undo step"); + + h.state_mut().toast = None; + type_and_tab(&mut h, "abcd"); + assert!(toast(&h).contains("At most 3 characters"), "the script's alert shows: {:?}", toast(&h)); + assert!(value(&h, "H_short").is_empty()); + assert_eq!(focused(&h).map(|(n, _)| n).as_deref(), Some("note")); + assert!(unchanged(&h)); + + // The next field fills in as usual, and so does a value in range. + type_and_tab(&mut h, "x"); + assert_eq!(value(&h, "note"), ["x"]); + click_field(&mut h, "G_range", 0); + type_and_tab(&mut h, "50"); + assert_eq!(value(&h, "G_range"), ["50"]); + // Undo steps through the two accepted values only. + h.state_mut().undo(); + h.run_steps(2); + assert!(value(&h, "G_range").is_empty()); + assert_eq!(value(&h, "note"), ["x"]); + h.state_mut().undo(); + h.run_steps(2); + assert!(value(&h, "note").is_empty()); + assert!(h.state().session.get(h.state().views[0].id).unwrap().can_undo().is_none(), "and nothing else is left to undo"); +} + fn pdf_from_objects(objs: &[&str]) -> Vec { let mut out = b"%PDF-1.7\n".to_vec(); let mut offsets = Vec::new(); @@ -951,7 +1026,7 @@ fn buttons_over_text_show_the_pointing_hand_not_the_i_beam() { } #[test] -fn a_rejected_value_keeps_the_typing_and_stops_the_save() { +fn a_rejected_value_is_dropped_and_stops_the_save() { let dir = scratch("rejected"); let out = dir.join("saved.pdf"); let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| { @@ -969,13 +1044,15 @@ fn a_rejected_value_keeps_the_typing_and_stops_the_save() { h.state_mut().save_override = Some(out.to_string_lossy().into_owned()); h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S); h.run_steps(4); - assert!(!out.exists(), "nothing is saved without the typed value"); + assert!(!out.exists(), "the save stops at the refusal, so the user sees it first"); + assert!(h.state().toast.as_ref().is_some_and(|t| t.0.contains("At most 100")), "the script's message is shown: {:?}", h.state().toast); assert_eq!(value(&h, "qty"), ["4"], "the field keeps its valid value"); - let focus = h.state().views[0].forms.focus.clone().expect("the editor stays open"); - assert_eq!(focus.text, "4500", "with the text (typed after the 4), so the user can fix it"); - // And closing asks rather than dropping it. + assert!(h.state().views[0].forms.focus.is_none(), "the rejected 4500 is dropped, not held in an editor"); + let doc = h.state().session.get(h.state().views[0].id).unwrap(); + assert!(!doc.dirty && doc.can_undo().is_none(), "a rejected value is no change and no undo step"); + // Closing has nothing to ask about. h.state_mut().request_close_tab(0); - assert!(h.state().close_request.is_some()); + assert!(h.state().close_request.is_none()); let _ = std::fs::remove_dir_all(&dir); } @@ -1027,11 +1104,11 @@ fn refused_value_stops_save(commit_key: egui::Key, case: &str) { h.run_steps(3); assert_eq!(value(&h, "qty"), ["4"]); assert!(!out.exists(), "nothing is saved right after the field refused its value"); - // The refused text is back in the field, so a later ⌘S stops again instead of saving 4. - assert_eq!(h.state().views[0].forms.focus.as_ref().map(|f| f.text.as_str()), Some("4500")); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S); - h.run_steps(4); - assert!(!out.exists()); + // The rejected text is dropped: Enter closes the editor, and Tab wraps to the only field, + // which shows the value it kept. + let expected = if commit_key == egui::Key::Tab { Some("4") } else { None }; + assert_eq!(h.state().views[0].forms.focus.as_ref().map(|f| f.text.as_str()), expected); + assert!(!h.state().session.get(h.state().views[0].id).unwrap().dirty); let _ = std::fs::remove_dir_all(&dir); } @@ -1109,7 +1186,8 @@ mod revert_tests { h.run_steps(2); h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S); h.run_steps(4); - assert_eq!(h.state().views[0].forms.focus.as_ref().unwrap().text, "99"); + assert!(h.state().views[0].forms.focus.is_none(), "the rejected 99 is dropped"); + assert_eq!(value(&h, "name"), ["Saved original"]); assert_eq!(std::fs::read(&path).unwrap(), saved, "rejection leaves the saved file untouched"); assert!(h.state_mut().execute("file.revert")); h.run_steps(2); diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 0b6f658dd6..c57a7fdd49 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -4643,8 +4643,8 @@ milestone = "M6" status = "shipped" commands = ["form.field.properties"] tools = ["form_set_props", "form_fill"] -evidence = ["crates/forms/src/af/tests.rs::validation_and_calculation", "crates/forms/src/tests.rs::formats_validation_and_calculations_run_like_acrobat", "crates/automation/tests/it/automation.rs::form_formats_and_calculations_through_tools"] -notes = "AFRange_Validate with Acrobat's messages" +evidence = ["crates/forms/src/af/tests.rs::validation_and_calculation", "crates/forms/src/tests.rs::formats_validation_and_calculations_run_like_acrobat", "crates/automation/tests/it/automation.rs::form_formats_and_calculations_through_tools", "crates/forms/src/tests.rs::a_validate_refusal_is_a_rejection_and_a_keystroke_refusal_is_not", "crates/ui-egui/tests/it/forms.rs::a_value_the_validate_action_rejects_reverts_and_tab_moves_on"] +notes = "AFRange_Validate with Acrobat's messages. A value it (or a custom validate script setting event.rc false) rejects is not stored: the app shows the message, the field keeps its previous value and Tab or a click moves on, with no undo step; form_fill reports it as an error. Messages still show as a notice, not a modal dialog." [[feature]] id = "form.af-simple-calculate" @@ -4679,8 +4679,8 @@ milestone = "M6" status = "shipped" commands = ["form.prepare"] tools = ["form_set_script"] -evidence = ["crates/engine/src/tests.rs::form_javascript_validates_calculates_and_formats", "crates/automation/tests/it/automation.rs::javascript_through_tools"] -notes = "Custom keystroke (commit), validate, calculate and format scripts run in Acrobat's event order; AF calls still run natively." +evidence = ["crates/engine/src/tests.rs::form_javascript_validates_calculates_and_formats", "crates/automation/tests/it/automation.rs::javascript_through_tools", "crates/ui-egui/tests/it/forms.rs::a_value_the_validate_action_rejects_reverts_and_tab_moves_on"] +notes = "Custom keystroke (commit), validate, calculate and format scripts run in Acrobat's event order; AF calls still run natively. A validate script that sets event.rc false rejects the value: it is not stored, its alert is the message shown, and the field keeps its previous value." [[feature]] id = "form.calculation-order" From 469ccef1c3383db2ff2f6ca54edb8f76eb68a175 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sun, 25 Oct 2026 01:53:18 +0800 Subject: [PATCH 007/114] M6: a toolbar action queued with a rejected field value does not run process_pending_edits already cleared the deferred shortcuts when the queued field edit was refused, but still ran the view's pending_action. Organize's Save pages queued in the same frame as a value the field's validate action (ISO 32000-2 Table 199 /V) rejects would therefore save behind the refusal, since the rejected draft is dropped and the commit before the save no longer stops it. The pending action is now taken and dropped unless the edit was applied. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0175FWj4xFhMhSH3UpMU8DSC --- crates/ui-egui/src/editing.rs | 72 ++++++++++++++++++++++++++++++++++- 1 file changed, 70 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs index 94e0c37921..e6c072abb7 100644 --- a/crates/ui-egui/src/editing.rs +++ b/crates/ui-egui/src/editing.rs @@ -400,10 +400,11 @@ impl PdfCraftApp { let Some(i) = self.active else { return true }; let applied = self.apply_queued_edit(i); if !applied { - // Nor may a shortcut pressed with it (⌘S right after Enter) run behind the refusal. + // Nor may a shortcut pressed with it (⌘S right after Enter) run behind the refusal, + // nor a toolbar action queued in the same frame (Organize ▸ Save pages). self.deferred_commands.clear(); } - match self.views.get_mut(i).and_then(|v| v.pending_action.take()) { + match self.views.get_mut(i).and_then(|v| v.pending_action.take()).filter(|_| applied) { Some(crate::canvas::ViewAction::InsertFromFile) => self.insert_from_file_dialog(), Some(crate::canvas::ViewAction::InsertFromFileAt(at)) => self.insert_from_file_at(Some(at)), Some(crate::canvas::ViewAction::ReplacePages) => self.replace_pages_dialog(), @@ -1229,3 +1230,70 @@ mod attention_tests { assert!(attend(&mut app, &ctx, false).is_empty(), "the user has seen it"); } } + +#[cfg(test)] +mod rejected_value_tests { + use crate::PdfCraftApp; + use crate::canvas::ViewAction; + use crate::forms_ui::Focus; + use pdfcraft_engine::Edit; + + /// One page with a text field `qty` (value 4) whose validate action (ISO 32000-2 Table 199 + /// `/V`) rejects anything over 100. + fn validated_form() -> Vec { + let objs = [ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>", + "<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>", + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (qty) /V (4) /Rect [20 350 280 372] /P 3 0 R /F 4 /AA << /V << /S /JavaScript /JS (if (event.value > 100) { app.alert('At most 100'); event.rc = false; }) >> >> >>", + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>", + ]; + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes()); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + out + } + + /// A toolbar Save (Organize ▸ Save pages) queued in the frame whose typed value the validate + /// action rejects does not run behind the refusal, just as a ⌘S pressed with it does not. + #[test] + fn a_save_action_queued_with_a_rejected_value_does_not_run() { + let dir = std::env::temp_dir().join(format!("pdfcraft-ui-rejected-action-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let out = dir.join("saved.pdf"); + let mut app = PdfCraftApp::new(); + app.open_bytes("order.pdf", None, validated_form()).unwrap(); + app.active = Some(0); + app.save_override = Some(out.to_string_lossy().into_owned()); + let view = &mut app.views[0]; + view.forms.committed = Some(Focus { + name: "qty".into(), + widget: 0, + text: "4500".into(), + picked: Vec::new(), + request_focus: false, + select_all: false, + press: None, + calendar: None, + calendar_rect: None, + calendar_text: None, + had_focus: false, + }); + view.pending_edit = Some(Edit::SetFieldValue { name: "qty".into(), value: pdfcraft_engine::FieldValue::Text("4500".into()) }); + view.pending_action = Some(ViewAction::Save); + assert!(!app.process_pending_edits(), "the validate action rejects 4500"); + assert!(!out.exists(), "the queued Save does not run behind the refusal"); + assert!(app.views[0].pending_action.is_none(), "nor is it left to run later"); + let _ = std::fs::remove_dir_all(&dir); + } +} From e9df5b65a3b612097544bb12444c4984a1ae61e0 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sun, 25 Oct 2026 02:41:12 +0800 Subject: [PATCH 008/114] M3: a GoToE link opens the PDF embedded in the document A link with an embedded go-to action only reported "This PDF uses the unsupported GoToE action." although the Attachments panel could open the attached PDF it names. - render::inspect reads GoToE (ISO 32000-2 12.6.4.4, Tables 204-205) to a child target (/R /C) by its EmbeddedFiles /N key or its file attachment annotation (/P page or named destination, /A index or /NM), with /D read by the GoToR destination reader. The parent, nested paths, /F and malformed targets stay unsupported. - ui-egui opens the attachment from the document's own bytes through the Attachments panel's path (attachment_data, open_bytes) and goes to /D as a GoToR link does; a file that isn't attached or isn't a PDF opens nothing and says so. - link_open follows GoToE headlessly; doc_info reports the target. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0175FWj4xFhMhSH3UpMU8DSC --- crates/automation/src/json.rs | 13 ++ crates/automation/src/links.rs | 85 +++++++++--- crates/automation/src/tools.rs | 2 +- crates/automation/tests/it/automation.rs | 59 +++++++++ crates/render/src/inspect/annotations.rs | 59 ++++++++- crates/render/src/inspect/model.rs | 9 ++ crates/render/src/inspect/tests.rs | 65 +++++++++ crates/ui-egui/src/app/links.rs | 45 +++++++ crates/ui-egui/src/canvas.rs | 41 ++++-- crates/ui-egui/tests/it/embedded_links.rs | 152 ++++++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + parity/acrobat-features.toml | 4 +- 12 files changed, 498 insertions(+), 37 deletions(-) create mode 100644 crates/ui-egui/tests/it/embedded_links.rs diff --git a/crates/automation/src/json.rs b/crates/automation/src/json.rs index 9e93d4c347..8ee20e8950 100644 --- a/crates/automation/src/json.rs +++ b/crates/automation/src/json.rs @@ -353,6 +353,19 @@ pub(crate) fn info(d: &Document) -> Value { }, "new_window": new_window, }), + pdfcraft_render::LinkTarget::EmbeddedGoTo { source, destination, new_window } => json!({ + "action": "GoToE", + "embedded_file": match source { + pdfcraft_render::AttachmentSource::Document { key } => json!({ "name": key }), + pdfcraft_render::AttachmentSource::Annotation { page, index } => json!({ "page": page1(*page), "annotation": index.saturating_add(1) }), + }, + "destination": match destination { + pdfcraft_render::RemoteDestination::Default => json!({ "kind": "default" }), + pdfcraft_render::RemoteDestination::Page { page, view } => json!({ "kind": "page", "page": page1(*page), "view": format!("{view:?}") }), + pdfcraft_render::RemoteDestination::Named(name) => json!({ "kind": "named", "name": name }), + }, + "new_window": new_window, + }), pdfcraft_render::LinkTarget::Other(o) => json!({ "other": o }), }, })).collect::>(), diff --git a/crates/automation/src/links.rs b/crates/automation/src/links.rs index 41fda9b7db..65124bd12d 100644 --- a/crates/automation/src/links.rs +++ b/crates/automation/src/links.rs @@ -4,7 +4,7 @@ use pdfcraft_engine::{ Edit, LinkAction, LinkHighlight, LinkStyle, read_remote_document, remote_document_path_is_absolute, resolve_remote_document_path, }; -use pdfcraft_render::{DestView, LinkTarget, RemoteDestination}; +use pdfcraft_render::{AttachmentSource, DestView, LinkTarget, RemoteDestination}; use serde_json::{Value, json}; use std::path::Path; @@ -117,10 +117,15 @@ impl Automation { .iter() .find(|link| link.page == page && link.index == index) .ok_or_else(|| failed(format!("page {page_number} has no link {index_number} (see link_list)")))?; - let LinkTarget::RemoteGoTo { file, destination, new_window, .. } = &link.target else { - return Err(bad("the selected link is not a supported local PDF GoToR link")); + let (file, destination, new_window) = match &link.target { + LinkTarget::RemoteGoTo { file, destination, new_window, .. } => (file.clone(), destination.clone(), *new_window), + LinkTarget::EmbeddedGoTo { source: attached, destination, new_window } => { + let (attached, destination, new_window) = (attached.clone(), destination.clone(), *new_window); + return self.open_embedded_link(a, &attached, destination, new_window); + } + _ => return Err(bad("the selected link is not a supported local PDF GoToR or embedded GoToE link")), }; - (source.path.clone(), file.clone(), destination.clone(), *new_window) + (source.path.clone(), file, destination, new_window) }; let path = resolve_remote_document_path(source_path.as_deref().map(Path::new), &file).map_err(failed)?; let allow_absolute = a.opt_bool("allow_absolute")?.unwrap_or(false); @@ -135,20 +140,7 @@ impl Automation { let id = self.session.open(name, Some(path.to_string_lossy().into_owned()), std::sync::Arc::new(bytes), a.opt_str("password")?).map_err(failed)?; let opened = self.session.get(id).ok_or_else(|| failed("the linked document vanished"))?; - let (destination_applied, destination_value, warning) = match destination { - RemoteDestination::Default => (true, json!({ "kind": "default" }), None), - RemoteDestination::Named(name) => { - (false, json!({ "kind": "named", "name": name }), Some("The PDF opened, but the named destination was not applied.")) - } - RemoteDestination::Page { page, view } if page < opened.info.pages.len() => { - (true, json!({ "kind": "page", "page": page.saturating_add(1), "view": dest_view_value(view) }), None) - } - RemoteDestination::Page { page, view } => ( - false, - json!({ "kind": "page", "page": page.saturating_add(1), "view": dest_view_value(view) }), - Some("The PDF opened, but the link's page destination is out of range."), - ), - }; + let (destination_applied, destination_value, warning) = destination_report(destination, opened.info.pages.len()); let mut display_path = path.to_string_lossy().into_owned(); if let Some(root) = &self.root && let Ok(relative) = path.strip_prefix(root) @@ -165,6 +157,44 @@ impl Automation { })) } + /// `link_open` for an embedded Go-To link (ISO 32000-2 §12.6.4.4): open the PDF attached to + /// the document, from the document's own bytes, as a new document. No file is read, so + /// `--root` has nothing to confine. + fn open_embedded_link( + &mut self, + a: &Args, + attached: &AttachmentSource, + destination: RemoteDestination, + new_window: Option, + ) -> Result { + let (name, bytes) = { + let doc = self.doc(a)?; + let att = doc + .info + .attachments + .iter() + .find(|x| x.source == *attached) + .ok_or_else(|| failed("the file this GoToE link names is not attached to the document"))?; + let bytes = pdfcraft_render::attachment_data(&doc.bytes, doc.password.as_deref(), att).map_err(failed)?; + (att.name.clone(), bytes) + }; + // "Embedded go-to actions work only for files of Type PDF" (§12.6.4.4). + if !bytes.get(..bytes.len().min(1024)).is_some_and(|head| head.windows(5).any(|w| w == b"%PDF-")) { + return Err(failed(format!("{name} is not a PDF, so the GoToE link can't open it"))); + } + let id = self.session.open(name.clone(), None, std::sync::Arc::new(bytes), a.opt_str("password")?).map_err(failed)?; + let opened = self.session.get(id).ok_or_else(|| failed("the linked document vanished"))?; + let (destination_applied, destination_value, warning) = destination_report(destination, opened.info.pages.len()); + Ok(json!({ + "document": crate::summary(opened), + "embedded_file": name, + "destination_applied": destination_applied, + "destination": destination_value, + "warning": warning, + "new_window_hint": new_window, + })) + } + pub(crate) fn link_add(&mut self, a: &Args) -> Result { let page = self.page(a)?; let rect = self.view_rect(a, page)?.ok_or_else(|| bad("link_add needs rect"))?; @@ -225,6 +255,25 @@ impl Automation { } } +/// Whether a remote or embedded Go-To's destination could be applied in a document of `pages` +/// pages, as `link_open` reports it, with a warning when not. +fn destination_report(destination: RemoteDestination, pages: usize) -> (bool, Value, Option<&'static str>) { + match destination { + RemoteDestination::Default => (true, json!({ "kind": "default" }), None), + RemoteDestination::Named(name) => { + (false, json!({ "kind": "named", "name": name }), Some("The PDF opened, but the named destination was not applied.")) + } + RemoteDestination::Page { page, view } if page < pages => { + (true, json!({ "kind": "page", "page": page.saturating_add(1), "view": dest_view_value(view) }), None) + } + RemoteDestination::Page { page, view } => ( + false, + json!({ "kind": "page", "page": page.saturating_add(1), "view": dest_view_value(view) }), + Some("The PDF opened, but the link's page destination is out of range."), + ), + } +} + fn dest_view_value(view: DestView) -> Value { match view { DestView::Top => json!({ "kind": "top" }), diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index c6c200cece..3cc78278a9 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -688,7 +688,7 @@ pub fn tools() -> Vec { t("link_list", "List links", "Every link: page, 1-based index (for link_edit/link_delete), rect (points from the top-left of the page), and where it goes (url or to_page).") .ro() .with(schema(json!({ "doc": doc() }), &["doc"])), - t("link_open", "Open a linked PDF", "Follow a local GoToR link in PdfCraft: open the referenced PDF as a new document, respecting --root. page and index use link_list numbering. Named destinations are reported but not applied. Absolute file specifications require allow_absolute: true after reviewing the target; relative links need no opt-in.") + t("link_open", "Open a linked PDF", "Follow a local GoToR link in PdfCraft: open the referenced PDF as a new document, respecting --root. page and index use link_list numbering. Named destinations are reported but not applied. Absolute file specifications require allow_absolute: true after reviewing the target; relative links need no opt-in. A GoToE link opens the PDF embedded in this document that it names (a child target), from the document itself.") .with(schema( json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "index": { "type": "integer", "minimum": 1 }, "password": { "type": "string", "description": "Optional password for the linked PDF." }, "allow_absolute": { "type": "boolean", "description": "Explicitly allow an absolute local GoToR target (default false). Existing validation and --root confinement still apply." } }), &["doc", "page", "index"], diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 6a5765b911..3db134f89c 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -5597,6 +5597,65 @@ fn a_launch_link_to_a_pdf_opens_it_like_a_remote_link() { assert_eq!(a.session().docs().len(), before, "nothing was opened or launched"); } +/// An embedded Go-To link (ISO 32000-2 §12.6.4.4) opens the PDF attached to the document, from +/// the document itself: no file of that name is read, inside the root or out of it. One to a +/// file that isn't attached, or isn't a PDF, opens nothing. +#[test] +fn an_embedded_go_to_link_opens_the_attached_pdf() { + let (_base, root) = sandbox("gotoe"); + // A file of the attachment's name next to the document, which must not be what opens. + std::fs::write(root.join("inner.pdf"), fixture(1)).unwrap(); + let embedded = fixture(3); + let stream = |dict: &str, data: &[u8]| { + let mut s = format!("<< {dict} /Length {} >>\nstream\n", data.len()).into_bytes(); + s.extend_from_slice(data); + s.extend_from_slice(b"\nendstream"); + s + }; + let objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles << /Names [(inner.pdf) 5 0 R (notes.txt) 6 0 R] >> >> >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /Annots [7 0 R 8 0 R 9 0 R] >>".to_vec(), + stream("/Type /EmbeddedFile", &embedded), + b"<< /Type /Filespec /F (inner.pdf) /UF (inner.pdf) /EF << /F 4 0 R >> >>".to_vec(), + b"<< /Type /Filespec /F (notes.txt) /EF << /F 10 0 R >> >>".to_vec(), + b"<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /A << /S /GoToE /T << /R /C /N (inner.pdf) >> /D [2 /Fit] >> >>".to_vec(), + b"<< /Type /Annot /Subtype /Link /Rect [0 20 10 30] /A << /S /GoToE /T << /R /C /N (missing.pdf) >> /D [0 /Fit] >> >>".to_vec(), + b"<< /Type /Annot /Subtype /Link /Rect [0 40 10 50] /A << /S /GoToE /T << /R /C /N (notes.txt) >> /D [0 /Fit] >> >>".to_vec(), + stream("/Type /EmbeddedFile", b"just some notes"), + ]; + let mut pdf = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(pdf.len()); + pdf.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + pdf.extend_from_slice(o); + pdf.extend_from_slice(b"\nendobj\n"); + } + let xref = pdf.len(); + pdf.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + pdf.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + pdf.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + std::fs::write(root.join("outer.pdf"), pdf).unwrap(); + let mut a = auto(&root); + let source = ok(&mut a, "doc_open", json!({ "path": "outer.pdf" }))["doc"].as_u64().unwrap(); + let info = ok(&mut a, "doc_info", json!({ "doc": source })); + let link = &info["links"][0]["target"]; + assert_eq!((link["action"].as_str(), &link["embedded_file"]), (Some("GoToE"), &json!({ "name": "inner.pdf" })), "{info}"); + let opened = ok(&mut a, "link_open", json!({ "doc": source, "page": 1, "index": 1 })); + assert_eq!(opened["document"]["pages"], 3, "the attached PDF, not the file beside the document: {opened}"); + assert_eq!((opened["embedded_file"].as_str(), opened["destination_applied"].as_bool()), (Some("inner.pdf"), Some(true))); + assert_eq!(opened["destination"], json!({ "kind": "page", "page": 3, "view": { "kind": "fit" } }), "{opened}"); + let before = a.session().docs().len(); + for (index, why) in [(2, "not attached"), (3, "notes.txt is not a PDF")] { + let e = err(&mut a, "link_open", json!({ "doc": source, "page": 1, "index": index })); + assert!(matches!(&e, ToolError::Failed(m) if m.contains(why)), "{e}"); + } + assert_eq!(a.session().docs().len(), before, "nothing else was opened"); +} + #[test] fn local_gotor_link_open_refuses_directories_devices_and_non_pdf_targets() { let (_base, root) = sandbox("gotor-not-a-file"); diff --git a/crates/render/src/inspect/annotations.rs b/crates/render/src/inspect/annotations.rs index 603aa88110..dace729e3d 100644 --- a/crates/render/src/inspect/annotations.rs +++ b/crates/render/src/inspect/annotations.rs @@ -214,6 +214,7 @@ impl<'a> Inspector<'a> { Some("SetOCGState") => self.layer_state(a), Some("GoToR") => self.remote_go_to(a).unwrap_or_else(|| LinkTarget::Other("GoToR".into())), Some("Launch") => self.launch_pdf(a).unwrap_or_else(|| LinkTarget::Other("Launch".into())), + Some("GoToE") => self.embedded_go_to(a, text_budget).unwrap_or_else(|| LinkTarget::Other("GoToE".into())), Some(other) => LinkTarget::Other(other.to_string()), None => return None, } @@ -223,7 +224,15 @@ impl<'a> Inspector<'a> { fn remote_go_to(&self, action: &Dictionary) -> Option { let file = self.action_file(action)?; - let destination = match action.get(b"D") { + let destination = self.remote_destination(action)?; + Some(LinkTarget::RemoteGoTo { launch: false, file, destination, new_window: self.new_window(action) }) + } + + /// The `/D` of a remote or embedded Go-To: a destination in another document, so an + /// explicit one names its page by number (§12.3.2.2). No `/D` is that document's default + /// view; an unusable one is `None`. + fn remote_destination(&self, action: &Dictionary) -> Option { + Some(match action.get(b"D") { Err(_) => RemoteDestination::Default, Ok(o) => match self.resolve(o) { Object::Array(items) => { @@ -248,8 +257,54 @@ impl<'a> Inspector<'a> { } _ => return None, }, + }) + } + + /// An embedded Go-To action (§12.6.4.4). Only a child of this document is opened: a target + /// dictionary with `/R /C` and no further `/T`, naming the file by its `/N` key in the + /// EmbeddedFiles name tree, or, for a file attachment annotation, by `/P` (a page number, or + /// a named destination giving it) and `/A` (the annotation's index in `/Annots`, or its + /// `/NM`) (Table 205). The parent (`/R /P`), a nested path, or a target under another root + /// document (`/F`) is `None`: not followed. + fn embedded_go_to(&self, action: &Dictionary, text_budget: &mut usize) -> Option { + if action.has(b"F") { + return None; + } + let t = self.dict(action.get(b"T").ok()?)?; + if self.name(t, b"R").as_deref() != Some("C") || t.has(b"T") { + return None; + } + let source = match t.get(b"N") { + Ok(n) => { + let Object::String(bytes, _) = self.resolve(n) else { return None }; + // Converted as the EmbeddedFiles keys `DocInfo::attachments` lists are. + AttachmentSource::Document { key: spend(bytes, text_budget, text_string)? } + } + Err(_) => { + let page = match self.resolve(t.get(b"P").ok()?) { + Object::Integer(p) => usize::try_from(*p).ok()?, + named @ Object::String(..) => self.dest(named, 0)?.0, + _ => return None, + }; + let index = match self.resolve(t.get(b"A").ok()?) { + Object::Integer(i) => usize::try_from(*i).ok()?, + Object::String(nm, _) => self.annotation_named(page, nm)?, + _ => return None, + }; + AttachmentSource::Annotation { page, index } + } }; - Some(LinkTarget::RemoteGoTo { launch: false, file, destination, new_window: self.new_window(action) }) + Some(LinkTarget::EmbeddedGoTo { source, destination: self.remote_destination(action)?, new_window: self.new_window(action) }) + } + + /// The position in page `page`'s `/Annots` of the first annotation whose `/NM` is `nm`. + fn annotation_named(&self, page: usize, nm: &[u8]) -> Option { + let id = *self.page_ids.get(page)?; + let page = self.doc.get_dictionary(id).ok()?; + let Object::Array(annots) = self.resolve(page.get(b"Annots").ok()?) else { return None }; + annots.iter().position(|a| { + self.dict(a).and_then(|d| d.get(b"NM").ok()).is_some_and(|n| matches!(self.resolve(n), Object::String(b, _) if b.as_slice() == nm)) + }) } /// The non-empty local file an action's `/F` names (a string or a file specification), shared diff --git a/crates/render/src/inspect/model.rs b/crates/render/src/inspect/model.rs index 490897b60f..bebcea06ba 100644 --- a/crates/render/src/inspect/model.rs +++ b/crates/render/src/inspect/model.rs @@ -220,6 +220,15 @@ pub enum LinkTarget { destination: RemoteDestination, new_window: Option, }, + /// An embedded Go-To action (ISO 32000-2 §12.6.4.4, Tables 204–205) to a PDF embedded in + /// this document: the attachment its target dictionary names as a child (`/R /C`), by its + /// `/N` key in the EmbeddedFiles name tree or by its file attachment annotation (`/P`, `/A`), + /// and the destination `/D` in it. The caller opens it from this document's bytes. + EmbeddedGoTo { + source: AttachmentSource, + destination: RemoteDestination, + new_window: Option, + }, Other(String), } diff --git a/crates/render/src/inspect/tests.rs b/crates/render/src/inspect/tests.rs index a5bfec474d..ef97f77a57 100644 --- a/crates/render/src/inspect/tests.rs +++ b/crates/render/src/inspect/tests.rs @@ -1245,6 +1245,71 @@ fn launch_actions_that_name_a_pdf_open_it_like_a_remote_link() { ); } +/// Embedded Go-To actions (§12.6.4.4, Tables 204–205) to a child of this document are read +/// with the attachment they name; the parent, a nested path, another root document or a +/// malformed target stays an action that isn't followed. +#[test] +fn links_read_embedded_go_to_actions_to_attached_pdfs() { + let actions = [ + "<< /S /GoToE /T << /R /C /N (inner.pdf) >> /D [2 /FitH 100] /NewWindow true >>", + "<< /S /GoToE /T << /R /C /P 0 /A 1 >> >>", + "<< /S /GoToE /T << /R /C /P 0 /A (att-1) >> /D (chapter) >>", + "<< /S /GoToE /T << /R /C /P (here) /A 1 >> /D [0 /Fit] >>", + "<< /S /GoToE /T << /R /P >> /D [0 /Fit] >>", + "<< /S /GoToE /T << /R /P /N (inner.pdf) >> /D [0 /Fit] >>", + "<< /S /GoToE /T << /R /C /N (inner.pdf) /T << /R /C /N (deeper.pdf) >> >> /D [0 /Fit] >>", + "<< /S /GoToE /F (other.pdf) /T << /R /C /N (inner.pdf) >> /D [0 /Fit] >>", + "<< /S /GoToE /T << /R /C /N /inner.pdf >> /D [0 /Fit] >>", + "<< /S /GoToE /T << /R /C /P 0 /A (no-such-name) >> /D [0 /Fit] >>", + "<< /S /GoToE /T << /R /C /P -1 /A 1 >> /D [0 /Fit] >>", + "<< /S /GoToE /T << /R /C /N (inner.pdf) >> /D [/Fit] >>", + "<< /S /GoToE >>", + ]; + let mut pdf = String::from( + "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R /Names << /Dests << /Names [(here) [3 0 R /Fit]] >> >> >> endobj\n\ + 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >> endobj\n", + ); + let annots: Vec = (0..=actions.len()).map(|k| format!("{} 0 R", 30 + k)).collect(); + pdf.push_str(&format!("3 0 obj << /Type /Page /Parent 2 0 R /Annots [{}] >> endobj\n", annots.join(" "))); + // Index 0 is a link; index 1 the file attachment annotation, named att-1. + pdf.push_str(&format!("30 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 10 10] /A {} >> endobj\n", actions[0])); + pdf.push_str("31 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 10 10] /NM (att-1) >> endobj\n"); + for (k, a) in actions.iter().enumerate().skip(1) { + pdf.push_str(&format!("{} 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 10 10] /A {a} >> endobj\n", 31 + k)); + } + pdf.push_str("trailer << /Root 1 0 R >>\n%%EOF"); + let info = inspect(Arc::new(pdf.into_bytes()), None).expect("opens"); + let targets: Vec<_> = info.links.iter().map(|l| l.target.clone()).collect(); + let annotation = AttachmentSource::Annotation { page: 0, index: 1 }; + let embedded = |source: &AttachmentSource, destination, new_window| LinkTarget::EmbeddedGoTo { source: source.clone(), destination, new_window }; + let other = || LinkTarget::Other("GoToE".into()); + assert_eq!( + targets, + [ + embedded( + &AttachmentSource::Document { key: "inner.pdf".into() }, + RemoteDestination::Page { page: 2, view: DestView::FitH { top: Some(100.0) } }, + Some(true) + ), + // No /D: the document's default view. + embedded(&annotation, RemoteDestination::Default, None), + // /A by the annotation's /NM; a named destination in the target. + embedded(&annotation, RemoteDestination::Named("chapter".into()), None), + // /P by a named destination of this document. + embedded(&annotation, RemoteDestination::Page { page: 0, view: DestView::Fit }, None), + other(), + other(), + other(), + other(), + other(), + other(), + other(), + other(), + other(), + ] + ); +} + #[test] fn links_read_bounded_local_remote_go_to_actions() { use DestView::{Fit, Xyz}; diff --git a/crates/ui-egui/src/app/links.rs b/crates/ui-egui/src/app/links.rs index 77f9519972..139d1db85e 100644 --- a/crates/ui-egui/src/app/links.rs +++ b/crates/ui-egui/src/app/links.rs @@ -65,6 +65,45 @@ impl PdfCraftApp { self.pending_remote_link = None; } + /// Follow a link's embedded Go-To action (ISO 32000-2 §12.6.4.4): open the PDF attached to + /// document `doc` at `source` in a new tab, as the Attachments panel's Open does (from the + /// document's own bytes: no file is read or written), then go to `destination` in it. A + /// file that isn't attached there, or isn't a PDF, opens nothing. + pub(crate) fn open_embedded_link( + &mut self, + doc: DocId, + source: pdfcraft_render::AttachmentSource, + destination: pdfcraft_render::RemoteDestination, + ) { + let Some(d) = self.session.get(doc) else { return }; + let Some(att) = d.info.attachments.iter().find(|a| a.source == source).cloned() else { + self.notify_fmt("This PDF uses the unsupported {s} action.", &[("s", "GoToE")]); + return; + }; + let bytes = match pdfcraft_render::attachment_data(&d.bytes, d.password.as_deref(), &att) { + Ok(bytes) => bytes, + Err(e) => { + self.notify_fmt("Couldn't read {name}: {e}", &[("name", &att.name), ("e", &e.to_string())]); + return; + } + }; + // "Embedded go-to actions work only for files of Type PDF" (§12.6.4.4). Checked here, as + // the Attachments panel's Open would turn a picture or text file into a new PDF. + if !looks_like_pdf(&bytes) { + self.notify_fmt("{name} isn't a PDF, so the link can't open it.", &[("name", &att.name)]); + return; + } + if let Err(e) = self.open_bytes(&crate::files::attachment_file_name(&att.name), None, bytes) { + self.notify_fmt("Couldn't open {name}: {e}", &[("name", &att.name), ("e", &e.to_string())]); + return; + } + // An encrypted attachment waits for its password; the destination waits with it. + match self.password_prompt.as_mut() { + Some(prompt) => prompt.after_open = Some(destination), + None => self.apply_remote_destination(destination), + } + } + pub(super) fn apply_remote_destination(&mut self, destination: pdfcraft_render::RemoteDestination) { let Some(index) = self.views.len().checked_sub(1) else { return }; let Some(doc) = self.session.get(self.views[index].id) else { return }; @@ -123,3 +162,9 @@ impl PdfCraftApp { } } } + +/// Whether `bytes` are a PDF file: the `%PDF-` header (ISO 32000-2 §7.5.2) within their first +/// 1024 bytes. +fn looks_like_pdf(bytes: &[u8]) -> bool { + bytes.get(..bytes.len().min(1024)).is_some_and(|head| head.windows(5).any(|w| w == b"%PDF-")) +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8b280ba75d..233bb55851 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1906,6 +1906,12 @@ fn link_hit(info: &DocInfo, xf: &PageXform, page: usize, p: Pos2) -> Option u.clone(), LinkTarget::SetLayers { .. } => tl!("Set layer visibility").to_string(), LinkTarget::RemoteGoTo { file, .. } => file.clone(), + // The attachment's name, as the Attachments panel lists it. + LinkTarget::EmbeddedGoTo { source, .. } => info + .attachments + .iter() + .find(|a| a.source == *source) + .map_or_else(|| crate::i18n::fmt(tl!("{s} action"), &[("s", "GoToE")]), |a| a.name.clone()), LinkTarget::Other(s) => crate::i18n::fmt(tl!("{s} action"), &[("s", s)]), }; let owner = crate::page_router::Owner::Link { index }; @@ -2774,13 +2780,9 @@ fn schedule_presentation_turn(ui: &egui::Ui, view: &mut DocView, click: Option, -) -> Option<(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination)> { +/// Follows the link that was clicked. A link to another file, or to a PDF attached to this one, +/// comes back, to be opened once the document is no longer borrowed. +fn follow_link(app: &mut PdfCraftApp, index: usize, target: Option) -> Option { let view_id = app.views[index].id; match target? { LinkTarget::Page(p, dest) => { @@ -2791,7 +2793,8 @@ fn follow_link( } LinkTarget::Uri(u) => app.request_document_url(&u, crate::LinkOrigin::Link), LinkTarget::SetLayers { changes, preserve_rb } => set_layers(app, index, &changes, preserve_rb), - LinkTarget::RemoteGoTo { file, destination, .. } => return Some((view_id, file, destination)), + LinkTarget::RemoteGoTo { file, destination, .. } => return Some(LinkOpen::Remote(view_id, file, destination)), + LinkTarget::EmbeddedGoTo { source, destination, .. } => return Some(LinkOpen::Embedded(view_id, source, destination)), LinkTarget::Other(s) => app.notify_fmt("This PDF uses the unsupported {s} action.", &[("s", &s)]), } None @@ -3320,7 +3323,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { None => {} } schedule_presentation_turn(ui, view, present, clicked_link.is_some()); - let remote_open = follow_link(app, index, clicked_link); + let link_open = follow_link(app, index, clicked_link); if tool == QuickTool::Crop && cropped { tool = QuickTool::Select; } @@ -3338,7 +3341,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { open_table, form_notice, copy_selected, - remote_open, + link_open, form, generation, avail, @@ -3359,7 +3362,7 @@ struct FrameRequests { open_table: Option<(usize, [f64; 4])>, form_notice: Option, copy_selected: bool, - remote_open: Option<(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination)>, + link_open: Option, form: Arc>, generation: u64, avail: Rect, @@ -3379,7 +3382,7 @@ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, open_table, form_notice, copy_selected, - remote_open, + link_open, form, generation, avail, @@ -3481,11 +3484,21 @@ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, if app.mode != crate::Mode::Read && !app.full_screen { quick_bar(app, avail, ui); } - if let Some((source, file, destination)) = remote_open { - app.open_remote_link(source, file, destination); + match link_open { + Some(LinkOpen::Remote(source, file, destination)) => app.open_remote_link(source, file, destination), + Some(LinkOpen::Embedded(doc, source, destination)) => app.open_embedded_link(doc, source, destination), + None => {} } } +/// A clicked link that opens another document once the frame no longer borrows this one. +enum LinkOpen { + /// A GoToR or Launch link: the document it is in, the file, and where in it to go. + Remote(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination), + /// A GoToE link: the document it is in, its attachment, and where in it to go. + Embedded(pdfcraft_engine::DocId, pdfcraft_render::AttachmentSource, pdfcraft_render::RemoteDestination), +} + /// The prepare-mode field menu's choices. enum FieldMenu { Properties, diff --git a/crates/ui-egui/tests/it/embedded_links.rs b/crates/ui-egui/tests/it/embedded_links.rs new file mode 100644 index 0000000000..c289933fb0 --- /dev/null +++ b/crates/ui-egui/tests/it/embedded_links.rs @@ -0,0 +1,152 @@ +//! A link's embedded Go-To action (GoToE, ISO 32000-2 §12.6.4.4) opens the PDF attached to the +//! document in a new tab, as the Attachments panel's Open does, and goes to its destination. + +use egui_kittest::Harness; +use pdfcraft_ui_egui::PdfCraftApp; + +/// A PDF of `objs` (object 1 the catalog), with a cross-reference table. +fn write_pdf(objs: &[Vec]) -> Vec { + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offs = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offs.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(o); + out.extend_from_slice(b"\nendobj\n"); + } + let x = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offs { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{x}\n%%EOF\n", objs.len() + 1).as_bytes()); + out +} + +fn stream(dict: &str, data: &[u8]) -> Vec { + let mut s = format!("<< {dict} /Length {} >>\nstream\n", data.len()).into_bytes(); + s.extend_from_slice(data); + s.extend_from_slice(b"\nendstream"); + s +} + +/// A three-page PDF to embed. +fn inner() -> Vec { + write_pdf(&[ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 /MediaBox [0 0 200 300] >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R >>".to_vec(), + ]) +} + +/// Link rows, by the y (PDF user space, 300 × 400 page) of their middle. +const TO_PAGE_3: f32 = 375.0; +const PARENT: f32 = 325.0; +const MISSING: f32 = 275.0; +const NOT_A_PDF: f32 = 225.0; +const BY_ANNOTATION: f32 = 175.0; + +/// One page with `inner.pdf` and `notes.txt` in the EmbeddedFiles name tree, a file attachment +/// annotation (index 0, `/NM (att-1)`) holding `inner.pdf` too, and a GoToE link per case. +fn fixture() -> Vec { + let links = [ + (TO_PAGE_3, "<< /S /GoToE /T << /R /C /N (inner.pdf) >> /D [2 /Fit] /NewWindow true >>"), + (PARENT, "<< /S /GoToE /T << /R /P >> /D [0 /Fit] >>"), + (MISSING, "<< /S /GoToE /T << /R /C /N (missing.pdf) >> /D [0 /Fit] >>"), + (NOT_A_PDF, "<< /S /GoToE /T << /R /C /N (notes.txt) >> /D [0 /Fit] >>"), + (BY_ANNOTATION, "<< /S /GoToE /T << /R /C /P 0 /A (att-1) >> /D [1 /Fit] >>"), + ]; + let first_link = 9; + let annots: Vec = std::iter::once("8 0 R".to_string()).chain((0..links.len()).map(|k| format!("{} 0 R", first_link + k))).collect(); + let mut objs = vec![ + b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles << /Names [(inner.pdf) 6 0 R (notes.txt) 7 0 R] >> >> >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>".to_vec(), + format!("<< /Type /Page /Parent 2 0 R /Annots [{}] >>", annots.join(" ")).into_bytes(), + stream("/Type /EmbeddedFile /Subtype /application#2Fpdf", &inner()), + stream("/Type /EmbeddedFile /Subtype /text#2Fplain", b"just some notes"), + b"<< /Type /Filespec /F (inner.pdf) /UF (inner.pdf) /EF << /F 4 0 R >> >>".to_vec(), + b"<< /Type /Filespec /F (notes.txt) /UF (notes.txt) /EF << /F 5 0 R >> >>".to_vec(), + b"<< /Type /Annot /Subtype /FileAttachment /Rect [270 10 290 30] /NM (att-1) /FS << /Type /Filespec /F (inner.pdf) /UF (inner.pdf) /EF << /F 4 0 R >> >> >>".to_vec(), + ]; + objs.extend( + links + .iter() + .map(|(y, a)| format!("<< /Type /Annot /Subtype /Link /Rect [20 {} 280 {}] /Border [0 0 0] /A {a} >>", y - 10.0, y + 10.0).into_bytes()), + ); + write_pdf(&objs) +} + +fn harness() -> Harness<'static, PdfCraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| { + let mut app = PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + app.open_bytes("outer.pdf", None, fixture()).unwrap(); + app.set_option("left", "closed").unwrap(); + app.set_option("panel", "none").unwrap(); + app.set_option("zoom", "100").unwrap(); + app + }); + h.run_steps(8); + h +} + +/// Click the link at height `y` on page 1 of the first tab. +fn click(h: &mut Harness<'static, PdfCraftApp>, y: f32) { + let r = h.state().views[0].page_screen_rect(0).expect("page 1 on screen"); + let k = r.width() / 300.0; + let p = r.min + egui::vec2(150.0 * k, (400.0 - y) * k); + h.hover_at(p); + h.run_steps(1); + h.drag_at(p); + h.run_steps(1); + h.drop_at(p); + h.run_steps(4); +} + +fn toast(h: &Harness<'static, PdfCraftApp>) -> Option { + h.state().toast.clone().map(|t| t.0) +} + +fn tab_name(h: &Harness<'static, PdfCraftApp>, i: usize) -> Option { + let s = h.state(); + s.views.get(i).and_then(|v| s.session.get(v.id)).map(|d| d.name.clone()) +} + +/// `/R /C /N`: the file in the EmbeddedFiles name tree opens in a new tab at `/D`. +#[test] +fn an_embedded_go_to_link_opens_the_attached_pdf_at_its_destination() { + let mut h = harness(); + click(&mut h, TO_PAGE_3); + assert_eq!(h.state().views.len(), 2, "{:?}", toast(&h)); + assert_eq!(h.state().active, Some(1)); + assert_eq!(tab_name(&h, 1).as_deref(), Some("inner.pdf")); + assert_eq!(h.state().session.get(h.state().views[1].id).unwrap().info.pages.len(), 3); + assert_eq!(h.state().views[1].current, 2, "the destination's page"); + assert_eq!(h.state().session.get(h.state().views[1].id).unwrap().path, None, "opened from the document, not from a file"); +} + +/// `/R /C /P /A`: the file of a file attachment annotation, found by its `/NM`. +#[test] +fn an_embedded_go_to_link_opens_a_file_attachment_annotations_pdf() { + let mut h = harness(); + click(&mut h, BY_ANNOTATION); + assert_eq!(h.state().views.len(), 2, "{:?}", toast(&h)); + assert_eq!(h.state().views[1].current, 1); +} + +/// The parent, a file that isn't attached, and a file that isn't a PDF open nothing and say so. +#[test] +fn embedded_go_to_links_that_cannot_be_followed_open_nothing() { + for (y, says) in [ + (PARENT, "This PDF uses the unsupported GoToE action."), + (MISSING, "This PDF uses the unsupported GoToE action."), + (NOT_A_PDF, "notes.txt isn't a PDF, so the link can't open it."), + ] { + let mut h = harness(); + click(&mut h, y); + assert_eq!(h.state().views.len(), 1, "nothing opened for the link at {y}"); + assert_eq!(toast(&h).as_deref(), Some(says)); + } +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index a5c3192358..5da75687cf 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -41,6 +41,7 @@ mod dialog_chrome; mod document_links; mod editing; mod editor_taps; +mod embedded_links; mod export; mod fill_sign; mod folders; diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 0b6f658dd6..468c2b3d12 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -1190,8 +1190,8 @@ milestone = "M3" status = "shipped" commands = [] tools = ["link_open"] -evidence = ["crates/ui-egui/tests/it/view.rs::clicking_a_link_goes_to_its_destination", "crates/ui-egui/tests/it/view.rs::link_destinations_scroll_to_their_position", "crates/ui-egui/tests/it/view.rs::a_link_without_a_position_keeps_the_place_on_the_next_page", "crates/ui-egui/src/canvas/tests.rs::a_null_xyz_coordinate_keeps_the_readers_place_on_the_new_page", "crates/render/src/inspect/tests.rs::bookmarks_and_links_keep_their_destination_view", "crates/render/src/inspect/tests.rs::links_read_bounded_local_remote_go_to_actions", "crates/automation/tests/it/automation.rs::local_gotor_link_open_applies_destinations_and_honors_root", "crates/ui-egui/tests/it/document_links.rs::a_local_gotor_link_opens_in_a_tab_and_applies_its_destination", "crates/ui-egui/tests/it/document_links.rs::an_absolute_gotor_waits_for_consent_and_keeps_its_destination_across_tabs", "crates/ui-egui/tests/it/document_links.rs::cancelling_an_absolute_gotor_by_button_escape_or_dismissal_changes_nothing", "crates/automation/tests/it/automation.rs::absolute_gotor_consent_does_not_bypass_validation_or_passwords", "crates/render/src/inspect/tests.rs::launch_actions_that_name_a_pdf_open_it_like_a_remote_link", "crates/automation/tests/it/automation.rs::a_launch_link_to_a_pdf_opens_it_like_a_remote_link"] -notes = "GoTo and URI links plus local-PDF GoToR links: source-relative or local absolute /F paths, /UF preferred in file-spec dictionaries, explicit numeric page/view destinations, and internal tabs. Absolute local GoToR targets require desktop Allow/Cancel confirmation or an explicit allow_absolute opt-in in link_open; relative links open normally. link_open honors --root. Named remote destinations open at default view with a warning; /NewWindow is a tab hint. A Launch action whose /F names a .pdf file (and has no /Win launch parameters) opens that PDF the same way, backslash separators read as / (#4168); URL/network file systems, GoToE, other Launch actions and other actions are not executed. Same-document destinations retain their supported /XYZ, /Fit, /FitH, /FitV and /FitR views; /FitB* is read as whole-page fit. A null /XYZ left or top keeps the reader's place, as ISO 32000-2 §12.3.2.2 says and Acrobat Reader was observed to do (synthetic fixture): the user-space point at the window's top-left stays there on the target page at the same zoom, along each axis the page overflows; CAD exports (WSCAD) write every cross-reference this way. Null /FitH top and /FitV left still go to the page edge." +evidence = ["crates/ui-egui/tests/it/view.rs::clicking_a_link_goes_to_its_destination", "crates/ui-egui/tests/it/view.rs::link_destinations_scroll_to_their_position", "crates/ui-egui/tests/it/view.rs::a_link_without_a_position_keeps_the_place_on_the_next_page", "crates/ui-egui/src/canvas/tests.rs::a_null_xyz_coordinate_keeps_the_readers_place_on_the_new_page", "crates/render/src/inspect/tests.rs::bookmarks_and_links_keep_their_destination_view", "crates/render/src/inspect/tests.rs::links_read_bounded_local_remote_go_to_actions", "crates/automation/tests/it/automation.rs::local_gotor_link_open_applies_destinations_and_honors_root", "crates/ui-egui/tests/it/document_links.rs::a_local_gotor_link_opens_in_a_tab_and_applies_its_destination", "crates/ui-egui/tests/it/document_links.rs::an_absolute_gotor_waits_for_consent_and_keeps_its_destination_across_tabs", "crates/ui-egui/tests/it/document_links.rs::cancelling_an_absolute_gotor_by_button_escape_or_dismissal_changes_nothing", "crates/automation/tests/it/automation.rs::absolute_gotor_consent_does_not_bypass_validation_or_passwords", "crates/render/src/inspect/tests.rs::launch_actions_that_name_a_pdf_open_it_like_a_remote_link", "crates/automation/tests/it/automation.rs::a_launch_link_to_a_pdf_opens_it_like_a_remote_link", "crates/render/src/inspect/tests.rs::links_read_embedded_go_to_actions_to_attached_pdfs", "crates/ui-egui/tests/it/embedded_links.rs::an_embedded_go_to_link_opens_the_attached_pdf_at_its_destination", "crates/ui-egui/tests/it/embedded_links.rs::an_embedded_go_to_link_opens_a_file_attachment_annotations_pdf", "crates/ui-egui/tests/it/embedded_links.rs::embedded_go_to_links_that_cannot_be_followed_open_nothing", "crates/automation/tests/it/automation.rs::an_embedded_go_to_link_opens_the_attached_pdf"] +notes = "GoTo and URI links plus local-PDF GoToR links: source-relative or local absolute /F paths, /UF preferred in file-spec dictionaries, explicit numeric page/view destinations, and internal tabs. Absolute local GoToR targets require desktop Allow/Cancel confirmation or an explicit allow_absolute opt-in in link_open; relative links open normally. link_open honors --root. Named remote destinations open at default view with a warning; /NewWindow is a tab hint. A Launch action whose /F names a .pdf file (and has no /Win launch parameters) opens that PDF the same way, backslash separators read as / (#4168); A GoToE link (ISO 32000-2 §12.6.4.4) to a PDF embedded in the document (a child target, /R /C, by its EmbeddedFiles /N key or its file attachment annotation /P and /A, index or /NM) opens it in a new tab from the document's own bytes, as the Attachments panel does, at its page destination (named destinations open at the default view with a warning); link_open does the same headlessly. GoToE to the parent (/R /P), through nested target dictionaries, under another root document (/F), to a file that isn't attached or to a non-PDF attachment is not followed, with a notice. URL/network file systems, other Launch actions and other actions are not executed. Same-document destinations retain their supported /XYZ, /Fit, /FitH, /FitV and /FitR views; /FitB* is read as whole-page fit. A null /XYZ left or top keeps the reader's place, as ISO 32000-2 §12.3.2.2 says and Acrobat Reader was observed to do (synthetic fixture): the user-space point at the window's top-left stays there on the target page at the same zoom, along each axis the page overflows; CAD exports (WSCAD) write every cross-reference this way. Null /FitH top and /FitV left still go to the page edge." [[feature]] id = "view.annotation-hover" From a02bf747fd12243a7611c1196e6e5a46c6eedca2 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:14:59 +0800 Subject: [PATCH 009/114] M3: GoToE targets look up /NM once per page, and one %PDF- check serves both callers - A GoToE target naming its file attachment annotation by /NM scanned the page's /Annots for every link: O(links x annotations). The inspector now builds each page's /NM index once, on first use, keeping the first annotation with a repeated name as the scan did. - The UI and link_open each had their own "%PDF- within the first 1024 bytes" check (ISO 32000-2 7.5.2; GoToE opens only PDFs, 12.6.4.4). pdfcraft_render::looks_like_pdf, next to attachment_data, is now the one both call, so they cannot disagree. Test: embedded_go_to_links_by_annotation_name_read_the_page_once (400 named attachments, 400 GoToE links) stays under 16,000 object reads; with the per-link scan restored it reads 83,410. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pq7HyCfwzyRXj4VfQAVVdv --- crates/automation/src/links.rs | 2 +- crates/render/src/inspect.rs | 2 +- crates/render/src/inspect/annotations.rs | 24 ++++++++++---- crates/render/src/inspect/core.rs | 8 ++++- crates/render/src/inspect/resources.rs | 7 ++++ crates/render/src/inspect/tests.rs | 41 ++++++++++++++++++++++++ crates/render/src/lib.rs | 3 +- crates/ui-egui/src/app/links.rs | 8 +---- 8 files changed, 77 insertions(+), 18 deletions(-) diff --git a/crates/automation/src/links.rs b/crates/automation/src/links.rs index 65124bd12d..c8d83a7236 100644 --- a/crates/automation/src/links.rs +++ b/crates/automation/src/links.rs @@ -179,7 +179,7 @@ impl Automation { (att.name.clone(), bytes) }; // "Embedded go-to actions work only for files of Type PDF" (§12.6.4.4). - if !bytes.get(..bytes.len().min(1024)).is_some_and(|head| head.windows(5).any(|w| w == b"%PDF-")) { + if !pdfcraft_render::looks_like_pdf(&bytes) { return Err(failed(format!("{name} is not a PDF, so the GoToE link can't open it"))); } let id = self.session.open(name.clone(), None, std::sync::Arc::new(bytes), a.opt_str("password")?).map_err(failed)?; diff --git a/crates/render/src/inspect.rs b/crates/render/src/inspect.rs index 0cf287b3f1..8807fdbdc7 100644 --- a/crates/render/src/inspect.rs +++ b/crates/render/src/inspect.rs @@ -41,7 +41,7 @@ pub use model::{ }; #[cfg(test)] use navigation::{OUTLINE_DEPTH, OUTLINE_WINDOW}; -pub use resources::attachment_data; +pub use resources::{attachment_data, looks_like_pdf}; #[cfg(test)] use resources::{xfa_config_dynamic_render, xfa_packet_text}; diff --git a/crates/render/src/inspect/annotations.rs b/crates/render/src/inspect/annotations.rs index dace729e3d..394d637687 100644 --- a/crates/render/src/inspect/annotations.rs +++ b/crates/render/src/inspect/annotations.rs @@ -1,7 +1,7 @@ use super::core::{limited_pdf_string, pretty_date, spend}; use super::model::{Annotation, AttachmentSource, DestView, Field, FieldKind, LayerOp, Link, LinkTarget, RemoteDestination, link_replies}; use super::navigation::text_string; -use super::{Dictionary, DocInfo, Entry, HashMap, HashSet, Inspector, Object, ObjectId}; +use super::{Dictionary, DocInfo, Entry, HashMap, HashSet, Inspector, Object, ObjectId, OnceCell}; /// At most this many `/State` entries of a set-layer-visibility action are read. const MAX_LAYER_STATE: usize = 1024; @@ -299,12 +299,22 @@ impl<'a> Inspector<'a> { /// The position in page `page`'s `/Annots` of the first annotation whose `/NM` is `nm`. fn annotation_named(&self, page: usize, nm: &[u8]) -> Option { - let id = *self.page_ids.get(page)?; - let page = self.doc.get_dictionary(id).ok()?; - let Object::Array(annots) = self.resolve(page.get(b"Annots").ok()?) else { return None }; - annots.iter().position(|a| { - self.dict(a).and_then(|d| d.get(b"NM").ok()).is_some_and(|n| matches!(self.resolve(n), Object::String(b, _) if b.as_slice() == nm)) - }) + let pages = self.annotation_names.get_or_init(|| self.page_ids.iter().map(|_| OnceCell::new()).collect()); + pages.get(page)?.get_or_init(|| self.annotation_names_on(page)).get(nm).copied() + } + + /// Each `/NM` on page `page`, with the position in its `/Annots` of the first annotation + /// that has it. + fn annotation_names_on(&self, page: usize) -> super::core::AnnotationNames { + let mut names = HashMap::new(); + let Some(page) = self.page_ids.get(page).and_then(|id| self.doc.get_dictionary(*id).ok()) else { return names }; + let Some(Object::Array(annots)) = page.get(b"Annots").ok().map(|a| self.resolve(a)) else { return names }; + for (i, a) in annots.iter().enumerate() { + if let Some(Object::String(nm, _)) = self.dict(a).and_then(|d| d.get(b"NM").ok()).map(|n| self.resolve(n)) { + names.entry(nm.clone()).or_insert(i); + } + } + names } /// The non-empty local file an action's `/F` names (a string or a file specification), shared diff --git a/crates/render/src/inspect/core.rs b/crates/render/src/inspect/core.rs index c190dc565b..d7c1145528 100644 --- a/crates/render/src/inspect/core.rs +++ b/crates/render/src/inspect/core.rs @@ -133,6 +133,9 @@ pub(super) fn inspect_structure(info: &mut DocInfo, fill: impl FnOnce(&mut DocIn } } +/// One page's annotations by `/NM`: the position in `/Annots` of the first one with each name. +pub(super) type AnnotationNames = HashMap, usize>; + pub(super) struct Inspector<'a> { pub(super) doc: &'a dyn Structure, pub(super) page_ids: Vec, @@ -144,13 +147,16 @@ pub(super) struct Inspector<'a> { /// has no `/P`. Searching every page's `/Annots` for each such field was O(fields × /// annotations): a second on a form of 8,000 fields. pub(super) annotation_pages: OnceCell>, + /// Per page, the position in `/Annots` of the first annotation with each `/NM`, built when a + /// GoToE target names one. Scanning `/Annots` for each link was O(links × annotations). + pub(super) annotation_names: OnceCell>>, } impl<'a> Inspector<'a> { pub(super) fn new(doc: &'a dyn Structure) -> Self { let page_ids = doc.page_ids(); let page_index = page_ids.iter().copied().enumerate().map(|(index, id)| (id, index)).collect(); - let mut me = Self { doc, page_ids, page_index, named: HashMap::new(), annotation_pages: OnceCell::new() }; + let mut me = Self { doc, page_ids, page_index, named: HashMap::new(), annotation_pages: OnceCell::new(), annotation_names: OnceCell::new() }; let mut named = HashMap::new(); if let Some(tree) = doc.catalog().ok().and_then(|c| c.get(b"Names").ok()).and_then(|o| me.dict(o)).and_then(|n| n.get(b"Dests").ok()).and_then(|o| me.dict(o)) diff --git a/crates/render/src/inspect/resources.rs b/crates/render/src/inspect/resources.rs index 0895c64f8a..39a20b691c 100644 --- a/crates/render/src/inspect/resources.rs +++ b/crates/render/src/inspect/resources.rs @@ -231,6 +231,13 @@ impl<'a> Inspector<'a> { } } +/// Whether `bytes` (an attachment's, from [`attachment_data`]) are a PDF file: the `%PDF-` +/// header (ISO 32000-2 §7.5.2) within their first 1024 bytes. Embedded go-to actions open only +/// these (§12.6.4.4). +pub fn looks_like_pdf(bytes: &[u8]) -> bool { + bytes.get(..bytes.len().min(1024)).is_some_and(|head| head.windows(5).any(|w| w == b"%PDF-")) +} + /// Fetch an attachment's bytes (decoded). Capped at 1 GiB to defuse decompression bombs. pub fn attachment_data(bytes: &[u8], password: Option<&str>, att: &Attachment) -> Result, String> { let run = || -> Result, String> { diff --git a/crates/render/src/inspect/tests.rs b/crates/render/src/inspect/tests.rs index ef97f77a57..d3da02548b 100644 --- a/crates/render/src/inspect/tests.rs +++ b/crates/render/src/inspect/tests.rs @@ -1310,6 +1310,47 @@ fn links_read_embedded_go_to_actions_to_attached_pdfs() { ); } +/// Many GoToE links naming a file attachment annotation by `/NM` read the page's annotations +/// once, not once per link, and a repeated `/NM` is the first annotation that has it. +#[test] +fn embedded_go_to_links_by_annotation_name_read_the_page_once() { + const N: usize = 400; + let att = |k: usize| 10 + k; + let link = |k: usize| 10 + N + k; + let mut pdf = + String::from("%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n"); + let annots: Vec = (0..N).map(att).chain((0..N).map(link)).map(|o| format!("{o} 0 R")).collect(); + pdf += &format!("3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [{}] >> endobj\n", annots.join(" ")); + for k in 0..N { + // The last two attachments share a name: the first of them is the one named. + let name = if k == N - 1 { N - 2 } else { k }; + pdf += &format!("{} 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 1 1] /NM (a{name}) >> endobj\n", att(k)); + } + for k in 0..N { + pdf += + &format!("{} 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 1 1] /A << /S /GoToE /T << /R /C /P 0 /A (a{k}) >> >> >> endobj\n", link(k)); + } + pdf += "trailer << /Root 1 0 R >>\n%%EOF"; + let doc = Document::load_mem(pdf.as_bytes()).expect("loads"); + let counting = CountingReads { doc: &doc, reads: std::cell::Cell::new(0) }; + let page = PageInfo { width: 200.0, height: 200.0, crop: [0.0, 0.0, 200.0, 200.0], rotation: 0, label: String::new() }; + let mut info = DocInfo { pages: vec![page], ..Default::default() }; + Inspector::new(&counting).fill(&mut info); + let indexes: Vec> = info + .links + .iter() + .map(|l| match &l.target { + LinkTarget::EmbeddedGoTo { source: AttachmentSource::Annotation { page: 0, index }, .. } => Some(*index), + _ => None, + }) + .collect(); + let want: Vec> = (0..N).map(|k| (k < N - 1).then_some(k)).collect(); + assert_eq!(indexes, want); + // A handful of reads per annotation; scanning `/Annots` for each link read about 80,000. + let reads = counting.reads.get(); + assert!(reads < 20 * 2 * N, "{reads} object reads"); +} + #[test] fn links_read_bounded_local_remote_go_to_actions() { use DestView::{Fit, Xyz}; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 6f9a3ac319..9bba9e4f9c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -19,7 +19,8 @@ pub mod transition; pub use inspect::{ Annotation, Attachment, AttachmentSource, DestView, DocInfo, Field, FieldKind, FontInfo, Layer, LayerOp, Link, LinkTarget, OutlineItem, PageInfo, - PageTransition, RemoteDestination, TransitionStyle, Xfa, attachment_data, check_pages, inspect, link_replies, pretty_date, thread_tops, + PageTransition, RemoteDestination, TransitionStyle, Xfa, attachment_data, check_pages, inspect, link_replies, looks_like_pdf, pretty_date, + thread_tops, }; pub use pixels::Pixels; pub use raster::{ diff --git a/crates/ui-egui/src/app/links.rs b/crates/ui-egui/src/app/links.rs index 139d1db85e..c1da5fb441 100644 --- a/crates/ui-egui/src/app/links.rs +++ b/crates/ui-egui/src/app/links.rs @@ -89,7 +89,7 @@ impl PdfCraftApp { }; // "Embedded go-to actions work only for files of Type PDF" (§12.6.4.4). Checked here, as // the Attachments panel's Open would turn a picture or text file into a new PDF. - if !looks_like_pdf(&bytes) { + if !pdfcraft_render::looks_like_pdf(&bytes) { self.notify_fmt("{name} isn't a PDF, so the link can't open it.", &[("name", &att.name)]); return; } @@ -162,9 +162,3 @@ impl PdfCraftApp { } } } - -/// Whether `bytes` are a PDF file: the `%PDF-` header (ISO 32000-2 §7.5.2) within their first -/// 1024 bytes. -fn looks_like_pdf(bytes: &[u8]) -> bool { - bytes.get(..bytes.len().min(1024)).is_some_and(|head| head.windows(5).any(|w| w == b"%PDF-")) -} From 3ab3dde44892a5cb0d5dd48b15600643b87f6678 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:39:30 +0800 Subject: [PATCH 010/114] M3: the GoToE /NM indexes share a byte budget, and a long /NM is scanned for Each page's /NM index copied every name it held. One /Annots array or one long name that many pages share was copied and hashed again for every page a GoToE target named, with no limit. Names over 1 KiB are no longer indexed: a target naming one is found by scanning the page. All the indexes together spend at most 16 MiB of name bytes (with a slot per entry); a page that does not fit what is left keeps no index and is scanned for each name instead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pq7HyCfwzyRXj4VfQAVVdv --- crates/render/src/inspect/annotations.rs | 56 +++++++++++++++--- crates/render/src/inspect/core.rs | 21 +++++-- crates/render/src/inspect/tests.rs | 72 ++++++++++++++++++++++++ 3 files changed, 136 insertions(+), 13 deletions(-) diff --git a/crates/render/src/inspect/annotations.rs b/crates/render/src/inspect/annotations.rs index 394d637687..39ac45ab0f 100644 --- a/crates/render/src/inspect/annotations.rs +++ b/crates/render/src/inspect/annotations.rs @@ -22,6 +22,14 @@ pub(super) const MAX_ANNOTATION_BYTES: usize = 64 << 20; /// key does not fit is not listed. pub(super) const MAX_LINK_ATTACHMENT_TEXT_BYTES: usize = 16 << 20; +/// `/NM` bytes, with a slot per entry, that the per-page annotation-name indexes for GoToE targets +/// hash in all. One `/Annots` array or one long name many pages share would otherwise be hashed +/// again for each page; past it a page is scanned for each name instead. +pub(super) const MAX_ANNOTATION_NAME_INDEX_BYTES: usize = 16 << 20; + +/// A longer `/NM` is not indexed: it is scanned for. Real names are short identifiers. +const MAX_INDEXED_ANNOTATION_NAME_BYTES: usize = 1024; + /// The bytes a listed annotation keeps. pub(super) fn retained(a: &Annotation) -> usize { let text = [&a.author, &a.contents, &a.modified, &a.name, &a.in_reply_to, &a.state, &a.intent]; @@ -300,21 +308,51 @@ impl<'a> Inspector<'a> { /// The position in page `page`'s `/Annots` of the first annotation whose `/NM` is `nm`. fn annotation_named(&self, page: usize, nm: &[u8]) -> Option { let pages = self.annotation_names.get_or_init(|| self.page_ids.iter().map(|_| OnceCell::new()).collect()); - pages.get(page)?.get_or_init(|| self.annotation_names_on(page)).get(nm).copied() + let names = pages.get(page)?.get_or_init(|| self.annotation_names_on(page)); + match names { + // A name longer than an indexed one is not in the index: scanned for. + Some(names) if nm.len() <= MAX_INDEXED_ANNOTATION_NAME_BYTES => names.get(nm).copied(), + _ => self.annotations_on(page)?.iter().position(|a| self.annotation_name(a) == Some(nm)), + } } - /// Each `/NM` on page `page`, with the position in its `/Annots` of the first annotation - /// that has it. + /// Each `/NM` on page `page` up to [`MAX_INDEXED_ANNOTATION_NAME_BYTES`] long, with the + /// position in its `/Annots` of the first annotation that has it, spent from + /// `annotation_name_budget`. `None` once the budget does not cover the page. fn annotation_names_on(&self, page: usize) -> super::core::AnnotationNames { let mut names = HashMap::new(); - let Some(page) = self.page_ids.get(page).and_then(|id| self.doc.get_dictionary(*id).ok()) else { return names }; - let Some(Object::Array(annots)) = page.get(b"Annots").ok().map(|a| self.resolve(a)) else { return names }; + let Some(annots) = self.annotations_on(page) else { return Some(names) }; + let mut budget = self.annotation_name_budget.get(); for (i, a) in annots.iter().enumerate() { - if let Some(Object::String(nm, _)) = self.dict(a).and_then(|d| d.get(b"NM").ok()).map(|n| self.resolve(n)) { - names.entry(nm.clone()).or_insert(i); - } + let Some(nm) = self.annotation_name(a).filter(|nm| nm.len() <= MAX_INDEXED_ANNOTATION_NAME_BYTES) else { continue }; + // Each entry costs its name and its slot, so many short names are bounded too. + let Some(left) = budget.checked_sub(nm.len().saturating_add(std::mem::size_of::<(Vec, usize)>())) else { + // What the page used so far is spent; nothing of it is kept. + self.annotation_name_budget.set(budget); + return None; + }; + budget = left; + names.entry(nm.to_vec()).or_insert(i); + } + self.annotation_name_budget.set(budget); + Some(names) + } + + /// Page `page`'s `/Annots`. + fn annotations_on(&self, page: usize) -> Option<&'a [Object]> { + let page = self.doc.get_dictionary(*self.page_ids.get(page)?).ok()?; + match self.resolve(page.get(b"Annots").ok()?) { + Object::Array(annots) => Some(annots), + _ => None, + } + } + + /// An annotation's `/NM` string bytes. + fn annotation_name(&self, a: &'a Object) -> Option<&'a [u8]> { + match self.resolve(self.dict(a)?.get(b"NM").ok()?) { + Object::String(nm, _) => Some(nm), + _ => None, } - names } /// The non-empty local file an action's `/F` names (a string or a file specification), shared diff --git a/crates/render/src/inspect/core.rs b/crates/render/src/inspect/core.rs index d7c1145528..bf69c19a04 100644 --- a/crates/render/src/inspect/core.rs +++ b/crates/render/src/inspect/core.rs @@ -1,10 +1,11 @@ -use super::annotations::MAX_LINK_ATTACHMENT_TEXT_BYTES; +use super::annotations::{MAX_ANNOTATION_NAME_INDEX_BYTES, MAX_LINK_ATTACHMENT_TEXT_BYTES}; use super::model::{AttachmentSource, PageInfo, Xfa}; use super::navigation::text_string; use super::{ Arc, AssertUnwindSafe, DecryptionError, Dictionary, DocInfo, Document, HashMap, HashSet, LazyStructure, LoadOptions, LoadPdfError, Object, ObjectId, OnceCell, OpenError, Pdf, Structure, catch_unwind, }; +use std::cell::Cell; /// lopdf decodes object and cross-reference streams while it loads, with no limit unless one is /// set: a few hundred bytes of nested FlateDecode then inflate to gigabytes. Real object and @@ -133,8 +134,10 @@ pub(super) fn inspect_structure(info: &mut DocInfo, fill: impl FnOnce(&mut DocIn } } -/// One page's annotations by `/NM`: the position in `/Annots` of the first one with each name. -pub(super) type AnnotationNames = HashMap, usize>; +/// The names are copies (borrowing them would make `Inspector` invariant in its lifetime), each +/// short, and all of them within [`MAX_ANNOTATION_NAME_INDEX_BYTES`]. `None` when the page's names +/// did not fit what was left of it: that page is scanned for each name instead. +pub(super) type AnnotationNames = Option, usize>>; pub(super) struct Inspector<'a> { pub(super) doc: &'a dyn Structure, @@ -150,13 +153,23 @@ pub(super) struct Inspector<'a> { /// Per page, the position in `/Annots` of the first annotation with each `/NM`, built when a /// GoToE target names one. Scanning `/Annots` for each link was O(links × annotations). pub(super) annotation_names: OnceCell>>, + /// What is left of [`MAX_ANNOTATION_NAME_INDEX_BYTES`] for `annotation_names`. + pub(super) annotation_name_budget: Cell, } impl<'a> Inspector<'a> { pub(super) fn new(doc: &'a dyn Structure) -> Self { let page_ids = doc.page_ids(); let page_index = page_ids.iter().copied().enumerate().map(|(index, id)| (id, index)).collect(); - let mut me = Self { doc, page_ids, page_index, named: HashMap::new(), annotation_pages: OnceCell::new(), annotation_names: OnceCell::new() }; + let mut me = Self { + doc, + page_ids, + page_index, + named: HashMap::new(), + annotation_pages: OnceCell::new(), + annotation_names: OnceCell::new(), + annotation_name_budget: Cell::new(MAX_ANNOTATION_NAME_INDEX_BYTES), + }; let mut named = HashMap::new(); if let Some(tree) = doc.catalog().ok().and_then(|c| c.get(b"Names").ok()).and_then(|o| me.dict(o)).and_then(|n| n.get(b"Dests").ok()).and_then(|o| me.dict(o)) diff --git a/crates/render/src/inspect/tests.rs b/crates/render/src/inspect/tests.rs index d3da02548b..a2fd612018 100644 --- a/crates/render/src/inspect/tests.rs +++ b/crates/render/src/inspect/tests.rs @@ -1351,6 +1351,78 @@ fn embedded_go_to_links_by_annotation_name_read_the_page_once() { assert!(reads < 20 * 2 * N, "{reads} object reads"); } +/// The `/NM` indexes for GoToE targets stay within `MAX_ANNOTATION_NAME_INDEX_BYTES` when many +/// pages share one `/Annots` array holding one very long name and many short ones, and every +/// target still resolves: the long name and the pages past the budget are scanned instead. +#[test] +fn embedded_go_to_annotation_name_indexes_share_a_byte_budget() { + use super::annotations::MAX_ANNOTATION_NAME_INDEX_BYTES; + const PAGES: usize = 32; + const SHORT: usize = 1100; + let page = |k: usize| 100 + k; + let short = |j: usize| 1000 + j; + let link = |k: usize, which: usize| 10_000 + 2 * k + which; + let links_page = page(PAGES); + let kids: Vec = (0..=PAGES).map(|k| format!("{} 0 R", page(k))).collect(); + let mut pdf = format!( + "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [{}] /Count {} >> endobj\n", + kids.join(" "), + PAGES + 1 + ); + let shared: Vec = std::iter::once(6).chain((0..SHORT).map(short)).map(|o| format!("{o} 0 R")).collect(); + pdf += &format!("4 0 obj [{}] endobj\n", shared.join(" ")); + // One name of a mebibyte, which every page's index would otherwise hash. + pdf += &format!("7 0 obj ({}) endobj\n", "x".repeat(1 << 20)); + pdf += "6 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 1 1] /NM 7 0 R >> endobj\n"; + for j in 0..SHORT { + pdf += &format!("{} 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 1 1] /NM (n{j:0>999}) >> endobj\n", short(j)); + } + for k in 0..PAGES { + pdf += &format!("{} 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots 4 0 R >> endobj\n", page(k)); + } + let links: Vec = (0..PAGES).flat_map(|k| [link(k, 0), link(k, 1)]).map(|o| format!("{o} 0 R")).collect(); + pdf += &format!("{links_page} 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [{}] >> endobj\n", links.join(" ")); + let target = |k: usize| (k * 37) % SHORT; + for k in 0..PAGES { + let action = |a: String| format!("<< /S /GoToE /T << /R /C /P {k} /A {a} >> /D [0 /Fit] >>"); + pdf += &format!("{} 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 1 1] /A {} >> endobj\n", link(k, 0), action("7 0 R".into())); + pdf += &format!( + "{} 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 1 1] /A {} >> endobj\n", + link(k, 1), + action(format!("(n{:0>999})", target(k))) + ); + } + pdf += "trailer << /Root 1 0 R >>\n%%EOF"; + let doc = Document::load_mem(pdf.as_bytes()).expect("loads"); + let blank = PageInfo { width: 200.0, height: 200.0, crop: [0.0, 0.0, 200.0, 200.0], rotation: 0, label: String::new() }; + let mut info = DocInfo { pages: vec![blank; PAGES + 1], ..Default::default() }; + let inspector = Inspector::new(&doc); + inspector.fill(&mut info); + let indexes: Vec<(usize, usize)> = info + .links + .iter() + .filter_map(|l| match &l.target { + LinkTarget::EmbeddedGoTo { source: AttachmentSource::Annotation { page, index }, .. } => Some((*page, *index)), + _ => None, + }) + .collect(); + let want: Vec<(usize, usize)> = (0..PAGES).flat_map(|k| [(k, 0), (k, 1 + target(k))]).collect(); + assert_eq!(indexes, want); + let indexed: Vec = inspector + .annotation_names + .get() + .into_iter() + .flatten() + .filter_map(|page| page.get().cloned().flatten()) + .flat_map(|names| names.into_keys()) + .map(|name| name.len()) + .collect(); + let total: usize = indexed.iter().sum(); + assert!(total > 0 && total <= MAX_ANNOTATION_NAME_INDEX_BYTES, "{total} name bytes indexed"); + // The mebibyte name is scanned for, never copied into an index. + assert!(indexed.iter().all(|&len| len < 1 << 20), "the long name was indexed"); +} + #[test] fn links_read_bounded_local_remote_go_to_actions() { use DestView::{Fit, Xyz}; From 205c7868eef6b1d3bd1a50eb5da22daf7464251e Mon Sep 17 00:00:00 2001 From: Muhammad Saad Date: Sun, 18 Oct 2026 23:52:07 +0400 Subject: [PATCH 011/114] M10: put image pages on a chosen paper size (#3273) A photo becomes a page as large as its pixels, so a 4000 x 3000 phone picture with no stored resolution gives a 4000 x 3000 pt page, about 1.41 x 1.06 m, and a set of photos of different pixel sizes gives pages of several sizes, none of them paper. doc_create (from: images) and doc_create_multiple (both modes) now take page_size: a paper name, resolved against the table pdfcraft-print already owns, or [width, height] in points. The image is scaled to fit, centred, and the sheet is turned to match its orientation unless page_turn is false. A square image never turns the sheet. ImagePage::Image keeps the old behaviour and is the default, so every existing caller writes the same file as before. The paper-name match moves out of doc_print into printing::paper_named, so Create and Print answer the same names rather than growing a second list. doc_combine converts its sources inside combine_unlocked_reporting and combine_grouped_reporting, so it would need those signatures changed; it is left for a follow-up and the parity note says so. --- crates/automation/src/assemble.rs | 26 ++++++- crates/automation/src/printing.rs | 5 +- crates/automation/src/tools.rs | 8 ++- crates/automation/tests/it/automation.rs | 60 ++++++++++++++++ crates/create/src/lib.rs | 58 +++++++++++++++- crates/create/src/tests.rs | 87 ++++++++++++++++++++++++ crates/engine/src/lib.rs | 2 +- crates/engine/src/session.rs | 2 +- crates/engine/src/session/files.rs | 27 ++++++-- parity/acrobat-features.toml | 4 +- 10 files changed, 263 insertions(+), 16 deletions(-) diff --git a/crates/automation/src/assemble.rs b/crates/automation/src/assemble.rs index deb2efa18a..6e9af489c1 100644 --- a/crates/automation/src/assemble.rs +++ b/crates/automation/src/assemble.rs @@ -4,6 +4,23 @@ use super::paths::{child, read_input, read_input_bytes, unused, write_atomic}; use super::{Arc, Automation, CombineSource, Edit, Path, PathBuf, Value, json}; impl Automation { + /// The sheet image pages go on: `page_size` as a paper name ("A4", "Letter", "ARCH C") or + /// `[width, height]` in points, with the image scaled to fit and centred. Absent, each page + /// is the size of its own image, which is what a phone photo's pixels give. + fn image_page(a: &Args) -> Result { + let turn = a.opt_bool("page_turn")?.unwrap_or(true); + let bad = || ToolError::InvalidArgs("page_size must be a paper name or [width, height] in points".into()); + match a.get("page_size") { + None | Some(Value::Null) => Ok(pdfcraft_engine::ImagePage::Image), + Some(Value::String(s)) => Ok(pdfcraft_engine::ImagePage::fixed(super::printing::paper_named(Some(s))?.1, turn)), + Some(Value::Array(v)) if v.len() == 2 => { + let side = |i: usize| v.get(i).and_then(Value::as_f64).ok_or_else(bad); + Ok(pdfcraft_engine::ImagePage::fixed((side(0)?, side(1)?), turn)) + } + Some(_) => Err(bad()), + } + } + pub(crate) fn doc_create(&mut self, a: &Args) -> Result { let (name, bytes) = match a.str("from")? { "blank" => { @@ -24,7 +41,7 @@ impl Automation { } else { "Images.pdf".into() }; - (name, self.session.create_from_images_with_resolution(&images, resolution).map_err(failed)?) + (name, self.session.create_from_images_with(&images, resolution, Self::image_page(a)?).map_err(failed)?) } "text" => { let (title, text) = match (a.opt_str("text")?, a.opt_str("path")?) { @@ -200,11 +217,12 @@ impl Automation { Some(_) => return Err(ToolError::InvalidArgs("pages must list a range (or null) for each path".into())), }; // Each file is read, converted and copied in turn, so a long list holds one file at a time. + let page = Self::image_page(a)?; let sources = paths.into_iter().zip(ranges).map(|(p, range)| -> std::result::Result { let path = self.resolve(p, false)?; let bytes = read_input(&path)?; let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - let (_, pdf) = self.session.convert_to_pdf(&name, &Arc::new(bytes)).map_err(failed)?; + let (_, pdf) = self.session.convert_to_pdf_with(&name, &Arc::new(bytes), page).map_err(failed)?; let title = path.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); Ok((title, pdf, range)) }); @@ -215,6 +233,8 @@ impl Automation { /// One PDF per file, written into `out_dir`; a file that fails doesn't stop the others. fn create_separate(&mut self, a: &Args, paths: &[&str]) -> Result { let dir = self.resolve(a.str("out_dir").map_err(|_| ToolError::InvalidArgs("mode \"separate\" needs out_dir".into()))?, true)?; + // Checked before the folder is made, so a bad page_size leaves nothing behind. + let page = Self::image_page(a)?; std::fs::create_dir_all(&dir).map_err(|e| failed(format!("{}: {e}", dir.display())))?; let mut out = Vec::new(); for &p in paths { @@ -222,7 +242,7 @@ impl Automation { let bytes = read_input_bytes(&src).map_err(|e| format!("{}: {e}", src.display()))?; let name = src.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); let stem = src.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "document".into()); - let (kind, pdf) = self.session.convert_to_pdf(&name, &Arc::new(bytes)).map_err(|e| e.to_string())?; + let (kind, pdf) = self.session.convert_to_pdf_with(&name, &Arc::new(bytes), page).map_err(|e| e.to_string())?; Ok((kind, stem, pdf)) }); out.push(match converted { diff --git a/crates/automation/src/printing.rs b/crates/automation/src/printing.rs index 9a1c1a6b7c..382a919a9d 100644 --- a/crates/automation/src/printing.rs +++ b/crates/automation/src/printing.rs @@ -39,7 +39,10 @@ fn bad(m: impl Into) -> ToolError { /// `doc_print`'s `paper`, by its name or a short form ("Letter", "ARCH D"), as its `PAPERS` /// index and size; US Letter when none is given. -fn paper_named(name: Option<&str>) -> Result<(usize, (f64, f64))> { +/// +/// `pub(crate)` so Create answers the same names as Print: `doc_create` takes a `page_size` that +/// may be a paper name, and a second copy of this table would drift from this one. +pub(crate) fn paper_named(name: Option<&str>) -> Result<(usize, (f64, f64))> { let mut papers = PAPERS.iter().enumerate(); let found = match name { None => papers.next(), diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index c6c200cece..3d70705da9 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -260,12 +260,13 @@ pub fn tools() -> Vec { "passwords": { "type": "array", "items": { "type": ["string", "null"] } }, "groups": { "type": "array", "items": { "type": ["integer", "null"], "minimum": 0 } }, "field_conflicts": { "type": "string", "enum": ["rename", "merge"] }, + "out": save_out, "open": open, }), &["paths"], )), - t("doc_create_multiple", "Create PDF from multiple files", "Convert several files (PDFs, PNG/JPEG/JPEG 2000/TIFF/GIF/BMP images, .txt files) to PDF in one run. mode \"combine\" (default) joins them, in order, into one PDF with a bookmark per file; pages optionally chooses each file's pages, in step with paths (a range such as \"1-3, 6\" or null). mode \"separate\" writes one PDF per file into out_dir (files that are already PDFs are skipped; existing files are never overwritten) and reports each file's result.") + t("doc_create_multiple", "Create PDF from multiple files", "Convert several files (PDFs, PNG/JPEG/JPEG 2000/TIFF/GIF/BMP images, .txt files) to PDF in one run; page_size puts each image on a sheet of one size instead of a page as large as the image. mode \"combine\" (default) joins them, in order, into one PDF with a bookmark per file; pages optionally chooses each file's pages, in step with paths (a range such as \"1-3, 6\" or null). mode \"separate\" writes one PDF per file into out_dir (files that are already PDFs are skipped; existing files are never overwritten) and reports each file's result.") .cmd("create.multiple") .with(schema( json!({ @@ -275,6 +276,8 @@ pub fn tools() -> Vec { "out": save_out.clone(), "open": open.clone(), "out_dir": { "type": "string", "description": "Folder for mode \"separate\"." }, + "page_size": { "type": ["string", "array"], "items": { "type": "number", "minimum": 3 }, "minItems": 2, "maxItems": 2, "description": "For image files: put each image on a sheet of this size instead of a page as large as the image. A paper name (A4, Letter, Legal, Tabloid, A0-A6, ARCH A-E, ANSI C-E) or [width, height] in points; the image is scaled to fit and centred." }, + "page_turn": { "type": "boolean", "description": "With page_size: turn the sheet to match each image's orientation, so a landscape photo gets a landscape page (default true)." }, }), &["paths"], )), @@ -1337,6 +1340,9 @@ pub fn tools() -> Vec { "width": { "type": "number", "minimum": 3 }, "height": { "type": "number", "minimum": 3 }, "name": { "type": "string", "description": "Name for the new document (default derived from the source)." }, + "page_size": { "type": ["string", "array"], "items": { "type": "number", "minimum": 3 }, "minItems": 2, "maxItems": 2, "description": "For image files: put each image on a sheet of this size instead of a page as large as the image. A paper name (A4, Letter, Legal, Tabloid, A0-A6, ARCH A-E, ANSI C-E) or [width, height] in points; the image is scaled to fit and centred." }, + "page_turn": { "type": "boolean", "description": "With page_size: turn the sheet to match each image's orientation, so a landscape photo gets a landscape page (default true)." }, + }), &["from"], )), diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 6a5765b911..8f6394715a 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -9414,6 +9414,66 @@ fn text_box_and_callout_fill_and_border_through_tools() { } } +/// #3273: images became pages as large as their pixels, so a set of photos gave pages of several +/// sizes and none of them paper. `page_size` puts them all on one sheet, scaled to fit. +#[test] +fn image_pages_go_on_a_chosen_paper_size_through_every_create_tool() { + let dir = workdir("image-page-size"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + // Two pictures of different shapes, from the fixture's own pages. + ok(&mut a, "doc_export_images", json!({ "doc": doc, "folder": "src", "dpi": 18, "pages": [1, 2] })); + let shots = ["src/a_page_1.png", "src/a_page_2.png"]; + let size = |a: &mut Automation, d: u64, page: usize| -> (f64, f64) { + let p = &ok(a, "doc_info", json!({ "doc": d }))["pages"][page]; + (p["width"].as_f64().unwrap(), p["height"].as_f64().unwrap()) + }; + const A4: (f64, f64) = (595.28, 841.89); + let close = |got: (f64, f64), want: (f64, f64)| (got.0 - want.0).abs() < 0.01 && (got.1 - want.1).abs() < 0.01; + + // Without it, pages follow the pixels, as they always have. + let plain = ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots }))["doc"].as_u64().unwrap(); + assert!(!close(size(&mut a, plain, 0), A4), "the default is unchanged: {:?}", size(&mut a, plain, 0)); + + // doc_create: a paper name, with the sheet turned to each image by default. + let named = ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots, "page_size": "A4" }))["doc"].as_u64().unwrap(); + for page in 0..2 { + let got = size(&mut a, named, page); + assert!(close(got, A4) || close(got, (A4.1, A4.0)), "page {page} is an A4 sheet either way up: {got:?}"); + } + // page_turn: false pins the orientation, so every page is portrait A4. + let pinned = + ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots, "page_size": "A4", "page_turn": false }))["doc"].as_u64().unwrap(); + for page in 0..2 { + assert!(close(size(&mut a, pinned, page), A4), "page {page}: {:?}", size(&mut a, pinned, page)); + } + // An explicit size in points works too, and the names Print accepts are accepted here. + let explicit = + ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots, "page_size": [300, 300], "page_turn": false }))["doc"].as_u64().unwrap(); + assert!(close(size(&mut a, explicit, 0), (300.0, 300.0))); + let letter = + ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots, "page_size": "Letter", "page_turn": false }))["doc"].as_u64().unwrap(); + assert!(close(size(&mut a, letter, 0), (612.0, 792.0))); + + // doc_create_multiple takes it as well. + ok(&mut a, "doc_create_multiple", json!({ "paths": shots, "page_size": "A4", "page_turn": false, "out": "multiple.pdf" })); + let multiple = ok(&mut a, "doc_open", json!({ "path": "multiple.pdf" }))["doc"].as_u64().unwrap(); + assert!(close(size(&mut a, multiple, 0), A4) && close(size(&mut a, multiple, 1), A4)); + + // mode "separate" writes one PDF per image, each on the sheet. + ok(&mut a, "doc_create_multiple", json!({ "paths": shots, "mode": "separate", "out_dir": "out", "page_size": "A4", "page_turn": false })); + let one = ok(&mut a, "doc_open", json!({ "path": "out/a_page_1.pdf" }))["doc"].as_u64().unwrap(); + assert!(close(size(&mut a, one, 0), A4)); + + // A size that is not a paper name or a pair of points is refused, on every tool. + for bad in [json!("A9"), json!([300]), json!(["a", "b"]), json!(5), json!({})] { + assert!( + matches!(a.call("doc_create", &json!({ "from": "images", "paths": shots, "page_size": bad })), Err(ToolError::InvalidArgs(_))), + "{bad} should be refused" + ); + } +} + /// Three paragraphs: Alpha (two rows), Bravo (one row) and Charlie (two rows), at the leading /// of #2516. Alpha's last baseline is 35.6 pt above Bravo's; moving Alpha down 21.2 pt leaves /// 14.4 pt, Alpha's own leading, so the next read groups the two as one paragraph. diff --git a/crates/create/src/lib.rs b/crates/create/src/lib.rs index 36b52d4211..ed978de807 100644 --- a/crates/create/src/lib.rs +++ b/crates/create/src/lib.rs @@ -659,6 +659,53 @@ pub enum ImageResolution { Dpi(f64), } +/// How the page an image is placed on is sized. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub enum ImagePage { + /// The page is the image's own size at its resolution, so a page is as large as its photo + /// (a 4000 × 3000 phone picture with no stored resolution gives a 4000 × 3000 pt page). + #[default] + Image, + /// Every page is this size in points, with the image scaled to fit inside it and centred, + /// so a set of photos of different pixel sizes gives one paper size throughout. + Fixed { + width: f64, + height: f64, + /// Turn the sheet to match each image, so a landscape photo gets a landscape page + /// instead of being shrunk into a portrait one. + turn: bool, + }, +} + +impl ImagePage { + /// A4, Letter and the rest are resolved by the caller: the paper table lives in + /// `pdfcraft-print`, which is this crate's own layer, so names are parsed above both. + pub fn fixed(size: (f64, f64), turn: bool) -> Self { + Self::Fixed { width: size.0, height: size.1, turn } + } + + fn check(self) -> Result<(), CreateError> { + let Self::Fixed { width, height, .. } = self else { return Ok(()) }; + if !(width.is_finite() && height.is_finite() && (3.0..=MAX_SIDE).contains(&width) && (3.0..=MAX_SIDE).contains(&height)) { + return Err(CreateError::Invalid(format!("the page must be between 3 and {MAX_SIDE} points on each side"))); + } + Ok(()) + } + + /// The page `(width, height)` for an image of `(w, h)` points, and where to draw it: + /// `(scaled width, scaled height, x, y)`. + fn place(self, w: f64, h: f64) -> ((f64, f64), (f64, f64, f64, f64)) { + let Self::Fixed { width, height, turn } = self else { return ((w, h), (w, h, 0.0, 0.0)) }; + // A square image keeps the page as given; only a clear difference turns the sheet. + let (pw, ph) = if turn && (w > h) != (width > height) && w != h { (height, width) } else { (width, height) }; + // `w` and `h` come from a decoded image, so both are above zero; `max` keeps the + // division defined even if a future decoder ever reports an empty one. + let k = (pw / w.max(f64::MIN_POSITIVE)).min(ph / h.max(f64::MIN_POSITIVE)).min(MAX_SIDE); + let (dw, dh) = (w * k, h * k); + ((pw, ph), (dw, dh, (pw - dw) / 2.0, (ph - dh) / 2.0)) + } +} + /// One page per image, each the size of its image at the image's resolution. pub fn from_images(images: &[(String, Vec)]) -> Result { from_images_with_resolution(images, ImageResolution::Embedded) @@ -666,11 +713,17 @@ pub fn from_images(images: &[(String, Vec)]) -> Result)], resolution: ImageResolution) -> Result { + from_images_with(images, resolution, ImagePage::Image) +} + +/// Create image pages at a resolution, each on a page of its own size or on a fixed sheet. +pub fn from_images_with(images: &[(String, Vec)], resolution: ImageResolution, page: ImagePage) -> Result { if let ImageResolution::Dpi(dpi) = resolution && (!dpi.is_finite() || !(1.0..=1200.0).contains(&dpi)) { return Err(CreateError::Invalid("image DPI must be finite and between 1 and 1200".into())); } + page.check()?; if images.is_empty() { return Err(CreateError::Invalid("no images".into())); } @@ -686,13 +739,14 @@ pub fn from_images_with_resolution(images: &[(String, Vec)], resolution: Ima let k = (MAX_SIDE / w.max(h)).min(1.0); w *= k; h *= k; + let ((pw, ph), (dw, dh, x, y)) = page.place(w, h); let xr = add_image(&mut doc, img, &mut profiles); let mut xobj = Dict::new(); xobj.set(b"Im0".to_vec(), Object::Ref(xr)); let mut res = Dict::new(); res.set(b"XObject".to_vec(), Object::Dict(xobj)); - let content = format!("q {w:.3} 0 0 {h:.3} 0 0 cm /Im0 Do Q\n").into_bytes(); - add_page(&mut doc, w, h, res, Some(content))?; + let content = format!("q {dw:.3} 0 0 {dh:.3} {x:.3} {y:.3} cm /Im0 Do Q\n").into_bytes(); + add_page(&mut doc, pw, ph, res, Some(content))?; } if let Some((name, _)) = images.first() { set_title(&mut doc, name.rsplit_once('.').map_or(name.as_str(), |(s, _)| s)); diff --git a/crates/create/src/tests.rs b/crates/create/src/tests.rs index 03c93d4a51..260713763d 100644 --- a/crates/create/src/tests.rs +++ b/crates/create/src/tests.rs @@ -2209,3 +2209,90 @@ fn jbig2_globals_are_decoded_within_a_limit_of_their_own() { assert!(why.starts_with("the JBIG2 globals can't be read") && why.contains(&format!("limit of {LIMIT} bytes")), "{why}"); } } + +/// A4 in points, as `pdfcraft-print`'s paper table has it (the tools resolve the name there). +const A4: (f64, f64) = (595.28, 841.89); + +#[test] +fn a_fixed_page_scales_the_image_to_fit_and_centres_it() { + // 4 x 2 points at 72 dpi: wider than A4's proportions, so the width is the limit. + let fit = ImagePage::fixed(A4, false); + let ((pw, ph), (dw, dh, x, y)) = fit.place(4.0, 2.0); + assert_eq!((pw, ph), A4, "the sheet keeps the size it was given"); + assert!((dw - A4.0).abs() < 1e-9, "the wide side fills the page: {dw}"); + assert!((dh - A4.0 / 2.0).abs() < 1e-9, "and the aspect ratio is kept: {dh}"); + assert!(x.abs() < 1e-9 && (y - (A4.1 - dh) / 2.0).abs() < 1e-9, "centred: {x}, {y}"); + // Nothing is ever cropped or stretched. + assert!(dw <= pw + 1e-9 && dh <= ph + 1e-9); + assert!((dw / dh - 2.0).abs() < 1e-9, "aspect ratio kept"); + + // A tall image on the same sheet is limited by the height instead. + let (_, (dw, dh, x, y)) = fit.place(2.0, 4.0); + assert!((dh - A4.1).abs() < 1e-9 && (dw - A4.1 / 2.0).abs() < 1e-9, "{dw} x {dh}"); + assert!(y.abs() < 1e-9 && (x - (A4.0 - dw) / 2.0).abs() < 1e-9); + + // An image smaller than the sheet is enlarged to fit it, not left in a corner. + let (_, (dw, dh, ..)) = fit.place(10.0, 10.0); + assert!((dw - A4.0).abs() < 1e-9 && (dh - A4.0).abs() < 1e-9, "a square fills the narrow side"); +} + +#[test] +fn turning_the_sheet_follows_the_image_but_leaves_a_square_alone() { + let turn = ImagePage::fixed(A4, true); + // A landscape image turns a portrait sheet; a portrait one leaves it. + assert_eq!(turn.place(4.0, 2.0).0, (A4.1, A4.0), "landscape photo, landscape sheet"); + assert_eq!(turn.place(2.0, 4.0).0, A4, "portrait photo, portrait sheet"); + // A landscape sheet turns the other way for a portrait image. + let landscape = ImagePage::fixed((A4.1, A4.0), true); + assert_eq!(landscape.place(2.0, 4.0).0, A4); + // A square image is neither, so the sheet is left as asked for. + assert_eq!(turn.place(5.0, 5.0).0, A4, "a square never turns the sheet"); + // Without turning, the sheet is whatever it was given. + assert_eq!(ImagePage::fixed(A4, false).place(4.0, 2.0).0, A4); +} + +#[test] +fn image_pages_sized_by_the_image_are_unchanged() { + // The default must still put the page exactly on the image, at the origin. + assert_eq!(ImagePage::Image.place(4.0, 2.0), ((4.0, 2.0), (4.0, 2.0, 0.0, 0.0))); + assert_eq!(ImagePage::default(), ImagePage::Image); + let images = [("photo.png".into(), png_bytes(true)), ("scan.jpg".into(), jpeg_bytes())]; + let by_image = from_images_with(&images, ImageResolution::Embedded, ImagePage::Image).unwrap(); + assert_eq!(reopen(&by_image).bytes(), reopen(&from_images(&images).unwrap()).bytes(), "the same file as before"); +} + +#[test] +fn a_set_of_differently_shaped_images_lands_on_one_paper_size() { + // #3273: a 4 x 2 and a 3 x 2 image gave pages of two different sizes, neither of them paper. + let images = [("photo.png".into(), png_bytes(true)), ("scan.jpg".into(), jpeg_bytes())]; + let doc = reopen(&from_images_with(&images, ImageResolution::Embedded, ImagePage::fixed(A4, false)).unwrap()); + let p = pages(&doc); + assert_eq!(p.len(), 2); + for d in &p { + let m = media(d); + assert!((m[2] - A4.0).abs() < 0.001 && (m[3] - A4.1).abs() < 0.001, "every page is A4: {m:?}"); + } + // The image is drawn scaled and centred, not at the page's origin. + let c = doc.resolve(p[0].get(b"Contents").unwrap()); + let Object::Stream(s) = &*c else { panic!("expected a content stream") }; + let text = String::from_utf8_lossy(&s.decoded().unwrap()).into_owned(); + assert!(text.contains("595.280 0 0 297.640 0.000 272.125 cm"), "scaled to the width and centred: {text}"); + + // Turning gives the landscape images landscape sheets instead. + let doc = reopen(&from_images_with(&images, ImageResolution::Embedded, ImagePage::fixed(A4, true)).unwrap()); + for d in pages(&doc).iter() { + let m = media(d); + assert!((m[2] - A4.1).abs() < 0.001 && (m[3] - A4.0).abs() < 0.001, "turned for a wide image: {m:?}"); + } +} + +#[test] +fn an_unusable_page_size_is_refused_and_nothing_is_written() { + let images = [("photo.png".into(), png_bytes(true))]; + for size in [(0.0, 100.0), (100.0, 0.0), (2.9, 100.0), (f64::NAN, 100.0), (100.0, f64::INFINITY), (20_000.0, 100.0), (-5.0, 100.0)] { + let page = ImagePage::fixed(size, true); + assert!(matches!(from_images_with(&images, ImageResolution::Embedded, page), Err(CreateError::Invalid(_))), "{size:?}"); + } + // The largest page PDF allows is fine. + assert!(from_images_with(&images, ImageResolution::Embedded, ImagePage::fixed((14_400.0, 14_400.0), true)).is_ok()); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 0b49cfd4e1..fe2268bc95 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -77,7 +77,7 @@ pub use pdfcraft_organize::check_custom_key; pub use pdfcraft_organize::view::{InitialView, Layout as InitialLayout, Magnification, Navigation}; pub use pdfcraft_cos::Algorithm; -pub use pdfcraft_create::{CONVERTIBLE, CreateError, ImageResolution, SourceKind, decode_text, source_kind}; +pub use pdfcraft_create::{CONVERTIBLE, CreateError, ImagePage, ImageResolution, SourceKind, decode_text, source_kind}; pub use pdfcraft_edit::added::{ CHAR_SPACING_LIMIT as ADDED_CHAR_SPACING_LIMIT, paste_place as added_paste_place, paste_rect as added_paste_rect, text_rect as added_text_rect, text_width as added_text_width, diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 9a4cb04dac..4bc642a3a3 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -10,7 +10,7 @@ use crate::check_refresh_panic; use crate::edit::{EditCtx, check_permission, run_edit}; use crate::history::{Keys, MAX_UNDO, Scope, keys_after, scope_of, uses_scripts}; use crate::{ - BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, Hidden, ImageResolution, + BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, Hidden, ImagePage, ImageResolution, LOW_RESOLUTION_PRINT_DPI, Label, ObjectKind, OptimizeReport, RecoverySnapshot, SignOptions, SourceKind, SplitPart, SummarySort, TrustStore, XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, apply_layer_state, comment_list, comment_summary, decode_text, display_bytes, display_config, guard, info_fields, js, local_utc_offset, note_warnings, open_source, open_source_with, optimize, outline_rows, parse_ymd, print, print_raster, diff --git a/crates/engine/src/session/files.rs b/crates/engine/src/session/files.rs index 34d75e5c82..9c90f84fa3 100644 --- a/crates/engine/src/session/files.rs +++ b/crates/engine/src/session/files.rs @@ -1,7 +1,7 @@ use super::{ - Arc, CombineSource, Combined, DataFormat, DocId, EditError, Hidden, ImageResolution, LOW_RESOLUTION_PRINT_DPI, OptimizeReport, SaveOptions, - Session, SourceKind, SplitPart, decode_text, guard, open_source, open_source_with, optimize, print, print_raster, set_default_layer_state, - source_kind, writable, write_full, + Arc, CombineSource, Combined, DataFormat, DocId, EditError, Hidden, ImagePage, ImageResolution, LOW_RESOLUTION_PRINT_DPI, OptimizeReport, + SaveOptions, Session, SourceKind, SplitPart, decode_text, guard, open_source, open_source_with, optimize, print, print_raster, + set_default_layer_state, source_kind, writable, write_full, }; impl Session { @@ -22,7 +22,18 @@ impl Session { /// Create image pages at embedded resolution or a fixed dpi, without resampling. pub fn create_from_images_with_resolution(&self, images: &[(String, Vec)], resolution: ImageResolution) -> Result>, EditError> { - self.write_new(&pdfcraft_create::from_images_with_resolution(images, resolution)?) + self.create_from_images_with(images, resolution, ImagePage::Image) + } + + /// Create image pages at a resolution, each on its own size or on one fixed sheet (scaled to + /// fit and centred). Pixels are never resampled either way. + pub fn create_from_images_with( + &self, + images: &[(String, Vec)], + resolution: ImageResolution, + page: ImagePage, + ) -> Result>, EditError> { + self.write_new(&pdfcraft_create::from_images_with(images, resolution, page)?) } /// A new document from plain text (US Letter, 11 pt Helvetica). Text Helvetica can't draw is @@ -42,6 +53,12 @@ impl Session { /// Convert a file Create understands (an image or plain text) to PDF bytes; a PDF is checked /// (it must open and allow copying pages) and returned as it is. pub fn convert_to_pdf(&self, name: &str, bytes: &Arc>) -> Result<(SourceKind, Arc>), EditError> { + self.convert_to_pdf_with(name, bytes, ImagePage::Image) + } + + /// [`Self::convert_to_pdf`], putting an image source on `page`. A PDF or text source is + /// unaffected: only an image is laid onto a sheet of a chosen size. + pub fn convert_to_pdf_with(&self, name: &str, bytes: &Arc>, page: ImagePage) -> Result<(SourceKind, Arc>), EditError> { let Some(kind) = source_kind(name, bytes) else { return Err(EditError::Source(format!("{name}: this file type can't be converted; use a PDF, an image or a .txt file"))); }; @@ -49,7 +66,7 @@ impl Session { // Image decoders read untrusted bytes: a panic in one must not take the app down. let created = guard(|| match kind { SourceKind::Pdf => open_source(name, bytes).map(|_| bytes.clone()), - SourceKind::Image => self.create_from_images(&[(name.to_string(), bytes.to_vec())]), + SourceKind::Image => self.create_from_images_with(&[(name.to_string(), bytes.to_vec())], ImageResolution::Embedded, page), SourceKind::Text => self.create_from_text(title, &decode_text(bytes)), }) .map_err(|_| EditError::Source(format!("{name}: the file could not be read")))?; diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 0b6f658dd6..63e2c6367d 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -6896,8 +6896,8 @@ milestone = "M10" status = "shipped" commands = ["create.images"] tools = ["doc_create"] -evidence = ["crates/create/src/tests.rs::black_and_white_images_are_stored_at_one_bit", "crates/create/src/tests.rs::jpeg_2000_images_are_embedded_as_is", "crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::embedded_icc_profiles_tag_the_image_colour_space"] -notes = "PNG, JPEG, TIFF (multi-page), GIF (first frame), BMP, and JPEG 2000 (JP2 or codestream, embedded as JPXDecode with its capture resolution). JPEG and PNG ICC profiles are kept as /ICCBased; TIFF profiles are not read yet. A picture of only pure black and white (a 1-bit PNG or TIFF, eight-bit grey, a two-colour palette, RGB without a profile) is stored at one bit per pixel, as CCITT Group 4 or Flate, whichever is smaller" +evidence = ["crates/create/src/tests.rs::black_and_white_images_are_stored_at_one_bit", "crates/create/src/tests.rs::jpeg_2000_images_are_embedded_as_is", "crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::embedded_icc_profiles_tag_the_image_colour_space", "crates/create/src/tests.rs::a_set_of_differently_shaped_images_lands_on_one_paper_size", "crates/automation/tests/automation.rs::image_pages_go_on_a_chosen_paper_size_through_every_create_tool"] +notes = "PNG, JPEG, TIFF (multi-page), GIF (first frame), BMP, and JPEG 2000 (JP2 or codestream, embedded as JPXDecode with its capture resolution). JPEG and PNG ICC profiles are kept as /ICCBased; TIFF profiles are not read yet. A picture of only pure black and white (a 1-bit PNG or TIFF, eight-bit grey, a two-colour palette, RGB without a profile) is stored at one bit per pixel, as CCITT Group 4 or Flate, whichever is smaller. Pages follow the image at its resolution, or sit on a chosen sheet (page_size: a paper name or points, scaled to fit, centred, turned to the image unless page_turn is false) in doc_create and doc_create_multiple; doc_combine does not take it yet, and there is no dialog for it" [[feature]] id = "create.from-multipage-tiff" From 86bd77fa9ddfda2e168da5992c4d3457bb2608b7 Mon Sep 17 00:00:00 2001 From: Muhammad Saad Date: Wed, 21 Oct 2026 08:34:27 +0400 Subject: [PATCH 012/114] M10: cover both tools in the page_size refusal test (#3273) Review follow-up. The test's comment said a bad page_size is refused "on every tool", but the loop called only doc_create. It now calls doc_create and both of doc_create_multiple's modes, so the comment is what the test proves rather than a claim beside it. create_separate checked page_size after creating out_dir, so a refused request left an empty folder behind. The check moves above the mkdir and the test asserts neither the file nor the folder appears. The parity entry listed only doc_create under tools, although its own notes and evidence already covered doc_create_multiple. --- crates/automation/tests/it/automation.rs | 16 +++++++++++----- parity/acrobat-features.toml | 4 ++-- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 8f6394715a..bee7551245 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -9465,13 +9465,19 @@ fn image_pages_go_on_a_chosen_paper_size_through_every_create_tool() { let one = ok(&mut a, "doc_open", json!({ "path": "out/a_page_1.pdf" }))["doc"].as_u64().unwrap(); assert!(close(size(&mut a, one, 0), A4)); - // A size that is not a paper name or a pair of points is refused, on every tool. + // A size that is not a paper name or a pair of points is refused, by every tool that takes + // one and in both of doc_create_multiple's modes, before anything is written. for bad in [json!("A9"), json!([300]), json!(["a", "b"]), json!(5), json!({})] { - assert!( - matches!(a.call("doc_create", &json!({ "from": "images", "paths": shots, "page_size": bad })), Err(ToolError::InvalidArgs(_))), - "{bad} should be refused" - ); + for (tool, args) in [ + ("doc_create", json!({ "from": "images", "paths": shots, "page_size": bad.clone() })), + ("doc_create_multiple", json!({ "paths": shots, "page_size": bad.clone(), "out": "refused.pdf" })), + ("doc_create_multiple", json!({ "paths": shots, "mode": "separate", "out_dir": "refused", "page_size": bad.clone() })), + ] { + assert!(matches!(a.call(tool, &args), Err(ToolError::InvalidArgs(_))), "{tool}: {bad} should be refused"); + } } + assert!(!dir.join("refused.pdf").exists(), "a refused page_size leaves no file behind"); + assert!(!dir.join("refused").exists(), "nor a folder"); } /// Three paragraphs: Alpha (two rows), Bravo (one row) and Charlie (two rows), at the leading diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 63e2c6367d..5b4a679304 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -6895,8 +6895,8 @@ tier = "P0" milestone = "M10" status = "shipped" commands = ["create.images"] -tools = ["doc_create"] -evidence = ["crates/create/src/tests.rs::black_and_white_images_are_stored_at_one_bit", "crates/create/src/tests.rs::jpeg_2000_images_are_embedded_as_is", "crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::embedded_icc_profiles_tag_the_image_colour_space", "crates/create/src/tests.rs::a_set_of_differently_shaped_images_lands_on_one_paper_size", "crates/automation/tests/automation.rs::image_pages_go_on_a_chosen_paper_size_through_every_create_tool"] +tools = ["doc_create", "doc_create_multiple"] +evidence = ["crates/create/src/tests.rs::black_and_white_images_are_stored_at_one_bit", "crates/create/src/tests.rs::jpeg_2000_images_are_embedded_as_is", "crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::embedded_icc_profiles_tag_the_image_colour_space", "crates/create/src/tests.rs::a_set_of_differently_shaped_images_lands_on_one_paper_size", "crates/automation/tests/it/automation.rs::image_pages_go_on_a_chosen_paper_size_through_every_create_tool"] notes = "PNG, JPEG, TIFF (multi-page), GIF (first frame), BMP, and JPEG 2000 (JP2 or codestream, embedded as JPXDecode with its capture resolution). JPEG and PNG ICC profiles are kept as /ICCBased; TIFF profiles are not read yet. A picture of only pure black and white (a 1-bit PNG or TIFF, eight-bit grey, a two-colour palette, RGB without a profile) is stored at one bit per pixel, as CCITT Group 4 or Flate, whichever is smaller. Pages follow the image at its resolution, or sit on a chosen sheet (page_size: a paper name or points, scaled to fit, centred, turned to the image unless page_turn is false) in doc_create and doc_create_multiple; doc_combine does not take it yet, and there is no dialog for it" [[feature]] From bbba4b2585f2ff90ef16e7644ddb8d61dfa88d06 Mon Sep 17 00:00:00 2001 From: Muhammad Saad Date: Fri, 23 Oct 2026 03:09:51 +0400 Subject: [PATCH 013/114] M10: let a small image fill its fixed page (#3273 review) The fit scale was capped with MAX_SIDE, which bounds a page side, not a ratio. Past that scale the image came out smaller than the sheet: a 4 x 2 image at 1200 dpi covered 3456 pt of a 14400 pt page instead of all of it, and a 30 x 30 JFIF at 65535 dpi covered 475 pt of Letter. The fit scale needs no cap of its own. It is min(pw / w, ph / h), so the drawn size is at most the page's by construction, and w and h are above zero because a decoded image has at least one pixel and every decoder here falls back to 72 dpi rather than pass on a non-positive resolution. The guards against a zero divisor went with the cap, with a comment saying why the division is defined. Found by the review bot. The test was written before the fix and observed failing at 3456 x 1728. --- crates/create/src/lib.rs | 13 ++++++++++--- crates/create/src/tests.rs | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/create/src/lib.rs b/crates/create/src/lib.rs index ed978de807..76bd79a362 100644 --- a/crates/create/src/lib.rs +++ b/crates/create/src/lib.rs @@ -698,9 +698,16 @@ impl ImagePage { let Self::Fixed { width, height, turn } = self else { return ((w, h), (w, h, 0.0, 0.0)) }; // A square image keeps the page as given; only a clear difference turns the sheet. let (pw, ph) = if turn && (w > h) != (width > height) && w != h { (height, width) } else { (width, height) }; - // `w` and `h` come from a decoded image, so both are above zero; `max` keeps the - // division defined even if a future decoder ever reports an empty one. - let k = (pw / w.max(f64::MIN_POSITIVE)).min(ph / h.max(f64::MIN_POSITIVE)).min(MAX_SIDE); + // A scale is a ratio, not a length, so `MAX_SIDE` has no business capping it: it bounds + // a page side, which `ImagePage::check` has already applied. Capping the scale with it + // only shrank a small image on a large sheet (a 4 x 2 image at 1200 dpi covered 3456 pt + // of a 14400 pt page instead of all of it). The fit scale needs no cap of its own: it is + // `min(pw / w, ph / h)`, so the drawn size is the page's by construction. + // + // `w` and `h` are above zero, so the division is defined: a decoded image has at least + // one pixel, and every decoder here falls back to 72 dpi rather than pass on a + // non-positive resolution (`xppu > 0 && yppu > 0` for PNG, `> 1.0` for JPEG). + let k = (pw / w).min(ph / h); let (dw, dh) = (w * k, h * k); ((pw, ph), (dw, dh, (pw - dw) / 2.0, (ph - dh) / 2.0)) } diff --git a/crates/create/src/tests.rs b/crates/create/src/tests.rs index 260713763d..f380340fee 100644 --- a/crates/create/src/tests.rs +++ b/crates/create/src/tests.rs @@ -2296,3 +2296,19 @@ fn an_unusable_page_size_is_refused_and_nothing_is_written() { // The largest page PDF allows is fine. assert!(from_images_with(&images, ImageResolution::Embedded, ImagePage::fixed((14_400.0, 14_400.0), true)).is_ok()); } + +/// A fixed page is filled by the image whatever its resolution: a tiny image at a high dpi is +/// enlarged to the sheet, not left small on it. `MAX_SIDE` bounds a page side, which +/// `ImagePage::check` has already applied, so it must not also cap the fit scale. +#[test] +fn a_tiny_high_dpi_image_still_fills_its_fixed_page() { + let images = [("photo.png".into(), png_bytes(true))]; + // 4 x 2 px at 1200 dpi is 0.24 x 0.12 pt: the fit scale is 60000, far past MAX_SIDE. + let page = ImagePage::fixed((MAX_SIDE, MAX_SIDE), false); + let doc = reopen(&from_images_with(&images, ImageResolution::Dpi(1200.0), page).unwrap()); + let p = pages(&doc); + let c = doc.resolve(p[0].get(b"Contents").unwrap()); + let Object::Stream(s) = &*c else { panic!("expected a content stream") }; + let text = String::from_utf8_lossy(&s.decoded().unwrap()).into_owned(); + assert!(text.contains("14400.000 0 0 7200.000 0.000 3600.000 cm"), "the image should span the full 14400 pt page: {text}"); +} From 8bd4d2986ea33fdf780741956e861863527efde2 Mon Sep 17 00:00:00 2001 From: Muhammad Saad Date: Mon, 26 Oct 2026 10:05:03 +0400 Subject: [PATCH 014/114] M10: refuse an out-of-range page_size before out_dir is made (#3273) image_page validated the shape of page_size but not its magnitude, so [14401, 792] passed it and only the conversion refused the page. In mode "separate" that is a side effect ahead of the check: create_separate makes out_dir first and then fails once per file, leaving an empty folder behind. The comment there claimed a bad page_size left nothing behind, which was only true of a malformed one. ImagePage::check already applies the 3 to 14400 point limit (ISO 32000-2 Annex C), so make it public and call it from image_page rather than repeat the number: an unmakeable page is the caller's argument being wrong, so it is InvalidArgs, and every creation path shares the one helper. The tool schema gains the maximum it was documenting only as a minimum. Tests: the existing refusal test gains [14401, 792], [612, 2] and [-612, 792], and already asserts that no file and no folder is left behind. Removing the check reds it with `doc_create: [14401,792] should be refused`. cargo fmt --check, clippy -D warnings, pdfcraft-create (52) and pdfcraft-automation (245 + 37) tests, xtask layers (37 crates) and xtask assets all pass. --- crates/automation/src/assemble.rs | 16 ++++++++++------ crates/automation/src/tools.rs | 4 ++-- crates/automation/tests/it/automation.rs | 9 ++++++--- crates/create/src/lib.rs | 7 ++++++- 4 files changed, 24 insertions(+), 12 deletions(-) diff --git a/crates/automation/src/assemble.rs b/crates/automation/src/assemble.rs index 6e9af489c1..8420f44f82 100644 --- a/crates/automation/src/assemble.rs +++ b/crates/automation/src/assemble.rs @@ -10,15 +10,19 @@ impl Automation { fn image_page(a: &Args) -> Result { let turn = a.opt_bool("page_turn")?.unwrap_or(true); let bad = || ToolError::InvalidArgs("page_size must be a paper name or [width, height] in points".into()); - match a.get("page_size") { - None | Some(Value::Null) => Ok(pdfcraft_engine::ImagePage::Image), - Some(Value::String(s)) => Ok(pdfcraft_engine::ImagePage::fixed(super::printing::paper_named(Some(s))?.1, turn)), + let page = match a.get("page_size") { + None | Some(Value::Null) => pdfcraft_engine::ImagePage::Image, + Some(Value::String(s)) => pdfcraft_engine::ImagePage::fixed(super::printing::paper_named(Some(s))?.1, turn), Some(Value::Array(v)) if v.len() == 2 => { let side = |i: usize| v.get(i).and_then(Value::as_f64).ok_or_else(bad); - Ok(pdfcraft_engine::ImagePage::fixed((side(0)?, side(1)?), turn)) + pdfcraft_engine::ImagePage::fixed((side(0)?, side(1)?), turn) } - Some(_) => Err(bad()), - } + Some(_) => return Err(bad()), + }; + // A page the creator cannot make is the caller's argument being wrong, not a conversion + // failure, and refusing it here is what keeps mode "separate" from making out_dir first. + page.check().map_err(|e| ToolError::InvalidArgs(e.to_string()))?; + Ok(page) } pub(crate) fn doc_create(&mut self, a: &Args) -> Result { diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 3d70705da9..b675f3d7e7 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -276,7 +276,7 @@ pub fn tools() -> Vec { "out": save_out.clone(), "open": open.clone(), "out_dir": { "type": "string", "description": "Folder for mode \"separate\"." }, - "page_size": { "type": ["string", "array"], "items": { "type": "number", "minimum": 3 }, "minItems": 2, "maxItems": 2, "description": "For image files: put each image on a sheet of this size instead of a page as large as the image. A paper name (A4, Letter, Legal, Tabloid, A0-A6, ARCH A-E, ANSI C-E) or [width, height] in points; the image is scaled to fit and centred." }, + "page_size": { "type": ["string", "array"], "items": { "type": "number", "minimum": 3, "maximum": 14400 }, "minItems": 2, "maxItems": 2, "description": "For image files: put each image on a sheet of this size instead of a page as large as the image. A paper name (A4, Letter, Legal, Tabloid, A0-A6, ARCH A-E, ANSI C-E) or [width, height] in points, each between 3 and 14400 (the largest a PDF page may be); the image is scaled to fit and centred." }, "page_turn": { "type": "boolean", "description": "With page_size: turn the sheet to match each image's orientation, so a landscape photo gets a landscape page (default true)." }, }), &["paths"], @@ -1340,7 +1340,7 @@ pub fn tools() -> Vec { "width": { "type": "number", "minimum": 3 }, "height": { "type": "number", "minimum": 3 }, "name": { "type": "string", "description": "Name for the new document (default derived from the source)." }, - "page_size": { "type": ["string", "array"], "items": { "type": "number", "minimum": 3 }, "minItems": 2, "maxItems": 2, "description": "For image files: put each image on a sheet of this size instead of a page as large as the image. A paper name (A4, Letter, Legal, Tabloid, A0-A6, ARCH A-E, ANSI C-E) or [width, height] in points; the image is scaled to fit and centred." }, + "page_size": { "type": ["string", "array"], "items": { "type": "number", "minimum": 3, "maximum": 14400 }, "minItems": 2, "maxItems": 2, "description": "For image files: put each image on a sheet of this size instead of a page as large as the image. A paper name (A4, Letter, Legal, Tabloid, A0-A6, ARCH A-E, ANSI C-E) or [width, height] in points, each between 3 and 14400 (the largest a PDF page may be); the image is scaled to fit and centred." }, "page_turn": { "type": "boolean", "description": "With page_size: turn the sheet to match each image's orientation, so a landscape photo gets a landscape page (default true)." }, }), diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index bee7551245..2c9ce9bc9d 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -9465,9 +9465,12 @@ fn image_pages_go_on_a_chosen_paper_size_through_every_create_tool() { let one = ok(&mut a, "doc_open", json!({ "path": "out/a_page_1.pdf" }))["doc"].as_u64().unwrap(); assert!(close(size(&mut a, one, 0), A4)); - // A size that is not a paper name or a pair of points is refused, by every tool that takes - // one and in both of doc_create_multiple's modes, before anything is written. - for bad in [json!("A9"), json!([300]), json!(["a", "b"]), json!(5), json!({})] { + // A size no page can be is refused the same way: not a paper name, not a pair of points, or + // a pair outside the 3 to 14400 points a PDF page may be (ISO 32000-2 Annex C). Checked for + // every tool that takes one and in both of doc_create_multiple's modes, because "separate" + // makes out_dir before it converts anything and a size reported only by the conversion would + // leave the folder behind. + for bad in [json!("A9"), json!([300]), json!(["a", "b"]), json!(5), json!({}), json!([14401, 792]), json!([612, 2]), json!([-612, 792])] { for (tool, args) in [ ("doc_create", json!({ "from": "images", "paths": shots, "page_size": bad.clone() })), ("doc_create_multiple", json!({ "paths": shots, "page_size": bad.clone(), "out": "refused.pdf" })), diff --git a/crates/create/src/lib.rs b/crates/create/src/lib.rs index 76bd79a362..b2fd766deb 100644 --- a/crates/create/src/lib.rs +++ b/crates/create/src/lib.rs @@ -684,7 +684,12 @@ impl ImagePage { Self::Fixed { width: size.0, height: size.1, turn } } - fn check(self) -> Result<(), CreateError> { + /// Refuse a page this crate cannot make. + /// + /// Public so a caller that acts before converting can refuse the size before the side effect: + /// `doc_create_multiple` in mode "separate" makes `out_dir` first, and an out-of-range size + /// reported only by the conversion would leave the folder behind. + pub fn check(self) -> Result<(), CreateError> { let Self::Fixed { width, height, .. } = self else { return Ok(()) }; if !(width.is_finite() && height.is_finite() && (3.0..=MAX_SIDE).contains(&width) && (3.0..=MAX_SIDE).contains(&height)) { return Err(CreateError::Invalid(format!("the page must be between 3 and {MAX_SIDE} points on each side"))); From 3ba8deed53087f700ebd87ce0a364892d9e8cdbc Mon Sep 17 00:00:00 2001 From: Muhammad Saad Date: Mon, 26 Oct 2026 20:11:41 +0400 Subject: [PATCH 015/114] M10: cover that page_size lays out images and nothing else (#3273) @FredApps approved at 2bc3cbd and said which part he had read but not run: whether a PDF or text source ignores page_size. It does, and the reason is one line in convert_to_pdf_with: only the SourceKind::Image arm is handed `page`, a PDF comes back as its own bytes and text goes through create_from_text, which takes no page at all. An approval resting on a reading is worth turning into evidence, especially for a behaviour that is easy to widen by accident. doc_create_multiple over a PDF, a .txt and an image with page_size: A4 now asserts the PDF's first page keeps its own size, the image's page is the sheet either way up, and all three sources contributed pages. It also asserts the fixture is not A4 to begin with, since otherwise the first assertion would pass for the wrong reason. Proved by regression: routing the Pdf arm through create_blank at the requested size reds it with `the PDF's first page keeps its own size: (595.28, 841.89)`. cargo fmt --check, clippy -D warnings and pdfcraft-automation (271 + 45 passed) all pass. --- crates/automation/tests/it/automation.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 2c9ce9bc9d..3754174f5c 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -9481,6 +9481,25 @@ fn image_pages_go_on_a_chosen_paper_size_through_every_create_tool() { } assert!(!dir.join("refused.pdf").exists(), "a refused page_size leaves no file behind"); assert!(!dir.join("refused").exists(), "nor a folder"); + + // page_size lays out images and nothing else. A PDF source is returned as it is and a .txt + // goes through create_from_text, so neither takes the sheet: #3273 asked for photos to stop + // dictating the page, not for every source to be re-sized. Covering it because the engine + // passes `page` only to the image arm of `convert_to_pdf_with`, which is easy to widen by + // accident later (@FredApps named this as the part he read but did not run). + std::fs::write(dir.join("notes.txt"), "Some notes").unwrap(); + let mixed = ok(&mut a, "doc_create_multiple", json!({ "paths": ["a.pdf", "notes.txt", shots[0]], "page_size": "A4", "out": "mixed.pdf" })); + assert!(mixed["bytes"].as_u64().unwrap_or(0) > 0, "the mixed run produced a file: {mixed}"); + let doc_mixed = ok(&mut a, "doc_open", json!({ "path": "mixed.pdf" }))["doc"].as_u64().unwrap(); + let pages = ok(&mut a, "doc_info", json!({ "doc": doc_mixed }))["pages"].as_array().cloned().unwrap_or_default(); + let a_pdf = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + let kept = size(&mut a, a_pdf, 0); + assert!(!close(kept, A4) && !close(kept, (A4.1, A4.0)), "the fixture is not A4 already, or this test proves nothing: {kept:?}"); + assert!(close(size(&mut a, doc_mixed, 0), kept), "the PDF's first page keeps its own size: {:?}", size(&mut a, doc_mixed, 0)); + let last = pages.len() - 1; + let image_page = size(&mut a, doc_mixed, last); + assert!(close(image_page, A4) || close(image_page, (A4.1, A4.0)), "the image page did go on the sheet: {image_page:?}"); + assert!(pages.len() > 2, "all three sources contributed pages: {}", pages.len()); } /// Three paragraphs: Alpha (two rows), Bravo (one row) and Charlie (two rows), at the leading From e931e0c817841d6cc9d95767a4c9a8182e9f9f48 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sat, 31 Oct 2026 18:16:57 +0800 Subject: [PATCH 016/114] M3: a repeated /NM costs the GoToE name index nothing The per-page /NM index keeps only the first annotation with each name, but it charged the shared byte budget for every /NM on the page. One long name repeated across about 16,000 annotations spent the whole 16 MiB budget without adding an entry, so the page's index was dropped and every GoToE target naming an annotation there went back to scanning /Annots. A name already in the index is now skipped before the budget is charged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pq7HyCfwzyRXj4VfQAVVdv --- crates/render/src/inspect/annotations.rs | 6 +++- crates/render/src/inspect/tests.rs | 42 ++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/render/src/inspect/annotations.rs b/crates/render/src/inspect/annotations.rs index 39ac45ab0f..c52865e5c4 100644 --- a/crates/render/src/inspect/annotations.rs +++ b/crates/render/src/inspect/annotations.rs @@ -325,6 +325,10 @@ impl<'a> Inspector<'a> { let mut budget = self.annotation_name_budget.get(); for (i, a) in annots.iter().enumerate() { let Some(nm) = self.annotation_name(a).filter(|nm| nm.len() <= MAX_INDEXED_ANNOTATION_NAME_BYTES) else { continue }; + // A repeated name keeps its first position and adds no entry, so it costs nothing. + if names.contains_key(nm) { + continue; + } // Each entry costs its name and its slot, so many short names are bounded too. let Some(left) = budget.checked_sub(nm.len().saturating_add(std::mem::size_of::<(Vec, usize)>())) else { // What the page used so far is spent; nothing of it is kept. @@ -332,7 +336,7 @@ impl<'a> Inspector<'a> { return None; }; budget = left; - names.entry(nm.to_vec()).or_insert(i); + names.insert(nm.to_vec(), i); } self.annotation_name_budget.set(budget); Some(names) diff --git a/crates/render/src/inspect/tests.rs b/crates/render/src/inspect/tests.rs index a2fd612018..e09bf6c251 100644 --- a/crates/render/src/inspect/tests.rs +++ b/crates/render/src/inspect/tests.rs @@ -1423,6 +1423,48 @@ fn embedded_go_to_annotation_name_indexes_share_a_byte_budget() { assert!(indexed.iter().all(|&len| len < 1 << 20), "the long name was indexed"); } +/// A `/NM` repeated across a page's `/Annots` is charged to the index budget once: one long name +/// on 17,000 annotations would otherwise spend the whole budget, drop the page's index and send +/// every GoToE target on that page back to scanning `/Annots`. +#[test] +fn embedded_go_to_repeated_annotation_name_is_charged_once() { + use super::annotations::MAX_ANNOTATION_NAME_INDEX_BYTES; + const REPEATS: usize = 17_000; + let long = "r".repeat(1000); + let annots = format!("{} 6 0 R", "5 0 R ".repeat(REPEATS)); + let mut pdf = + String::from("%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >> endobj\n"); + pdf += &format!("3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [{annots}] >> endobj\n"); + pdf += "4 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [8 0 R 9 0 R] >> endobj\n"; + pdf += &format!("5 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 1 1] /NM ({long}) >> endobj\n"); + pdf += "6 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 1 1] /NM (last) >> endobj\n"; + let link = |o: usize, nm: &str| { + format!("{o} 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 1 1] /A << /S /GoToE /T << /R /C /P 0 /A ({nm}) >> /D [0 /Fit] >> >> endobj\n") + }; + pdf += &link(8, &long); + pdf += &link(9, "last"); + pdf += "trailer << /Root 1 0 R >>\n%%EOF"; + let doc = Document::load_mem(pdf.as_bytes()).expect("loads"); + let blank = PageInfo { width: 200.0, height: 200.0, crop: [0.0, 0.0, 200.0, 200.0], rotation: 0, label: String::new() }; + let mut info = DocInfo { pages: vec![blank; 2], ..Default::default() }; + let inspector = Inspector::new(&doc); + inspector.fill(&mut info); + let indexes: Vec = info + .links + .iter() + .filter_map(|l| match &l.target { + LinkTarget::EmbeddedGoTo { source: AttachmentSource::Annotation { page: 0, index }, .. } => Some(*index), + _ => None, + }) + .collect(); + assert_eq!(indexes, [0, REPEATS]); + let page = inspector.annotation_names.get().and_then(|pages| pages.first()).and_then(|page| page.get()); + let Some(Some(names)) = page else { panic!("page 0's /NM index was dropped: {page:?}") }; + assert_eq!(names.len(), 2); + let spent = MAX_ANNOTATION_NAME_INDEX_BYTES - inspector.annotation_name_budget.get(); + assert!(spent < 2 * (1000 + 64), "{spent} budget bytes spent on two names"); +} + #[test] fn links_read_bounded_local_remote_go_to_actions() { use DestView::{Fit, Xyz}; From a70b3f67300216dabb09e26a2c26bf88437a310f Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:56:26 +0800 Subject: [PATCH 017/114] test(engine): probe an opaque pixel in main's cropped copy-image check Main added a crop step to copy_image_finds_the_image_under_a_point_and_decodes_it_at_full_size that probes the image centre, which is a transparent pixel. With this branch a picture is picked only where it shows, so that probe found nothing. Probe the red pixel inside the kept box instead, and the red top-left corner for the cropped-away check, so both still test the crop. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pq7HyG234xeYkJfr41E6iP --- crates/engine/src/tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 300fb4782f..6a0abd8d8a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8145,8 +8145,10 @@ fn copy_image_finds_the_image_under_a_point_and_decodes_it_at_full_size() { let crop_keep = [r[0] + (r[2] - r[0]) * 0.25, r[1] + (r[3] - r[1]) * 0.25, r[0] + (r[2] - r[0]) * 0.75, r[1] + (r[3] - r[1]) * 0.75]; s.apply(id, Edit::EditPageImage { page: 0, index: 0, change: ImageEdit::Crop(crop_keep) }).unwrap(); let d = s.get(id).unwrap(); - assert_eq!(d.page_image_at(0, [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0]), Some(0)); - assert_eq!(d.page_image_at(0, [r[0] + 0.1, r[1] + 0.1]), None, "cropped-away corner must not hit-test positive"); + // Probe the red pixel: a picture is picked only where it shows, so a transparent pixel would + // not hit-test positive whether or not it was cropped away. + assert_eq!(d.page_image_at(0, [r[0] + (r[2] - r[0]) * 0.29, r[1] + (r[3] - r[1]) * 0.65]), Some(0)); + assert_eq!(d.page_image_at(0, [r[0] + 0.1, r[3] - 0.1]), None, "cropped-away corner must not hit-test positive"); } /// Copy Image: a JPEG drawn through grouped Form artwork (as Word, InDesign and scanners write From dc686b51cf4ca1da8097b8a0c6f1eb6b4014120e Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:36:12 +0800 Subject: [PATCH 018/114] M7: the opacity grid decodes its picture and masks through an ImageBudget Main now decodes images outside the renderer only through `pdfcraft_cos::ImageBudget` (`Document::decoded_image_within` became test-only), so the size checks of the picture and its `/SMask` or `/Mask` and the extraction that follows share one allowance. The byte bound each check passes is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pq7HyG234xeYkJfr41E6iP --- crates/engine/src/image_alpha.rs | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/image_alpha.rs b/crates/engine/src/image_alpha.rs index 3accb79df9..8cb93070c2 100644 --- a/crates/engine/src/image_alpha.rs +++ b/crates/engine/src/image_alpha.rs @@ -104,18 +104,20 @@ fn build(cos: &pdfcraft_cos::Document, object: ObjRef) -> Option { // The picture and the mask images it brings are decoded in full before anything is scaled // down to the picture's size, so each must be small enough, in pixels and in decoded bytes, // before any of it is decoded. + // One decoding allowance for the picture and its masks (`ImageBudget`), however many there are. + let mut budget = pdfcraft_cos::ImageBudget::new(cos); let components = if stencil { 1 } else { components(cos, s.dict.get(b"ColorSpace")) }; - if !within_budget(cos, s, components, stencil) { + if !within_budget(cos, &mut budget, s, components, stencil) { return None; } for key in [&b"SMask"[..], b"Mask"] { if let Some(Object::Stream(mask)) = s.dict.get(key).map(|v| cos.resolve(v)).as_deref() - && !within_budget(cos, mask, 1, key == b"Mask" || flag(cos, mask, b"ImageMask")) + && !within_budget(cos, &mut budget, mask, 1, key == b"Mask" || flag(cos, mask, b"ImageMask")) { return None; } } - let (_, bytes) = pdfcraft_create::image_file(cos, object).ok()?; + let (_, bytes) = pdfcraft_create::image_file_within(cos, object, &mut budget).ok()?; let format = image::guess_format(&bytes).ok()?; let mut reader = image::ImageReader::with_format(std::io::Cursor::new(bytes.as_slice()), format); let mut limits = image::Limits::default(); @@ -182,8 +184,15 @@ fn flag(cos: &pdfcraft_cos::Document, s: &pdfcraft_cos::Stream, key: &[u8]) -> b /// its samples are decoded through its filters, no more decoded bytes than its declared size /// needs, with room for padding a writer left after the samples. Without that bound a 1 × 1 /// picture whose stream inflates to a gigabyte would be decoded in full on the first hover. JPEG, -/// JPEG 2000 and JBIG2 data go to their own decoders instead. -fn within_budget(cos: &pdfcraft_cos::Document, s: &pdfcraft_cos::Stream, components: u64, stencil: bool) -> bool { +/// JPEG 2000 and JBIG2 data go to their own decoders instead. The decode is charged to +/// `allowance`, the picture's shared [`ImageBudget`](pdfcraft_cos::ImageBudget). +fn within_budget( + cos: &pdfcraft_cos::Document, + allowance: &mut pdfcraft_cos::ImageBudget, + s: &pdfcraft_cos::Stream, + components: u64, + stencil: bool, +) -> bool { let size = |key: &[u8]| u64::try_from(s.dict.int(key).unwrap_or(0)).unwrap_or(0); let (w, h) = (size(b"Width"), size(b"Height")); if w.saturating_mul(h) > MAX_DECODE_PIXELS { @@ -201,7 +210,7 @@ fn within_budget(cos: &pdfcraft_cos::Document, s: &pdfcraft_cos::Stream, compone let row = w.checked_mul(components).and_then(|n| n.checked_mul(bpc)).map(|bits| bits.div_ceil(8)); let budget = row.and_then(|r| r.checked_mul(h)).and_then(|n| n.checked_add(n / 4)).and_then(|n| n.checked_add(DECODE_SLACK)); let Some(budget) = budget.and_then(|n| usize::try_from(n).ok()) else { return false }; - cos.decoded_image_within(s, budget).is_ok() + allowance.decode(cos, s, budget).is_ok() } /// The colour components of an image in colour space `space` (ISO 32000-2 §8.6): one for an From a2d2432afc62fc35717bc02422ac7129887e0ebf Mon Sep 17 00:00:00 2001 From: Perchenko Anton <101743951+PerchAnton@users.noreply.github.com> Date: Wed, 4 Nov 2026 18:41:27 +0200 Subject: [PATCH 019/114] fix(ui): persist form-field reminder preference --- Cargo.lock | 1 + ROADMAP.md | 1 + crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/app.rs | 4 +- crates/ui-egui/src/app/control.rs | 7 + crates/ui-egui/src/app/prefs.rs | 4 + crates/ui-egui/src/canvas.rs | 4 +- crates/ui-egui/src/canvas/bars.rs | 24 +- crates/ui-egui/src/control.rs | 3 + crates/ui-egui/src/control/host.rs | 2 + crates/ui-egui/src/dialogs/preferences.rs | 1 + crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/tests/it/form_reminder.rs | 280 ++++++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + docs/development.md | 13 + docs/roadmap.md | 2 +- parity/acrobat-features.toml | 8 +- 17 files changed, 345 insertions(+), 14 deletions(-) create mode 100644 crates/ui-egui/tests/it/form_reminder.rs diff --git a/Cargo.lock b/Cargo.lock index 4df93ed3fe..3e984b5159 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4684,6 +4684,7 @@ dependencies = [ "pdfcraft-model", "pdfcraft-platform", "pdfcraft-render", + "pdfcraft-testkit", "pdfcraft-xfa", "plist", "png 0.18.1", diff --git a/ROADMAP.md b/ROADMAP.md index 6ef9e2c369..ac3e7c4d8f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -261,6 +261,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md - **2026-10-29 (M7, #2517):** Widening a paragraph rejoins a wrap with the number of spaces that wrap consumed, including a typed run and none for a Chinese or Japanese word split. The count survives an incremental save and a full rewrite, and a width-only `text_edit` uses it. Estimates unchanged. - **2026-10-26 (M11, JBIG2 symbols):** Lossless JBIG2 now stores each distinct mark of a black-and-white image once, as a symbol, and places its exact copies, when that is smaller than the generic region: on six pages of rendered 300 dpi text 28% of the generic region's size and 17% of Group 4's, and the same bits back through two independent decoders (hayro-jbig2 and Poppler). Scans, whose letters are seldom identical, gain little until refinement coding; a dictionary shared between pages (`/JBIG2Globals`) is next. Estimates unchanged. - **2026-10-25 (M5, comment replies):** One reply can be deleted from the Comments panel without its thread. On the selected card each reply has its own "…" menu (Edit, Copy text, Delete); Delete takes that reply with its pop-up and the replies to it, as `comment_delete` already did headlessly, and the comment and its other replies stay. The card stays selected, and the panel's editor stays open, on what they were on though the delete moved it in `/Annots`. Undo and Redo close the editor, since either can move what it was open on. A locked reply can't be deleted. Estimates unchanged. +- **2026-10-25 (M4, #2725):** Dismissing the ordinary form-field reminder persists across launches, while security, repair and XFA notices keep their independent controls and defaults. Estimates unchanged. - **2026-10-24 (M10, #4158 partial):** Word, HTML, RTF and PowerPoint export keep a block that continues another on its line (an italic case name, a link, a superscript) as a run in its own style inside that paragraph, with the source's word space, instead of a paragraph of its own. Style changes that wrap onto the next line still split paragraphs (the reading blocks keep style boundaries). Estimates unchanged. - **2026-10-24 (M3, window move on Wayland, #3970 follow-up):** After a move or resize by PdfCraft's own title bar or edges, the button release given back to egui goes before the pointer leaving the window, so hover no longer sticks at the old place until the pointer moves. Found by CodeRabbit in review of #3970; a unit test covers it. Estimates unchanged. - **2026-10-24 (M14, #4253):** The annotation quick bar remembers Keep tool selected across restarts, including unpinning. Old and malformed settings keep safe defaults; the opt-in UI control channel reads and changes the same preference. Estimates unchanged. diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index c859b93cf6..e29bd2393a 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -91,6 +91,7 @@ web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlE [dev-dependencies] craft-update = { workspace = true } +pdfcraft-testkit = { workspace = true } pdfcraft-xfa = { workspace = true } egui_kittest = { workspace = true, features = ["eframe", "wgpu"] } # Tests draw PdfCraft text without a system provider: the bundled and monochrome emoji faces must diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 6ac8ea8783..1a4d71f0a2 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -62,7 +62,8 @@ impl PdfCraftApp { } } - /// Construct an application with the default session, panels, theme and control state. + /// Construct an application with the default session, panels, theme, control state + /// and enabled ordinary form reminders. pub fn new() -> Self { Self { session: Session::new(), @@ -72,6 +73,7 @@ impl PdfCraftApp { mode: Mode::AllTools, default_mode: Mode::AllTools, view_defaults: Default::default(), + show_form_field_reminder: true, units: Default::default(), blank_paper: crate::paper::Paper::system(), date_format_draft: None, diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 0309042bf1..d8ba6d2e92 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -85,6 +85,13 @@ impl PdfCraftApp { ("default-mode", _) => { self.default_mode = Mode::parse(value).ok_or("default-mode must be all, read, edit, convert or sign")?; } + ("form-reminder", _) => { + self.show_form_field_reminder = match value { + "on" | "true" => true, + "off" | "false" => false, + _ => return Err("form-reminder must be on or off".to_string()), + }; + } ("date-format", _) => self.session.set_date_format(value)?, ("date-language", _) => self.session.set_date_language(Some(value).filter(|v| *v != "auto"))?, ("tool", _) => { diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs index 08a20afb45..c1f0123f97 100644 --- a/crates/ui-egui/src/app/prefs.rs +++ b/crates/ui-egui/src/app/prefs.rs @@ -146,6 +146,7 @@ impl PdfCraftApp { v["pinned_tools"] = serde_json::json!(self.pinned_tools); // Set outside json! above, which is at serde_json's macro recursion limit. v["hide_empty_highlight_hover"] = serde_json::Value::Bool(self.comment_prefs.hide_empty_highlight_hover); + v["show_form_field_reminder"] = serde_json::Value::Bool(self.show_form_field_reminder); v["show_page_edge_shadows"] = self.show_page_edge_shadows.into(); v["hotbar"] = serde_json::to_value(&self.hotbar).unwrap_or_default(); v["comment_tool_pinned"] = serde_json::Value::Bool(self.comment_prefs.pinned); @@ -276,6 +277,9 @@ impl PdfCraftApp { if let Some(on) = v["highlight_fields"].as_bool() { self.view_defaults.highlight_fields = on; } + if let Some(show) = v["show_form_field_reminder"].as_bool() { + self.show_form_field_reminder = show; + } if let Some(closed) = v["comments_panel_closed"].as_bool() { self.comments_panel_closed = closed; } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index be2dd97d53..52de7a9e6c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2380,6 +2380,7 @@ fn apply_notice(app: &mut PdfCraftApp, index: usize, notice: Option) { } Some(Notice::Signatures) => app.right = Some(RightPanel::Signatures), Some(Notice::FieldHighlights(on)) => app.view_defaults.highlight_fields = on, + Some(Notice::DismissFormReminder) => app.show_form_field_reminder = false, Some(Notice::Console) => app.dialog = Some(crate::Dialog::JsConsole), // Back on in Preferences ▸ General. Some(Notice::HideSecured) => app.show_secured_notice = false, @@ -2875,8 +2876,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { // the user turned it off (#4035): the restrictions themselves, and Document Properties ▸ // Security, stay as they are. let secured = show_secured_notice && doc.security_summary().is_some_and(|s| !(s.owner || (s.permissions.modify() && s.permissions.assemble()))); - let repaired = !doc.repair_log().is_empty(); - let notice = notices(view, doc, secured, repaired, crate::sign_ui::banner(&doc.signatures), ui, &t); + let notice = notices(view, doc, app.show_form_field_reminder, secured, crate::sign_ui::banner(&doc.signatures), ui, &t); apply_notice(app, index, notice); let Some(doc) = app.session.get(app.views[index].id) else { return }; let info = &doc.info; diff --git a/crates/ui-egui/src/canvas/bars.rs b/crates/ui-egui/src/canvas/bars.rs index dd3fe8c498..d377031815 100644 --- a/crates/ui-egui/src/canvas/bars.rs +++ b/crates/ui-egui/src/canvas/bars.rs @@ -48,6 +48,8 @@ pub(super) enum Notice { Repairs, /// Highlight fields was turned on or off. FieldHighlights(bool), + /// Remember dismissal of the ordinary form-field reminder, independently of warnings. + DismissFormReminder, /// Open the JavaScript console (the form's scripts were turned off; the error is there). Console, /// Unlock… (enter the permissions password). @@ -64,14 +66,15 @@ pub(super) enum Notice { pub(super) fn notices( view: &mut DocView, doc: &pdfcraft_engine::Document, + show_form_field_reminder: bool, secured: bool, - repaired: bool, signed: Option<(&str, Color32, &str, String)>, ui: &mut egui::Ui, t: &Tokens, ) -> Option { let info = &doc.info; let xfa = doc.xfa.as_ref(); + let repaired = !doc.repair_log().is_empty(); // The file changed on disk while this document has unsaved changes (#431): ask before // replacing it, ahead of every other notice. if view.disk_changed { @@ -128,9 +131,6 @@ pub(super) fn notices( }); return open.then_some(Notice::Signatures); } - if view.notice_dismissed { - return None; - } let mut open_security = false; let mut unlock = false; let mut hide_secured = false; @@ -140,6 +140,14 @@ pub(super) fn notices( // A form whose scripts were turned off no longer calculates or answers its buttons: that // comes before what else there is to say about the document. let scripts_off = doc.xfa_scripts_off(); + // Only the ordinary fillable-field hint is optional. Skipping it must still allow + // security, repair and XFA warnings through, and never set the general dismissal flag. + let fillable_form = info.fields.iter().any(|f| f.kind != pdfcraft_render::FieldKind::PushButton); + let form_reminder = show_form_field_reminder && !scripts_off && !secured && xfa.is_none() && info.xfa.is_none() && fillable_form; + // Restoring this hint must not be blocked by, or clear, a dismissed repair warning. + if view.notice_dismissed && !form_reminder { + return None; + } // What the document is as a form, if it is one: what the bar says first, secured or not. let form = if let Some(x) = xfa { let lang = crate::i18n::current(); @@ -169,7 +177,7 @@ pub(super) fn notices( tl!("XFA form: its fields and its XFA data are kept in step, so other viewers show what you fill in.").to_string(), true, )) - } else if info.fields.iter().any(|f| f.kind != pdfcraft_render::FieldKind::PushButton) { + } else if fillable_form && (show_form_field_reminder || secured) { // Push buttons alone (LaTeX `animate` frames, navigation buttons) leave nothing to fill in. Some(( "text-cursor-input", @@ -201,7 +209,11 @@ pub(super) fn notices( let (icon, text, fields) = msg?; notice_bar(ui, t, icon, t.accent_text, text, |ui| { if icons::button(ui, "x", 22.0, false, tl!("Dismiss")).clicked() { - view.notice_dismissed = true; + if form_reminder { + toggled = Some(Notice::DismissFormReminder); + } else { + view.notice_dismissed = true; + } } if fields { let label = if view.highlight_fields { tl!("Hide field highlights") } else { tl!("Highlight fields") }; diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 44e5481a11..a9461ec9f1 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -38,6 +38,9 @@ //! for this session without changing the saved preference. `ui.state.default_mode` reports it. //! `theme=light|dark|system` changes the saved theme preference; `ui.state.theme_preference` //! reports the choice and `ui.state.theme` reports the resolved light/dark colours. +//! `form-reminder=on|off` persistently shows or hides the ordinary form-field reminder, +//! independently of security, repair and XFA notices. `ui.state.show_form_field_reminder` +//! reports the choice; it can also be changed before opening a document. //! `comment-tool-pinned=true|false` remembers the annotation quick bar's pin across restarts; //! `hotbar-tools` accepts comma-separated command IDs (empty clears the bar), and //! `hotbar-side=float|left|right|top|bottom` floats or docks the customizable hotbar; diff --git a/crates/ui-egui/src/control/host.rs b/crates/ui-egui/src/control/host.rs index b803f2738c..7a5a942f12 100644 --- a/crates/ui-egui/src/control/host.rs +++ b/crates/ui-egui/src/control/host.rs @@ -55,6 +55,7 @@ impl Host for crate::PdfCraftApp { self.request_quit(ctx) } + /// Report UI and preference state through the authenticated control channel. fn state(&self) -> Value { let active = self.active.and_then(|i| self.views.get(i)); let docs: Vec = self @@ -133,6 +134,7 @@ impl Host for crate::PdfCraftApp { "home": self.active.is_none(), "mode": format!("{:?}", self.mode), "default_mode": self.default_mode, + "show_form_field_reminder": self.show_form_field_reminder, "hotbar": self.hotbar, "comment_tool_pinned": self.comment_prefs.pinned, "left_panel": if self.left_open { json!(format!("{:?}", self.left)) } else { Value::Null }, diff --git a/crates/ui-egui/src/dialogs/preferences.rs b/crates/ui-egui/src/dialogs/preferences.rs index 9e3182e416..52f17db1cb 100644 --- a/crates/ui-egui/src/dialogs/preferences.rs +++ b/crates/ui-egui/src/dialogs/preferences.rs @@ -660,6 +660,7 @@ fn card_general(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, ctx: &mut #[cfg(not(target_arch = "wasm32"))] ctx.checkbox(ui, &mut app.reload_changed_files, tl!("Reload documents when their files change on disk"), t); ctx.checkbox(ui, &mut app.show_secured_notice, tl!("Show a notice when a document is secured"), t); + ctx.checkbox(ui, &mut app.show_form_field_reminder, tl!("Show form field reminder"), t); #[cfg(not(target_arch = "wasm32"))] { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 643d5e90ff..86a1dabaae 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -264,6 +264,9 @@ pub struct PdfCraftApp { /// Documents and view). Continuous scrolling at fit width by default, which never snaps /// between pages. pub view_defaults: canvas::ViewDefaults, + /// Show the ordinary AcroForm field reminder; dismissing it persists across sessions. + /// Security, repair, signature and XFA notices are independent of this preference. + pub show_form_field_reminder: bool, /// The unit page sizes and margins are shown in (Preferences ▸ Documents and view). pub units: units::Unit, /// The paper Create ▸ Blank page makes (#5644): the system region's. diff --git a/crates/ui-egui/tests/it/form_reminder.rs b/crates/ui-egui/tests/it/form_reminder.rs new file mode 100644 index 0000000000..45481e2bd7 --- /dev/null +++ b/crates/ui-egui/tests/it/form_reminder.rs @@ -0,0 +1,280 @@ +//! Persistent dismissal of the ordinary AcroForm reminder (#2725). + +use egui_kittest::{Harness, kittest::Queryable}; +use pdfcraft_testkit::Pdf; +use pdfcraft_ui_egui::PdfCraftApp; + +const REMINDER: &str = "This document contains 1 interactive form fields."; +const PREFERENCE: &str = "Show form field reminder"; + +/// Build one synthetic AcroForm text field for reminder-visibility regressions. +fn form() -> Vec { + Pdf::new() + .obj("<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] >> >>") + .obj("<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>") + .obj("<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>") + .obj("<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /V (Synthetic) /Rect [50 300 250 330] /P 3 0 R >>") + .build() +} + +/// Restore optional saved preferences and open the synthetic document in a headless UI. +fn harness(saved: Option, bytes: Vec) -> Harness<'static, PdfCraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1000.0)).build_eframe(move |_cc| { + let mut app = PdfCraftApp::new(); + if let Some(saved) = saved { + app.restore(&saved); + } + app.set_option("language", "en").unwrap(); + app.open_bytes("synthetic-form.pdf", None, bytes).unwrap(); + app.set_option("left", "closed").unwrap(); + app.set_option("panel", "none").unwrap(); + app + }); + h.run_steps(6); + h +} + +/// Optional private visual checks use the real egui shell with only our synthetic form. +fn shot(h: &mut Harness<'static, PdfCraftApp>, name: &str) { + if let Ok(dir) = std::env::var("PDFCRAFT_FORM_REMINDER_SHOT_DIR") { + let path = std::path::Path::new(&dir).join(format!("{name}.png")); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(std::path::Path::new(&dir).join("synthetic-form.pdf"), form()).unwrap(); + h.render().unwrap().save(path).unwrap(); + } +} + +/// Closing the existing reminder applies to another document and a freshly restored app. +#[test] +fn dismissing_form_reminder_survives_new_documents_and_restart() { + let mut h = harness(None, form()); + let id = h.state().views[0].id; + let original = h.state().session.get(id).unwrap().bytes.clone(); + assert!(h.state().session.get(id).unwrap().repair_log().is_empty(), "use a valid fixture"); + h.get_by_label(REMINDER); + let highlights = h.state().views[0].highlight_fields; + h.get_by_label("Dismiss").click(); + h.run_steps(4); + assert!(h.query_by_label(REMINDER).is_none()); + assert!(!h.state().views[0].notice_dismissed, "the general warning dismissal must remain session-local"); + assert!(!h.state().session.get(id).unwrap().dirty); + assert_eq!(h.state().views[0].highlight_fields, highlights); + assert_eq!(h.state().session.get(id).unwrap().bytes, original, "a UI preference must not change PDF bytes"); + let saved = h.state().persist(); + h.state_mut().open_bytes("another-form.pdf", None, form()).unwrap(); + h.run_steps(4); + assert!(h.query_by_label(REMINDER).is_none(), "another form must keep the preference"); + let h = harness(Some(saved), form()); + assert!(h.query_by_label(REMINDER).is_none(), "the reminder must stay dismissed after restarting"); +} + +/// Preferences can restore a dismissed reminder immediately and keep the choice on restart. +#[test] +fn preferences_can_restore_the_form_reminder() { + use egui::accesskit::Role; + let mut h = harness(None, form()); + shot(&mut h, "reminder-on"); + h.get_by_label("Dismiss").click(); + h.run_steps(4); + shot(&mut h, "reminder-dismissed"); + h.state_mut().set_option("dialog", "preferences").unwrap(); + h.run_steps(4); + h.get_by_role_and_label(Role::CheckBox, PREFERENCE).scroll_to_me(); + h.run_steps(4); + shot(&mut h, "preferences-reminder-off"); + h.get_by_role_and_label(Role::CheckBox, PREFERENCE).click(); + h.run_steps(4); + h.get_by_label("OK").scroll_to_me(); + h.run_steps(4); + h.get_by_label("OK").click(); + h.run_steps(4); + assert!(h.state().dialog.is_none(), "Preferences must actually close before checking the restored reminder"); + h.get_by_label(REMINDER); + shot(&mut h, "reminder-restored"); + let saved = h.state().persist(); + let h = harness(Some(saved), form()); + h.get_by_label(REMINDER); +} + +/// Older or malformed settings retain the previous default, while a stored false is honoured. +#[test] +fn stored_form_reminder_choice_preserves_old_settings_defaults() { + for (saved, expected) in [ + ("{}", true), + (r#"{"show_form_field_reminder":null}"#, true), + (r#"{"show_form_field_reminder":"off"}"#, true), + (r#"{"show_form_field_reminder":0}"#, true), + (r#"{"show_form_field_reminder":true}"#, true), + (r#"{"show_form_field_reminder":false}"#, false), + ] { + let h = harness(Some(saved.to_string()), form()); + assert_eq!(h.query_by_label(REMINDER).is_some(), expected, "{saved}"); + } +} + +/// Hiding a normal form reminder must leave damage warnings visible and session-local. +#[test] +fn a_hidden_form_reminder_does_not_hide_repair_warnings() { + let mut bytes = form(); + let xref = bytes.windows(5).position(|w| w == b"xref\n").unwrap(); + bytes.truncate(xref); + bytes.extend_from_slice(b"trailer << /Root 1 0 R >>\n%%EOF\n"); + let saved = r#"{"show_form_field_reminder":false}"#.to_string(); + let mut h = harness(Some(saved), bytes.clone()); + assert!(h.query_by_label(REMINDER).is_none()); + h.get_by_label("This file was damaged and has been repaired. Saving keeps the repaired version."); + h.get_by_label("Dismiss").click(); + h.run_steps(4); + let h = harness(Some(h.state().persist()), bytes); + h.get_by_label("This file was damaged and has been repaired. Saving keeps the repaired version."); +} + +/// Restoring the ordinary hint must neither be blocked by nor revive a dismissed warning. +#[test] +fn a_dismissed_repair_warning_does_not_block_restoring_the_form_reminder() { + let mut bytes = form(); + let xref = bytes.windows(5).position(|w| w == b"xref\n").unwrap(); + bytes.truncate(xref); + bytes.extend_from_slice(b"trailer << /Root 1 0 R >>\n%%EOF\n"); + let mut h = harness(Some(r#"{"show_form_field_reminder":false}"#.to_string()), bytes); + let warning = "This file was damaged and has been repaired. Saving keeps the repaired version."; + h.get_by_label(warning); + h.get_by_label("Dismiss").click(); + h.run_steps(4); + assert!(h.state().views[0].notice_dismissed); + assert!(h.query_by_label(warning).is_none()); + shot(&mut h, "warning-dismissed"); + h.state_mut().set_option("form-reminder", "on").unwrap(); + h.run_steps(4); + h.get_by_label(REMINDER); + assert!(h.query_by_label(warning).is_none()); + shot(&mut h, "reminder-after-dismissed-warning"); + assert!(h.state().views[0].notice_dismissed, "do not clear the independent warning dismissal"); + h.get_by_label("Dismiss").click(); + h.run_steps(4); + assert!(h.query_by_label(REMINDER).is_none()); + assert!(h.query_by_label(warning).is_none(), "the warning must stay dismissed after hiding the reminder again"); +} + +/// The persistent preference is independent of the document's security restrictions. +#[test] +fn a_hidden_form_reminder_does_not_hide_security_notices() { + let mut doc = pdfcraft_cos::Document::open(std::sync::Arc::new(form())).unwrap(); + doc.set_encryption(&pdfcraft_cos::NewEncryption { + algorithm: pdfcraft_cos::Algorithm::Aes256, + user_password: "", + owner_password: "synthetic-owner", + permissions: 0b0100, + encrypt_metadata: true, + seed: [7; 32], + }) + .unwrap(); + let bytes = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(); + for show in [true, false] { + let saved = serde_json::json!({"show_form_field_reminder":show}).to_string(); + let mut h = harness(Some(saved), bytes.clone()); + let id = h.state().views[0].id; + h.get_by_label_contains("interactive form fields. This document is secured. Some changes are restricted by its security settings."); + h.get_by_label("Security settings"); + let before = h.state().views[0].highlight_fields; + let label = if before { "Hide field highlights" } else { "Highlight fields" }; + h.get_by_label(label).click(); + h.run_steps(4); + assert_eq!(h.state().views[0].highlight_fields, !before); + assert_eq!(h.state().session.get(id).unwrap().bytes.as_ref(), bytes.as_slice()); + assert!(!h.state().session.get(id).unwrap().dirty); + if !show { + shot(&mut h, "secured-form-with-reminder-off"); + } + h.get_by_label("Dismiss").click(); + h.run_steps(4); + assert!(h.query_by_label_contains("This document is secured").is_none()); + assert!(h.state().views[0].notice_dismissed); + let saved = h.state().persist(); + assert_eq!(serde_json::from_str::(&saved).unwrap()["show_form_field_reminder"], show); + let h = harness(Some(saved), bytes.clone()); + h.get_by_label_contains("interactive form fields. This document is secured."); + h.get_by_label("Security settings"); + } +} + +/// The security-notice preference and ordinary form reminder remain independent after restart. +#[test] +fn form_and_security_notice_preferences_remain_independent() { + let mut doc = pdfcraft_cos::Document::open(std::sync::Arc::new(form())).unwrap(); + doc.set_encryption(&pdfcraft_cos::NewEncryption { + algorithm: pdfcraft_cos::Algorithm::Aes256, + user_password: "", + owner_password: "synthetic-owner", + permissions: 0b0100, + encrypt_metadata: true, + seed: [8; 32], + }) + .unwrap(); + let bytes = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(); + for show_form in [false, true] { + for show_security in [false, true] { + let settings = serde_json::json!({ + "show_form_field_reminder": show_form, + "show_secured_notice": show_security, + }) + .to_string(); + let h = harness(Some(settings), bytes.clone()); + let settings = h.state().persist(); + let h = harness(Some(settings), bytes.clone()); + assert_eq!(h.query_by_label_contains("This document is secured").is_some(), show_security); + assert_eq!(h.query_by_label(REMINDER).is_some(), show_form && !show_security); + let id = h.state().views[0].id; + assert!(h.state().session.get(id).unwrap().security_summary().is_some_and(|s| !s.owner)); + assert!(!h.state().session.get(id).unwrap().dirty); + } + } +} + +/// XFA status and disabled-script warnings keep their existing dismissal behaviour. +#[test] +fn a_hidden_form_reminder_does_not_hide_xfa_notices() { + let template = pdfcraft_xfa::fixtures::scripted_template(); + let h = harness(Some(r#"{"show_form_field_reminder":false}"#.to_string()), pdfcraft_xfa::fixtures::shell(&template)); + h.get_by_label_contains("Dynamic XFA form laid out from its template:"); + let runaway = "function f() { for (var j = 0; j < 99999; j++) {} } for (var k = 0; k < 5000; k++) f();"; + let template = template.replace("if (qty.rawValue === null) qty.rawValue = 2;", runaway); + let mut h = harness(Some(r#"{"show_form_field_reminder":false}"#.to_string()), pdfcraft_xfa::fixtures::shell(&template)); + let id = h.state().views[0].id; + assert!(h.state().session.get(id).unwrap().xfa_scripts_off()); + h.state_mut().toast = None; + h.run_steps(4); + h.get_by_label_contains("This form's scripts are turned off because one ran too long."); + h.get_by_label("JavaScript Console"); +} + +/// The existing control channel changes and reports the same persistent preference. +#[test] +fn control_form_reminder_is_persistent_and_rejects_invalid_values() { + use serde_json::json; + let mut h = harness(None, form()); + let ctx = h.ctx.clone(); + let control = h.state_mut().attach_control(&ctx); + let call = |h: &mut Harness<'static, PdfCraftApp>, method: &str, params| { + let reply = control.send(method, params); + for _ in 0..30 { + h.step(); + if let Ok(result) = reply.try_recv() { + return result; + } + } + panic!("no control reply for {method}"); + }; + call(&mut h, "ui.set", json!({"key":"form-reminder","value":"off"})).unwrap(); + h.run_steps(4); + assert!(h.query_by_label(REMINDER).is_none()); + assert_eq!(call(&mut h, "ui.state", json!({})).unwrap()["show_form_field_reminder"], false); + assert!(call(&mut h, "ui.set", json!({"key":"form-reminder","value":"maybe"})).is_err()); + assert_eq!(call(&mut h, "ui.state", json!({})).unwrap()["show_form_field_reminder"], false); + let saved = h.state().persist(); + let h = harness(Some(saved), form()); + assert!(h.query_by_label(REMINDER).is_none()); + let mut app = PdfCraftApp::new(); + app.set_option("form-reminder", "off").unwrap(); + assert_eq!(serde_json::from_str::(&app.persist()).unwrap()["show_form_field_reminder"], false); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 20243ea86d..08f3f5dd91 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -45,6 +45,7 @@ mod export; mod fill_sign; mod folders; mod fonts; +mod form_reminder; mod forms; mod identity; mod javascript; diff --git a/docs/development.md b/docs/development.md index 8cb132d9f8..79d5071e68 100644 --- a/docs/development.md +++ b/docs/development.md @@ -138,6 +138,19 @@ the app logs the failure and continues using the original preferences folder. The existing PrintCraft-to-PdfCraft migration runs first. macOS, Windows and portable copies retain their current preferences locations. +Preferences ▸ Documents and view ▸ **Show form field reminder** controls the ordinary +"This document contains … interactive form fields" notice. Closing that notice turns the +preference off for all open and future documents, including after a restart. Turn the checkbox +back on to restore it immediately. Older settings default to showing the reminder; malformed +values are ignored. This does not change field highlighting or hide security, repair, signature +or XFA notices, and it does not modify the PDF. +Secured forms retain their combined form/security notice and field-highlighting controls with +either reminder preference. Closing that security notice dismisses it only for the current view. + +The opt-in UI control channel uses `ui.set` with `key=form-reminder`, `value=on|off`; the same +option is available as `pdfcraft --form-reminder off`. `ui.state.show_form_field_reminder` +reports the persistent choice even with no document open. + ## Environment variables | Variable | Effect | diff --git a/docs/roadmap.md b/docs/roadmap.md index d17893c1aa..898a16f278 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -217,7 +217,7 @@ total matches the parity estimate. | M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. A custom text match that ends on a reconstructed separator stops before the next glyph (#1315). Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings | | M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); Lab Bradford adaptation uses LMS white-point ratios, covered by independent neutral/chromatic and direct/Indexed render oracles; inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Literal page-label prefix whitespace is preserved; nine public-inspection cases cover prefix spaces, encodings and empty-prefix controls | | M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel
Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). | -| M4 | Engine, history, save, organize | 100–180 | 95% | 8–15 | Done:
- command registry (menus, shortcuts and palette all use it);
- undo/redo; incremental, atomic and encrypted saves;
- autosave and crash recovery;
- organize, combine, extract, split and insert-from-file, with identical fonts and images stored once;
- CLI `edit/combine/extract/split`.
Done since: Organize opens directly into the page overview, with checkbox selection, an editable page-range selection (#1092), and per-page rotate/delete controls; Combine files in its own tab (sortable, resizable columns; folders; early warnings; unlocking protected files), bookmark editing, page labels (Number pages), CLI `run`, Set Page Boxes, Crop tool, Duplicate pages, Ctrl+A / Cmd+A to select all pages in Organize, Replace pages, bookmarks from tagged headings. Extract and Split preserve shared Type 3 glyph resource graphs, retaining conservative pruning limits. Undo back to the opened or last saved file is clean; Revert opens that saved file after an undo; a later save appends to it so the saved revision stays in the file (#1310, #1311, #1312). Ctrl-drag (Option on macOS) on a grid thumbnail copies the pages into the drop gap, with a "+" badge and the copies selected (#2997). Initial-view window and interface options resolve indirect boolean preferences. Done since: #3309: Stack-safe named-destination pruning visits shared/cyclic indirect nodes once, without a name-count limit. Synthetic deep-tree and 60,000-name tests verify deletion, surviving targets, undo/redo, both save modes and reopening. Organize drags cancel after document edits and Undo/Redo (#3916 partial). Missing: page transitions, recovery on the web | +| M4 | Engine, history, save, organize | 100–180 | 95% | 8–15 | Done:
- command registry (menus, shortcuts and palette all use it);
- undo/redo; incremental, atomic and encrypted saves;
- autosave and crash recovery;
- organize, combine, extract, split and insert-from-file, with identical fonts and images stored once;
- CLI `edit/combine/extract/split`.
Done since: Organize opens directly into the page overview, with checkbox selection, an editable page-range selection (#1092), and per-page rotate/delete controls; Combine files in its own tab (sortable, resizable columns; folders; early warnings; unlocking protected files), bookmark editing, page labels (Number pages), CLI `run`, Set Page Boxes, Crop tool, Duplicate pages, Ctrl+A / Cmd+A to select all pages in Organize, Replace pages, bookmarks from tagged headings. Extract and Split preserve shared Type 3 glyph resource graphs, retaining conservative pruning limits. Undo back to the opened or last saved file is clean; Revert opens that saved file after an undo; a later save appends to it so the saved revision stays in the file (#1310, #1311, #1312). Ctrl-drag (Option on macOS) on a grid thumbnail copies the pages into the drop gap, with a "+" badge and the copies selected (#2997). Initial-view window and interface options resolve indirect boolean preferences. Done since: #3309: Stack-safe named-destination pruning visits shared/cyclic indirect nodes once, without a name-count limit. Synthetic deep-tree and 60,000-name tests verify deletion, surviving targets, undo/redo, both save modes and reopening. Organize drags cancel after document edits and Undo/Redo (#3916 partial). Missing: page transitions, recovery on the web Candidate #2725: Dismissing the ordinary form-field reminder persists across launches. Preferences and UI control restore it. | | M4 | Engine, history, save, organize | 100–180 | 95% | 8–15 | Done:
- command registry (menus, shortcuts and palette all use it);
- undo/redo; incremental, atomic and encrypted saves;
- autosave and crash recovery;
- organize, combine, extract, split and insert-from-file, with identical fonts and images stored once;
- CLI `edit/combine/extract/split`.
Done since: Organize opens directly into the page overview, with checkbox selection, an editable page-range selection (#1092), and per-page rotate/delete controls; Combine files in its own tab (sortable, resizable columns; folders; early warnings; unlocking protected files), bookmark editing, page labels (Number pages), CLI `run`, Set Page Boxes, Crop tool, Duplicate pages, Ctrl+A / Cmd+A to select all pages in Organize, Replace pages, bookmarks from tagged headings. Extract and Split preserve shared Type 3 glyph resource graphs, retaining conservative pruning limits. Undo back to the opened or last saved file is clean; Revert opens that saved file after an undo; a later save appends to it so the saved revision stays in the file (#1310, #1311, #1312). Rotation queries and edits resolve indirect values on pages and ancestors. Refreshed against upstream `99941daa` (2026-10-15). Repeated page indices accumulate rotations from the latest local value (#1919); saved/reopened regressions retain inherited angles and siblings. Missing: page transitions, recovery on the web | | M4 | Engine, history, save, organize | 100–180 | 95% | 8–15 | Done:
- command registry (menus, shortcuts and palette all use it);
- undo/redo; incremental, atomic and encrypted saves;
- autosave and crash recovery;
- organize, combine, extract, split and insert-from-file, with identical fonts and images stored once;
- CLI `edit/combine/extract/split`.
Done since: Organize opens directly into the page overview, with checkbox selection, an editable page-range selection (#1092), and per-page rotate/delete controls; Combine files in its own tab (sortable, resizable columns; folders; early warnings; unlocking protected files), bookmark editing, page labels (Number pages), CLI `run`, Set Page Boxes, Crop tool, Duplicate pages, Ctrl+A / Cmd+A to select all pages in Organize, Replace pages, bookmarks from tagged headings. Extract and Split preserve shared Type 3 glyph resource graphs, retaining conservative pruning limits. Undo back to the opened or last saved file is clean; Revert opens that saved file after an undo; a later save appends to it so the saved revision stays in the file (#1310, #1311, #1312). Rotation queries and edits resolve indirect values on pages and ancestors. Missing: page transitions, recovery on the web | | M4 | Engine, history, save, organize | 100–180 | 95% | 8–15 | Done:
- command registry (menus, shortcuts and palette all use it);
- undo/redo; incremental, atomic and encrypted saves;
- autosave and crash recovery;
- organize, combine, extract, split and insert-from-file, with identical fonts and images stored once;
- CLI `edit/combine/extract/split`.
Done since: Organize opens directly into the page overview, with checkbox selection, an editable page-range selection (#1092), and per-page rotate/delete controls; Combine files in its own tab (sortable, resizable columns; folders; early warnings; unlocking protected files), bookmark editing, page labels (Number pages), CLI `run`, Set Page Boxes, Crop tool, Duplicate pages, Ctrl+A / Cmd+A to select all pages in Organize, Replace pages, bookmarks from tagged headings. Extract and Split preserve shared Type 3 glyph resource graphs, retaining conservative pruning limits. Missing: page transitions, recovery on the web M4: Insert-from-file preserves source bookmarks; integration tests retained with current main. | diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 822496df3b..4d658d6c6f 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -9992,11 +9992,11 @@ title = "Preferences: forms" area = "N" tier = "P1" milestone = "M14" -status = "planned" -commands = [] +status = "partial" +commands = ["app.preferences"] tools = [] -evidence = [] -notes = "" +evidence = ["crates/ui-egui/tests/it/form_reminder.rs::dismissing_form_reminder_survives_new_documents_and_restart", "crates/ui-egui/tests/it/form_reminder.rs::preferences_can_restore_the_form_reminder", "crates/ui-egui/tests/it/form_reminder.rs::stored_form_reminder_choice_preserves_old_settings_defaults", "crates/ui-egui/tests/it/form_reminder.rs::a_hidden_form_reminder_does_not_hide_repair_warnings", "crates/ui-egui/tests/it/form_reminder.rs::a_hidden_form_reminder_does_not_hide_security_notices", "crates/ui-egui/tests/it/form_reminder.rs::a_hidden_form_reminder_does_not_hide_xfa_notices", "crates/ui-egui/tests/it/form_reminder.rs::control_form_reminder_is_persistent_and_rejects_invalid_values", "crates/ui-egui/tests/it/form_reminder.rs::a_dismissed_repair_warning_does_not_block_restoring_the_form_reminder"] +notes = "The ordinary AcroForm field reminder can be persistently dismissed and restored in Preferences or through opt-in UI control. Existing settings default to showing it. Security, repair, signature and XFA notices remain independent; this does not change field highlighting or PDF data. Other Forms preferences, including a Preferences field-highlighting toggle, remain missing." [[feature]] id = "misc.prefs-identity" From e7efae03b6cb3b46f2669dbcddb3644718d8c7c9 Mon Sep 17 00:00:00 2001 From: jweaver3 <43688514+jweaver3@users.noreply.github.com> Date: Thu, 5 Nov 2026 17:29:31 -0500 Subject: [PATCH 020/114] fix(edit): Update header & footer changes only the one chosen (#5785) Each header/footer mark now records its settings in a private /PCHeaderFooter dict, so the document is the source of truth for what Update can change. Update targets one mark by its settings and leaves every other header and footer on those pages in place; the dialog offers "Which header and footer:" when there is more than one, and automation gains doc_header_footers plus an `update` index on doc_header_footer. Fixes #5785 Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/dispatch.rs | 1 + crates/automation/src/documents.rs | 43 +++++++++- crates/automation/src/tools.rs | 7 +- crates/automation/tests/it/automation.rs | 22 +++++ crates/edit/src/apply.rs | 86 ++++++++++++++++--- crates/edit/src/lib.rs | 4 +- crates/edit/src/marks.rs | 78 ++++++++++++++++- crates/edit/src/place.rs | 43 ++++++---- crates/edit/src/tests.rs | 63 ++++++++++++++ crates/engine/src/document.rs | 5 ++ crates/engine/src/edit.rs | 7 ++ crates/engine/src/edit/labels.rs | 2 +- crates/engine/src/edit/run.rs | 5 ++ crates/engine/src/history.rs | 1 + crates/engine/src/lib.rs | 3 +- crates/engine/src/session/editing.rs | 9 +- crates/ui-egui/src/commands.rs | 10 +++ crates/ui-egui/src/dialogs/marks_ui.rs | 101 +++++++++++++++++++++-- crates/ui-egui/tests/it/marks.rs | 39 +++++++++ parity/acrobat-features.toml | 6 +- 20 files changed, 489 insertions(+), 46 deletions(-) diff --git a/crates/automation/src/dispatch.rs b/crates/automation/src/dispatch.rs index 49d4e6fd4d..80871bc57e 100644 --- a/crates/automation/src/dispatch.rs +++ b/crates/automation/src/dispatch.rs @@ -691,6 +691,7 @@ impl Automation { "doc_export_images" | "doc_export_text" | "doc_export_all_images" => self.export(name, &a)?, "doc_header_footer" | "doc_watermark" | "doc_background" | "doc_remove_marks" => self.marks(name, &a)?, "doc_backdrops" => self.backdrops(&a)?, + "doc_header_footers" => self.header_footers(&a)?, "doc_unprotect" => { let mut out = self.apply(&a, Edit::RemoveProtection)?; out["security"] = security(self.doc(&a)?); diff --git a/crates/automation/src/documents.rs b/crates/automation/src/documents.rs index 979b041a73..fdccc7309a 100644 --- a/crates/automation/src/documents.rs +++ b/crates/automation/src/documents.rs @@ -452,6 +452,23 @@ impl Automation { Ok(out) } + /// The headers and footers with recorded settings, as `doc_header_footer`'s `update` names them. + pub(crate) fn header_footers(&mut self, a: &Args) -> Result { + let found: Vec = self + .doc(a)? + .header_footers() + .iter() + .enumerate() + .map(|(i, m)| { + let boxes = ["header_left", "header_center", "header_right", "footer_left", "footer_center", "footer_right"]; + let text: serde_json::Map = + boxes.iter().zip(&m.settings.text).filter(|(_, t)| !t.is_empty()).map(|(k, t)| ((*k).to_string(), json!(t))).collect(); + json!({ "index": i, "pages": m.pages.iter().map(|p| p + 1).collect::>(), "text": text }) + }) + .collect(); + Ok(json!({ "header_footers": found })) + } + /// Pages whose own backdrop hides a background (see `pdfcraft_edit::backdrop`). pub(crate) fn backdrops(&mut self, a: &Args) -> Result { let n = self.doc(a)?.info.pages.len(); @@ -477,9 +494,24 @@ impl Automation { pub(crate) fn marks(&mut self, tool: &str, a: &Args) -> Result { use pdfcraft_engine::{Background, HeaderFooter, MarkKind, Watermark}; let n = self.doc(a)?.info.pages.len(); - let pages = match a.opt_ints("pages")? { - Some(_) => self.pages(a, "pages")?, - None => (0..n).collect(), + // The header and footer `update` names, as `doc_header_footers` lists it. + let updating = match a.opt_int("update")? { + Some(_) if tool != "doc_header_footer" => return Err(ToolError::InvalidArgs("update is only for doc_header_footer".into())), + Some(_) if a.opt_bool("replace")?.is_some() => return Err(ToolError::InvalidArgs("give update or replace, not both".into())), + Some(index) => { + let found = self.doc(a)?.header_footers(); + let mark = usize::try_from(index).ok().and_then(|i| found.get(i)).cloned(); + let listed = found.len(); + Some(mark.ok_or_else(|| { + ToolError::InvalidArgs(format!("update must be an index doc_header_footers lists ({listed} found), not {index}")) + })?) + } + None => None, + }; + let pages = match (a.opt_ints("pages")?, &updating) { + (Some(_), _) => self.pages(a, "pages")?, + (None, Some(mark)) => mark.pages.clone(), + (None, None) => (0..n).collect(), }; let color = |key: &str, default: [f64; 3]| -> Result<[f64; 3]> { Ok(a.opt_str(key)?.map(comments::parse_color).transpose()?.unwrap_or(default)) }; @@ -510,7 +542,10 @@ impl Automation { hf.start_number = s.clamp(1, u32::MAX as i64) as u32; } hf.shrink = a.opt_bool("shrink")?.unwrap_or(false); - Edit::AddHeaderFooter { pages, settings: hf, replace } + match updating { + Some(mark) => Edit::UpdateHeaderFooter { old: mark.settings, pages, settings: hf }, + None => Edit::AddHeaderFooter { pages, settings: hf, replace }, + } } "doc_watermark" => { let d = Watermark::default(); diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 7cafcb4a37..1d87eaf6cd 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -992,13 +992,14 @@ pub fn tools() -> Vec { t( "doc_header_footer", "Add header and footer", - "Add a header and/or footer to pages. Text boxes: header_left/center/right, footer_left/center/right. Tokens: <<1>> page number, <> page count, <<1 of n>>, <>, <<1/n>>, dates <> <> <> <> (and more), Bates <>. shrink: true scales the page content down evenly into the room the header and footer leave free, so they don't cover it. font: Helvetica (default), Times or Courier. replace: true swaps out existing ones (Update). Undoable.", + "Add a header and/or footer to pages. Text boxes: header_left/center/right, footer_left/center/right. Tokens: <<1>> page number, <> page count, <<1 of n>>, <>, <<1/n>>, dates <> <> <> <> (and more), Bates <>. shrink: true scales the page content down evenly into the room the header and footer leave free, so they don't cover it. font: Helvetica (default), Times or Courier. replace: true swaps out every one on those pages. update: an index from doc_header_footers changes that one alone, on its own pages unless pages is given; settings left out go back to their defaults. Undoable.", ) .cmd("edit.header_footer") .with(schema( json!({ "doc": doc(), "pages": pages("to mark (default: all)"), + "update": { "type": "integer", "minimum": 0, "description": "The index doc_header_footers lists for the header and footer to change. Not with replace." }, "header_left": { "type": "string" }, "header_center": { "type": "string" }, "header_right": { "type": "string" }, "footer_left": { "type": "string" }, "footer_center": { "type": "string" }, "footer_right": { "type": "string" }, "font": { "type": "string", "enum": ["Helvetica", "Times", "Courier"] }, @@ -1042,6 +1043,10 @@ pub fn tools() -> Vec { .ro() .cmd("edit.background") .with(schema(json!({ "doc": doc(), "pages": pages("to check (default: all)") }), &["doc"])), + t("doc_header_footers", "List headers and footers", "The headers and footers in the document, each with an `index` for doc_header_footer's `update`, its 1-based `pages` and the `text` of its boxes, tokens unexpanded. Lists those PdfCraft recorded settings for; older ones and other tools' are left out.") + .ro() + .cmd("edit.header_footer.update") + .with(schema(json!({ "doc": doc() }), &["doc"])), t("doc_remove_marks", "Remove header & footer, watermark or background", "Remove every header and footer, watermark or background PdfCraft (or a compatible tool) added. Undoable.") .destructive() .with(schema(json!({ "doc": doc(), "kind": { "type": "string", "enum": ["header_footer", "watermark", "background"] } }), &["doc", "kind"])), diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 0b0a7d598e..c2248b2c8c 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -2800,6 +2800,28 @@ fn duplicating_and_cropping_through_tools() { assert!(matches!(a.call("page_set_box", &json!({ "doc": doc, "rect": [0, 0, 10, 10] })), Err(ToolError::InvalidArgs(_)))); } +#[test] +fn header_footer_update_changes_the_one_named() { + let dir = workdir("marks-update"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [1], "header_left": "FIRST" })); + ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [2, 3], "header_left": "SECOND" })); + let listed = ok(&mut a, "doc_header_footers", json!({ "doc": doc })); + assert_eq!(listed["header_footers"][0]["pages"], json!([1])); + assert_eq!(listed["header_footers"][1], json!({ "index": 1, "pages": [2, 3], "text": { "header_left": "SECOND" } })); + // Added after listing, so index 0 is still FIRST; it shares page 1 with FIRST and must stay. + ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [1], "footer_left": "THIRD" })); + ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": 0, "header_left": "CHANGED" })); + let texts = page_text(&mut a, doc); + assert!(texts[0].contains("CHANGED") && !texts[0].contains("FIRST"), "{texts:?}"); + assert!(texts[0].contains("THIRD"), "the other one on that page stays: {texts:?}"); + assert!(texts[1].contains("SECOND") && !texts[1].contains("CHANGED"), "{texts:?}"); + for bad in [json!({ "doc": doc, "update": 9, "header_left": "X" }), json!({ "doc": doc, "update": 0, "replace": true, "header_left": "X" })] { + assert!(matches!(a.call("doc_header_footer", &bad), Err(ToolError::InvalidArgs(_))), "{bad}"); + } +} + #[test] fn headers_watermarks_and_backgrounds_through_tools() { let dir = workdir("marks"); diff --git a/crates/edit/src/apply.rs b/crates/edit/src/apply.rs index 0d0213904b..933132c6d6 100644 --- a/crates/edit/src/apply.rs +++ b/crates/edit/src/apply.rs @@ -1,9 +1,10 @@ use super::marks::{ - Background, Context, HeaderFooter, MarkKind, Watermark, add_picture_resource, bates_start, expand, matrix_number, n, picture, rgb, shrink_matrix, + Background, Context, HeaderFooter, HeaderFooterMark, MarkKind, SETTINGS_KEY, Watermark, add_picture_resource, bates_start, expand, matrix_number, + n, picture, rgb, shrink_matrix, }; use super::place::{ - END, Isolation, add_page_resources, add_resources, begin, check, check_on_top, contents, free_font_name, isolation, page_fonts, page_list, place, - place_inside_wrapper, stream_tag, text_op, undrawable, wrapper_role, + END, Isolation, add_page_resources, add_resources, begin, check, check_on_top, content_list, contents, free_font_name, isolation, page_fonts, + page_list, place, place_inside_wrapper, stream_tag, text_op, undrawable, wrapper_role, }; use super::{Document, EditError, Object, added, backdrop, helvetica_width}; @@ -22,10 +23,57 @@ fn apply_mark_transaction(doc: &mut Document, apply: impl FnOnce(&mut Document) /// those pages are removed first (Acrobat's Replace Existing). The whole call is atomic: /// on error, the document (including earlier selected pages) is unchanged. pub fn add_header_footer(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> { - apply_mark_transaction(doc, |staged| add_header_footer_in_place(staged, pages, hf, replace, cx)) + let replacing = if replace { Replacing::OnThosePages } else { Replacing::Nothing }; + apply_mark_transaction(doc, |staged| add_header_footer_in_place(staged, pages, hf, replacing, cx)) } -fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> { +/// Replace one header and footer: `old` (settings from [`header_footers`]) goes from every page +/// it is on and `hf` is added to `pages`. Any other header or footer stays, on those pages too +/// (#5785). The whole call is atomic. +pub fn update_header_footer(doc: &mut Document, old: &HeaderFooter, pages: &[usize], hf: &HeaderFooter, cx: &Context) -> Result<(), EditError> { + apply_mark_transaction(doc, |staged| add_header_footer_in_place(staged, pages, hf, Replacing::Only(old), cx)) +} + +/// How many different headers and footers [`header_footers`] lists: enough for any real document, +/// and a limit on the work a file with a different one in every stream can ask for. +const MAX_HEADER_FOOTERS: usize = 256; + +/// The settings a content stream records for its header and footer, if it records any. +fn recorded_settings(doc: &Document, stream: &Object) -> Option { + if stream_tag(doc, stream).as_deref() != Some(MarkKind::HeaderFooter.tag()) { + return None; + } + let resolved = doc.resolve(stream); + HeaderFooter::from_object(doc, resolved.as_dict()?.get(SETTINGS_KEY)?) +} + +/// The headers and footers that record their settings, in page order, each with the pages it is +/// on. Marks from before settings were recorded, or from another tool, are not listed. +pub fn header_footers(doc: &Document) -> Vec { + let mut found: Vec = Vec::new(); + for (i, page) in page_list(doc).iter().enumerate() { + for settings in content_list(doc, page).iter().filter_map(|o| recorded_settings(doc, o)) { + if let Some(mark) = found.iter_mut().find(|m| m.settings == settings) { + if mark.pages.last() != Some(&i) { + mark.pages.push(i); + } + } else if found.len() < MAX_HEADER_FOOTERS { + found.push(HeaderFooterMark { pages: vec![i], settings }); + } + } + } + found +} + +/// Which existing headers and footers an added one takes the place of. +#[derive(Clone, Copy)] +enum Replacing<'a> { + Nothing, + OnThosePages, + Only(&'a HeaderFooter), +} + +fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replacing: Replacing, cx: &Context) -> Result<(), EditError> { let all = page_list(doc); check(pages, all.len())?; if hf.text.iter().all(|t| t.trim().is_empty()) { @@ -68,9 +116,18 @@ fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFo for &i in pages { check_on_top(doc, &all[i])?; } - if replace { - remove_marks(doc, pages, MarkKind::HeaderFooter)?; + match replacing { + Replacing::Nothing => {} + Replacing::OnThosePages => { + remove_marks(doc, pages, MarkKind::HeaderFooter)?; + } + Replacing::Only(old) => { + let on = header_footers(doc).into_iter().find(|m| m.settings == *old).map(|m| m.pages); + let on = on.ok_or_else(|| EditError::Invalid("that header and footer is no longer in the document".into()))?; + remove_matching(doc, &on, MarkKind::HeaderFooter, |doc, o| recorded_settings(doc, o).as_ref() == Some(old))?; + } } + let settings = hf.to_object(); let all = page_list(doc); let count = all.len(); for (k, &i) in pages.iter().enumerate() { @@ -127,11 +184,15 @@ fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFo add_page_resources(doc, page, None, &[(resource.into_bytes(), base)])?; } let page = &page_list(doc)[i]; - place(doc, page, MarkKind::HeaderFooter, content, false)?; + let mark = place(doc, page, MarkKind::HeaderFooter, content, false)?; + doc.update_dict(mark, |d| d.set(SETTINGS_KEY.to_vec(), settings.clone()))?; if let Some(Some(m)) = shrinks.get(k) { let cm = format!("{} cm\n", m.map(matrix_number).join(" ")); let page = &page_list(doc)[i]; - place_inside_wrapper(doc, page, MarkKind::HeaderFooter.tag(), cm.into_bytes())?; + // The shrink goes with its header: it records the same settings, so Update takes it too. + if let Some(shrink) = place_inside_wrapper(doc, page, MarkKind::HeaderFooter.tag(), cm.into_bytes())? { + doc.update_dict(shrink, |d| d.set(SETTINGS_KEY.to_vec(), settings.clone()))?; + } } } Ok(()) @@ -266,6 +327,11 @@ fn add_background_in_place(doc: &mut Document, pages: &[usize], bg: &Background, /// turns a backdrop [`add_background`] replaced back on where that is still safe; the pages where /// it isn't are [`backdrops_left_off`]. pub fn remove_marks(doc: &mut Document, pages: &[usize], kind: MarkKind) -> Result { + remove_matching(doc, pages, kind, |_, _| true) +} + +/// [`remove_marks`], only for the mark streams `matches` accepts. +fn remove_matching(doc: &mut Document, pages: &[usize], kind: MarkKind, matches: impl Fn(&Document, &Object) -> bool) -> Result { let all = page_list(doc); check(pages, all.len())?; let mut removed = 0; @@ -276,7 +342,7 @@ pub fn remove_marks(doc: &mut Document, pages: &[usize], kind: MarkKind) -> Resu } let list = contents(doc, page)?; let before = list.len(); - let mut kept: Vec = list.into_iter().filter(|o| stream_tag(doc, o).as_deref() != Some(kind.tag())).collect(); + let mut kept: Vec = list.into_iter().filter(|o| stream_tag(doc, o).as_deref() != Some(kind.tag()) || !matches(doc, o)).collect(); removed += before - kept.len(); // Strip only wrapper pairs whose close ends the list (after stripping the pairs after // it): nothing comes after them to need the state they restore. Pairs come from the diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs index 44a6730acc..d719c32ec6 100644 --- a/crates/edit/src/lib.rs +++ b/crates/edit/src/lib.rs @@ -69,10 +69,10 @@ mod apply; mod marks; mod place; -pub use apply::{add_background, add_header_footer, add_watermark, marks_present, remove_marks}; +pub use apply::{add_background, add_header_footer, add_watermark, header_footers, marks_present, remove_marks, update_header_footer}; #[cfg(test)] use marks::bates_start; -pub use marks::{Background, Context, HeaderFooter, MarkKind, MarkSource, Watermark, expand}; +pub use marks::{Background, Context, HeaderFooter, HeaderFooterMark, MarkKind, MarkSource, Watermark, expand}; use marks::{matrix_number, n}; pub(crate) use place::undrawable; #[cfg(test)] diff --git a/crates/edit/src/marks.rs b/crates/edit/src/marks.rs index d936955184..3024e3e38a 100644 --- a/crates/edit/src/marks.rs +++ b/crates/edit/src/marks.rs @@ -1,4 +1,4 @@ -use super::{Document, EditError, Object, Rgb, added}; +use super::{Dict, Document, EditError, Object, Rgb, added}; /// The kinds of page marks. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -86,6 +86,82 @@ impl HeaderFooter { } } +/// One header and footer in a document: its settings and the pages (0-based, ascending) it is on. +/// Marks with the same settings count as one. +#[derive(Clone, Debug, PartialEq)] +pub struct HeaderFooterMark { + pub pages: Vec, + pub settings: HeaderFooter, +} + +/// The entry of a header and footer's content streams that keeps its settings, so Update can tell +/// several apart and fill the dialog with the one chosen (#5785). Drawn text alone can't say +/// which tokens made it. Private to PdfCraft (like `/PCMark`); other readers ignore it. +pub(crate) const SETTINGS_KEY: &[u8] = b"PCHeaderFooter"; + +fn numbers(doc: &Document, o: &Object) -> Option<[f64; N]> { + let values: Vec = doc.resolve(o).as_array()?.iter().map(Object::as_f64).collect::>()?; + <[f64; N]>::try_from(values).ok() +} + +impl HeaderFooter { + /// These settings as the [`SETTINGS_KEY`] entry. + pub(crate) fn to_object(&self) -> Object { + let reals = |v: &[f64]| Object::Array(v.iter().copied().map(Object::Real).collect()); + let mut d = Dict::new(); + d.set(b"Text".to_vec(), Object::Array(self.text.iter().map(|t| Object::String(pdfcraft_cos::PdfString::text(t))).collect())); + d.set( + b"Font".to_vec(), + Object::name(match self.font { + added::Family::Helvetica => "Helvetica", + added::Family::Times => "Times", + added::Family::Courier => "Courier", + }), + ); + d.set(b"Size".to_vec(), Object::Real(self.font_size)); + d.set(b"Color".to_vec(), reals(&self.color)); + d.set(b"Underline".to_vec(), Object::Bool(self.underline)); + d.set(b"Margins".to_vec(), reals(&self.margins)); + d.set(b"Start".to_vec(), Object::Int(i64::from(self.start_number))); + d.set(b"Shrink".to_vec(), Object::Bool(self.shrink)); + Object::Dict(d) + } + + /// Settings back from a [`SETTINGS_KEY`] entry. `None` unless every value is one the dialog + /// could have written: a file can say anything here. + pub(crate) fn from_object(doc: &Document, o: &Object) -> Option { + let resolved = doc.resolve(o); + let d = resolved.as_dict()?; + let flag = |key: &[u8]| match &*doc.resolve(d.get(key)?) { + Object::Bool(b) => Some(*b), + _ => None, + }; + let texts: Vec = + doc.resolve(d.get(b"Text")?).as_array()?.iter().map(|t| Some(doc.resolve(t).as_string()?.to_text())).collect::>()?; + let hf = Self { + text: texts.try_into().ok()?, + font: match d.name(b"Font")? { + b"Helvetica" => added::Family::Helvetica, + b"Times" => added::Family::Times, + b"Courier" => added::Family::Courier, + _ => return None, + }, + font_size: doc.resolve(d.get(b"Size")?).as_f64()?, + color: numbers(doc, d.get(b"Color")?)?, + underline: flag(b"Underline")?, + margins: numbers(doc, d.get(b"Margins")?)?, + start_number: u32::try_from(d.int(b"Start")?).ok()?, + shrink: flag(b"Shrink")?, + }; + let sane = hf.font_size.is_finite() + && hf.font_size > 0.0 + && hf.font_size <= 200.0 + && hf.margins.iter().all(|m| m.is_finite() && *m >= 0.0) + && hf.color.iter().all(|c| (0.0..=1.0).contains(c)); + sane.then_some(hf) + } +} + /// The `cm` that shrinks a page's original content (user space) into the band `hf` leaves free, /// for a page shown `size` (display space) with view matrix `view` (display to user space): an /// even scale, centred across, the content's bottom on the footer's band. diff --git a/crates/edit/src/place.rs b/crates/edit/src/place.rs index b535d60563..d872b73f67 100644 --- a/crates/edit/src/place.rs +++ b/crates/edit/src/place.rs @@ -293,11 +293,11 @@ pub(crate) fn isolation(doc: &Document, list: &[Object]) -> Isolation { /// Put a mark's content on a page: behind (with the behind-marks at the start) or on top /// (appended, after wrapping the original content in q/Q). -pub(crate) fn place(doc: &mut Document, page: &pdfcraft_model::Page, kind: MarkKind, content: Vec, behind: bool) -> Result<(), EditError> { - place_tagged(doc, page, kind.tag(), content, behind)?; +pub(crate) fn place(doc: &mut Document, page: &pdfcraft_model::Page, kind: MarkKind, content: Vec, behind: bool) -> Result { + let mark = place_tagged(doc, page, kind.tag(), content, behind)?; #[cfg(test)] fail_after_mark_placement(kind)?; - Ok(()) + Ok(mark) } #[cfg(test)] @@ -378,29 +378,38 @@ fn too_deep_on_top() -> EditError { /// The refusal [`place_tagged`] gives for a mark on top of `page`, checked before an edit changes /// anything (removing old marks, adding resources) so a refused edit leaves the document as it was. pub(crate) fn check_on_top(doc: &Document, page: &pdfcraft_model::Page) -> Result<(), EditError> { - let obj = doc.get(page.obj); - let list = match obj.as_dict().and_then(|d| d.get(b"Contents")) { - None => return Ok(()), - Some(Object::Ref(r)) => doc.get(*r).as_array().cloned().unwrap_or_else(|| vec![Object::Ref(*r)]), - Some(Object::Array(a)) => a.clone(), - Some(other) => vec![other.clone()], - }; - match isolation(doc, &list) { + match isolation(doc, &content_list(doc, page)) { Isolation::TooDeep => Err(too_deep_on_top()), _ => Ok(()), } } +/// The streams of a page's /Contents, read without changing the document. +pub(crate) fn content_list(doc: &Document, page: &pdfcraft_model::Page) -> Vec { + let obj = doc.get(page.obj); + match obj.as_dict().and_then(|d| d.get(b"Contents")) { + None => Vec::new(), + Some(Object::Ref(r)) => doc.get(*r).as_array().cloned().unwrap_or_else(|| vec![Object::Ref(*r)]), + Some(Object::Array(a)) => a.clone(), + Some(other) => vec![other.clone()], + } +} + /// Put content tagged `tag` first inside the q/Q wrapper, so it applies to the page's original /// content and nothing else (a header's shrink). A page without a wrapper has no original content -/// on it and is left alone. -pub(crate) fn place_inside_wrapper(doc: &mut Document, page: &pdfcraft_model::Page, tag: &str, content: Vec) -> Result<(), EditError> { +/// on it and is left alone. Returns the new content stream, if one was placed. +pub(crate) fn place_inside_wrapper( + doc: &mut Document, + page: &pdfcraft_model::Page, + tag: &str, + content: Vec, +) -> Result, EditError> { let mut list = contents(doc, page)?; - let Some(open) = list.iter().position(|o| stream_tag(doc, o).as_deref() == Some("Wrap")) else { return Ok(()) }; - let stream = Object::Ref(doc.add(Object::Stream(Stream::flate(tagged(tag), &content)))); - list.insert(open + 1, stream); + let Some(open) = list.iter().position(|o| stream_tag(doc, o).as_deref() == Some("Wrap")) else { return Ok(None) }; + let stream = doc.add(Object::Stream(Stream::flate(tagged(tag), &content))); + list.insert(open + 1, Object::Ref(stream)); doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?; - Ok(()) + Ok(Some(stream)) } /// Draw `content` on top of a page (0-based) as permanent page content, with standard Helvetica diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index a6eb76b62b..7410410dfb 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -300,6 +300,69 @@ fn replace_and_remove_restore_the_original_content() { assert_eq!(streams(&reopen(&doc), 0), original, "back to exactly the original content"); } +fn with_text(text: &str) -> HeaderFooter { + let mut hf = HeaderFooter::default(); + hf.text[1] = text.into(); + hf +} + +/// #5785: Update could only reach the newest header and footer, and took every other one on +/// those pages with it. +#[test] +fn update_changes_one_header_and_footer_and_leaves_the_others() { + let mut doc = fixture(); + let (header, footer) = (with_text("Héader <<1>>"), with_text("Footer")); + add_header_footer(&mut doc, &[0], &header, false, &cx()).unwrap(); + add_header_footer(&mut doc, &[0], &footer, false, &cx()).unwrap(); + // Listed after a save too, in the document's own words: tokens unexpanded, accents kept. + let doc = &mut reopen(&doc); + let found = header_footers(doc); + assert_eq!(found.iter().map(|m| (&m.settings, &m.pages[..])).collect::>(), [(&header, &[0][..]), (&footer, &[0][..])]); + + update_header_footer(doc, &found[0].settings, &[0], &with_text("New"), &cx()).unwrap(); + let s = streams(doc, 0); + assert!(s.iter().any(|x| x.contains("(New)")) && s.iter().any(|x| x.contains("(Footer)")), "{s:?}"); + assert!(!s.iter().any(|x| x.contains("eader 1")), "the old header is gone: {s:?}"); + assert_eq!(header_footers(doc).len(), 2); + + let gone = update_header_footer(doc, &header, &[0], &with_text("Again"), &cx()); + assert!(matches!(gone, Err(EditError::Invalid(_))), "{gone:?}"); + assert!(streams(doc, 0).iter().any(|x| x.contains("(New)")), "a refused update changes nothing"); +} + +#[test] +fn updating_a_shrinking_header_takes_its_shrink_away_too() { + let mut doc = fixture(); + let original = streams(&doc, 0); + let shrunk = HeaderFooter { shrink: true, ..with_text("Small") }; + add_header_footer(&mut doc, &[0], &shrunk, false, &cx()).unwrap(); + update_header_footer(&mut doc, &shrunk, &[0], &with_text("Plain"), &cx()).unwrap(); + let s = streams(&doc, 0); + assert_eq!(s.iter().filter(|x| x.contains("/PCMark")).count(), 1); + assert!(original.iter().all(|o| s.contains(o)), "{s:?}"); + assert_eq!(s.len(), original.len() + 3, "the original, one wrapper and the new mark: {s:?}"); +} + +#[test] +fn settings_a_file_makes_up_are_not_listed() { + let mut doc = fixture(); + add_header_footer(&mut doc, &[0], &with_text("Real"), false, &cx()).unwrap(); + let page = crate::page_list(&doc).swap_remove(0); + let marks: Vec<_> = crate::contents(&mut doc, &page) + .unwrap() + .iter() + .filter_map(Object::as_ref) + .filter(|r| doc.get(*r).as_dict().is_some_and(|d| d.contains(b"PCHeaderFooter"))) + .collect(); + assert_eq!(marks.len(), 1); + let mut hostile = Dict::new(); + hostile.set(b"Text".to_vec(), Object::Array(vec![Object::Int(1)])); + hostile.set(b"Size".to_vec(), Object::Real(f64::NAN)); + doc.update_dict(marks[0], |d| d.set(b"PCHeaderFooter".to_vec(), Object::Dict(hostile))).unwrap(); + assert!(header_footers(&doc).is_empty()); + assert_eq!(marks_present(&doc), [MarkKind::HeaderFooter], "still a mark: Remove and page-wide Update reach it"); +} + /// The six numbers of the first `… cm` in `content`. fn first_cm(content: &str) -> [f64; 6] { let line = content.lines().find(|l| l.ends_with(" cm")).unwrap_or_else(|| panic!("no cm in {content:?}")); diff --git a/crates/engine/src/document.rs b/crates/engine/src/document.rs index fa98a18417..55b2a0384f 100644 --- a/crates/engine/src/document.rs +++ b/crates/engine/src/document.rs @@ -455,6 +455,11 @@ impl Document { .marks } + /// The headers and footers Update can tell apart (`pdfcraft_edit::header_footers`). + pub fn header_footers(&self) -> Vec { + self.editor.as_ref().map(|e| pdfcraft_edit::header_footers(&e.cos)).unwrap_or_default() + } + /// Text and images added with Edit a PDF ▸ Add content (still editable). pub fn added(&self) -> &[pdfcraft_edit::Added] { &self diff --git a/crates/engine/src/edit.rs b/crates/engine/src/edit.rs index 8f43689aa9..e531f4889f 100644 --- a/crates/engine/src/edit.rs +++ b/crates/engine/src/edit.rs @@ -436,6 +436,13 @@ pub enum Edit { settings: HeaderFooter, replace: bool, }, + /// Update one header and footer: `old` (settings from `Document::header_footers`) goes from + /// every page it is on and `settings` is added to `pages`. Others stay. + UpdateHeaderFooter { + old: HeaderFooter, + pages: Vec, + settings: HeaderFooter, + }, /// `file`: a picture from a file (an image, or a page of a PDF) instead of text. AddWatermark { pages: Vec, diff --git a/crates/engine/src/edit/labels.rs b/crates/engine/src/edit/labels.rs index 5343804ef3..82be79e017 100644 --- a/crates/engine/src/edit/labels.rs +++ b/crates/engine/src/edit/labels.rs @@ -276,7 +276,7 @@ impl Edit { ImageEdit::RemoveCrop => "Remove crop", }), Edit::AddHeaderFooter { replace: false, .. } => Label::of("Add header & footer"), - Edit::AddHeaderFooter { .. } => Label::of("Update header & footer"), + Edit::AddHeaderFooter { .. } | Edit::UpdateHeaderFooter { .. } => Label::of("Update header & footer"), Edit::AddWatermark { replace: false, .. } => Label::of("Add watermark"), Edit::AddWatermark { .. } => Label::of("Update watermark"), Edit::AddBackground { replace: false, .. } => Label::of("Add background"), diff --git a/crates/engine/src/edit/run.rs b/crates/engine/src/edit/run.rs index 5ed70aed7a..f67581ebca 100644 --- a/crates/engine/src/edit/run.rs +++ b/crates/engine/src/edit/run.rs @@ -96,6 +96,7 @@ pub(crate) fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Re } Edit::SetInfo { .. } | Edit::AddHeaderFooter { .. } + | Edit::UpdateHeaderFooter { .. } | Edit::AddWatermark { .. } | Edit::AddBackground { .. } | Edit::RemoveMarks { .. } @@ -708,6 +709,10 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E let date = cx.today; pdfcraft_edit::add_header_footer(doc, pages, settings, *replace, &pdfcraft_edit::Context { date })?; } + Edit::UpdateHeaderFooter { old, pages, settings } => { + let date = cx.today; + pdfcraft_edit::update_header_footer(doc, old, pages, settings, &pdfcraft_edit::Context { date })?; + } Edit::AddWatermark { pages, settings, replace, file } => { let mut s = settings.clone(); if let Some(f) = file { diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index fafa65b4c2..8c2ac7587a 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -84,6 +84,7 @@ pub(crate) fn scope_of(edit: &Edit) -> Scope { | Edit::ReplaceImage { .. } | Edit::PasteContent { .. } | Edit::AddHeaderFooter { .. } + | Edit::UpdateHeaderFooter { .. } | Edit::AddWatermark { .. } | Edit::AddBackground { .. } | Edit::RemoveMarks { .. } => Scope::Content, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index fe139164be..93d22b1bb2 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -86,7 +86,8 @@ pub use pdfcraft_edit::added::{ }; pub use pdfcraft_edit::paragraph_align; pub use pdfcraft_edit::{ - Added, AddedImage, AddedText, Align as TextAlign, Background, Content as AddedContent, Family as FontFamily, HeaderFooter, MarkKind, Watermark, + Added, AddedImage, AddedText, Align as TextAlign, Background, Content as AddedContent, Family as FontFamily, HeaderFooter, HeaderFooterMark, + MarkKind, Watermark, }; pub use pdfcraft_forms::{ BorderStyle, CalculatedField, CalculationIssue, CalculationOrder, CheckStyle, Field as FormField, FieldAction, FieldChange, FieldFont, diff --git a/crates/engine/src/session/editing.rs b/crates/engine/src/session/editing.rs index be7fd5aca5..2e0c8e6ded 100644 --- a/crates/engine/src/session/editing.rs +++ b/crates/engine/src/session/editing.rs @@ -417,7 +417,14 @@ impl Session { ) || matches!(e, Edit::MoveObjects { objects, .. } if objects.iter().any(|o| o.kind == ObjectKind::Added)) }); let touches_marks = edit.is_none_or(|e| { - matches!(e, Edit::AddHeaderFooter { .. } | Edit::AddWatermark { .. } | Edit::AddBackground { .. } | Edit::RemoveMarks { .. }) + matches!( + e, + Edit::AddHeaderFooter { .. } + | Edit::UpdateHeaderFooter { .. } + | Edit::AddWatermark { .. } + | Edit::AddBackground { .. } + | Edit::RemoveMarks { .. } + ) }); (touches_added, touches_marks) } diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs index f072b7febe..e0296d2e4a 100644 --- a/crates/ui-egui/src/commands.rs +++ b/crates/ui-egui/src/commands.rs @@ -495,6 +495,15 @@ impl PdfCraftApp { K::Background }; self.marks_draft.replace = id.ends_with(".update"); + let header_footers = match (id, self.active_ids()) { + ("edit.header_footer.update", Some((i, doc))) => { + let found = self.session.get(doc).map(|d| d.header_footers()).unwrap_or_default(); + Some((found, self.views[i].current)) + } + _ => None, + }; + let (found, current) = header_footers.unwrap_or_default(); + self.marks_draft.update_choices(found, current); self.marks_draft.opened(kind); self.marks_draft.preview = None; self.dialog = Some(Dialog::Marks(kind)); @@ -503,6 +512,7 @@ impl PdfCraftApp { // Bates numbering ▸ Add: the header & footer dialog with a Bates number in the // bottom-right box (6 digits from 1), ready to edit. self.marks_draft.replace = false; + self.marks_draft.update_choices(Vec::new(), 0); if self.marks_draft.hf.text.iter().all(|t| !t.contains("< Self { + let (Some(&first), Some(&last)) = (pages.first(), pages.last()) else { return Self::default() }; + let every_other = pages.len() > 1 && pages.windows(2).all(|w| matches!(w, [a, b] if a + 2 == *b)); + let subset = match every_other.then_some((first + 1) % 2) { + Some(0) => Subset::Even, + Some(_) => Subset::Odd, + None => Subset::All, + }; + Self { all: false, from: first + 1, to: last + 1, subset } + } + /// The pages (0-based) the range selects in a document of `count` pages. pub fn pages(&self, count: usize) -> Vec { let (a, b) = if self.all { (1, count) } else { (self.from.max(1), self.to.min(count)) }; @@ -201,6 +214,11 @@ pub struct MarksDraft { pub range: PageRange, /// Replace existing marks of this kind (Update). pub replace: bool, + /// Update: the headers and footers in the document, to pick the one to change (#5785). + pub header_footers: Vec, + /// Which of [`Self::header_footers`] Update changes, and the range that was filled in for it. + /// That range can only approximate pages such as 1, 2 and 5: while it stands, OK means them. + pub updating: Option<(usize, PageRange)>, /// Which header/footer box Insert Page Number / Insert Date type into. pub focused_box: usize, pub page_format: usize, @@ -226,6 +244,8 @@ impl Default for MarksDraft { bg: Background::default(), range: PageRange::default(), replace: false, + header_footers: Vec::new(), + updating: None, focused_box: 1, page_format: 0, date_format: 0, @@ -239,6 +259,54 @@ impl Default for MarksDraft { } } +impl MarksDraft { + /// Update opens on the header and footer of page `current` (0-based), the newest one there, + /// or the document's last. No choices (a mark from before settings were recorded, or Add) + /// leaves the draft as it is. + pub fn update_choices(&mut self, found: Vec, current: usize) { + self.header_footers = found; + self.updating = None; + let on_current = self.header_footers.iter().rposition(|m| m.pages.contains(¤t)); + if let Some(i) = on_current.or(self.header_footers.len().checked_sub(1)) { + self.choose_header_footer(i); + } + } + + /// Fill the dialog with header and footer `i`. + pub fn choose_header_footer(&mut self, i: usize) { + let Some(mark) = self.header_footers.get(i) else { return }; + self.hf = mark.settings.clone(); + self.range = PageRange::around(&mark.pages); + self.updating = Some((i, self.range)); + self.preview = None; + } + + /// The header and footer OK replaces. + fn updated(&self) -> Option<&pdfcraft_engine::HeaderFooterMark> { + self.header_footers.get(self.updating?.0) + } + + /// The pages (0-based) OK applies to, in a document of `count` pages. + pub fn pages(&self, count: usize) -> Vec { + match (self.updated(), self.updating) { + (Some(mark), Some((_, range))) if self.replace && range == self.range => mark.pages.clone(), + _ => self.range.pages(count), + } + } +} + +/// What the Update dialog calls a header and footer: its pages and the start of its text. +fn header_footer_label(mark: &pdfcraft_engine::HeaderFooterMark) -> String { + const SHOWN_CHARS: usize = 40; + let pages = pages_phrase(&mark.pages, tl!("Page {pages}"), tl!("Pages {pages}")); + let text = mark.settings.text.iter().find(|t| !t.trim().is_empty()).map_or("", |t| t.trim()); + let mut shown: String = text.chars().take(SHOWN_CHARS).collect(); + if text.chars().nth(SHOWN_CHARS).is_some() { + shown.push('…'); + } + format!("{pages}: {shown}") +} + const PAGE_FORMATS: [&str; 5] = ["<<1>>", "<<1 of n>>", "<<1/n>>", "<>", "<>"]; // New formats go last: `date_format` is an index into this list. const DATE_FORMATS: [&str; 11] = [ @@ -472,6 +540,24 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, kind: M }; ui.label(egui::RichText::new(title).font(theme::semibold(18.0))); ui.add_space(8.0); + if kind == MarkKind::HeaderFooter && d.replace && d.header_footers.len() > 1 { + ui.horizontal(|ui| { + ui.label(tl!("Which header and footer:")); + let shown = d.updated().map(header_footer_label).unwrap_or_default(); + let mut picked = None; + craft_ui::ComboBox::from_id_salt("mark-header-footer").selected_text(shown).show_ui(ui, |ui| { + for (i, mark) in d.header_footers.iter().enumerate() { + if ui.selectable_label(d.updating.is_some_and(|(at, _)| at == i), header_footer_label(mark)).clicked() { + picked = Some(i); + } + } + }); + if let Some(i) = picked { + d.choose_header_footer(i); + } + }); + ui.add_space(6.0); + } match kind { MarkKind::HeaderFooter => { ui.horizontal(|ui| { @@ -734,11 +820,13 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, kind: M d.preview = next.or(d.preview); } }); - let n = d.range.pages(count).len(); + let n = d.pages(count).len(); let applies = if n == 1 { tl!("Applies to 1 page").to_string() } else { crate::i18n::fmt(tl!("Applies to {n} pages"), &[("n", &n.to_string())]) }; ui.label(egui::RichText::new(applies).small().color(t.text_faint)); - if d.replace { + if d.replace && kind == MarkKind::HeaderFooter && d.updated().is_some() { + ui.label(egui::RichText::new(tl!("Replaces this header and footer, and no other.")).small().color(t.text_faint)); + } else if d.replace { ui.label(egui::RichText::new(tl!("Replaces the existing one on those pages.")).small().color(t.text_faint)); } }); @@ -765,7 +853,7 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, kind: M } MarkKind::Background => !d.use_file || d.file.is_some(), } - && !d.range.pages(count).is_empty(); + && !d.pages(count).is_empty(); if ui.add_enabled_ui(ready, |ui| widgets::pill_button(ui, tl!("OK"), true)).inner.clicked() { apply = true; } @@ -867,9 +955,12 @@ fn backdrop_options(ui: &mut egui::Ui, t: &Tokens, d: &mut MarksDraft, doc: &pdf /// The edit the dialog's OK makes. pub fn edit(d: &MarksDraft, kind: MarkKind, count: usize) -> Edit { - let pages = d.range.pages(count); + let pages = d.pages(count); match kind { - MarkKind::HeaderFooter => Edit::AddHeaderFooter { pages, settings: d.hf.clone(), replace: d.replace }, + MarkKind::HeaderFooter => match d.updated().filter(|_| d.replace) { + Some(mark) => Edit::UpdateHeaderFooter { old: mark.settings.clone(), pages, settings: d.hf.clone() }, + None => Edit::AddHeaderFooter { pages, settings: d.hf.clone(), replace: d.replace }, + }, MarkKind::Watermark => { let mut wm = d.wm.clone(); if d.fit { diff --git a/crates/ui-egui/tests/it/marks.rs b/crates/ui-egui/tests/it/marks.rs index 22832a012e..03762919db 100644 --- a/crates/ui-egui/tests/it/marks.rs +++ b/crates/ui-egui/tests/it/marks.rs @@ -63,6 +63,45 @@ fn header_and_footer_dialog_inserts_tokens_and_applies_to_a_subset() { assert!(marks(&h).is_empty()); } +/// #5785: with several headers and footers, Update reaches any of them, on the page it opens on +/// or through the list, and changes that one alone. +#[test] +fn update_can_change_an_earlier_header_and_footer() { + use pdfcraft_engine::{Edit, HeaderFooter}; + let mut h = harness(); + let add = |h: &mut Harness<'static, PdfCraftApp>, pages: Vec, text: &str| { + let mut settings = HeaderFooter::default(); + settings.text[1] = text.into(); + h.state_mut().apply_edit(Edit::AddHeaderFooter { pages, settings, replace: false }); + h.run_steps(2); + }; + add(&mut h, vec![0, 1], "Earlier"); + add(&mut h, vec![2], "Later"); + add(&mut h, vec![0, 1, 2], "Over all"); + + assert!(h.state_mut().execute("edit.header_footer.update")); + h.run_steps(3); + assert_eq!(h.state().marks_draft.hf.text[1], "Over all", "the newest on the page shown"); + h.get_by_label("Which header and footer:"); + h.state_mut().marks_draft.choose_header_footer(0); + h.run_steps(2); + assert_eq!(h.state().marks_draft.hf.text[1], "Earlier", "the dialog fills in from the one chosen"); + assert_eq!(h.state().marks_draft.pages(3), [0, 1], "on its own pages"); + h.state_mut().marks_draft.hf.text[1] = "Changed".into(); + h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(4); + + let s = h.state(); + let texts: Vec<(String, Vec)> = + s.session.get(s.views[0].id).unwrap().header_footers().into_iter().map(|m| (m.settings.text[1].clone(), m.pages)).collect(); + assert_eq!( + texts, + [("Over all".to_string(), vec![0, 1, 2]), ("Changed".to_string(), vec![0, 1]), ("Later".to_string(), vec![2])], + "the others are as they were" + ); +} + #[test] fn header_and_footer_dialog_draws_in_the_chosen_face() { // #3754: the dialog offers Helvetica, Times and Courier (it only said "Font: Helvetica"), diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 290a410e14..c849cd8af1 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -2459,9 +2459,9 @@ tier = "P0" milestone = "M7" status = "shipped" commands = ["edit.header_footer.update", "edit.header_footer.remove"] -tools = ["doc_header_footer", "doc_remove_marks"] -evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/ui-egui/tests/it/marks.rs::header_and_footer_dialog_inserts_tokens_and_applies_to_a_subset", "crates/edit/src/mark_transaction_tests.rs::header_footer_changes_are_atomic_after_a_later_page_failure", "crates/edit/src/mark_transaction_tests.rs::replacements_commit_all_selected_pages_and_preserve_other_marks_and_shared_resources"] -notes = "Add and Update are atomic across all selected pages: errors preserve existing marks, page content/resources and pending edits (#5657). recognises PdfCraft marks; Acrobat-made headers are not detected yet" +tools = ["doc_header_footer", "doc_header_footers", "doc_remove_marks"] +evidence = ["crates/edit/src/tests.rs::update_changes_one_header_and_footer_and_leaves_the_others", "crates/ui-egui/tests/it/marks.rs::update_can_change_an_earlier_header_and_footer", "crates/automation/tests/it/automation.rs::header_footer_update_changes_the_one_named", "crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/ui-egui/tests/it/marks.rs::header_and_footer_dialog_inserts_tokens_and_applies_to_a_subset", "crates/edit/src/mark_transaction_tests.rs::header_footer_changes_are_atomic_after_a_later_page_failure", "crates/edit/src/mark_transaction_tests.rs::replacements_commit_all_selected_pages_and_preserve_other_marks_and_shared_resources"] +notes = "Add and Update are atomic across all selected pages: errors preserve existing marks, page content/resources and pending edits (#5657). Each header and footer records its settings, so Update can choose among several and fills the dialog from the one chosen, leaving the others in place (#5785); marks made before that, which record none, are still replaced page by page, and the dialog's preview still hides every header and footer on the page, not just the one chosen. recognises PdfCraft marks; Acrobat-made headers are not detected yet" [[feature]] id = "edit.header-footer-tokens" From 193f0750a4e6796d884f0910fdafc21aa227eac2 Mon Sep 17 00:00:00 2001 From: jweaver3 <43688514+jweaver3@users.noreply.github.com> Date: Thu, 5 Nov 2026 19:18:15 -0500 Subject: [PATCH 021/114] fix(edit): address review of header & footer Update (#5785) - Redaction removes /PCHeaderFooter from a redacted header's stream and from its shrink stream, so a full save keeps no copy of the text. - edit.header_footer.update no longer routes to the read-only doc_header_footers tool. - Recorded settings: resolve indirect values, check the Text count and box sizes before decoding, and list only settings add would accept (shared HeaderFooter::check). The colour is recorded as drawn. - doc_header_footers withholds text when copying is not allowed; an update returns the renumbered listing. - Update dialog: opens on the header added last to the page, offers older headers without settings as a page-wide choice, refuses when another document came forward, keeps sizes and start numbers past its controls' range, previews the pages OK changes, and applies an edited range as shown. The chooser is labelled for screen readers. Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/documents.rs | 33 ++- crates/automation/src/tools.rs | 6 +- crates/automation/tests/it/automation.rs | 13 +- crates/edit/src/apply.rs | 33 ++- crates/edit/src/lib.rs | 5 +- crates/edit/src/marks.rs | 62 +++-- crates/edit/src/tests.rs | 100 +++++++- crates/engine/src/document.rs | 10 + crates/redact/src/lib.rs | 17 ++ crates/redact/src/tests.rs | 16 ++ crates/ui-egui/src/commands.rs | 17 +- crates/ui-egui/src/dialogs.rs | 12 +- crates/ui-egui/src/dialogs/marks_ui.rs | 277 ++++++++++++++++++----- crates/ui-egui/tests/it/marks.rs | 28 ++- parity/acrobat-features.toml | 4 +- 15 files changed, 510 insertions(+), 123 deletions(-) diff --git a/crates/automation/src/documents.rs b/crates/automation/src/documents.rs index fdccc7309a..fe774c77c0 100644 --- a/crates/automation/src/documents.rs +++ b/crates/automation/src/documents.rs @@ -453,20 +453,30 @@ impl Automation { } /// The headers and footers with recorded settings, as `doc_header_footer`'s `update` names them. + /// Their text is copied out only where the document allows copying, as with `doc_to_copy`. pub(crate) fn header_footers(&mut self, a: &Args) -> Result { - let found: Vec = self - .doc(a)? + let doc = self.doc(a)?; + let copying = doc.check_copying().is_ok(); + let found: Vec = doc .header_footers() .iter() .enumerate() .map(|(i, m)| { - let boxes = ["header_left", "header_center", "header_right", "footer_left", "footer_center", "footer_right"]; - let text: serde_json::Map = - boxes.iter().zip(&m.settings.text).filter(|(_, t)| !t.is_empty()).map(|(k, t)| ((*k).to_string(), json!(t))).collect(); - json!({ "index": i, "pages": m.pages.iter().map(|p| p + 1).collect::>(), "text": text }) + let mut out = json!({ "index": i, "pages": m.pages.iter().map(|p| p + 1).collect::>() }); + if copying { + let boxes = ["header_left", "header_center", "header_right", "footer_left", "footer_center", "footer_right"]; + let text: serde_json::Map = + boxes.iter().zip(&m.settings.text).filter(|(_, t)| !t.is_empty()).map(|(k, t)| ((*k).to_string(), json!(t))).collect(); + out["text"] = Value::Object(text); + } + out }) .collect(); - Ok(json!({ "header_footers": found })) + let mut out = json!({ "header_footers": found }); + if !copying { + out["text_withheld"] = json!("the document does not allow copying its text"); + } + Ok(out) } /// Pages whose own backdrop hides a background (see `pdfcraft_edit::backdrop`). @@ -508,6 +518,7 @@ impl Automation { } None => None, }; + let updated = updating.is_some(); let pages = match (a.opt_ints("pages")?, &updating) { (Some(_), _) => self.pages(a, "pages")?, (None, Some(mark)) => mark.pages.clone(), @@ -592,7 +603,13 @@ impl Automation { Edit::RemoveMarks { kind } } }; - self.apply(a, edit) + let mut out = self.apply(a, edit)?; + // An update renumbers the listing (the replacement goes on top of the page), so earlier + // indices no longer hold: hand back the list they now refer to. + if updated { + out["header_footers"] = self.header_footers(a)?["header_footers"].take(); + } + Ok(out) } pub(crate) fn export(&mut self, tool: &str, a: &Args) -> Result { diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 1d87eaf6cd..b48ef5b9cc 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -992,7 +992,7 @@ pub fn tools() -> Vec { t( "doc_header_footer", "Add header and footer", - "Add a header and/or footer to pages. Text boxes: header_left/center/right, footer_left/center/right. Tokens: <<1>> page number, <> page count, <<1 of n>>, <>, <<1/n>>, dates <> <> <> <> (and more), Bates <>. shrink: true scales the page content down evenly into the room the header and footer leave free, so they don't cover it. font: Helvetica (default), Times or Courier. replace: true swaps out every one on those pages. update: an index from doc_header_footers changes that one alone, on its own pages unless pages is given; settings left out go back to their defaults. Undoable.", + "Add a header and/or footer to pages. Text boxes: header_left/center/right, footer_left/center/right. Tokens: <<1>> page number, <> page count, <<1 of n>>, <>, <<1/n>>, dates <> <> <> <> (and more), Bates <>. shrink: true scales the page content down evenly into the room the header and footer leave free, so they don't cover it. font: Helvetica (default), Times or Courier. replace: true swaps out every one on those pages. update: an index from doc_header_footers changes that one alone, on its own pages unless pages is given; settings left out go back to their defaults, and the result lists them again with their new indices. Undoable.", ) .cmd("edit.header_footer") .with(schema( @@ -1043,9 +1043,9 @@ pub fn tools() -> Vec { .ro() .cmd("edit.background") .with(schema(json!({ "doc": doc(), "pages": pages("to check (default: all)") }), &["doc"])), - t("doc_header_footers", "List headers and footers", "The headers and footers in the document, each with an `index` for doc_header_footer's `update`, its 1-based `pages` and the `text` of its boxes, tokens unexpanded. Lists those PdfCraft recorded settings for; older ones and other tools' are left out.") + // No command: edit.header_footer.update changes the document, and this only lists. + t("doc_header_footers", "List headers and footers", "The headers and footers in the document, each with an `index` for doc_header_footer's `update`, its 1-based `pages` and the `text` of its boxes, tokens unexpanded (left out, with `text_withheld`, when the document does not allow copying). Lists those PdfCraft recorded settings for; older ones and other tools' are left out. An index holds only until the next change: an update returns the list again.") .ro() - .cmd("edit.header_footer.update") .with(schema(json!({ "doc": doc() }), &["doc"])), t("doc_remove_marks", "Remove header & footer, watermark or background", "Remove every header and footer, watermark or background PdfCraft (or a compatible tool) added. Undoable.") .destructive() diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index c2248b2c8c..241ef5af92 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -2463,6 +2463,11 @@ fn copy_restricted_text_stays_in_the_document() { } let restyled = ok(&mut a, "text_edit", json!({ "doc": re, "page": 1, "paragraph": 1, "size": 30 })); assert!(!restyled.to_string().contains("Page"), "{restyled}"); + // A header's text is listed only where copying is allowed: its index and pages still are. + ok(&mut a, "doc_header_footer", json!({ "doc": re, "pages": [1], "header_left": "HEADERTEXT" })); + let listed = ok(&mut a, "doc_header_footers", json!({ "doc": re })); + assert!(!listed.to_string().contains("HEADERTEXT") && listed["text_withheld"].is_string(), "{listed}"); + assert_eq!(listed["header_footers"][0]["pages"], json!([1])); if ok(&mut a, "ocr_status", json!({}))["available"] != true { eprintln!("skipped the OCR part: OCR models not installed"); return; @@ -2812,7 +2817,8 @@ fn header_footer_update_changes_the_one_named() { assert_eq!(listed["header_footers"][1], json!({ "index": 1, "pages": [2, 3], "text": { "header_left": "SECOND" } })); // Added after listing, so index 0 is still FIRST; it shares page 1 with FIRST and must stay. ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [1], "footer_left": "THIRD" })); - ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": 0, "header_left": "CHANGED" })); + let updated = ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": 0, "header_left": "CHANGED" })); + assert_eq!(updated["header_footers"], ok(&mut a, "doc_header_footers", json!({ "doc": doc }))["header_footers"], "the indices that hold now"); let texts = page_text(&mut a, doc); assert!(texts[0].contains("CHANGED") && !texts[0].contains("FIRST"), "{texts:?}"); assert!(texts[0].contains("THIRD"), "the other one on that page stays: {texts:?}"); @@ -2820,6 +2826,11 @@ fn header_footer_update_changes_the_one_named() { for bad in [json!({ "doc": doc, "update": 9, "header_left": "X" }), json!({ "doc": doc, "update": 0, "replace": true, "header_left": "X" })] { assert!(matches!(a.call("doc_header_footer", &bad), Err(ToolError::InvalidArgs(_))), "{bad}"); } + // The Update command changes a document: it must not run the read-only listing and report success. + let by_command = json!({ "id": "edit.header_footer.update", "params": { "doc": doc, "update": 0, "header_left": "VIA COMMAND" } }); + let listed = ok(&mut a, "doc_header_footers", json!({ "doc": doc })); + assert!(a.call("command_run", &by_command).is_err()); + assert_eq!(ok(&mut a, "doc_header_footers", json!({ "doc": doc })), listed); } #[test] diff --git a/crates/edit/src/apply.rs b/crates/edit/src/apply.rs index 933132c6d6..ee3fda99ff 100644 --- a/crates/edit/src/apply.rs +++ b/crates/edit/src/apply.rs @@ -65,6 +65,29 @@ pub fn header_footers(doc: &Document) -> Vec { found } +/// The header and footer added last to page `page` (0-based): `Some(None)` when it records no +/// settings (from before they were recorded, or another tool), `None` when the page has none. +/// Each mark's own stream goes on top of the page's content, so the last one is the newest; a +/// shrink goes underneath, inside the wrapper, and is never last. +pub fn newest_header_footer(doc: &Document, page: usize) -> Option> { + let page = page_list(doc).into_iter().nth(page)?; + let content = content_list(doc, &page); + let newest = content.iter().rev().find(|o| stream_tag(doc, o).as_deref() == Some(MarkKind::HeaderFooter.tag()))?; + Some(recorded_settings(doc, newest)) +} + +/// Pages (0-based) with a header and footer that records no settings: Update can only replace +/// those page-wide, as it did before settings were recorded. +pub fn unrecorded_header_footer_pages(doc: &Document) -> Vec { + let tagged = |o: &Object| stream_tag(doc, o).as_deref() == Some(MarkKind::HeaderFooter.tag()); + page_list(doc) + .iter() + .enumerate() + .filter(|(_, page)| content_list(doc, page).iter().any(|o| tagged(o) && recorded_settings(doc, o).is_none())) + .map(|(i, _)| i) + .collect() +} + /// Which existing headers and footers an added one takes the place of. #[derive(Clone, Copy)] enum Replacing<'a> { @@ -76,15 +99,7 @@ enum Replacing<'a> { fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replacing: Replacing, cx: &Context) -> Result<(), EditError> { let all = page_list(doc); check(pages, all.len())?; - if hf.text.iter().all(|t| t.trim().is_empty()) { - return Err(EditError::Invalid("type the header or footer text first".into())); - } - if let Some(c) = hf.first_undrawable() { - return Err(undrawable(c)); - } - if !(hf.font_size.is_finite() && hf.font_size > 0.0 && hf.font_size <= 200.0 && hf.margins.iter().all(|m| m.is_finite() && *m >= 0.0)) { - return Err(EditError::Invalid("invalid font size or margins".into())); - } + hf.check()?; // Page numbers count up from start_number, so the last selected page needs the most room. // Refuse the whole run before drawing anything: headers applied to some pages and then a // failed page number would leave the document half changed. diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs index d719c32ec6..2af4168bd5 100644 --- a/crates/edit/src/lib.rs +++ b/crates/edit/src/lib.rs @@ -69,7 +69,10 @@ mod apply; mod marks; mod place; -pub use apply::{add_background, add_header_footer, add_watermark, header_footers, marks_present, remove_marks, update_header_footer}; +pub use apply::{ + add_background, add_header_footer, add_watermark, header_footers, marks_present, newest_header_footer, remove_marks, + unrecorded_header_footer_pages, update_header_footer, +}; #[cfg(test)] use marks::bates_start; pub use marks::{Background, Context, HeaderFooter, HeaderFooterMark, MarkKind, MarkSource, Watermark, expand}; diff --git a/crates/edit/src/marks.rs b/crates/edit/src/marks.rs index 3024e3e38a..ac959ab09c 100644 --- a/crates/edit/src/marks.rs +++ b/crates/edit/src/marks.rs @@ -99,15 +99,40 @@ pub struct HeaderFooterMark { /// which tokens made it. Private to PdfCraft (like `/PCMark`); other readers ignore it. pub(crate) const SETTINGS_KEY: &[u8] = b"PCHeaderFooter"; +/// The most bytes one recorded text box may take. A dialog box never needs more, and it bounds +/// what listing the headers and footers of a hostile file decodes. +const MAX_RECORDED_TEXT: usize = 16 * 1024; + +/// An array of exactly `N` numbers, each resolved: a rewriting tool may make any of them indirect. fn numbers(doc: &Document, o: &Object) -> Option<[f64; N]> { - let values: Vec = doc.resolve(o).as_array()?.iter().map(Object::as_f64).collect::>()?; + let array = doc.resolve(o); + let items = array.as_array().filter(|a| a.len() == N)?; + let values: Vec = items.iter().map(|v| doc.resolve(v).as_f64()).collect::>()?; <[f64; N]>::try_from(values).ok() } impl HeaderFooter { - /// These settings as the [`SETTINGS_KEY`] entry. + /// Why [`add_header_footer`] refuses these settings, if it does. A recorded header and footer + /// is listed only when it passes too, so every one Update offers is one OK can apply. + pub(crate) fn check(&self) -> Result<(), EditError> { + if self.text.iter().all(|t| t.trim().is_empty()) { + return Err(EditError::Invalid("type the header or footer text first".into())); + } + if let Some(c) = self.first_undrawable() { + return Err(super::place::undrawable(c)); + } + if !(self.font_size.is_finite() && self.font_size > 0.0 && self.font_size <= 200.0 && self.margins.iter().all(|m| m.is_finite() && *m >= 0.0)) + { + return Err(EditError::Invalid("invalid font size or margins".into())); + } + Ok(()) + } + + /// These settings as the [`SETTINGS_KEY`] entry. The colour is recorded as drawn (see `rgb`), + /// so a header added with an out-of-range colour can still be listed and updated. pub(crate) fn to_object(&self) -> Object { let reals = |v: &[f64]| Object::Array(v.iter().copied().map(Object::Real).collect()); + let drawn = self.color.map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.0 }); let mut d = Dict::new(); d.set(b"Text".to_vec(), Object::Array(self.text.iter().map(|t| Object::String(pdfcraft_cos::PdfString::text(t))).collect())); d.set( @@ -119,7 +144,7 @@ impl HeaderFooter { }), ); d.set(b"Size".to_vec(), Object::Real(self.font_size)); - d.set(b"Color".to_vec(), reals(&self.color)); + d.set(b"Color".to_vec(), reals(&drawn)); d.set(b"Underline".to_vec(), Object::Bool(self.underline)); d.set(b"Margins".to_vec(), reals(&self.margins)); d.set(b"Start".to_vec(), Object::Int(i64::from(self.start_number))); @@ -132,32 +157,39 @@ impl HeaderFooter { pub(crate) fn from_object(doc: &Document, o: &Object) -> Option { let resolved = doc.resolve(o); let d = resolved.as_dict()?; - let flag = |key: &[u8]| match &*doc.resolve(d.get(key)?) { + // Every value resolved: a rewriting tool may make any of them indirect. + let value = |key: &[u8]| d.get(key).map(|v| doc.resolve(v)); + let flag = |key: &[u8]| match &*value(key)? { Object::Bool(b) => Some(*b), _ => None, }; - let texts: Vec = - doc.resolve(d.get(b"Text")?).as_array()?.iter().map(|t| Some(doc.resolve(t).as_string()?.to_text())).collect::>()?; + // The count and each size are checked before anything is decoded or copied. + let texts = value(b"Text")?; + let texts = texts.as_array().filter(|a| a.len() == 6)?; + let text: Vec = texts + .iter() + .map(|t| { + let t = doc.resolve(t); + let s = t.as_string().filter(|s| s.bytes.len() <= MAX_RECORDED_TEXT)?; + Some(s.to_text()) + }) + .collect::>()?; let hf = Self { - text: texts.try_into().ok()?, - font: match d.name(b"Font")? { + text: text.try_into().ok()?, + font: match value(b"Font")?.as_name()? { b"Helvetica" => added::Family::Helvetica, b"Times" => added::Family::Times, b"Courier" => added::Family::Courier, _ => return None, }, - font_size: doc.resolve(d.get(b"Size")?).as_f64()?, + font_size: value(b"Size")?.as_f64()?, color: numbers(doc, d.get(b"Color")?)?, underline: flag(b"Underline")?, margins: numbers(doc, d.get(b"Margins")?)?, - start_number: u32::try_from(d.int(b"Start")?).ok()?, + start_number: u32::try_from(value(b"Start")?.as_int()?).ok()?, shrink: flag(b"Shrink")?, }; - let sane = hf.font_size.is_finite() - && hf.font_size > 0.0 - && hf.font_size <= 200.0 - && hf.margins.iter().all(|m| m.is_finite() && *m >= 0.0) - && hf.color.iter().all(|c| (0.0..=1.0).contains(c)); + let sane = hf.check().is_ok() && hf.color.iter().all(|c| (0.0..=1.0).contains(c)); sane.then_some(hf) } } diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index 7410410dfb..fab26bbcaa 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -318,11 +318,13 @@ fn update_changes_one_header_and_footer_and_leaves_the_others() { let doc = &mut reopen(&doc); let found = header_footers(doc); assert_eq!(found.iter().map(|m| (&m.settings, &m.pages[..])).collect::>(), [(&header, &[0][..]), (&footer, &[0][..])]); + // "Héader 1" is drawn with its é as an escape: what follows it is the old header's drawing. + assert!(streams(doc, 0).iter().any(|x| x.contains("ader 1)")), "{:?}", streams(doc, 0)); update_header_footer(doc, &found[0].settings, &[0], &with_text("New"), &cx()).unwrap(); let s = streams(doc, 0); assert!(s.iter().any(|x| x.contains("(New)")) && s.iter().any(|x| x.contains("(Footer)")), "{s:?}"); - assert!(!s.iter().any(|x| x.contains("eader 1")), "the old header is gone: {s:?}"); + assert!(!s.iter().any(|x| x.contains("ader 1)")), "the old header is gone: {s:?}"); assert_eq!(header_footers(doc).len(), 2); let gone = update_header_footer(doc, &header, &[0], &with_text("Again"), &cx()); @@ -343,8 +345,8 @@ fn updating_a_shrinking_header_takes_its_shrink_away_too() { assert_eq!(s.len(), original.len() + 3, "the original, one wrapper and the new mark: {s:?}"); } -#[test] -fn settings_a_file_makes_up_are_not_listed() { +/// A document with one header "Real" on page 1, and that header's stream. +fn one_recorded_header() -> (Document, pdfcraft_cos::ObjRef) { let mut doc = fixture(); add_header_footer(&mut doc, &[0], &with_text("Real"), false, &cx()).unwrap(); let page = crate::page_list(&doc).swap_remove(0); @@ -355,12 +357,92 @@ fn settings_a_file_makes_up_are_not_listed() { .filter(|r| doc.get(*r).as_dict().is_some_and(|d| d.contains(b"PCHeaderFooter"))) .collect(); assert_eq!(marks.len(), 1); - let mut hostile = Dict::new(); - hostile.set(b"Text".to_vec(), Object::Array(vec![Object::Int(1)])); - hostile.set(b"Size".to_vec(), Object::Real(f64::NAN)); - doc.update_dict(marks[0], |d| d.set(b"PCHeaderFooter".to_vec(), Object::Dict(hostile))).unwrap(); - assert!(header_footers(&doc).is_empty()); - assert_eq!(marks_present(&doc), [MarkKind::HeaderFooter], "still a mark: Remove and page-wide Update reach it"); + (doc, marks[0]) +} + +/// A change made to recorded settings, for [`settings_a_file_makes_up_are_not_listed`]. +type Change = Box; + +/// The recorded settings of `with_text("Real")`, changed by `change`. +fn real_settings_with(doc: &mut Document, change: impl FnOnce(&mut Document, &mut Dict)) -> Object { + let mut d = with_text("Real").to_object().as_dict().cloned().unwrap(); + change(doc, &mut d); + Object::Dict(d) +} + +#[test] +fn settings_a_file_makes_up_are_not_listed() { + let texts = |entries: Vec<&[u8]>| Object::Array(entries.into_iter().map(|t| Object::String(pdfcraft_cos::PdfString::literal(t))).collect()); + let long = vec![b'x'; 16 * 1024 + 1]; + let cases: Vec<(&str, Change)> = vec![ + ("not text", Box::new(|_, d| d.set(b"Text".to_vec(), Object::Array(vec![Object::Int(1); 6])))), + ("five boxes", Box::new(move |_, d| d.set(b"Text".to_vec(), texts(vec![&b"a"[..]; 5])))), + ("a million boxes", Box::new(|_, d| d.set(b"Text".to_vec(), Object::Array(vec![Object::Null; 1_000_000])))), + ("a box too long", Box::new(move |_, d| d.set(b"Text".to_vec(), texts(vec![&b""[..], &long[..], &b""[..], &b""[..], &b""[..], &b""[..]])))), + ("no text", Box::new(move |_, d| d.set(b"Text".to_vec(), texts(vec![&b""[..]; 6])))), + ("undrawable", Box::new(|_, d| d.set(b"Text".to_vec(), Object::Array(vec![Object::String(pdfcraft_cos::PdfString::text("中")); 6])))), + ("size not a number", Box::new(|_, d| d.set(b"Size".to_vec(), Object::Real(f64::NAN)))), + ("size too big", Box::new(|_, d| d.set(b"Size".to_vec(), Object::Real(300.0)))), + ("a negative margin", Box::new(|_, d| d.set(b"Margins".to_vec(), Object::Array(vec![Object::Real(-1.0); 4])))), + ("three margins", Box::new(|_, d| d.set(b"Margins".to_vec(), Object::Array(vec![Object::Real(1.0); 3])))), + ("a colour out of range", Box::new(|_, d| d.set(b"Color".to_vec(), Object::Array(vec![Object::Real(2.0); 3])))), + ("an unknown face", Box::new(|_, d| d.set(b"Font".to_vec(), Object::name("Comic")))), + ("a negative start", Box::new(|_, d| d.set(b"Start".to_vec(), Object::Int(-1)))), + ]; + for (what, change) in cases { + let (mut doc, mark) = one_recorded_header(); + let hostile = real_settings_with(&mut doc, change); + doc.update_dict(mark, |d| d.set(b"PCHeaderFooter".to_vec(), hostile)).unwrap(); + assert!(header_footers(&doc).is_empty(), "{what}"); + assert_eq!(marks_present(&doc), [MarkKind::HeaderFooter], "{what}: still a mark: Remove and page-wide Update reach it"); + assert_eq!(unrecorded_header_footer_pages(&doc), [0], "{what}"); + assert_eq!(newest_header_footer(&doc, 0), Some(None), "{what}"); + } +} + +#[test] +fn settings_a_rewriting_tool_made_indirect_are_still_listed() { + let (mut doc, mark) = one_recorded_header(); + let indirect = real_settings_with(&mut doc, |doc, d| { + for key in [&b"Font"[..], b"Size", b"Start", b"Underline", b"Text"] { + let value = d.get(key).cloned().unwrap(); + d.set(key.to_vec(), Object::Ref(doc.add(value))); + } + let half = Object::Ref(doc.add(Object::Real(0.5))); + d.set(b"Color".to_vec(), Object::Array(vec![half.clone(), half.clone(), half])); + let margins = Object::Array(vec![Object::Ref(doc.add(Object::Real(36.0))), Object::Real(36.0), Object::Real(72.0), Object::Real(72.0)]); + d.set(b"Margins".to_vec(), Object::Ref(doc.add(margins))); + }); + doc.update_dict(mark, |d| d.set(b"PCHeaderFooter".to_vec(), indirect)).unwrap(); + let found = header_footers(&doc); + assert_eq!(found.len(), 1); + assert_eq!(found[0].settings, HeaderFooter { color: [0.5; 3], ..with_text("Real") }); + assert!(unrecorded_header_footer_pages(&doc).is_empty()); +} + +#[test] +fn a_header_added_with_an_out_of_range_colour_can_be_updated() { + let mut doc = fixture(); + let bright = HeaderFooter { color: [2.0, -1.0, 0.5], ..with_text("Bright") }; + add_header_footer(&mut doc, &[0], &bright, false, &cx()).unwrap(); + let found = header_footers(&doc); + assert_eq!(found.len(), 1, "listed with the colour it is drawn in"); + assert_eq!(found[0].settings.color, [1.0, 0.0, 0.5]); + update_header_footer(&mut doc, &found[0].settings, &[0], &with_text("Calm"), &cx()).unwrap(); + assert_eq!(header_footers(&doc).iter().map(|m| m.settings.text[1].as_str()).collect::>(), ["Calm"]); +} + +#[test] +fn the_newest_header_on_a_page_is_the_one_added_last() { + let mut doc = fixture(); + assert_eq!(newest_header_footer(&doc, 0), None); + let (first, second) = (HeaderFooter { shrink: true, ..with_text("First") }, HeaderFooter { shrink: true, ..with_text("Second") }); + add_header_footer(&mut doc, &[0, 1], &first, false, &cx()).unwrap(); + add_header_footer(&mut doc, &[0], &second, false, &cx()).unwrap(); + // The second shrink goes in ahead of the first, so content order alone would say First. + assert_eq!(newest_header_footer(&doc, 0), Some(Some(second))); + assert_eq!(newest_header_footer(&doc, 1), Some(Some(first))); + assert_eq!(newest_header_footer(&doc, 9), None); } /// The six numbers of the first `… cm` in `content`. diff --git a/crates/engine/src/document.rs b/crates/engine/src/document.rs index 55b2a0384f..523485d399 100644 --- a/crates/engine/src/document.rs +++ b/crates/engine/src/document.rs @@ -460,6 +460,16 @@ impl Document { self.editor.as_ref().map(|e| pdfcraft_edit::header_footers(&e.cos)).unwrap_or_default() } + /// The header and footer added last to page `page` (`pdfcraft_edit::newest_header_footer`). + pub fn newest_header_footer(&self, page: usize) -> Option> { + self.editor.as_ref().and_then(|e| pdfcraft_edit::newest_header_footer(&e.cos, page)) + } + + /// Pages whose header and footer records no settings (`pdfcraft_edit::unrecorded_header_footer_pages`). + pub fn unrecorded_header_footer_pages(&self) -> Vec { + self.editor.as_ref().map(|e| pdfcraft_edit::unrecorded_header_footer_pages(&e.cos)).unwrap_or_default() + } + /// Text and images added with Edit a PDF ▸ Add content (still editable). pub fn added(&self) -> &[pdfcraft_edit::Added] { &self diff --git a/crates/redact/src/lib.rs b/crates/redact/src/lib.rs index 41ac47357e..f86954f08c 100644 --- a/crates/redact/src/lib.rs +++ b/crates/redact/src/lib.rs @@ -680,6 +680,8 @@ fn redact_page_content( retired_properties.extend(out.retired_properties); let mut new_list = list.clone(); let mut changed = false; + // Header and footer settings taken off a redacted stream (see below). + let mut redacted_settings: Vec = Vec::new(); for (i, new) in out.streams.into_iter().enumerate() { let Some(bytes) = new else { continue }; let mut dict = match &*doc.resolve(&list[i]) { @@ -691,10 +693,25 @@ fn redact_page_content( // are redacted, keeping it would leave the redacted text in the file. The item stays // as plain drawn content but is no longer editable. dict.remove(b"PCAdded"); + // A header and footer keeps its text templates in `/PCHeaderFooter` (#5785): the same goes. + // The mark stays as drawn content, which Update can only replace page-wide. + redacted_settings.extend(dict.remove(b"PCHeaderFooter")); // A new object: the original may be shared with other pages. new_list[i] = Object::Ref(doc.add(Object::Stream(Stream::flate(dict, &bytes)))); changed = true; } + // A shrinking header's `cm` stream records the same settings but draws no text, so it is + // never rewritten above: take its copy of the templates away too. + if !redacted_settings.is_empty() { + for o in new_list.iter_mut() { + let mut stream = match &*doc.resolve(o) { + Object::Stream(s) if s.dict.get(b"PCHeaderFooter").is_some_and(|v| redacted_settings.contains(v)) => s.clone(), + _ => continue, + }; + stream.dict.remove(b"PCHeaderFooter"); + *o = Object::Ref(doc.add(Object::Stream(stream))); + } + } if changed || !out.xobjects.is_empty() || !out.replaced.is_empty() { let mut res = resources.clone(); if !out.xobjects.is_empty() || !out.replaced.is_empty() { diff --git a/crates/redact/src/tests.rs b/crates/redact/src/tests.rs index 2d0268d525..2067e240d2 100644 --- a/crates/redact/src/tests.rs +++ b/crates/redact/src/tests.rs @@ -123,6 +123,22 @@ fn added_text_parameters_do_not_keep_redacted_text() { assert!(!bytes.windows(4).any(|w| w == b"1234"), "redacted text left in the saved file"); } +#[test] +fn a_redacted_header_keeps_no_copy_of_its_text() { + // A header and footer records its templates in /PCHeaderFooter, on its own stream and, when + // it shrinks the page, on the shrink's `cm` stream too (#5785). + let mut doc = one_page(b"BT /F1 10 Tf 10 100 Td (AB) Tj ET", "", vec![]); + let mut hf = pdfcraft_edit::HeaderFooter { shrink: true, ..Default::default() }; + hf.text[1] = "SECRET9".into(); + pdfcraft_edit::add_header_footer(&mut doc, &[0], &hf, false, &pdfcraft_edit::Context { date: (2026, 10, 1) }).unwrap(); + assert!(write_full(&doc, &SaveOptions::default()).unwrap().windows(7).any(|w| w == b"SECRET9"), "the settings are written in the clear"); + mark(&mut doc, 0, &[[0.0, 240.0, 300.0, 300.0]], ""); + apply(&mut doc, None).unwrap(); + let bytes = write_full(&doc, &SaveOptions::default()).unwrap(); + assert!(!bytes.windows(7).any(|w| w == b"SECRET9"), "the redacted header's text left in the saved file"); + assert!(content(&doc, 0).contains("(AB)"), "the rest of the page stays"); +} + #[test] fn operators_split_across_content_streams_are_redacted_whole() { // One content stream in three pieces, split between tokens: a marked-content dictionary diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs index e0296d2e4a..7bf9107342 100644 --- a/crates/ui-egui/src/commands.rs +++ b/crates/ui-egui/src/commands.rs @@ -495,15 +495,16 @@ impl PdfCraftApp { K::Background }; self.marks_draft.replace = id.ends_with(".update"); - let header_footers = match (id, self.active_ids()) { - ("edit.header_footer.update", Some((i, doc))) => { - let found = self.session.get(doc).map(|d| d.header_footers()).unwrap_or_default(); - Some((found, self.views[i].current)) - } + let choices = match (id, self.active_ids()) { + ("edit.header_footer.update", Some((i, doc))) => self.session.get(doc).map(|d| crate::marks_ui::UpdateChoices { + doc, + found: d.header_footers(), + older_pages: d.unrecorded_header_footer_pages(), + newest: d.newest_header_footer(self.views[i].current), + }), _ => None, }; - let (found, current) = header_footers.unwrap_or_default(); - self.marks_draft.update_choices(found, current); + self.marks_draft.update_choices(choices); self.marks_draft.opened(kind); self.marks_draft.preview = None; self.dialog = Some(Dialog::Marks(kind)); @@ -512,7 +513,7 @@ impl PdfCraftApp { // Bates numbering ▸ Add: the header & footer dialog with a Bates number in the // bottom-right box (6 digits from 1), ready to edit. self.marks_draft.replace = false; - self.marks_draft.update_choices(Vec::new(), 0); + self.marks_draft.update_choices(None); if self.marks_draft.hf.text.iter().all(|t| !t.contains("<, - /// Which of [`Self::header_footers`] Update changes, and the range that was filled in for it. - /// That range can only approximate pages such as 1, 2 and 5: while it stands, OK means them. - pub updating: Option<(usize, PageRange)>, + /// Update: pages whose header and footer records no settings (from before they were + /// recorded, or another tool), which only a page-wide replace reaches. + pub older_pages: Vec, + /// The document the choices were read from: OK changes no other. + pub update_doc: Option, + /// Which header and footer Update changes. + pub updating: Option, + /// The range is still the one filled in for [`Self::updating`]. It can only approximate pages + /// such as 1, 2 and 5: until the range is changed, OK means those pages. + pub range_kept: bool, /// Which header/footer box Insert Page Number / Insert Date type into. pub focused_box: usize, pub page_format: usize, @@ -245,7 +252,10 @@ impl Default for MarksDraft { range: PageRange::default(), replace: false, header_footers: Vec::new(), + older_pages: Vec::new(), + update_doc: None, updating: None, + range_kept: false, focused_box: 1, page_format: 0, date_format: 0, @@ -259,16 +269,54 @@ impl Default for MarksDraft { } } +/// The header and footer the Update dialog changes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Updating { + /// One of [`MarksDraft::header_footers`], alone. + Recorded(usize), + /// Those on [`MarksDraft::older_pages`], replaced page-wide with any other there. + Older, +} + +/// What Update reads from the document to offer its choices. +pub struct UpdateChoices { + pub doc: pdfcraft_engine::DocId, + pub found: Vec, + pub older_pages: Vec, + /// The header and footer added last to the current page (see `Document::newest_header_footer`). + pub newest: Option>, +} + impl MarksDraft { - /// Update opens on the header and footer of page `current` (0-based), the newest one there, - /// or the document's last. No choices (a mark from before settings were recorded, or Add) - /// leaves the draft as it is. - pub fn update_choices(&mut self, found: Vec, current: usize) { - self.header_footers = found; + /// Update opens on the newest header and footer of the current page, or else the document's + /// last. With none to choose (or for Add, `None`), the draft is left as it is. + pub fn update_choices(&mut self, choices: Option) { self.updating = None; - let on_current = self.header_footers.iter().rposition(|m| m.pages.contains(¤t)); - if let Some(i) = on_current.or(self.header_footers.len().checked_sub(1)) { - self.choose_header_footer(i); + self.range_kept = false; + let Some(UpdateChoices { doc, found, older_pages, newest }) = choices else { + self.update_doc = None; + self.header_footers.clear(); + self.older_pages.clear(); + return; + }; + self.update_doc = Some(doc); + self.header_footers = found; + self.older_pages = older_pages; + match newest { + Some(Some(settings)) => match self.header_footers.iter().position(|m| m.settings == settings) { + Some(i) => self.choose_header_footer(i), + None => self.choose_last(), + }, + Some(None) if !self.older_pages.is_empty() => self.choose_older(), + _ => self.choose_last(), + } + } + + fn choose_last(&mut self) { + match self.header_footers.len().checked_sub(1) { + Some(i) => self.choose_header_footer(i), + None if !self.older_pages.is_empty() => self.choose_older(), + None => {} } } @@ -277,22 +325,63 @@ impl MarksDraft { let Some(mark) = self.header_footers.get(i) else { return }; self.hf = mark.settings.clone(); self.range = PageRange::around(&mark.pages); - self.updating = Some((i, self.range)); + self.updating = Some(Updating::Recorded(i)); + self.range_kept = true; self.preview = None; } - /// The header and footer OK replaces. + /// Choose the headers and footers that record no settings. Their settings can't be read + /// back, so the dialog keeps what it shows. + pub fn choose_older(&mut self) { + if self.older_pages.is_empty() { + return; + } + self.range = PageRange::around(&self.older_pages); + self.updating = Some(Updating::Older); + self.range_kept = true; + self.preview = None; + } + + /// How many headers and footers Update can choose between. + fn update_choice_count(&self) -> usize { + self.header_footers.len() + usize::from(!self.older_pages.is_empty()) + } + + /// The header and footer OK replaces alone. fn updated(&self) -> Option<&pdfcraft_engine::HeaderFooterMark> { - self.header_footers.get(self.updating?.0) + match self.updating? { + Updating::Recorded(i) => self.header_footers.get(i), + Updating::Older => None, + } + } + + /// The range was changed by hand: OK now means the pages it shows. + pub fn range_changed(&mut self) { + self.range_kept = false; } /// The pages (0-based) OK applies to, in a document of `count` pages. pub fn pages(&self, count: usize) -> Vec { - match (self.updated(), self.updating) { - (Some(mark), Some((_, range))) if self.replace && range == self.range => mark.pages.clone(), + let kept = match self.updating { + Some(Updating::Recorded(_)) => self.updated().map(|m| &m.pages), + Some(Updating::Older) => Some(&self.older_pages), + None => None, + }; + match kept { + Some(pages) if self.replace && self.range_kept => pages.iter().copied().filter(|&p| p < count).collect(), _ => self.range.pages(count), } } + + /// Update read its choices from another document than `doc`: OK must not apply them there. + pub fn update_is_for_another(&self, doc: pdfcraft_engine::DocId) -> bool { + self.replace && self.updating.is_some() && self.update_doc.is_some_and(|d| d != doc) + } +} + +fn older_header_footer_label(pages: &[usize]) -> String { + let pages = pages_phrase(pages, tl!("Page {pages}"), tl!("Pages {pages}")); + format!("{pages}: {}", tl!("an older header and footer (replaced with all others on those pages)")) } /// What the Update dialog calls a header and footer: its pages and the start of its text. @@ -498,29 +587,27 @@ impl UnmarkedPage { } } -/// The page (0-based) the preview shows: the current one when the range selects it, otherwise the -/// first page the range selects (the current one again when it selects none). -fn preview_page(range: &PageRange, current: usize, count: usize) -> usize { - let pages = range.pages(count); +/// The page (0-based) the preview shows: the current one when OK applies to it (`pages`), +/// otherwise the first page it applies to (the current one again when it applies to none). +fn preview_page(pages: &[usize], current: usize) -> usize { if pages.contains(¤t) { current } else { pages.first().copied().unwrap_or(current) } } /// [`preview_page`] for the page stepped to (`stepped`), or the current page if none. A page /// stepped to that the range leaves out is replaced by the page shown, so widening the range again /// keeps that page rather than jumping back. -fn shown_preview(range: &PageRange, stepped: &mut Option, current: usize, count: usize) -> usize { - let shown = preview_page(range, stepped.unwrap_or(current), count); +fn shown_preview(pages: &[usize], stepped: &mut Option, current: usize) -> usize { + let shown = preview_page(pages, stepped.unwrap_or(current)); if stepped.is_some() { *stepped = Some(shown); } shown } -/// The page the preview steps to from `shown`: the range's next page after it (`forward`) or the -/// last one before it, or `None` at either end. -fn step_preview(range: &PageRange, shown: usize, count: usize, forward: bool) -> Option { - let pages = range.pages(count); - if forward { pages.into_iter().find(|&p| p > shown) } else { pages.into_iter().rev().find(|&p| p < shown) } +/// The page the preview steps to from `shown`: the next page OK applies to after it (`forward`) +/// or the last one before it, or `None` at either end. +fn step_preview(pages: &[usize], shown: usize, forward: bool) -> Option { + if forward { pages.iter().copied().find(|&p| p > shown) } else { pages.iter().rev().copied().find(|&p| p < shown) } } /// The dialog for `kind`; returns (apply, cancel). @@ -540,20 +627,34 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, kind: M }; ui.label(egui::RichText::new(title).font(theme::semibold(18.0))); ui.add_space(8.0); - if kind == MarkKind::HeaderFooter && d.replace && d.header_footers.len() > 1 { + if kind == MarkKind::HeaderFooter && d.replace && d.update_choice_count() > 1 { ui.horizontal(|ui| { - ui.label(tl!("Which header and footer:")); - let shown = d.updated().map(header_footer_label).unwrap_or_default(); + let label = ui.label(tl!("Which header and footer:")); + let shown = match d.updating { + Some(Updating::Older) => older_header_footer_label(&d.older_pages), + _ => d.updated().map(header_footer_label).unwrap_or_default(), + }; let mut picked = None; - craft_ui::ComboBox::from_id_salt("mark-header-footer").selected_text(shown).show_ui(ui, |ui| { - for (i, mark) in d.header_footers.iter().enumerate() { - if ui.selectable_label(d.updating.is_some_and(|(at, _)| at == i), header_footer_label(mark)).clicked() { - picked = Some(i); + craft_ui::ComboBox::from_id_salt("mark-header-footer") + .selected_text(shown) + .show_ui(ui, |ui| { + for (i, mark) in d.header_footers.iter().enumerate() { + if ui.selectable_label(d.updating == Some(Updating::Recorded(i)), header_footer_label(mark)).clicked() { + picked = Some(Updating::Recorded(i)); + } } - } - }); - if let Some(i) = picked { - d.choose_header_footer(i); + if !d.older_pages.is_empty() + && ui.selectable_label(d.updating == Some(Updating::Older), older_header_footer_label(&d.older_pages)).clicked() + { + picked = Some(Updating::Older); + } + }) + .response + .labelled_by(label.id); + match picked { + Some(Updating::Recorded(i)) => d.choose_header_footer(i), + Some(Updating::Older) => d.choose_older(), + None => {} } }); ui.add_space(6.0); @@ -569,7 +670,8 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, kind: M } }); ui.label(tl!("Size")); - ui.add(egui::DragValue::new(&mut d.hf.font_size).range(4.0..=72.0).speed(0.5)); + // An existing header and footer may use any size applying accepts: shown as it is, not clamped. + ui.add(egui::DragValue::new(&mut d.hf.font_size).range(4.0..=72.0).clamp_existing_to_range(false).speed(0.5)); ui.add(widgets::checkbox(&mut d.hf.underline, tl!("Underline"))); color_button(ui, &mut d.hf.color); ui.add_space(16.0); @@ -628,7 +730,7 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, kind: M } ui.add_space(12.0); ui.label(tl!("Start page number")); - ui.add(egui::DragValue::new(&mut d.hf.start_number).range(1..=999_999)); + ui.add(egui::DragValue::new(&mut d.hf.start_number).range(1..=999_999).clamp_existing_to_range(false)); }); ui.add(widgets::checkbox(&mut d.hf.shrink, tl!("Shrink the page content to make room for the header and footer"))); } @@ -713,14 +815,19 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, kind: M } ui.add_space(8.0); ui.label(egui::RichText::new(tl!("Page Range Options")).font(theme::semibold(12.5))); + let before = d.range; d.range.ui(ui, count); + if d.range != before { + d.range_changed(); + } ui.add_space(8.0); // The preview: the current page (or the page stepped to), or the first one the range selects // if it leaves that out, drawn from its thumbnail at its displayed size (after /Rotate), the // frame the engine lays the marks out in. Update draws it without the marks it replaces. - let target = shown_preview(&d.range, &mut d.preview, current, count); + let applies_to = d.pages(count); + let target = shown_preview(&applies_to, &mut d.preview, current); let page = doc.info.pages.get(target).map(|p| (p.width as f64, p.height as f64)).unwrap_or((612.0, 792.0)); - let near: Vec = [false, true].into_iter().filter_map(|forward| step_preview(&d.range, target, count, forward)).collect(); + let near: Vec = [false, true].into_iter().filter_map(|forward| step_preview(&applies_to, target, forward)).collect(); let unmarked = app.unmarked_page.picture(ui.ctx(), (doc, id), target, &near, kind, d.replace); let picture = unmarked.or_else(|| { app.views.get_mut(i).and_then(|view| { @@ -804,7 +911,7 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, kind: M ui.vertical(|ui| { ui.horizontal(|ui| { // Steps through the pages the range selects. - let (back, next) = (step_preview(&d.range, target, count, false), step_preview(&d.range, target, count, true)); + let (back, next) = (step_preview(&applies_to, target, false), step_preview(&applies_to, target, true)); if ui.add_enabled_ui(back.is_some(), |ui| icons::button(ui, "chevron-left", 22.0, false, tl!("Previous page"))).inner.clicked() { d.preview = back.or(d.preview); } @@ -976,6 +1083,52 @@ pub fn edit(d: &MarksDraft, kind: MarkKind, count: usize) -> Edit { mod tests { use super::*; + fn mark(pages: Vec, text: &str) -> pdfcraft_engine::HeaderFooterMark { + let mut settings = HeaderFooter::default(); + settings.text[1] = text.into(); + pdfcraft_engine::HeaderFooterMark { pages, settings } + } + + fn updating(found: Vec, older_pages: Vec, newest: Option>) -> MarksDraft { + let mut d = MarksDraft { replace: true, ..MarksDraft::default() }; + d.update_choices(Some(UpdateChoices { doc: pdfcraft_engine::DocId(1), found, older_pages, newest })); + d + } + + #[test] + fn update_applies_to_a_marks_own_pages_until_the_range_is_changed() { + let mut d = updating(vec![mark(vec![0, 1, 4], "Gappy")], vec![], None); + assert_eq!(d.pages(5), [0, 1, 4], "pages 1, 2 and 5, which no range shows"); + // Changed and changed back: what the range shows now is meant, page 4 included. + d.range_changed(); + assert_eq!(d.pages(5), [0, 1, 2, 3, 4]); + assert!(matches!(edit(&d, MarkKind::HeaderFooter, 5), Edit::UpdateHeaderFooter { pages, .. } if pages == [0, 1, 2, 3, 4])); + } + + #[test] + fn update_opens_on_the_newest_on_the_page_and_offers_older_ones_too() { + let found = vec![mark(vec![0], "First"), mark(vec![0], "Second")]; + let d = updating(found.clone(), vec![], Some(Some(found[0].settings.clone()))); + assert_eq!(d.updating, Some(Updating::Recorded(0)), "the newest on the page, not the last listed"); + // An older header and footer on page 1 (no settings) and a recorded one on page 2. + let mut d = updating(vec![mark(vec![1], "Recorded")], vec![0], Some(None)); + assert_eq!((d.update_choice_count(), d.updating), (2, Some(Updating::Older))); + assert_eq!(d.pages(2), [0]); + assert!(matches!(edit(&d, MarkKind::HeaderFooter, 2), Edit::AddHeaderFooter { replace: true, .. }), "replaced page-wide"); + d.choose_header_footer(0); + assert!(matches!(edit(&d, MarkKind::HeaderFooter, 2), Edit::UpdateHeaderFooter { .. })); + } + + #[test] + fn update_is_refused_on_another_document() { + let d = updating(vec![mark(vec![0], "Mine")], vec![], None); + assert!(!d.update_is_for_another(pdfcraft_engine::DocId(1))); + assert!(d.update_is_for_another(pdfcraft_engine::DocId(2))); + let mut add = d.clone(); + add.update_choices(None); + assert!(!add.update_is_for_another(pdfcraft_engine::DocId(2)), "Add has no document of its own"); + } + #[test] fn text_applying_would_refuse_is_caught_in_the_dialog() { let mut d = MarksDraft::default(); @@ -1020,47 +1173,47 @@ mod tests { #[test] fn the_preview_shows_a_page_the_range_selects() { let all = PageRange::default(); - assert_eq!(preview_page(&all, 2, 5), 2, "the current page when the range selects it"); + assert_eq!(preview_page(&all.pages(5), 2), 2, "the current page when the range selects it"); let even = PageRange { all: true, subset: Subset::Even, ..PageRange::default() }; - assert_eq!(preview_page(&even, 0, 5), 1, "otherwise the first page the range selects"); + assert_eq!(preview_page(&even.pages(5), 0), 1, "otherwise the first page the range selects"); let later = PageRange { all: false, from: 3, to: 4, subset: Subset::All }; - assert_eq!(preview_page(&later, 0, 5), 2); + assert_eq!(preview_page(&later.pages(5), 0), 2); let none = PageRange { all: false, from: 4, to: 2, subset: Subset::All }; - assert_eq!(preview_page(&none, 1, 5), 1, "the current page when the range selects none"); - assert_eq!(preview_page(&all, 0, 0), 0, "no pages at all"); + assert_eq!(preview_page(&none.pages(5), 1), 1, "the current page when the range selects none"); + assert_eq!(preview_page(&all.pages(0), 0), 0, "no pages at all"); } #[test] fn the_preview_steps_through_the_pages_the_range_selects() { let odd = PageRange { all: true, subset: Subset::Odd, ..PageRange::default() }; // Pages 1, 3 and 5 (0-based 0, 2, 4) of 5. - assert_eq!(step_preview(&odd, 0, 5, true), Some(2)); - assert_eq!(step_preview(&odd, 2, 5, true), Some(4)); - assert_eq!(step_preview(&odd, 4, 5, true), None, "the last page has no next"); - assert_eq!(step_preview(&odd, 4, 5, false), Some(2)); - assert_eq!(step_preview(&odd, 0, 5, false), None, "the first page has no previous"); + assert_eq!(step_preview(&odd.pages(5), 0, true), Some(2)); + assert_eq!(step_preview(&odd.pages(5), 2, true), Some(4)); + assert_eq!(step_preview(&odd.pages(5), 4, true), None, "the last page has no next"); + assert_eq!(step_preview(&odd.pages(5), 4, false), Some(2)); + assert_eq!(step_preview(&odd.pages(5), 0, false), None, "the first page has no previous"); // From a page the range leaves out, to the nearest one it selects on that side. - assert_eq!(step_preview(&odd, 1, 5, true), Some(2)); - assert_eq!(step_preview(&odd, 1, 5, false), Some(0)); - assert_eq!(step_preview(&odd, 0, 0, true), None, "no pages at all"); + assert_eq!(step_preview(&odd.pages(5), 1, true), Some(2)); + assert_eq!(step_preview(&odd.pages(5), 1, false), Some(0)); + assert_eq!(step_preview(&odd.pages(0), 0, true), None, "no pages at all"); // A page stepped to is previewed while the range selects it, and the range's first page // once a new range leaves it out. - assert_eq!(preview_page(&odd, 2, 5), 2); + assert_eq!(preview_page(&odd.pages(5), 2), 2); let later = PageRange { all: false, from: 4, to: 5, subset: Subset::All }; - assert_eq!(preview_page(&later, 2, 5), 3); + assert_eq!(preview_page(&later.pages(5), 2), 3); // Narrowing the range past the page stepped to keeps the page shown instead, also once // the range is widened again. let mut stepped = Some(4); let first_two = PageRange { all: false, from: 1, to: 2, subset: Subset::All }; - assert_eq!(shown_preview(&first_two, &mut stepped, 1, 5), 0); + assert_eq!(shown_preview(&first_two.pages(5), &mut stepped, 1), 0); assert_eq!(stepped, Some(0)); - assert_eq!(shown_preview(&PageRange::default(), &mut stepped, 1, 5), 0); + assert_eq!(shown_preview(&PageRange::default().pages(5), &mut stepped, 1), 0); // A page stepped to inside the range stays; with none stepped to, the current page shows. let mut stepped = Some(2); - assert_eq!(shown_preview(&odd, &mut stepped, 0, 5), 2); + assert_eq!(shown_preview(&odd.pages(5), &mut stepped, 0), 2); assert_eq!(stepped, Some(2)); let mut stepped = None; - assert_eq!(shown_preview(&odd, &mut stepped, 4, 5), 4); + assert_eq!(shown_preview(&odd.pages(5), &mut stepped, 4), 4); assert_eq!(stepped, None); } diff --git a/crates/ui-egui/tests/it/marks.rs b/crates/ui-egui/tests/it/marks.rs index 03762919db..b9e2066a2c 100644 --- a/crates/ui-egui/tests/it/marks.rs +++ b/crates/ui-egui/tests/it/marks.rs @@ -82,8 +82,10 @@ fn update_can_change_an_earlier_header_and_footer() { assert!(h.state_mut().execute("edit.header_footer.update")); h.run_steps(3); assert_eq!(h.state().marks_draft.hf.text[1], "Over all", "the newest on the page shown"); - h.get_by_label("Which header and footer:"); - h.state_mut().marks_draft.choose_header_footer(0); + // Chosen through the list, as a user would: open it, then click the earlier one. + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Which header and footer:").click(); + h.run_steps(2); + h.get_by_label_contains(": Earlier").click(); h.run_steps(2); assert_eq!(h.state().marks_draft.hf.text[1], "Earlier", "the dialog fills in from the one chosen"); assert_eq!(h.state().marks_draft.pages(3), [0, 1], "on its own pages"); @@ -102,6 +104,28 @@ fn update_can_change_an_earlier_header_and_footer() { ); } +/// Update shows a header and footer's size and start number as they are, even past the range +/// the dialog's own controls step through, so changing only its text keeps them. +#[test] +fn update_keeps_a_size_and_start_number_the_controls_do_not_reach() { + use pdfcraft_engine::{Edit, HeaderFooter}; + let mut h = harness(); + let mut settings = HeaderFooter { font_size: 100.0, start_number: 1_000_000, ..HeaderFooter::default() }; + settings.text[1] = "Big".into(); + h.state_mut().apply_edit(Edit::AddHeaderFooter { pages: vec![0], settings, replace: false }); + h.run_steps(2); + assert!(h.state_mut().execute("edit.header_footer.update")); + h.run_steps(3); + h.state_mut().marks_draft.hf.text[1] = "Bigger".into(); + h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(4); + let s = h.state(); + let found = s.session.get(s.views[0].id).unwrap().header_footers(); + assert_eq!(found.len(), 1); + assert_eq!((found[0].settings.text[1].as_str(), found[0].settings.font_size, found[0].settings.start_number), ("Bigger", 100.0, 1_000_000)); +} + #[test] fn header_and_footer_dialog_draws_in_the_chosen_face() { // #3754: the dialog offers Helvetica, Times and Courier (it only said "Font: Helvetica"), diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index c849cd8af1..5fd9cf21e6 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -2460,8 +2460,8 @@ milestone = "M7" status = "shipped" commands = ["edit.header_footer.update", "edit.header_footer.remove"] tools = ["doc_header_footer", "doc_header_footers", "doc_remove_marks"] -evidence = ["crates/edit/src/tests.rs::update_changes_one_header_and_footer_and_leaves_the_others", "crates/ui-egui/tests/it/marks.rs::update_can_change_an_earlier_header_and_footer", "crates/automation/tests/it/automation.rs::header_footer_update_changes_the_one_named", "crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/ui-egui/tests/it/marks.rs::header_and_footer_dialog_inserts_tokens_and_applies_to_a_subset", "crates/edit/src/mark_transaction_tests.rs::header_footer_changes_are_atomic_after_a_later_page_failure", "crates/edit/src/mark_transaction_tests.rs::replacements_commit_all_selected_pages_and_preserve_other_marks_and_shared_resources"] -notes = "Add and Update are atomic across all selected pages: errors preserve existing marks, page content/resources and pending edits (#5657). Each header and footer records its settings, so Update can choose among several and fills the dialog from the one chosen, leaving the others in place (#5785); marks made before that, which record none, are still replaced page by page, and the dialog's preview still hides every header and footer on the page, not just the one chosen. recognises PdfCraft marks; Acrobat-made headers are not detected yet" +evidence = ["crates/edit/src/tests.rs::update_changes_one_header_and_footer_and_leaves_the_others", "crates/ui-egui/tests/it/marks.rs::update_can_change_an_earlier_header_and_footer", "crates/automation/tests/it/automation.rs::header_footer_update_changes_the_one_named", "crates/edit/src/tests.rs::settings_a_file_makes_up_are_not_listed", "crates/edit/src/tests.rs::the_newest_header_on_a_page_is_the_one_added_last", "crates/redact/src/tests.rs::a_redacted_header_keeps_no_copy_of_its_text", "crates/ui-egui/tests/it/marks.rs::update_keeps_a_size_and_start_number_the_controls_do_not_reach", "crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/ui-egui/tests/it/marks.rs::header_and_footer_dialog_inserts_tokens_and_applies_to_a_subset", "crates/edit/src/mark_transaction_tests.rs::header_footer_changes_are_atomic_after_a_later_page_failure", "crates/edit/src/mark_transaction_tests.rs::replacements_commit_all_selected_pages_and_preserve_other_marks_and_shared_resources"] +notes = "Add and Update are atomic across all selected pages: errors preserve existing marks, page content/resources and pending edits (#5657). Each header and footer records its settings, so Update can choose among several and fills the dialog from the one chosen, leaving the others in place (#5785). Marks made before that, or redacted since, record none: the dialog offers them as one choice replaced page-wide, with any other header and footer on those pages. Still missing: the preview hides every header and footer on the page, not just the one chosen; the replacement is drawn on top of the page, so where two overlap it now covers the other; and page numbers count the selected pages only (an update on pages 1, 2 and 5 numbers them 1, 2 and 3). Automation indices hold only until the next change (an update returns the new list). recognises PdfCraft marks; Acrobat-made headers are not detected yet" [[feature]] id = "edit.header-footer-tokens" From bb0a19323bc947e0dd8a35c8e8556a7b0c65ea55 Mon Sep 17 00:00:00 2001 From: cyfung1031 <44498510+cyfung1031@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:06:32 +0000 Subject: [PATCH 022/114] M14: show an opening notice during PDF preparation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rebased onto main as one commit (the branch had merged main several times). The catalogs added on main since (ca, ckb, fi, hi, id, ko, lo, nb, ro, sq, th) get the "Opening {name}…" string too; ATTRIBUTION.toml no longer records catalog hashes. --- crates/ui-egui/src/platform/open_worker/tests.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/ui-egui/src/platform/open_worker/tests.rs b/crates/ui-egui/src/platform/open_worker/tests.rs index c0fe2f03a2..b930297794 100644 --- a/crates/ui-egui/src/platform/open_worker/tests.rs +++ b/crates/ui-egui/src/platform/open_worker/tests.rs @@ -71,6 +71,10 @@ fn open_prepare_keeps_control_and_existing_tabs_live_until_atomic_commit() { let open_reply = request(&mut harness, &client, "ui.open", json!({ "path": path.to_string_lossy() })); assert_eq!(open_reply["pending"], true); started.recv_timeout(Duration::from_secs(5)).expect("worker reached prepare barrier"); + let name = path.file_name().expect("test path has a file name").to_string_lossy(); + let opening_label = format!("Opening {name}…"); + assert_eq!(harness.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(opening_label.as_str())); + harness.get_by_label(&opening_label); let state = request(&mut harness, &client, "ui.state", json!({})); assert_eq!(state["documents"].as_array().map(Vec::len), Some(1)); @@ -87,6 +91,8 @@ fn open_prepare_keeps_control_and_existing_tabs_live_until_atomic_commit() { assert_eq!(app.views.len(), 2, "one prepared document commits exactly once"); assert_eq!(app.session.get(app.views[1].id).expect("new tab").info.pages.len(), 2); assert_eq!(app.active, Some(1)); + assert!(app.opening_notice.is_none(), "the opening notice clears after commit"); + assert!(harness.query_by_label(&opening_label).is_none(), "the opening notice is no longer visible"); let _ = std::fs::remove_file(path); } From fb59affa415bfbfc0242118f8c1e27c2b60304ae Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 01:44:58 +0000 Subject: [PATCH 023/114] M14: re-translate the opening notice after a language change A language change while an open was pending kept the notice in the previous language: the label was built once per pending open. The notice records its language and is rebuilt when the current language differs (CodeRabbit review). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VnaJBEsWwx1aCoDEMofbXs --- crates/ui-egui/src/platform/open_worker/tests.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/ui-egui/src/platform/open_worker/tests.rs b/crates/ui-egui/src/platform/open_worker/tests.rs index b930297794..669f9dfdc4 100644 --- a/crates/ui-egui/src/platform/open_worker/tests.rs +++ b/crates/ui-egui/src/platform/open_worker/tests.rs @@ -75,6 +75,14 @@ fn open_prepare_keeps_control_and_existing_tabs_live_until_atomic_commit() { let opening_label = format!("Opening {name}…"); assert_eq!(harness.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(opening_label.as_str())); harness.get_by_label(&opening_label); + // A language change while the open is pending re-translates the notice. + let language = std::mem::replace(&mut harness.state_mut().language, "ja".into()); + harness.step(); + let japanese_label = format!("{name} を開いています…"); + assert_eq!(harness.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(japanese_label.as_str())); + harness.state_mut().language = language; + harness.step(); + assert_eq!(harness.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(opening_label.as_str())); let state = request(&mut harness, &client, "ui.state", json!({})); assert_eq!(state["documents"].as_array().map(Vec::len), Some(1)); From fd6f7b602b07ec2a1f1f548c6aa280d49207dd1b Mon Sep 17 00:00:00 2001 From: CY Fung Date: Thu, 5 Nov 2026 21:35:30 +0000 Subject: [PATCH 024/114] M14: restore opening feedback on current UI structure --- crates/ui-egui/src/app.rs | 2 ++ crates/ui-egui/src/app/files.rs | 19 ++++++++++ crates/ui-egui/src/app/frame.rs | 2 ++ crates/ui-egui/src/lib.rs | 9 +++++ crates/ui-egui/src/widgets.rs | 63 ++++++++++++++++++++++++++++++++- 5 files changed, 94 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 04dbd19447..87f805e11f 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -143,6 +143,8 @@ impl PdfCraftApp { #[cfg(not(target_arch = "wasm32"))] pending_opens: Vec::new(), #[cfg(not(target_arch = "wasm32"))] + opening_notice: None, + #[cfg(not(target_arch = "wasm32"))] next_open_token: 0, #[cfg(not(target_arch = "wasm32"))] launch_layout: None, diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index c4d0a26c85..0a6820c7c8 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -120,9 +120,27 @@ impl PdfCraftApp { then: request.then, display_override: None, }); + self.refresh_opening_notice(); Ok(token) } + #[cfg(not(target_arch = "wasm32"))] + fn refresh_opening_notice(&mut self) { + let Some(pending) = self.pending_opens.first() else { + self.opening_notice = None; + return; + }; + let lang = i18n::current(); + if self.opening_notice.as_ref().is_some_and(|notice| notice.token == pending.token && notice.lang == lang) { + return; + } + self.opening_notice = Some(OpeningNotice { + token: pending.token, + lang, + label: i18n::fmt(tl!("Opening {name}…"), &[("name", &pending.name)]), + }); + } + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn poll_pending_opens(&mut self) { let pending_opens = std::mem::take(&mut self.pending_opens); @@ -149,6 +167,7 @@ impl PdfCraftApp { // earlier waiting replies, without consuming a blocked receiver's result. waiting.append(&mut self.pending_opens); self.pending_opens = waiting; + self.refresh_opening_notice(); self.settle_launch_layout(); } diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 3d6f493e10..4802bfea09 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -3,6 +3,8 @@ use super::*; impl PdfCraftApp { /// Draw the running job's progress card and pass a Cancel click on to the job. pub(super) fn show_progress(&mut self, ctx: &egui::Context) { + #[cfg(not(target_arch = "wasm32"))] + widgets::opening_notice(self.opening_notice.as_ref().map(|notice| notice.label.as_str()), self.progress_notice.is_some(), ctx); if widgets::progress_notice(self, ctx) { self.cancel_optimize(); self.cancel_scan_clean(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 380f84a644..604eec3c15 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -254,6 +254,13 @@ struct PendingOpen { display_override: Option<(canvas::PageLayout, bool)>, } +#[cfg(not(target_arch = "wasm32"))] +struct OpeningNotice { + token: u64, + lang: i18n::Lang, + label: String, +} + pub struct PdfCraftApp { /// Tools side and pane widths; which panes are open is `left_open` and `right`. pub side_panels: side_panels::SidePanels, @@ -404,6 +411,8 @@ pub struct PdfCraftApp { #[cfg(not(target_arch = "wasm32"))] pending_opens: Vec, #[cfg(not(target_arch = "wasm32"))] + opening_notice: Option, + #[cfg(not(target_arch = "wasm32"))] next_open_token: u64, /// Explicit CLI layout waits for flagged launch opens, never targeting restored tabs. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index f621c7832b..7d24a9af5f 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -17,6 +17,8 @@ const FIELD_MIN_HEIGHT: f32 = 30.0; /// Padding inside every modal. const DIALOG_PAD_X: i8 = 20; const DIALOG_PAD_Y: i8 = 16; +#[cfg(not(target_arch = "wasm32"))] +const OPENING_HEIGHT: &str = "opening-notice-height"; fn dialog_frame(ctx: &egui::Context) -> egui::Frame { let t = Tokens::get(ctx); @@ -476,7 +478,15 @@ pub fn toast(app: &mut PdfCraftApp, ctx: &egui::Context) { let screen = ctx.content_rect(); // Above the progress notice while a job runs. let card = if app.progress_notice.is_some() { ctx.data(|d| d.get_temp::(egui::Id::unique(PROGRESS_HEIGHT))).unwrap_or(0.0) } else { 0.0 }; - let lift = if card > 0.0 { 28.0 + card + 10.0 } else { 28.0 }; + #[cfg(not(target_arch = "wasm32"))] + let opening = if app.opening_notice.is_some() { + ctx.data(|d| d.get_temp::(egui::Id::new(OPENING_HEIGHT))).unwrap_or(0.0) + 10.0 + } else { + 0.0 + }; + #[cfg(target_arch = "wasm32")] + let opening = 0.0; + let lift = if card > 0.0 { 28.0 + card + 10.0 + opening } else { 28.0 + opening }; // A running batch keeps its toast up (poll_ocr re-notifies), so it can carry the one // control a long job needs: Cancel — the file in flight finishes, the rest are not run. let batch_running = app.ocr_batch.is_some(); @@ -610,6 +620,57 @@ pub fn progress_notice(app: &PdfCraftApp, ctx: &egui::Context) -> bool { cancel } +/// Draw the indeterminate opening card above the progress card, if any. +#[cfg(not(target_arch = "wasm32"))] +pub fn opening_notice(label: Option<&str>, progress_visible: bool, ctx: &egui::Context) { + let Some(label) = label else { + ctx.data_mut(|d| d.insert_temp(egui::Id::new(OPENING_HEIGHT), 0.0_f32)); + return; + }; + let t = Tokens::get(ctx); + let screen = ctx.content_rect(); + let (fill, text) = if t.dark() { + (Color32::from_rgb(0xEC, 0xEC, 0xEF), Color32::from_rgb(0x22, 0x22, 0x26)) + } else { + (Color32::from_rgb(0x2A, 0x2A, 0x2F), Color32::WHITE) + }; + let progress_height = if progress_visible { ctx.data(|d| d.get_temp::(egui::Id::unique(PROGRESS_HEIGHT))).unwrap_or(0.0) + 10.0 } else { 0.0 }; + let animated = crate::motion::animated(ctx); + let area = egui::Area::new(egui::Id::new("opening-notice")) + .order(egui::Order::Tooltip) + .pivot(Align2::CENTER_BOTTOM) + .fixed_pos(screen.center_bottom() - vec2(0.0, 28.0 + progress_height)) + .show(ctx, |ui| { + egui::Frame::NONE.fill(fill).corner_radius(CornerRadius::same(10)).inner_margin(egui::Margin::symmetric(16, 12)).show(ui, |ui| { + let width = 340.0_f32.min(screen.width() - 64.0).max(160.0); + ui.set_width(width); + ui.horizontal(|ui| { + let (rect, response) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::new(egui::WidgetType::ProgressIndicator)); + let center = rect.center(); + let painter = ui.painter(); + if animated { + let now = ui.input(|i| i.time); + let phase = if now.is_finite() && now >= 0.0 { (now * 8.0).floor() as usize % 8 } else { 0 }; + for i in 0..8 { + let angle = std::f32::consts::TAU * i as f32 / 8.0; + let point = center + vec2(angle.cos() * 6.0, angle.sin() * 6.0); + let age = (phase + 8 - i) % 8; + painter.circle_filled(point, 1.5, text.gamma_multiply(0.2 + 0.8 * (1.0 - age as f32 / 8.0))); + } + } else { + painter.circle_stroke(center, 6.0, Stroke::new(1.5, text.gamma_multiply(0.7))); + } + ui.add(egui::Label::new(egui::RichText::new(label).color(text)).wrap()); + }); + }); + }); + ctx.data_mut(|d| d.insert_temp(egui::Id::new(OPENING_HEIGHT), area.response.rect.height())); + if animated { + ctx.request_repaint_after(std::time::Duration::from_millis(80)); + } +} + /// The ArtCraft wordmark (Storyteller's brand, docs/brand/; not open source), sized to `height`. pub fn artcraft_logo(ui: &mut egui::Ui, height: f32) -> Response { let dark = ui.visuals().dark_mode; From b8c44a5e7976b061510326a11114bb632089ab57 Mon Sep 17 00:00:00 2001 From: cyfung1031 <44498510+cyfung1031@users.noreply.github.com> Date: Fri, 6 Nov 2026 07:10:39 +0900 Subject: [PATCH 025/114] Fix opening indicator review comments --- crates/ui-egui/src/app/files.rs | 7 ++----- crates/ui-egui/src/platform/open_worker/tests.rs | 16 +++++++++------- crates/ui-egui/src/widgets.rs | 3 ++- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 0a6820c7c8..0b42a7c54b 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -134,11 +134,8 @@ impl PdfCraftApp { if self.opening_notice.as_ref().is_some_and(|notice| notice.token == pending.token && notice.lang == lang) { return; } - self.opening_notice = Some(OpeningNotice { - token: pending.token, - lang, - label: i18n::fmt(tl!("Opening {name}…"), &[("name", &pending.name)]), - }); + self.opening_notice = + Some(OpeningNotice { token: pending.token, lang, label: i18n::fmt(tl!("Opening {name}…"), &[("name", &pending.name)]) }); } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/platform/open_worker/tests.rs b/crates/ui-egui/src/platform/open_worker/tests.rs index 669f9dfdc4..0650af2d47 100644 --- a/crates/ui-egui/src/platform/open_worker/tests.rs +++ b/crates/ui-egui/src/platform/open_worker/tests.rs @@ -75,13 +75,15 @@ fn open_prepare_keeps_control_and_existing_tabs_live_until_atomic_commit() { let opening_label = format!("Opening {name}…"); assert_eq!(harness.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(opening_label.as_str())); harness.get_by_label(&opening_label); - // A language change while the open is pending re-translates the notice. - let language = std::mem::replace(&mut harness.state_mut().language, "ja".into()); - harness.step(); - let japanese_label = format!("{name} を開いています…"); - assert_eq!(harness.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(japanese_label.as_str())); - harness.state_mut().language = language; - harness.step(); + // A language change while the open is pending re-translates the notice when catalogs exist. + if crate::i18n::needs_catalogs() { + let language = std::mem::replace(&mut harness.state_mut().language, "ja".into()); + harness.step(); + let japanese_label = format!("{name} を開いています…"); + assert_eq!(harness.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(japanese_label.as_str())); + harness.state_mut().language = language; + harness.step(); + } assert_eq!(harness.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(opening_label.as_str())); let state = request(&mut harness, &client, "ui.state", json!({})); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 7d24a9af5f..01b02ebf89 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -634,7 +634,8 @@ pub fn opening_notice(label: Option<&str>, progress_visible: bool, ctx: &egui::C } else { (Color32::from_rgb(0x2A, 0x2A, 0x2F), Color32::WHITE) }; - let progress_height = if progress_visible { ctx.data(|d| d.get_temp::(egui::Id::unique(PROGRESS_HEIGHT))).unwrap_or(0.0) + 10.0 } else { 0.0 }; + let progress_height = + if progress_visible { ctx.data(|d| d.get_temp::(egui::Id::unique(PROGRESS_HEIGHT))).unwrap_or(0.0) + 10.0 } else { 0.0 }; let animated = crate::motion::animated(ctx); let area = egui::Area::new(egui::Id::new("opening-notice")) .order(egui::Order::Tooltip) From 48cf60e055268f8606db0c7b01b5f89c912e15b1 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Mon, 9 Nov 2026 11:19:33 +0800 Subject: [PATCH 026/114] M3: a bookmark's GoToE action is read as a link's is (view.follow-links) Main's bookmark actions (#5410) share Inspector::action_target with links, so the GoToE arm serves bookmarks too; the test now covers it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pq7HyCHD1R3rywQBPCHXZA --- crates/render/src/inspect/tests.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/render/src/inspect/tests.rs b/crates/render/src/inspect/tests.rs index 587572f093..91880e754d 100644 --- a/crates/render/src/inspect/tests.rs +++ b/crates/render/src/inspect/tests.rs @@ -1963,8 +1963,8 @@ fn outline_items_carry_their_colour_and_style() { /// A bookmark's action (`/A`, ISO 32000-2 §12.3.3 Table 151) is read as a link's is. Only a /// go-to's `/D` is a page of this document: a remote go-to's names a page or destination of the /// other file (§12.6.4.3), so `[0 /FitH 200]` there is not this file's first page. A web address, -/// another PDF and actions PdfCraft doesn't run are kept for the bookmark to run or report. An -/// action without a type is still read as the go-to its `/D` suggests. +/// another PDF, a PDF attached to this one (GoToE, §12.6.4.4) and actions PdfCraft doesn't run +/// are kept for the bookmark to run or report. An action without a type is still read as the go-to its `/D` suggests. #[test] fn bookmark_actions_are_read_as_links_read_them() { use DestView::*; @@ -1974,6 +1974,7 @@ fn bookmark_actions_are_read_as_links_read_them() { ("Other file", "/A << /S /GoToR /F (other.pdf) /D [0 /FitH 200] /NewWindow true >>"), ("Other file, named", "/A << /S /GoToR /F (other.pdf) /D (sec) >>"), ("Launch", "/A << /S /Launch /F (other.pdf) >>"), + ("Attached", "/A << /S /GoToE /T << /R /C /N (inner.pdf) >> /D [1 /Fit] >>"), ("Menu item", "/A << /S /Named /N /NextPage >>"), ("Script", "/A << /S /JavaScript /JS (app.alert\\(1\\)) >>"), ("No type", "/A << /D [3 0 R /Fit] >>"), @@ -2004,6 +2005,16 @@ fn bookmark_actions_are_read_as_links_read_them() { Top, Some(LinkTarget::RemoteGoTo { launch: true, file: "other.pdf".into(), destination: RemoteDestination::Default, new_window: None }) ), + ( + "Attached", + None, + Top, + Some(LinkTarget::EmbeddedGoTo { + source: AttachmentSource::Document { key: "inner.pdf".into() }, + destination: RemoteDestination::Page { page: 1, view: Fit }, + new_window: None + }) + ), ("Menu item", None, Top, Some(LinkTarget::Other("Named".into()))), ("Script", None, Top, Some(LinkTarget::Other("JavaScript".into()))), ("No type", Some(0), Fit, None), From 76d57c7c88fedd69bc8462f221ada4425583ab87 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Tue, 10 Nov 2026 00:17:34 +0800 Subject: [PATCH 027/114] Re-run CI From 2405fcb5a439e0315c7b104a4c091c71c538072c Mon Sep 17 00:00:00 2001 From: alehel Date: Wed, 11 Nov 2026 11:52:37 +0100 Subject: [PATCH 028/114] fix(js, engine, ui): XFA message boxes return the button picked (#4291) xfa.host.messageBox, $host.messageBox and app.alert in XFA scripts always returned 1 (OK), so a form could never branch on No or Cancel. They now return the button picked: 1 OK, 2 Cancel, 3 No, 4 Yes, the same way AcroForm's app.alert does since #5699. - App: an XFA button click runs on a worker, through the same pending script AcroForm buttons use. Each message box of the click, and of the calculations after it, shows in the existing script dialog while the script waits. The script's time limit and the event's budget stop while it waits. The click is kept as one undo step once it ends. It is dropped, with a notice, if the document changed meanwhile; scrolling or zooming doesn't drop it. - Limits: a click asks at most 32 times across all its script sessions. A click whose script runs away turns the form's scripts off even when the click itself is dropped. The app's backstop for an XFA click is 60 s, since the click's own limits can add up past AcroForm's 10 s. - Engine: Session::apply is split into begin_edit and finish_edit, so the click's edit can run on the worker between the two. XfaSession passes the scripts' questions on to the app. - Headless: js_run's answers now reach XFA buttons. Once they run out, a message box gets its buttons' safe default: OK alone 1, Yes/No 3, otherwise 2. - Web build: it has no worker, so nothing can be asked there. XFA message boxes and AcroForm's app.alert both return the safe default. Before, app.alert returned 1 on the web, even for Yes/No. A web version that can wait for an answer is left to a separate change. Scripts that run on their own (open, calculate, validate, enter, exit, preSign) still don't ask; they get the safe default. Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/tools.rs | 4 +- crates/automation/tests/it/automation.rs | 36 ++++ crates/engine/src/document.rs | 4 + crates/engine/src/edit/run.rs | 4 + crates/engine/src/js.rs | 137 +++++++++++-- crates/engine/src/open.rs | 2 + crates/engine/src/session.rs | 5 + crates/engine/src/session/editing.rs | 60 +++++- crates/engine/src/tests.rs | 251 ++++++++++++++++++++++- crates/engine/src/xfa.rs | 57 ++++- crates/engine/src/xfa_form.rs | 1 + crates/js/src/formcalc.rs | 2 + crates/js/src/formcalc/eval.rs | 15 +- crates/js/src/globals.rs | 27 +-- crates/js/src/interaction.rs | 4 +- crates/js/src/model.rs | 35 ++++ crates/js/src/tests.rs | 128 +++++++++++- crates/js/src/xfa/globals.rs | 20 +- crates/js/src/xfa/host.rs | 30 +++ crates/js/src/xfa/model.rs | 12 ++ crates/js/src/xfa/run.rs | 4 +- crates/js/src/xfa_session.rs | 64 +++++- crates/ui-egui/src/script_dialog.rs | 14 +- crates/ui-egui/src/workflows/js_ui.rs | 8 +- crates/ui-egui/tests/it/xfa.rs | 89 +++++++- parity/acrobat-features.toml | 10 +- 26 files changed, 931 insertions(+), 92 deletions(-) diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 4f1342605b..b0998a86ca 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -1415,10 +1415,10 @@ pub fn tools() -> Vec { t("form_merge_data", "Merge data files into spreadsheet", "Collect the field values of form data files (FDF, XFDF) or filled-in PDF forms into one CSV file at path: a column per field name, a row per file. Returns the row and column counts.") .cmd("form.merge_data") .with(schema(json!({ "paths": { "type": "array", "items": { "type": "string" }, "minItems": 1 }, "path": { "type": "string" } }), &["paths", "path"])), - t("js_run", "Run JavaScript", "Run Acrobat JavaScript in the document, as the JavaScript console does (or as push button `field`'s Mouse Up script when field is given; on a laid-out XFA form, `field` runs that button's XFA click script instead, JavaScript or FormCalc, which can add and remove rows and show or hide subforms). The form object model is available: this/getField, event, app, util, console, display, color, and the document-level scripts (except the PDF container scripts when XFA layout is active; they remain available through js_document_scripts). Field changes and resetForm are applied as one undoable step; returns the script's and subsequent field scripts' alerts (each with its message, title, icon and buttons, in order; AcroForm replies consume ordered answers; missing replies cancel input or use the alert button set's safe default), console output, requests (print, page, url, submit, attachment), error, and the errors of document-level scripts that failed (the rest still ran), plus warnings from applying the changes.") + t("js_run", "Run JavaScript", "Run Acrobat JavaScript in the document, as the JavaScript console does (or as push button `field`'s Mouse Up script when field is given; on a laid-out XFA form, `field` runs that button's XFA click script instead, JavaScript or FormCalc, which can add and remove rows and show or hide subforms). The form object model is available: this/getField, event, app, util, console, display, color, and the document-level scripts (except the PDF container scripts when XFA layout is active; they remain available through js_document_scripts). Field changes and resetForm are applied as one undoable step; returns the script's and subsequent field scripts' alerts (each with its message, title, icon and buttons, in order; popups, responses and message boxes take the ordered answers, an XFA button's xfa.host.messageBox, $host.messageBox and app.alert included, each message box returning the button answered (1 OK, 2 Cancel, 3 No, 4 Yes); missing replies cancel input or give the message box's safe default: OK alone 1, Yes/No 3, otherwise 2), console output, requests (print, page, url, submit, attachment), error, and the errors of document-level scripts that failed (the rest still ran), plus warnings from applying the changes.") .cmd("tools.js_console") .with(schema( - json!({ "doc": doc(), "script": { "type": "string" }, "field": { "type": "string", "description": "Run as this button's Mouse Up event." }, "field_id": {"type":"integer","minimum":0,"maximum":281474976710655u64,"description":"Optional exact field identity from form_fields; requires matching field name and is scoped to this document."}, "answers": {"type":"array","maxItems":32,"items":{"type":["string","null"],"maxLength":4096},"description":"Ordered popup, response and alert answers; strings are limited to 4096 UTF-8 bytes at runtime; null cancels a popup or response, and selects an alert default (OK, Cancel or No, by button set)."} }), + json!({ "doc": doc(), "script": { "type": "string" }, "field": { "type": "string", "description": "Run as this button's Mouse Up event." }, "field_id": {"type":"integer","minimum":0,"maximum":281474976710655u64,"description":"Optional exact field identity from form_fields; requires matching field name and is scoped to this document."}, "answers": {"type":"array","maxItems":32,"items":{"type":["string","null"],"maxLength":4096},"description":"Ordered popup, response and message box answers (every message box takes one, OK-only ones too; \"1\" OK, \"2\" Cancel, \"3\" No, \"4\" Yes); strings are limited to 4096 UTF-8 bytes at runtime; null cancels a popup or response, and selects a message box's default (OK, Cancel or No, by button set)."} }), &["doc", "script"], )), t( diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 54e10a035e..09825ca81c 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -11039,6 +11039,42 @@ fn xfa_scripts_run_for_buttons_and_field_changes_through_tools() { assert_eq!(r["alerts"], json!([{ "message": "Hello 4", "title": null, "icon": "error", "buttons": "ok" }])); } +/// An XFA button that asks Yes or No branches on the answer `js_run` gives, in JavaScript and +/// FormCalc alike, and without one takes the No branch (#4291). +#[test] +fn js_run_answers_an_xfa_buttons_message_boxes() { + let dir = workdir("xfa-answers"); + let tpl = pdfcraft_xfa::fixtures::scripted_template() + .replace( + r#"xfa.host.messageBox("Hello " + qty.rawValue);"#, + r#"qty.rawValue = xfa.host.messageBox("Clear?", "Order form", 2, 2) == 4 ? 0 : 7;"#, + ) + .replace(r#"$host.messageBox("FormCalc")"#, r#"if ($host.messageBox("Sure?", "", 2, 1) == 1) then qty = 50 else qty = 9 endif"#); + std::fs::write(dir.join("asking.pdf"), pdfcraft_xfa::fixtures::shell(&tpl)).unwrap(); + let mut a = auto(&dir).with_xfa_time_scale(100); + let doc = ok(&mut a, "doc_open", json!({ "path": "asking.pdf" }))["doc"].as_u64().unwrap(); + let qty = |a: &mut Automation| { + let f = ok(a, "form_fields", json!({ "doc": doc })); + f["fields"].as_array().unwrap().iter().find(|f| f["name"] == "qty").unwrap()["value"].clone() + }; + let r = ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello", "answers": ["4"] })); + assert!(r["error"].is_null(), "{r}"); + assert_eq!(r["alerts"], json!([{ "message": "Clear?", "title": "Order form", "icon": "question", "buttons": "yes_no" }])); + assert_eq!(qty(&mut a), "0"); + ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello", "answers": ["3"] })); + assert_eq!(qty(&mut a), "7"); + ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "legacy", "answers": ["1"] })); + assert_eq!(qty(&mut a), "50"); + // No answer: No, and Cancel. + ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello" })); + assert_eq!(qty(&mut a), "7"); + ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "legacy", "answers": [null] })); + assert_eq!(qty(&mut a), "9"); + // An answer the buttons can't give is the script's error, naming it. + let r = ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello", "answers": ["2"] })); + assert!(r["error"].as_str().is_some_and(|e| e.contains("message box 1 (2)")), "{r}"); +} + #[test] fn active_xfa_skips_container_fallback_scripts_after_save_and_reopen() { let dir = workdir("xfa-container-scripts"); diff --git a/crates/engine/src/document.rs b/crates/engine/src/document.rs index 602410922f..1da62570c1 100644 --- a/crates/engine/src/document.rs +++ b/crates/engine/src/document.rs @@ -66,6 +66,10 @@ pub struct Document { /// since they last gained focus: their exit on losing focus has run already /// ([`Session::field_focus`]). pub(crate) xfa_exited: std::collections::HashSet, + /// An XFA button click run on a worker ([`Session::start_javascript_target`]) had a script + /// run away: the next edit turns the form's scripts off, as it would have had the click been + /// kept (it may have been dropped: the document changed, or the app stopped waiting). + pub(crate) xfa_ran_away: std::sync::Arc, /// A content-only refresh keeps `info` from before the edit; an edit may have added or /// embedded fonts, so the font list is read again on demand ([`Session::refresh_fonts`]). pub(crate) fonts_stale: bool, diff --git a/crates/engine/src/edit/run.rs b/crates/engine/src/edit/run.rs index 57e5729fc8..d887155d3d 100644 --- a/crates/engine/src/edit/run.rs +++ b/crates/engine/src/edit/run.rs @@ -234,6 +234,8 @@ pub(crate) struct EditCtx { pub(crate) xfa_unchanged: bool, /// What the XFA scripts' time limits are multiplied by ([`Session::with_xfa_time_scale`]). pub(crate) xfa_time_scale: u32, + /// The answers the edit's XFA event takes ([`Session::xfa_answers`](crate::Session)). + pub(crate) xfa_answers: xfa::XfaAnswers, /// The edit took the XFA out of the form: what went with it, for the document's warnings. pub(crate) xfa_removed: Vec, /// Pages in the document, for `xfa.layout.pageCount()`. @@ -300,6 +302,7 @@ impl EditCtx { xfa_ran_away: false, xfa_unchanged: false, xfa_time_scale: 1, + xfa_answers: Default::default(), xfa_removed: Vec::new(), pages: 0, highlight: false, @@ -749,6 +752,7 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E ran_away: false, highlight, time_scale: cx.xfa_time_scale, + answers: std::mem::take(&mut cx.xfa_answers), }; let ran = if matches!(activity.as_str(), "enter" | "exit") { xfa::on_focus(doc, &tpl, som, activity, &mut run).map(|changes| changes.is_empty()) diff --git a/crates/engine/src/js.rs b/crates/engine/src/js.rs index bde0d5a02c..9fa96e100e 100644 --- a/crates/engine/src/js.rs +++ b/crates/engine/src/js.rs @@ -1168,24 +1168,18 @@ impl Session { let doc = self.get(id).ok_or(EditError::NoDocument)?; let cos = doc.editor.as_ref().map(|e| e.cos.clone()).ok_or_else(|| EditError::ReadOnly(doc.read_only_reason.clone().unwrap_or_default()))?; validate_script_target(target, target_id, &doc.form)?; - // A button PdfCraft generated from an XFA template runs its XFA click script. - if let Some(t) = target - && event_name.is_none_or(|n| n == "Mouse Up") - && let Some(tpl) = doc.xfa_template.clone() - && let Some(field) = doc.form.iter().find(|f| f.name == t && target_id.is_none_or(|id| field_object_id(f.obj) == id)) - && field.kind == crate::FormFieldKind::PushButton - && let Some(som) = crate::xfa::clickable_som(&cos, &tpl, field) + // A button PdfCraft generated from an XFA template runs its XFA click script, its + // message boxes taking `answers` (then their buttons' safe default: nobody is asked). + if event_name.is_none_or(|n| n == "Mouse Up") + && let Some(som) = xfa_click_som(doc, &cos, target, target_id) { + self.xfa_answers = Some(crate::xfa::XfaAnswers { given: answers.to_vec(), ..Default::default() }); // The click returns only the output of its own edit; output from opening or from earlier edits stays. - let ((), out) = self.with_own_js_output(id, |s| s.apply(id, Edit::XfaEvent { som, activity: "click".into() }))?; - return Ok(Outcome { - rc: true, - alerts: out.alerts, - console: out.console, - requests: out.requests, - error: out.errors.first().cloned(), - ..Default::default() - }); + let ran = self.with_own_js_output(id, |s| s.apply(id, Edit::XfaEvent { som, activity: "click".into() })); + // Not taken when the edit stopped before it ran the event: no later edit takes it. + self.xfa_answers = None; + let ((), out) = ran?; + return Ok(xfa_click_outcome(out)); } let mut runner = JsRunner::new(&cos, &doc.name, self.field_highlight); runner.doc.zoom = doc.js_zoom; @@ -1626,6 +1620,32 @@ mod caption_tests { } } +/// The SOM path of the XFA click script button `target` runs, when it is a push button PdfCraft +/// generated from a laid-out XFA form's template. +fn xfa_click_som(doc: &crate::Document, cos: &pdfcraft_cos::Document, target: Option<&str>, target_id: Option) -> Option { + let t = target?; + let tpl = doc.xfa_template.as_ref()?; + let field = doc.form.iter().find(|f| f.name == t && target_id.is_none_or(|id| field_object_id(f.obj) == id))?; + if field.kind != crate::FormFieldKind::PushButton { + return None; + } + crate::xfa::clickable_som(cos, tpl, field) +} + +/// What an XFA button click did, as a button script's outcome. +fn xfa_click_outcome(out: JsOutput) -> Outcome { + Outcome { rc: true, alerts: out.alerts, console: out.console, requests: out.requests, error: out.errors.first().cloned(), ..Default::default() } +} + +/// Stack for the thread an XFA button click runs on in the app: it lays the form out again, as +/// the app's main thread does for other edits. +#[cfg(not(target_arch = "wasm32"))] +const XFA_CLICK_STACK: usize = 8 << 20; + +/// An XFA button click's edit, once its worker has run it ([`Session::start_javascript_target`]). +#[cfg(not(target_arch = "wasm32"))] +type XfaClick = std::sync::Arc)>>>; + #[cfg(not(target_arch = "wasm32"))] pub struct PendingScript { pub id: DocId, @@ -1633,6 +1653,16 @@ pub struct PendingScript { runtime: Runtime, states: std::sync::Arc>, pub receiver: std::sync::mpsc::Receiver, + /// An XFA button click: its edit, filled in by its worker before it completes. + xfa: Option, +} +#[cfg(not(target_arch = "wasm32"))] +impl PendingScript { + /// Whether this is an XFA button's click ([`Session::start_javascript_target`]). It reads + /// no view state (zoom, page) the way an AcroForm script does, and its own limits bound it. + pub fn is_xfa(&self) -> bool { + self.xfa.is_some() + } } #[cfg(not(target_arch = "wasm32"))] impl Session { @@ -1657,11 +1687,14 @@ impl Session { } let doc = self.get(id).ok_or(EditError::NoDocument)?; let cos = &doc.editor.as_ref().ok_or_else(|| EditError::ReadOnly(doc.read_only_reason.clone().unwrap_or_default()))?.cos; + let fields = pdfcraft_forms::fields(cos); + validate_script_target(target, target_id, &fields)?; + if let Some(som) = xfa_click_som(doc, cos, target, target_id) { + return self.start_xfa_click(id, som); + } let mut runner = JsRunner::new(cos, &doc.name, self.field_highlight); runner.doc.zoom = doc.js_zoom; runner.doc.page = doc.js_page; - let fields = pdfcraft_forms::fields(cos); - validate_script_target(target, target_id, &fields)?; let states = std::sync::Arc::new(fields.iter().map(|f| field_state(cos, f, &runner.doc)).collect::>()); let job = pdfcraft_js::session::Job { script: script.into(), @@ -1676,10 +1709,59 @@ impl Session { }; let receiver = doc.js_runtime.lock().map_err(|_| EditError::Invalid("script runtime unavailable".into()))?.start(job).map_err(EditError::Invalid)?; - Ok(PendingScript { id, generation: doc.generation, runtime: doc.js_runtime.clone(), states, receiver }) + Ok(PendingScript { id, generation: doc.generation, runtime: doc.js_runtime.clone(), states, receiver, xfa: None }) + } + + /// Start XFA button `som`'s click on a worker, so the app goes on drawing while it runs and + /// can ask its message boxes' questions: each comes through the pending script's receiver + /// as a prompt, and the script waits for the answer with its clock stopped. Once the worker + /// is done, [`Session::finish_javascript`] keeps the click as one undo step, as + /// [`Session::apply`] would, unless the document changed meanwhile. + fn start_xfa_click(&mut self, id: DocId, som: String) -> Result { + let (prompts, receiver) = std::sync::mpsc::channel(); + self.xfa_answers = Some(crate::xfa::XfaAnswers { prompts: Some(prompts.clone()), ..Default::default() }); + let begun = self.begin_edit(id, Edit::XfaEvent { som, activity: "click".into() }); + // Not taken when the edit stopped before it began. + self.xfa_answers = None; + let begun = begun?; + let doc = self.get(id).ok_or(EditError::NoDocument)?; + let click: XfaClick = Default::default(); + let pending = PendingScript { + id, + generation: doc.generation, + runtime: doc.js_runtime.clone(), + states: Default::default(), + receiver, + xfa: Some(click.clone()), + }; + let Some(mut begun) = begun else { + // Nothing to run: done at once. + let _ = prompts.send(InteractiveEvent::Complete(Outcome::default())); + return Ok(pending); + }; + let ran_away = std::sync::Arc::clone(&doc.xfa_ran_away); + std::thread::Builder::new() + .name("pdfcraft-xfa-click".into()) + .stack_size(XFA_CLICK_STACK) + .spawn(move || { + let checked = crate::session::run_checked_edit(&mut begun.next, &begun.edit, &mut begun.cx); + if begun.cx.xfa_ran_away { + ran_away.store(true, std::sync::atomic::Ordering::Relaxed); + } + // A poisoned lock only means a panic elsewhere while it was held: the slot is still ours. + *click.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some((begun, checked)); + // The app may have stopped waiting: then nobody takes the click. + let _ = prompts.send(InteractiveEvent::Complete(Outcome::default())); + }) + .map_err(|e| EditError::Invalid(format!("the form script could not start: {e}")))?; + Ok(pending) } /// Discard only the captured runtime, preserving a newer realm created by an intervening edit. pub fn discard_javascript(&mut self, p: &PendingScript) { + // An XFA click's worker holds no realm: what it did is dropped with the pending script. + if p.xfa.is_some() { + return; + } if let Some(doc) = self.docs.iter_mut().find(|d| d.id == p.id) && std::sync::Arc::ptr_eq(&doc.js_runtime, &p.runtime) { @@ -1688,6 +1770,10 @@ impl Session { } /// Discard a timed-out invocation and retain the worker slot until its thread exits. pub fn timeout_javascript(&mut self, p: PendingScript) { + // An XFA click's scripts are bounded on its worker; what it did is dropped. + if p.xfa.is_some() { + return; + } if self.script_pending_current(&p) && let Ok(mut runtime) = p.runtime.lock() { @@ -1699,6 +1785,19 @@ impl Session { /// Apply a current worker result, or discard it and reset the realm when the document changed. pub fn finish_javascript(&mut self, p: PendingScript, out: Outcome) -> Result { + if let Some(click) = &p.xfa { + if !self.script_pending_current(&p) { + return Err(EditError::Invalid("document changed while the script was running".into())); + } + let ran = click.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); + let Some((begun, checked)) = ran else { return Ok(Outcome { rc: true, ..Default::default() }) }; + let ((), out) = self.with_own_js_output(p.id, |s| s.finish_edit(p.id, begun, checked).map(|_| ()))?; + // Kept, the click turned the scripts off itself (if they ran away): not again. + if let Some(d) = self.get(p.id) { + d.xfa_ran_away.store(false, std::sync::atomic::Ordering::Relaxed); + } + return Ok(xfa_click_outcome(out)); + } if !self.script_pending_current(&p) { self.discard_javascript(&p); return Err(EditError::Invalid("document changed while the script was running".into())); diff --git a/crates/engine/src/open.rs b/crates/engine/src/open.rs index 685ac50432..8e28cdefc3 100644 --- a/crates/engine/src/open.rs +++ b/crates/engine/src/open.rs @@ -225,6 +225,7 @@ impl Session { ran_away: false, highlight: context.highlight, time_scale: context.xfa_time_scale, + answers: Default::default(), }; let changes = xfa::on_open(&mut work, &tpl, &mut run); if run.ran_away { @@ -389,6 +390,7 @@ impl Session { xfa_template: None, xfa_scripts_off: false, xfa_exited: Default::default(), + xfa_ran_away: Default::default(), fonts_stale: false, xfa_warnings: Vec::new(), edit_notices: Vec::new(), diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 187cc217d8..536c35e4cb 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -20,6 +20,8 @@ use crate::{ }; mod editing; +#[cfg(not(target_arch = "wasm32"))] +pub(crate) use editing::{BegunEdit, run_checked_edit}; mod files; mod save; mod view; @@ -51,4 +53,7 @@ pub struct Session { /// What the XFA scripts' time limits are multiplied by (`None`: 1); see /// [`Session::with_xfa_time_scale`]. pub(crate) xfa_time_scale: Option, + /// The answers the next XFA event takes for its message boxes, set by the caller running it + /// (`js_run`'s answers, an app's button click) and taken by that event's edit. + pub(crate) xfa_answers: Option, } diff --git a/crates/engine/src/session/editing.rs b/crates/engine/src/session/editing.rs index 4a6f372fb4..917e0048a6 100644 --- a/crates/engine/src/session/editing.rs +++ b/crates/engine/src/session/editing.rs @@ -46,7 +46,7 @@ fn deletes_pages(edit: &Edit) -> bool { } /// Keep edits to the working copy until both the operation and its script callbacks succeed. -fn run_checked_edit(next: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -> Result<(), EditError> { +pub(crate) fn run_checked_edit(next: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -> Result<(), EditError> { let result = guard(|| run_edit(next, edit, cx)) .unwrap_or_else(|m| Err(EditError::Invalid(format!("{} failed unexpectedly ({m}); the document was not changed", edit.label())))); let refusal = cx.js.as_mut().and_then(|runner| runner.refused.take()); @@ -122,6 +122,20 @@ fn sync_script_history(doc: &Document, previous: &pdfcraft_cos::Document, restor } } +/// An edit between [`Session::begin_edit`] and [`Session::finish_edit`]: the copy of the +/// document it runs on (`next`) and its context. Send, so an XFA button click can run on a +/// worker while the app goes on drawing and asks the click's questions. +pub(crate) struct BegunEdit { + pub(crate) edit: Edit, + pub(crate) next: pdfcraft_cos::Document, + pub(crate) cx: EditCtx, + scope: Scope, + is_xfa: bool, + signed: bool, + /// The document's generation it was made from: a changed document doesn't take it. + generation: u64, +} + impl Session { /// Apply an edit. On success the previous state is undoable and the view data is refreshed. pub fn apply(&mut self, id: DocId, edit: Edit) -> Result<(), EditError> { @@ -138,12 +152,27 @@ impl Session { /// [`Session::apply`], giving back what an [`Edit::PrepareText`] did (`None` for other edits). fn apply_reporting(&mut self, id: DocId, edit: Edit) -> Result, EditError> { + let Some(mut begun) = self.begin_edit(id, edit)? else { return Ok(None) }; + // `next` is a copy: if the edit fails or crashes, the document is unchanged. + let checked = run_checked_edit(&mut begun.next, &begun.edit, &mut begun.cx); + self.finish_edit(id, begun, checked) + } + + /// The first part of [`Session::apply`]: check that `edit` may be made, and make the copy of + /// the document it runs on, with its context. `None`: there is nothing to do. + pub(crate) fn begin_edit(&mut self, id: DocId, edit: Edit) -> Result, EditError> { let now = self.now(); let today = self.today(); let js_off = self.js_off; let highlight = self.field_highlight; let xfa_time_scale = self.xfa_time_scale.unwrap_or(1); + let xfa_answers = self.xfa_answers.take().unwrap_or_default(); let doc = self.doc_mut(id)?; + // A script of an XFA click run on a worker ran away: the form's scripts go off, whether + // or not the click was kept. + if doc.xfa_ran_away.swap(false, std::sync::atomic::Ordering::Relaxed) { + take_xfa_output(doc, js::JsOutput::default(), true); + } // An edit must never read globals from a completed-but-unapplied button invocation. // Fork its realm before any edit-triggered calculation, even if the edit later fails. #[cfg(not(target_arch = "wasm32"))] @@ -153,12 +182,13 @@ impl Session { doc.edit_notices.clear(); let name = doc.name.clone(); let is_xfa = doc.info.xfa.is_some(); - let mut scope = scope_of(&edit); + let scope = scope_of(&edit); let mut cx = EditCtx::new(now, doc.generation ^ (id.0 << 48)); if !js_off { cx.xfa = doc.xfa_template.clone(); } cx.xfa_time_scale = xfa_time_scale; + cx.xfa_answers = xfa_answers; cx.pages = doc.info.pages.len(); cx.highlight = highlight; cx.today = today; @@ -175,7 +205,7 @@ impl Session { if matches!(&edit, Edit::FlattenFillSign) && !pdfcraft_annot::has_visible_fill_sign(&editor.cos) { return Ok(None); } - let mut next = editor.cos.clone(); + let next = editor.cos.clone(); if !js_off && uses_scripts(&edit) { let mut runner = js::JsRunner::new(&next, &name, highlight); runner.runtime = doc.js_runtime.clone(); @@ -185,8 +215,27 @@ impl Session { } cx.renamed_fields.clear(); cx.redaction_overlays.clear(); - // `next` is a copy: if the edit fails or crashes, the document is unchanged. - run_checked_edit(&mut next, &edit, &mut cx)?; + Ok(Some(BegunEdit { edit, next, cx, scope, is_xfa, signed, generation: doc.generation })) + } + + /// The last part of [`Session::apply`]: keep the edit [`Session::begin_edit`] prepared once + /// it ran (`checked`), as one undo step, unless it failed or the document changed meanwhile + /// (an XFA button click runs on a worker: [`Session::start_javascript_target`]). + pub(crate) fn finish_edit( + &mut self, + id: DocId, + begun: BegunEdit, + checked: Result<(), EditError>, + ) -> Result, EditError> { + let BegunEdit { edit, mut next, mut cx, mut scope, is_xfa, signed, generation } = begun; + let doc = self.doc_mut(id)?; + if doc.generation != generation { + discard_edit_callbacks(&cx); + return Err(EditError::Invalid("the document changed while the form's script ran; what it did was not kept".into())); + } + let reason = doc.read_only_reason.clone().unwrap_or_default(); + let editor = doc.editor.as_mut().ok_or(EditError::ReadOnly(reason))?; + checked?; // A field's enter or exit scripts that changed nothing leave no edit behind (no undo step, // nothing unsaved); what they showed or asked for still goes out. Only an event on its own: // a batch keeps the other edits it holds. @@ -264,6 +313,7 @@ impl Session { ran_away: false, highlight, time_scale: cx.xfa_time_scale, + answers: Default::default(), }; // Every changed field's scripts, then the calculations once (after a reset, // only those). diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 4e24a4f608..18b815dfa8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8064,11 +8064,27 @@ fn on_changes_notes_only_the_exits_that_ran() { let names = vec!["probe".to_string()]; let mut exited = Vec::new(); let mut out = crate::js::JsOutput::default(); - let mut stopped = crate::xfa::XfaRun { page_count: 1, out: &mut out, datasets: None, ran_away: true, highlight: false, time_scale: 1 }; + let mut stopped = crate::xfa::XfaRun { + page_count: 1, + out: &mut out, + datasets: None, + ran_away: true, + highlight: false, + time_scale: 1, + answers: Default::default(), + }; crate::xfa::on_changes(&mut cos, &tpl, &names, &mut stopped, &mut exited).unwrap(); assert!(exited.is_empty(), "no exit ran: {exited:?}"); let mut out = crate::js::JsOutput::default(); - let mut running = crate::xfa::XfaRun { page_count: 1, out: &mut out, datasets: None, ran_away: false, highlight: false, time_scale: 1 }; + let mut running = crate::xfa::XfaRun { + page_count: 1, + out: &mut out, + datasets: None, + ran_away: false, + highlight: false, + time_scale: 1, + answers: Default::default(), + }; crate::xfa::on_changes(&mut cos, &tpl, &names, &mut running, &mut exited).unwrap(); assert_eq!(exited.len(), 1, "the exit ran: {exited:?}"); } @@ -9862,6 +9878,237 @@ fn xfa_message_boxes_keep_their_title_icon_and_buttons() { assert_eq!(o.alerts, vec![titled("Too many", "Limits", MessageIcon::Warning, MessageButtons::OkCancel)]); } +/// A form whose buttons branch on their message boxes' answers (#4291): `hello` (JavaScript) +/// shows a message, then asks two questions; `legacy` (FormCalc) asks one. +fn asking_form() -> (Session, DocId) { + let tpl = pdfcraft_xfa::fixtures::scripted_template() + .replace( + r#"xfa.host.messageBox("Hello " + qty.rawValue);"#, + r#"xfa.host.messageBox("Starting"); var a = xfa.host.messageBox("Clear?", "T", 2, 2); var b = app.alert("Really?", 2, 1); qty.rawValue = (a == 4 ? 10 : 20) + (b == 1 ? 1 : 2);"#, + ) + .replace(r#"$host.messageBox("FormCalc")"#, r#"if ($host.messageBox("Sure?", "", 2, 2) == 4) then qty = 50 else qty = 1 endif"#); + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("asking.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens"); + (s, id) +} + +fn qty(s: &Session, id: DocId) -> Vec { + s.get(id).unwrap().form.iter().find(|f| f.name == "qty").unwrap().value.clone() +} + +fn answers(a: &[&str]) -> Vec> { + a.iter().map(|a| Some(a.to_string())).collect() +} + +/// An XFA button's message boxes return the answers given, in order, headless (`js_run`'s +/// answers), in JavaScript and FormCalc alike: a form can branch on No and Cancel (#4291). +/// Without answers each question gets its buttons' safe default (No; Cancel), not OK. +#[test] +fn xfa_message_boxes_return_the_answers_given() { + let (mut s, id) = asking_form(); + assert_eq!(qty(&s, id), ["2"]); + let o = s.run_javascript_answers(id, "", Some("hello"), &answers(&["1", "4", "1"])).unwrap(); + assert_eq!((o.error.as_deref(), o.alerts.len()), (None, 3), "{o:?}"); + assert_eq!(qty(&s, id), ["11"]); + let o = s.run_javascript_answers(id, "", Some("hello"), &answers(&["1", "3", "2"])).unwrap(); + assert_eq!(o.error, None); + assert_eq!(qty(&s, id), ["22"]); + s.run_javascript(id, "", Some("hello")).unwrap(); + assert_eq!(qty(&s, id), ["22"], "no answers: No and Cancel"); + s.run_javascript_answers(id, "", Some("legacy"), &answers(&["4"])).unwrap(); + assert_eq!(qty(&s, id), ["50"]); + s.run_javascript(id, "", Some("legacy")).unwrap(); + assert_eq!(qty(&s, id), ["1"]); + // An answer the buttons can't give fails the script and says which. + let o = s.run_javascript_answers(id, "", Some("hello"), &answers(&["1", "2"])).unwrap(); + assert!(o.error.as_deref().is_some_and(|e| e.contains("message box 2 (2)")), "{o:?}"); +} + +/// Wait for the next event of an XFA click started as the app starts it. +#[cfg(not(target_arch = "wasm32"))] +fn next_event(p: &crate::js::PendingScript) -> crate::js::InteractiveEvent { + p.receiver.recv_timeout(std::time::Duration::from_secs(20)).expect("the click goes on") +} + +/// Answer the click's questions in turn with `answers` (each prompt checked against `asked`), +/// then keep the click. Returns the outcome. +#[cfg(not(target_arch = "wasm32"))] +fn answer_click(s: &mut Session, p: crate::js::PendingScript, asked: &[&str], answers: &[Option<&str>]) -> Result { + use crate::js::{InteractiveEvent, Prompt}; + for (want, answer) in asked.iter().zip(answers) { + match next_event(&p) { + InteractiveEvent::Prompt(Prompt::Alert(m), reply) => { + assert_eq!(m.text, *want); + reply.send(answer.map(String::from)).expect("the script waits"); + } + InteractiveEvent::Prompt(other, _) => panic!("{other:?}"), + InteractiveEvent::Complete(_) => panic!("finished before asking {want}"), + } + } + let InteractiveEvent::Complete(out) = next_event(&p) else { panic!("asked more than {asked:?}") }; + s.finish_javascript(p, out) +} + +/// An XFA button clicked in the app runs on a worker and asks its message boxes' questions, +/// each script waiting for its answer, in JavaScript and FormCalc alike (#4291), as an AcroForm +/// script's `app.alert` does: nothing changes while it asks, and the click is kept as one undo +/// step once answered. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_xfa_click_started_in_the_app_asks_and_waits_for_each_answer() { + use crate::js::{InteractiveEvent, Prompt}; + let (mut s, id) = asking_form(); + let p = s.start_javascript_target(id, "", Some("hello"), None).unwrap(); + let InteractiveEvent::Prompt(Prompt::Alert(m), reply) = next_event(&p) else { panic!("asks") }; + assert_eq!((m.text.as_str(), m.buttons), ("Starting", js::MessageButtons::Ok)); + // The script waits; the document is as it was. + assert_eq!(qty(&s, id), ["2"]); + assert!(s.get(id).unwrap().can_undo().is_none()); + reply.send(Some("1".into())).unwrap(); + let o = answer_click(&mut s, p, &["Clear?", "Really?"], &[Some("4"), None]).unwrap(); + assert_eq!((o.error, o.alerts.len()), (None, 3)); + assert_eq!(qty(&s, id), ["12"], "Yes, then closed (Cancel)"); + assert!(s.get(id).unwrap().can_undo().is_some()); + let p = s.start_javascript_target(id, "", Some("legacy"), None).unwrap(); + answer_click(&mut s, p, &["Sure?"], &[Some("3")]).unwrap(); + assert_eq!(qty(&s, id), ["1"]); +} + +/// A document changed while its XFA click waits for an answer doesn't take the click. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_xfa_click_is_dropped_when_the_document_changes_while_it_asks() { + use crate::js::{InteractiveEvent, Prompt}; + let (mut s, id) = asking_form(); + let p = s.start_javascript_target(id, "", Some("legacy"), None).unwrap(); + let InteractiveEvent::Prompt(Prompt::Alert(_), reply) = next_event(&p) else { panic!("asks") }; + s.apply(id, Edit::SetFieldValue { name: "qty".into(), value: FieldValue::Text("7".into()) }).unwrap(); + reply.send(Some("4".into())).unwrap(); + let InteractiveEvent::Complete(out) = next_event(&p) else { panic!("finishes") }; + assert!(!s.script_pending_current(&p)); + assert!(s.finish_javascript(p, out).is_err()); + assert_eq!(qty(&s, id), ["7"]); +} + +/// A click's prompts are limited as an AcroForm script's are: past 32 the script fails, and +/// keeps what it did before, as a failing script does. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_xfa_click_asks_at_most_32_questions() { + use crate::js::{InteractiveEvent, Prompt}; + let tpl = pdfcraft_xfa::fixtures::scripted_template().replace( + r#"xfa.host.messageBox("Hello " + qty.rawValue);"#, + r#"for (var i = 0; i < 1000; i++) { if (xfa.host.messageBox("Again?", "", 2, 2) == 4) qty.rawValue = i + 1; }"#, + ); + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("many.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens"); + let p = s.start_javascript_target(id, "", Some("hello"), None).unwrap(); + let mut asked = 0; + let out = loop { + match next_event(&p) { + InteractiveEvent::Prompt(Prompt::Alert(_), reply) => { + asked += 1; + reply.send(Some("4".into())).unwrap(); + } + InteractiveEvent::Prompt(other, _) => panic!("{other:?}"), + InteractiveEvent::Complete(out) => break out, + } + }; + assert_eq!(asked, 32); + let o = s.finish_javascript(p, out).unwrap(); + assert!(o.error.as_deref().is_some_and(|e| e.contains("too many interactive prompts")), "{o:?}"); + assert_eq!(qty(&s, id), ["32"]); +} + +/// The 32-question limit holds for the whole click, not for each script session: a script that +/// turns field highlighting on or off starts a new session for the next, and the calculations +/// after it still can't ask more (they get the buttons' safe default). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_xfa_clicks_question_limit_holds_across_its_script_sessions() { + use crate::js::{InteractiveEvent, Prompt}; + let asks = "app.runtimeHighlight = !app.runtimeHighlight; for (var i = 0; i < 20; i++) xfa.host.messageBox(\"Again?\", \"\", 0, 1);"; + let tpl = pdfcraft_xfa::fixtures::scripted_template() + .replace(r#"xfa.host.messageBox("Hello " + qty.rawValue);"#, asks) + .replace( + "", + &format!(""), + ) + .replace( + r#"var t = 0; var rows = xfa.resolveNodes("table.row[*]"); for (var i = 0; i < rows.length; i++) { t += (rows.item(i).amount.rawValue || 0); } t"#, + &format!("{asks} 0"), + ); + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("hostile.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens"); + let p = s.start_javascript_target(id, "", Some("hello"), None).unwrap(); + let mut asked = 0; + loop { + match next_event(&p) { + InteractiveEvent::Prompt(Prompt::Alert(_), reply) => { + asked += 1; + reply.send(Some("1".into())).unwrap(); + } + InteractiveEvent::Prompt(other, _) => panic!("{other:?}"), + InteractiveEvent::Complete(_) => break, + } + } + assert_eq!(asked, 32, "the click and two calculations would ask 60 times"); +} + +/// A click whose script ran away turns the form's scripts off even when the click itself is +/// dropped (here the document changed while it ran), as a kept one does. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_dropped_xfa_click_that_ran_away_still_turns_the_scripts_off() { + use crate::js::InteractiveEvent; + let tpl = pdfcraft_xfa::fixtures::scripted_template().replace( + r#"xfa.host.messageBox("Hello " + qty.rawValue);"#, + "function f() { for (var j = 0; j < 99999; j++) {} } for (var k = 0; k < 5000; k++) f();", + ); + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("runaway.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens"); + let p = s.start_javascript_target(id, "", Some("hello"), None).unwrap(); + s.apply(id, Edit::SetFieldValue { name: "price".into(), value: FieldValue::Text("6".into()) }).unwrap(); + let InteractiveEvent::Complete(out) = next_event(&p) else { panic!("finishes") }; + assert!(s.finish_javascript(p, out).is_err(), "the document changed"); + assert!(!s.get(id).unwrap().xfa_scripts_off()); + s.apply(id, Edit::SetFieldValue { name: "price".into(), value: FieldValue::Text("7".into()) }).unwrap(); + assert!(s.get(id).unwrap().xfa_scripts_off(), "the next edit turns them off"); + assert!(s.take_js_output(id).errors.iter().any(|e| e.contains("scripts are off"))); +} + +/// The time a calculation waits for the user isn't the event's: the calculations after it still +/// run, though the wait is longer than their whole budget. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn waiting_for_an_answer_does_not_spend_the_events_time() { + use crate::js::{InteractiveEvent, Prompt}; + let tpl = pdfcraft_xfa::fixtures::scripted_template() + .replace(r#"xfa.host.messageBox("Hello " + qty.rawValue);"#, "qty.rawValue = 5;") + .replace( + "", + "", + ) + .replace( + r#"var t = 0; var rows = xfa.resolveNodes("table.row[*]"); for (var i = 0; i < rows.length; i++) { t += (rows.item(i).amount.rawValue || 0); } t"#, + "qty.rawValue + 100", + ); + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("slow.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens"); + let grand = |s: &Session| s.get(id).unwrap().form.iter().find(|f| f.name == "grand").unwrap().value.clone(); + assert_eq!(grand(&s), ["102"]); + let p = s.start_javascript_target(id, "", Some("hello"), None).unwrap(); + let InteractiveEvent::Prompt(Prompt::Alert(m), reply) = next_event(&p) else { panic!("asks") }; + assert_eq!(m.text, "Recalculate?"); + // Longer than the calculations' 3 s budget. + std::thread::sleep(std::time::Duration::from_millis(3_500)); + reply.send(Some("4".into())).unwrap(); + let InteractiveEvent::Complete(out) = next_event(&p) else { panic!("finishes") }; + let o = s.finish_javascript(p, out).unwrap(); + assert_eq!(o.error, None, "{o:?}"); + assert_eq!(grand(&s), ["105"], "the calculation after the question ran"); +} + #[test] fn runaway_xfa_calculations_at_open_end_quickly_with_a_report() { // Nested loops in one frame stop at the loop limit; loops in nested calls (that limit is per diff --git a/crates/engine/src/xfa.rs b/crates/engine/src/xfa.rs index ee8c92cfdd..e5cd4a4141 100644 --- a/crates/engine/src/xfa.rs +++ b/crates/engine/src/xfa.rs @@ -67,6 +67,8 @@ struct Clock { #[cfg(not(target_arch = "wasm32"))] started: std::time::Instant, budget_ms: u64, + /// Time the scripts spent waiting for the user: not counted. + waited: std::time::Duration, } impl Clock { @@ -75,17 +77,23 @@ impl Clock { #[cfg(not(target_arch = "wasm32"))] started: std::time::Instant::now(), budget_ms, + waited: std::time::Duration::ZERO, } } + /// Leave `waited` out of the time spent: the time the scripts waited for the user isn't theirs. + fn extend(&mut self, waited: std::time::Duration) { + self.waited = self.waited.saturating_add(waited); + } + fn spent(&self) -> bool { #[cfg(not(target_arch = "wasm32"))] { - self.started.elapsed() >= std::time::Duration::from_millis(self.budget_ms) + self.started.elapsed().saturating_sub(self.waited) >= std::time::Duration::from_millis(self.budget_ms) } #[cfg(target_arch = "wasm32")] { - let _ = self.budget_ms; + let _ = (self.budget_ms, self.waited); false } } @@ -135,6 +143,28 @@ pub(crate) struct XfaRun<'a> { /// start and each script's own): 1, unless the session was given another /// ([`crate::Session::with_xfa_time_scale`]). pub time_scale: u32, + /// The answers to the event's message boxes. + pub answers: XfaAnswers, +} + +/// The answers to one event's message boxes (`xfa.host.messageBox`, `$host.messageBox`, +/// `app.alert`): its click script and the calculations after it take them in order, each +/// script starting after the ones the scripts before it took. Past them, a message box asks the +/// user when `prompts` is set (an app's button click, run on a worker: +/// [`crate::Session::start_javascript_target`]), and otherwise gets its buttons' safe default. +#[derive(Clone, Debug, Default)] +pub(crate) struct XfaAnswers { + /// The answers, in order (`None`: closed without picking a button). + pub given: Vec>, + /// Message boxes the event's scripts have shown so far. + pub used: usize, + /// Where the scripts' questions go, for the viewer to ask. + #[cfg(not(target_arch = "wasm32"))] + pub prompts: Option>, + /// Questions the event has asked, across the script sessions it uses + /// ([`XfaSession::with_prompts`]). + #[cfg(not(target_arch = "wasm32"))] + pub asked: Arc, } /// The script engine's copies of a form's property trees, by the address of the tree each was @@ -546,7 +576,17 @@ impl<'a, 'b> Runner<'a, 'b> { fn session(&mut self) -> &mut XfaSession { let doc_info = XfaDoc { file_name: String::new(), page: 0, page_count: self.run.page_count, highlight: self.run.highlight }; let scale = self.run.time_scale; - self.session.get_or_insert_with(|| XfaSession::new(doc_info).with_time_scale(scale)) + #[cfg(not(target_arch = "wasm32"))] + let (prompts, asked) = (self.run.answers.prompts.clone(), Arc::clone(&self.run.answers.asked)); + self.session.get_or_insert_with(|| { + let session = XfaSession::new(doc_info).with_time_scale(scale); + #[cfg(not(target_arch = "wasm32"))] + let session = match prompts { + Some(p) => session.with_prompts(p, asked), + None => session, + }; + session + }) } /// Give the object at `som` the value `text` in the data and in the live form (refreshed @@ -986,7 +1026,14 @@ impl<'a, 'b> Runner<'a, 'b> { self.runs += 1; #[cfg(test)] self.check_live(); - let event = XfaEvent { activity: ev.activity.clone(), target: ev.som.clone(), new_text: new_text.to_string(), prev_text: String::new() }; + let used = self.run.answers.used; + let event = XfaEvent { + activity: ev.activity.clone(), + target: ev.som.clone(), + new_text: new_text.to_string(), + prev_text: String::new(), + answers: self.run.answers.given.get(used..).unwrap_or_default().to_vec(), + }; let tpl = self.tpl; let root = match &self.js_root { Some(r) => Arc::clone(r), @@ -1010,6 +1057,8 @@ impl<'a, 'b> Runner<'a, 'b> { // The thread is left to the runaway script: nothing more is sent to it. self.session = None; } + self.clock.extend(o.waited); + self.run.answers.used = used.saturating_add(o.messages); self.console(o.console.iter().cloned()); for n in &o.notes { self.error(format!("{} ({}): {n}", ev.som, ev.activity)); diff --git a/crates/engine/src/xfa_form.rs b/crates/engine/src/xfa_form.rs index be2ff1883e..d35f451647 100644 --- a/crates/engine/src/xfa_form.rs +++ b/crates/engine/src/xfa_form.rs @@ -243,6 +243,7 @@ pub(crate) fn xfa_after_data_change(doc: &mut pdfcraft_cos::Document, cx: &mut E ran_away: false, highlight, time_scale: cx.xfa_time_scale, + answers: Default::default(), }; let r = guard(|| xfa::on_data_replaced(doc, &tpl, calculate, &mut run)) .unwrap_or_else(|m| Err(format!("laying the form out again failed unexpectedly ({m})"))); diff --git a/crates/js/src/formcalc.rs b/crates/js/src/formcalc.rs index 7e171bc369..2e472841b0 100644 --- a/crates/js/src/formcalc.rs +++ b/crates/js/src/formcalc.rs @@ -138,6 +138,7 @@ pub(crate) fn run_formcalc_at( Err(e) => return XfaOutcome { error: Some(e), ..Default::default() }, }; let mut host = XHost::new(root, reuse, &event.target, doc); + host.answers = event.answers.clone(); #[cfg(target_arch = "wasm32")] let _ = deadline; let mut interp = Interp { @@ -186,6 +187,7 @@ pub(crate) fn run_formcalc_at( out.notes = host.notes(); out.effects = host.effects; out.console = host.console; + out.messages = host.messages; clip_result(&mut out); out } diff --git a/crates/js/src/formcalc/eval.rs b/crates/js/src/formcalc/eval.rs index c146fd65b9..6947ff4fd0 100644 --- a/crates/js/src/formcalc/eval.rs +++ b/crates/js/src/formcalc/eval.rs @@ -249,10 +249,17 @@ impl Interp<'_> { let title = Some(self.arg_str(args, 1)?).filter(|t| !t.is_empty()); let icon = MessageIcon::from_code(Some(self.arg_num(args, 2)?)); let buttons = MessageButtons::from_code(Some(self.arg_num(args, 3)?)); - self.h.push(XfaEffect::MessageBox(Message { text, title, icon, buttons })); - // Always OK for now: the viewer can't ask the user and run the script on - // with the answer yet (#4291). - Ok(Val::Num(1.0)) + // The button picked: 1 OK, 2 Cancel, 3 No, 4 Yes. Time spent waiting for the + // user isn't the script's: its deadline moves on by it. + #[cfg(not(target_arch = "wasm32"))] + let asked = std::time::Instant::now(); + let reply = self.h.message_box(Message { text, title, icon, buttons })?; + #[cfg(not(target_arch = "wasm32"))] + if crate::interaction::has_host() { + let waited = asked.elapsed(); + self.deadline = self.deadline.and_then(|d| d.checked_add(waited)); + } + Ok(Val::Num(f64::from(reply))) } "resetdata" => { let list = self.arg_str(args, 0)?; diff --git a/crates/js/src/globals.rs b/crates/js/src/globals.rs index ef7b95c8c7..93b6e0bdef 100644 --- a/crates/js/src/globals.rs +++ b/crates/js/src/globals.rs @@ -75,33 +75,18 @@ pub(crate) fn message_box_message(args: &[JsValue], ctx: &mut Context) -> JsResu } /// `app.alert(cMsg, nIcon, nType, cTitle)`: records the message with its title, icon and buttons, -/// given in that order or as one object with those keys, and returns 1 (the OK button). +/// given in that order or as one object with those keys, and returns the button picked (1 OK, +/// 2 Cancel, 3 No, 4 Yes). Where nobody can be asked (the web build, a script run outside a +/// document's session), that is the buttons' safe default, as when the dialog is closed. fn alert(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult { let m = alert_message(args, ctx)?; host(ctx)?.borrow_mut().alert(m.clone()); if !crate::interaction::has_host() { - return Ok(JsValue::from(1)); + return Ok(JsValue::from(i32::from(m.buttons.safe_default()))); } let answer = crate::interaction::ask(crate::interaction::Prompt::Alert(m.clone()))?; - let fallback = match m.buttons { - MessageButtons::Ok => "1", - MessageButtons::YesNo => "3", - _ => "2", - }; - let answer = answer.as_deref().unwrap_or(fallback); - let accepted = match m.buttons { - MessageButtons::Ok => ["1"].as_slice(), - MessageButtons::OkCancel => ["1", "2"].as_slice(), - MessageButtons::YesNo => ["3", "4"].as_slice(), - MessageButtons::YesNoCancel => ["2", "3", "4"].as_slice(), - }; - if answer == "1" && !accepted.contains(&"1") { - return Ok(JsValue::from(2)); - } - if !accepted.contains(&answer) { - return Err(error("invalid alert response")); - } - Ok(JsValue::from(answer.parse::().unwrap_or(2))) + let reply = m.buttons.reply(answer.as_deref()).ok_or_else(|| error("invalid alert response"))?; + Ok(JsValue::from(i32::from(reply))) } /// `app.beep()`: queues a request to beep. diff --git a/crates/js/src/interaction.rs b/crates/js/src/interaction.rs index 525acf930a..4662533fdc 100644 --- a/crates/js/src/interaction.rs +++ b/crates/js/src/interaction.rs @@ -21,6 +21,8 @@ pub enum InteractiveEvent { Prompt(Prompt, Sender>), Complete(Outcome), } +/// Most prompts one script invocation (an AcroForm script, an XFA event) shows the user. +pub const MAX_PROMPTS: usize = 32; thread_local! { static HOST:RefCell,usize)>>=const {RefCell::new(None)}; } /// Tell alert/menu helpers whether this worker has an interactive or deterministic reply channel. pub(crate) fn has_host() -> bool { @@ -36,7 +38,7 @@ pub(crate) fn ask(prompt: Prompt) -> JsResult> { let sender = HOST.with(|h| { let mut h = h.borrow_mut(); let Some((tx, n)) = h.as_mut() else { return Ok(None) }; - if *n >= 32 { + if *n >= MAX_PROMPTS { return Err(error("too many interactive prompts")); } *n += 1; diff --git a/crates/js/src/model.rs b/crates/js/src/model.rs index b162007420..82ec4f1d5a 100644 --- a/crates/js/src/model.rs +++ b/crates/js/src/model.rs @@ -262,6 +262,41 @@ impl MessageButtons { MessageButtons::YesNoCancel => "yes_no_cancel", } } + + /// What a script receives when nobody picks a button (closing the dialog, no answer given): + /// OK (1) when that is the only button, No (3) for Yes/No, otherwise Cancel (2). + pub fn safe_default(self) -> u8 { + match self { + MessageButtons::Ok => 1, + MessageButtons::YesNo => 3, + MessageButtons::OkCancel | MessageButtons::YesNoCancel => 2, + } + } + + /// The number a script receives for `answer`, the button picked as the references number + /// them (1 OK, 2 Cancel, 3 No, 4 Yes): no answer is [`MessageButtons::safe_default`], and OK + /// where these buttons have none is Cancel. `None`: an answer these buttons can't give. + pub fn reply(self, answer: Option<&str>) -> Option { + let Some(answer) = answer else { return Some(self.safe_default()) }; + let n = match answer { + "1" => 1, + "2" => 2, + "3" => 3, + "4" => 4, + _ => return None, + }; + let accepted: &[u8] = match self { + MessageButtons::Ok => &[1], + MessageButtons::OkCancel => &[1, 2], + MessageButtons::YesNo => &[3, 4], + MessageButtons::YesNoCancel => &[2, 3, 4], + }; + match n { + 1 if !accepted.contains(&1) => Some(2), + n if accepted.contains(&n) => Some(n), + _ => None, + } + } } /// `code` as one of the numbers 0 to 3 the references define, when it is exactly one. diff --git a/crates/js/src/tests.rs b/crates/js/src/tests.rs index 1a41afeea8..fbb4a34775 100644 --- a/crates/js/src/tests.rs +++ b/crates/js/src/tests.rs @@ -493,9 +493,32 @@ fn app_alert_falls_back_on_bad_icon_and_button_numbers() { assert_eq!(m, Message::plain("Hi"), "{bad}"); } assert_eq!(alerted("'Hi', '2', '3'"), Message { icon: MessageIcon::Question, buttons: MessageButtons::YesNoCancel, ..Message::plain("Hi") }); - // Every call still answers OK (1) until answers are asked for (#4291). - let o = go("event.value = String(app.alert('Delete?', 2, 2));", &Event::field("Mouse Up", "agree", "")); - assert_eq!(o.value, "1"); + // Outside a document's session (and on the web build) nobody can be asked: each call gets + // its buttons' safe default, as a closed dialog does (#4291). + for (buttons, want) in [(0, "1"), (1, "2"), (2, "3"), (3, "2")] { + let o = go(&format!("event.value = String(app.alert('Delete?', 2, {buttons}));"), &Event::field("Mouse Up", "agree", "")); + assert_eq!(o.value, want, "{buttons}"); + } +} + +/// The number a script receives for each answer: the references' button numbers, checked +/// against the buttons shown, with no answer the safe default (#4291). +#[test] +fn message_replies_follow_the_buttons() { + use MessageButtons as B; + let cases = [ + (B::Ok, [Some(1), Some(1), None, None, None]), + (B::OkCancel, [Some(2), Some(1), Some(2), None, None]), + (B::YesNo, [Some(3), Some(2), None, Some(3), Some(4)]), + (B::YesNoCancel, [Some(2), Some(2), Some(2), Some(3), Some(4)]), + ]; + for (buttons, want) in cases { + let got = [None, Some("1"), Some("2"), Some("3"), Some("4")].map(|a| buttons.reply(a)); + assert_eq!(got, want, "{buttons:?}"); + for bad in ["0", "5", " 4", "04", "yes", ""] { + assert_eq!(buttons.reply(Some(bad)), None, "{buttons:?} {bad}"); + } + } } /// A title is cut to a message's length like the text, and both are charged to the run's byte @@ -1211,9 +1234,35 @@ mod xfa_model { assert_eq!(boxed("xfa.host.messageBox('Hi', null, 2.5, 'x')"), Message::plain("Hi")); let m = boxed("xfa.host.messageBox('Hi', new Array(100000).join('t'))"); assert!(m.title.as_deref().is_some_and(|t| t.chars().count() <= 4_097)); - // Answers are always OK for now (#4291). - let o = go("this.rawValue = xfa.host.messageBox('Delete?', 'T', 2, 2)", "form1[0].page1[0].qty[0]", "click"); - assert!(o.effects.iter().any(|e| matches!(e, XfaEffect::SetValue { value, .. } if value == "1")), "{:?}", o.effects); + } + + /// Run the JavaScript `script` as the go button's click, with `answers` to its message boxes. + fn answered(script: &str, answers: &[Option<&str>]) -> XfaOutcome { + let ev = XfaEvent { + activity: "click".into(), + target: "form1[0].page1[0].go[0]".into(), + answers: answers.iter().map(|a| a.map(String::from)).collect(), + ..Default::default() + }; + run_xfa(script, &ev, &XfaDoc::default(), &form(), Limits::default()) + } + + /// `xfa.host.messageBox` and `app.alert` in an XFA script return the button picked, from the + /// event's answers in order (#4291), so a script can branch on No and Cancel; past the + /// answers, where nobody can be asked, each gets its buttons' safe default. + #[test] + fn message_box_returns_the_answer_given() { + let script = "var r = [xfa.host.messageBox('Clear?', 'T', 2, 2), app.alert('Sure?', 2, 3), xfa.host.messageBox('Saved')]; r.join(',')"; + let o = answered(script, &[Some("4"), Some("2"), None]); + assert_eq!((o.result.as_deref(), o.error.as_deref(), o.messages), (Some("4,2,1"), None, 3), "{o:?}"); + let o = answered(script, &[Some("3"), Some("4")]); + assert_eq!(o.result.as_deref(), Some("3,4,1"), "{o:?}"); + // No answers: the safe defaults (No; Cancel; OK). + let o = answered(script, &[]); + assert_eq!(o.result.as_deref(), Some("3,2,1"), "{o:?}"); + // An answer the buttons can't give fails the script, naming it. + let o = answered("xfa.host.messageBox('Clear?', 'T', 2, 2)", &[Some("2")]); + assert!(o.error.as_deref().is_some_and(|e| e.contains("message box 1 (2)") && e.contains("yes_no")), "{o:?}"); } /// `app.alert` in an XFA form's script reads its own order (`cMsg, nIcon, nType, cTitle`) @@ -2030,6 +2079,35 @@ $host.gotoURL("https://example.org")"#, assert!(matches!(o.effects.as_slice(), [XfaEffect::MessageBox(m)] if m.title.as_deref().is_some_and(|t| t.chars().count() <= 4_097))); } + /// FormCalc's `$host.messageBox` returns the button picked, from the event's answers in + /// order, as the JavaScript one does (#4291). + #[test] + fn formcalc_message_box_returns_the_answer_given() { + let run = |answers: &[Option<&str>]| { + let ev = XfaEvent { + activity: "click".into(), + target: "form1[0].page1[0].go[0]".into(), + answers: answers.iter().map(|a| a.map(String::from)).collect(), + ..Default::default() + }; + run_formcalc( + "Concat($host.messageBox(\"Clear?\", \"T\", 2, 3), \",\", $host.messageBox(\"Sure?\", \"\", 2, 1))", + &ev, + &XfaDoc::default(), + &form(), + Limits::default(), + ) + }; + let o = run(&[Some("3"), Some("1")]); + assert_eq!(o.result.as_deref(), Some("3,1"), "{o:?}"); + let o = run(&[Some("4")]); + assert_eq!(o.result.as_deref(), Some("4,2"), "{o:?}"); + let o = run(&[None, None]); + assert_eq!(o.result.as_deref(), Some("2,2"), "{o:?}"); + let o = run(&[Some("9")]); + assert!(o.error.as_deref().is_some_and(|e| e.contains("message box 1 (9)")), "{o:?}"); + } + fn run_hostile_formcalc(script: &str) -> XfaOutcome { let ev = XfaEvent { activity: "calculate".into(), target: "form1[0].page1[0].total[0]".into(), ..Default::default() }; let doc = XfaDoc::default(); @@ -2098,6 +2176,44 @@ mod session { assert_eq!(o.result.as_deref(), Some("4:hidden"), "{o:?}"); } + /// A session that can ask passes each message box's question on and gives the script the + /// answer, in JavaScript and FormCalc alike (#4291). The user's time isn't the script's: one + /// answered after its time limit has passed still finishes, and says how long it waited. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_session_that_can_ask_waits_for_the_answer_with_its_clock_stopped() { + use crate::interaction::{InteractiveEvent, Prompt}; + let (tx, rx) = std::sync::mpsc::channel(); + let answerer = std::thread::spawn(move || { + let mut asked = Vec::new(); + for answer in ["4", "3", "2"] { + let Ok(InteractiveEvent::Prompt(Prompt::Alert(m), reply)) = rx.recv() else { break }; + asked.push(m.text); + // Longer than the scripts' time limit below. + std::thread::sleep(std::time::Duration::from_millis(400)); + let _ = reply.send(Some(answer.to_string())); + } + asked + }); + let mut s = XfaSession::new(XfaDoc::default()).with_prompts(tx, Default::default()); + let mut js = script("xfa.host.messageBox('Clear?', 'T', 2, 2) + ',' + app.alert('Sure?', 2, 2)", false, "form1[0].page1[0].go[0]", "click"); + js.timeout = std::time::Duration::from_millis(300); + let o = s.run(js); + assert_eq!((o.result.as_deref(), o.error.as_deref(), o.abandoned), (Some("4,3"), None, false), "{o:?}"); + assert!(o.waited >= std::time::Duration::from_millis(800), "{:?}", o.waited); + // FormCalc keeps its own deadline, read as it works: it works on after the answer. + let mut fc = script( + "var r = $host.messageBox(\"Save?\", \"\", 2, 3)\nvar i = 0\nwhile (i < 20000) do i = i + 1 endwhile\nr", + true, + "form1[0].page1[0].go[0]", + "click", + ); + fc.timeout = std::time::Duration::from_millis(300); + assert_eq!(s.run(fc).result.as_deref(), Some("2")); + drop(s); + assert_eq!(answerer.join().unwrap_or_default(), ["Clear?", "Sure?", "Save?"]); + } + /// JavaScript and FormCalc scripts run in turn in one session, each on the form the caller /// sends: nothing an earlier script changed or defined leaks into the next, a failing script /// doesn't end the session, and hundreds of scripts run on its one thread. diff --git a/crates/js/src/xfa/globals.rs b/crates/js/src/xfa/globals.rs index de57d7fd49..fc22923476 100644 --- a/crates/js/src/xfa/globals.rs +++ b/crates/js/src/xfa/globals.rs @@ -41,23 +41,25 @@ fn set_runtime_highlight(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> Js Ok(JsValue::undefined()) } -/// `xfa.host.messageBox(message, title, icon, buttons)`: records the message with its title, -/// icon and buttons, its text and title cut to [`MAX_LINE`] characters, and returns 1. +/// Shows message box `m` and returns the button picked ([`XHost::message_box`]). +fn show(ctx: &mut Context, m: crate::Message) -> JsResult { + let reply = host(ctx)?.borrow_mut().message_box(m).map_err(super::error)?; + Ok(JsValue::from(f64::from(reply))) +} + +/// `xfa.host.messageBox(message, title, icon, buttons)`: shows the message with its title, +/// icon and buttons, its text and title cut to [`MAX_LINE`] characters, and returns the button +/// picked: 1 OK, 2 Cancel, 3 No, 4 Yes. fn message_box(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult { let m = crate::globals::message_box_message(args, ctx)?; - effect(ctx, XfaEffect::MessageBox(m))?; - // Always OK for now: the viewer can't ask the user and run the script on with the answer - // yet (#4291). - Ok(JsValue::from(1.0)) + show(ctx, m) } /// `app.alert(cMsg, nIcon, nType, cTitle)` in an XFA form's script: the same message box, its /// arguments in `app.alert`'s order (or one object with those keys). fn app_alert(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult { let m = crate::globals::alert_message(args, ctx)?; - effect(ctx, XfaEffect::MessageBox(m))?; - // The OK button, as for `messageBox` (#4291). - Ok(JsValue::from(1.0)) + show(ctx, m) } /// `xfa.host.resetData(names)`: asks to reset the comma-separated fields, or every field when diff --git a/crates/js/src/xfa/host.rs b/crates/js/src/xfa/host.rs index 902f5c7dc0..2f1fc3f7e4 100644 --- a/crates/js/src/xfa/host.rs +++ b/crates/js/src/xfa/host.rs @@ -110,6 +110,10 @@ pub(crate) struct XHost { /// Bytes of edges and corners copied when a script reached sides a border doesn't list, /// against [`super::props::MAX_COPIED`]. pub(super) copied: usize, + /// The answers to the script's message boxes ([`super::XfaEvent::answers`]). + pub(crate) answers: Vec>, + /// Message boxes shown so far ([`super::XfaOutcome::messages`]). + pub(crate) messages: usize, } impl XHost { @@ -153,9 +157,35 @@ impl XHost { prop_writes: super::props::PropWrites::new(), dropped_prop_writes: 0, copied: 0, + answers: Vec::new(), + messages: 0, } } + /// Show message box `m` and return the button picked: the next of the event's answers + /// (headless runs); past them, the user's answer when the viewer can ask (an app's button + /// click: the script waits on its thread, as an AcroForm script's `app.alert` does), or + /// else the buttons' safe default. `Err`: an answer `m`'s buttons can't give, or the + /// event's prompts are spent. + pub(crate) fn message_box(&mut self, m: Message) -> Result { + let at = self.messages; + self.messages = self.messages.saturating_add(1); + let invalid = |answer: Option<&str>| { + let given: String = answer.unwrap_or("null").chars().take(32).collect(); + format!("the answer to the script's message box {} ({given}) is not one of its buttons ({})", at.saturating_add(1), m.buttons.name()) + }; + let reply = match self.answers.get(at) { + Some(answer) => m.buttons.reply(answer.as_deref()).ok_or_else(|| invalid(answer.as_deref()))?, + None if crate::interaction::has_host() => { + let answer = crate::interaction::ask(crate::interaction::Prompt::Alert(m.clone())).map_err(|e| e.to_string())?; + m.buttons.reply(answer.as_deref()).ok_or_else(|| invalid(answer.as_deref()))? + } + None => m.buttons.safe_default(), + }; + self.push(XfaEffect::MessageBox(m)); + Ok(reply) + } + /// Room for `bytes` more bytes of kept text: charged when there is, a drop counted when not. pub(super) fn room(&mut self, bytes: usize) -> bool { match self.kept.checked_add(bytes).filter(|k| *k <= MAX_PAYLOAD) { diff --git a/crates/js/src/xfa/model.rs b/crates/js/src/xfa/model.rs index 212c2dd38c..984d029903 100644 --- a/crates/js/src/xfa/model.rs +++ b/crates/js/src/xfa/model.rs @@ -64,6 +64,12 @@ pub struct XfaEvent { pub target: String, pub new_text: String, pub prev_text: String, + /// Answers to the script's message boxes, in order: each `xfa.host.messageBox`, + /// `$host.messageBox` or `app.alert` takes the next (`None`: closed without picking a + /// button), checked against its buttons by [`crate::MessageButtons::reply`]. Past the end, + /// a message asks the user when the viewer can ask ([`crate::xfa_session::XfaSession::with_prompts`]), + /// and otherwise gets its buttons' safe default. + pub answers: Vec>, } /// About the document. @@ -141,6 +147,12 @@ pub struct XfaOutcome { /// The script ran past its time limit and was left running on its own thread (the engine /// can't interrupt it): the caller should run no more of this form's scripts. pub abandoned: bool, + /// How many message boxes the script showed: the answers it took from + /// [`XfaEvent::answers`], so the next script of the event starts after them. + pub messages: usize, + /// How long the script waited for the user to answer its message boxes: not counted + /// against its time limit, nor the event's. + pub waited: std::time::Duration, } /// Most nodes a snapshot may hold. diff --git a/crates/js/src/xfa/run.rs b/crates/js/src/xfa/run.rs index 6044c37c05..6eb98010f2 100644 --- a/crates/js/src/xfa/run.rs +++ b/crates/js/src/xfa/run.rs @@ -143,7 +143,8 @@ pub(crate) fn run_here( }; ctx.runtime_limits_mut().set_loop_iteration_limit(limits.loop_iterations); ctx.runtime_limits_mut().set_recursion_limit(limits.recursion); - let host_state = XHost::new(root, reuse, &event.target, doc); + let mut host_state = XHost::new(root, reuse, &event.target, doc); + host_state.answers = event.answers.clone(); let current = host_state.current; ctx.insert_data(RefCell::new(host_state)); let mut out = XfaOutcome::default(); @@ -174,6 +175,7 @@ pub(crate) fn run_here( out.notes = h.notes(); out.effects = h.effects; out.console = h.console; + out.messages = h.messages; } clip_result(&mut out); out diff --git a/crates/js/src/xfa_session.rs b/crates/js/src/xfa_session.rs index 88e0748625..2dce06bfbc 100644 --- a/crates/js/src/xfa_session.rs +++ b/crates/js/src/xfa_session.rs @@ -75,13 +75,22 @@ mod native { use std::time::{Duration, Instant}; use super::{Script, run_script}; + use crate::interaction::{InteractiveEvent, MAX_PROMPTS, Prompt}; use crate::xfa::{ENGINE_START_LIMIT, XfaDoc, XfaOutcome}; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Longest a script waits for the user to answer one message box, as an AcroForm script's + /// prompt waits; then it gets the buttons' safe default. + const PROMPT_LIMIT: Duration = Duration::from_secs(300); enum Reply { /// The thread is up. Ready, /// The engine is ready for the script just sent: its time starts now. Started, + /// The script asks the user (a message box) and waits for the answer. + Prompt(Prompt, Sender>), Outcome(Box), } @@ -99,11 +108,26 @@ mod native { dead: Option, /// How long the engine has to be ready for a script ([`ENGINE_START_LIMIT`] by default). start_limit: Duration, + /// Where the scripts' questions go, when the viewer can ask the user + /// ([`XfaSession::with_prompts`]), and how many the event has asked. + prompts: Option<(Sender, Arc)>, } impl XfaSession { pub fn new(doc: XfaDoc) -> XfaSession { - XfaSession { doc, worker: None, dead: None, start_limit: ENGINE_START_LIMIT } + XfaSession { doc, worker: None, dead: None, start_limit: ENGINE_START_LIMIT, prompts: None } + } + + /// Let the scripts' message boxes ask the user: each question goes to `prompts` with a + /// sender for the answer, and the script waits on its thread (at most [`PROMPT_LIMIT`] + /// for each), its time limit stopped meanwhile. `asked` counts the event's questions, + /// across every session the event uses (a script turning field highlighting on or off + /// starts a new one): past [`MAX_PROMPTS`] nobody is asked and each message box gets its + /// buttons' safe default, so a form can't keep the user answering. Without it a message + /// box takes the event's answers, then its buttons' safe default. + pub fn with_prompts(mut self, prompts: Sender, asked: Arc) -> XfaSession { + self.prompts = Some((prompts, asked)); + self } /// Multiply the time the engine has to be ready for a script by `factor` (a script's @@ -125,7 +149,26 @@ mod native { let (to, inbox) = channel::>(); let (reply, from) = channel::(); let doc = self.doc.clone(); + let asking = self.prompts.is_some(); let spawned = std::thread::Builder::new().name("pdfcraft-xfa-session".into()).stack_size(crate::SCRIPT_STACK).spawn(move || { + // The scripts' questions reach the session (which passes them on and stops + // the clock while the user answers) through the reply channel. The host is + // set once for the thread, so the prompt limit holds for the whole event. + if asking { + let (questions, asked) = channel::(); + let forward = reply.clone(); + let forwarder = std::thread::Builder::new().name("pdfcraft-xfa-prompts".into()).spawn(move || { + while let Ok(InteractiveEvent::Prompt(prompt, answer)) = asked.recv() { + if forward.send(Reply::Prompt(prompt, answer)).is_err() { + break; + } + } + }); + // Without the forwarder nobody would answer: the scripts don't ask. + if forwarder.is_ok() { + crate::interaction::set_host(Some(questions)); + } + } crate::xfa::warm_up(); // The caller is gone when a send fails: nothing to report then. let _ = reply.send(Reply::Ready); @@ -164,6 +207,7 @@ mod native { } let timeout = script.timeout; let start_limit = self.start_limit; + let prompts = self.prompts.clone(); let worker = match self.worker() { Ok(w) => w, Err(why) => return failed(why), @@ -176,18 +220,34 @@ mod native { // The engine's start, then the script's own time. let (mut running, mut limit) = (false, start_limit); let mut deadline = Instant::now().checked_add(limit); + let mut waited = Duration::ZERO; loop { let left = deadline.map_or(limit, |d| d.saturating_duration_since(Instant::now())); match worker.from.recv_timeout(left) { - Ok(Reply::Outcome(o)) => { + Ok(Reply::Outcome(mut o)) => { // A FormCalc script its own clock stopped reports as abandoned: the // session ends as it does when the wait runs out first. if o.abandoned { self.dead = o.error.clone(); self.worker = None; } + o.waited = waited; return *o; } + Ok(Reply::Prompt(prompt, answer)) => { + // The user's time isn't the script's: its clock stops until the answer. + let asked = Instant::now(); + let (give, given) = channel(); + let sent = prompts.as_ref().is_some_and(|(p, asked)| { + asked.fetch_add(1, Ordering::Relaxed) < MAX_PROMPTS && p.send(InteractiveEvent::Prompt(prompt, give)).is_ok() + }); + let reply = if sent { given.recv_timeout(PROMPT_LIMIT).ok().flatten() } else { None }; + // The script's own wait may have ended first: then it took the default. + let _ = answer.send(reply); + let paused = asked.elapsed(); + waited = waited.saturating_add(paused); + deadline = deadline.and_then(|d| d.checked_add(paused)); + } Ok(Reply::Started) => { // A second call changes nothing: the script's time has already begun. if !running { diff --git a/crates/ui-egui/src/script_dialog.rs b/crates/ui-egui/src/script_dialog.rs index 2249f7bfd7..73b4ccc0eb 100644 --- a/crates/ui-egui/src/script_dialog.rs +++ b/crates/ui-egui/src/script_dialog.rs @@ -87,6 +87,8 @@ impl PdfCraftApp { /// Receive worker prompts/results and invalidate stale or timed-out interactions before applying their edits. pub(crate) fn poll_script_dialog(&mut self, ctx: &egui::Context) { let Some(mut pending) = self.script_pending.take() else { return }; + // An XFA click reads no view state, so scrolling or zooming while it runs leaves it be. + let xfa = pending.run.is_xfa(); let current = (self.active_ids().is_some_and(|(_, id)| id == pending.run.id) || self.compare.as_ref().is_some_and(|c| { c.side_by_side @@ -94,12 +96,20 @@ impl PdfCraftApp { && self.active_ids().is_some_and(|(_, active)| active == c.old || active == c.new) })) && self.session.script_pending_current(&pending.run) - && self.views.iter().find(|v| v.id == pending.run.id).is_some_and(|v| v.zoom == pending.zoom && v.current == pending.page); + && (xfa || self.views.iter().find(|v| v.id == pending.run.id).is_some_and(|v| v.zoom == pending.zoom && v.current == pending.page)); if !current { self.session.discard_javascript(&pending.run); + // The user clicked an XFA button and saw nothing happen: say why. + if xfa { + self.notify("The document changed while the form's script ran; what it did was not kept"); + } return; } - if (pending.prompt.is_none() && pending.started.elapsed() > Duration::from_secs(10)) + // An XFA click is bounded by its own limits (the engine's start, the click's and the + // calculations' budgets, laying the form out again), which can add up past 10 s: this + // is only a backstop. + let limit = Duration::from_secs(if xfa { 60 } else { 10 }); + if (pending.prompt.is_none() && pending.started.elapsed() > limit) || (pending.prompt.is_some() && pending.started.elapsed() > Duration::from_secs(300)) { self.session.timeout_javascript(pending.run); diff --git a/crates/ui-egui/src/workflows/js_ui.rs b/crates/ui-egui/src/workflows/js_ui.rs index 1f3721c511..4c0052407a 100644 --- a/crates/ui-egui/src/workflows/js_ui.rs +++ b/crates/ui-egui/src/workflows/js_ui.rs @@ -227,11 +227,11 @@ impl PdfCraftApp { if !self.commit_form_typing() { return; } + // On a worker, so its questions can be asked: an XFA button's click too (#4291). #[cfg(not(target_arch = "wasm32"))] - if self.session.get(id).is_some_and(|d| d.info.xfa.is_none()) { - self.start_ui_script(id, script, Some(field), identity); - return; - } + self.start_ui_script(id, script, Some(field), identity); + // The web build has no worker: the script runs here, and nobody can be asked. + #[cfg(target_arch = "wasm32")] match self.session.run_javascript_target(id, script, Some(field), identity) { Ok(o) => { if let Some(i) = self.views.iter().position(|v| v.id == id) diff --git a/crates/ui-egui/tests/it/xfa.rs b/crates/ui-egui/tests/it/xfa.rs index 6b78041b75..66aa9ce550 100644 --- a/crates/ui-egui/tests/it/xfa.rs +++ b/crates/ui-egui/tests/it/xfa.rs @@ -139,10 +139,88 @@ fn xfa_buttons_run_their_scripts_in_the_app() { }; assert!(!names(&h).iter().any(|n| n == "amount_2")); click_field(&mut h, "addRow"); - assert!(names(&h).iter().any(|n| n == "amount_2"), "{:?}; script console: {:?}", names(&h), h.state().js_console.log); - // The message box shows as a notice. + until(&mut h, "the row is added", |h| names(h).iter().any(|n| n == "amount_2")); + // The message box shows in a dialog, as an AcroForm script's app.alert does, and OK closes it. click_field(&mut h, "hello"); - assert!(h.query_by_label_contains("Hello 2").is_some(), "script console: {:?}", h.state().js_console.log); + until(&mut h, "the message is shown", |h| h.query_by_label("Hello 2").is_some()); + h.get_by_label("OK").click(); + until(&mut h, "OK closes it", |h| h.query_by_label("Hello 2").is_none()); +} + +/// Run frames until `done`, for a script running on its worker (the app goes on drawing). +fn until(h: &mut Harness<'static, PdfCraftApp>, what: &str, done: impl Fn(&Harness<'static, PdfCraftApp>) -> bool) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(12); + while std::time::Instant::now() < deadline { + h.run_steps(1); + if done(h) { + return; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("{what}: timed out; script console: {:?}", h.state().js_console.log); +} + +/// An XFA button that asks Yes or No shows the question in a dialog while its script waits, and +/// branches on the button the user picks (#4291): nothing changes while it asks, and Escape +/// answers No. +#[test] +fn an_xfa_buttons_question_is_asked_and_its_answer_used() { + let tpl = pdfcraft_xfa::fixtures::scripted_template().replace( + r#"xfa.host.messageBox("Hello " + qty.rawValue);"#, + r#"qty.rawValue = xfa.host.messageBox("Clear the order?", "Order form", 2, 2) == 4 ? 0 : 7;"#, + ); + let mut h = open(pdfcraft_xfa::fixtures::shell(&tpl)); + crate::support::settle(&mut h); + let qty = |h: &Harness<'static, PdfCraftApp>| { + let s = h.state(); + let doc = s.session.get(s.views[0].id).unwrap(); + doc.form.iter().find(|f| f.name == "qty").and_then(|f| f.value.first().cloned()).unwrap_or_default() + }; + assert_eq!(qty(&h), "2"); + for (answer, before, want) in [("Yes", "2", "0"), ("No", "0", "7")] { + click_field(&mut h, "hello"); + until(&mut h, "the question is shown", |h| h.query_by_label("Clear the order?").is_some()); + assert!(h.query_by_label("Order form").is_some()); + assert_eq!(qty(&h), before, "nothing changes while it asks"); + h.get_by_label(answer).click(); + until(&mut h, answer, |h| qty(h) == want); + assert!(h.query_by_label("Clear the order?").is_none(), "{answer} closes it"); + } + let id = h.state().views[0].id; + h.state_mut() + .session + .apply(id, pdfcraft_engine::Edit::SetFieldValue { name: "qty".into(), value: pdfcraft_engine::FieldValue::Text("5".into()) }) + .unwrap(); + h.run_steps(2); + click_field(&mut h, "hello"); + until(&mut h, "the question is shown again", |h| h.query_by_label("Clear the order?").is_some()); + h.key_press(egui::Key::Escape); + until(&mut h, "Escape answers No", |h| qty(h) == "7"); + assert!(h.query_by_label("Clear the order?").is_none()); +} + +/// An XFA click reads no view state: zooming or moving to another page while it asks doesn't +/// drop it, as it drops an AcroForm script that read them. +#[test] +fn an_xfa_click_is_kept_when_the_view_changes_while_it_asks() { + let tpl = pdfcraft_xfa::fixtures::scripted_template().replace( + r#"xfa.host.messageBox("Hello " + qty.rawValue);"#, + r#"qty.rawValue = xfa.host.messageBox("Clear the order?", "Order form", 2, 2) == 4 ? 0 : 7;"#, + ); + let mut h = open(pdfcraft_xfa::fixtures::shell(&tpl)); + crate::support::settle(&mut h); + let qty = |h: &Harness<'static, PdfCraftApp>| { + let s = h.state(); + let doc = s.session.get(s.views[0].id).unwrap(); + doc.form.iter().find(|f| f.name == "qty").and_then(|f| f.value.first().cloned()).unwrap_or_default() + }; + click_field(&mut h, "hello"); + until(&mut h, "the question is shown", |h| h.query_by_label("Clear the order?").is_some()); + let zoom = h.state().views[0].zoom; + h.state_mut().views[0].zoom = zoom * 1.5; + h.run_steps(2); + h.get_by_label("Yes").click(); + until(&mut h, "the answer is used", |h| qty(h) == "0"); } /// Every way the focus moves (a click, Tab, Shift+Tab, Escape) runs the field it left's exit @@ -277,9 +355,10 @@ fn scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back() { h.get_by_label("Dismiss").click(); h.run_steps(2); assert!(h.state().views[0].notice_dismissed); - // The button's script runs away: a toast says the scripts are off and the bar is back. + // The button's script runs away (on its worker): a toast says the scripts are off and the + // bar is back. click_field(&mut h, "hello"); - assert!(h.state().session.get(id).unwrap().xfa_scripts_off(), "script console: {:?}", h.state().js_console.log); + until(&mut h, "the scripts are off", |h| h.state().session.get(id).unwrap().xfa_scripts_off()); assert!(says_scripts_are_off(&h.state().toast), "{:?}", h.state().toast); assert!(!h.state().views[0].notice_dismissed); h.state_mut().toast = None; diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 2f3cda2051..e6666fa9f3 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -5364,7 +5364,7 @@ status = "partial" commands = ["tools.js_console"] tools = ["js_run", "js_event"] evidence = ["crates/js/src/tests.rs::to_source_writes_plain_state_as_a_literal", "crates/js/src/tests.rs::to_source_refuses_cycles_functions_and_oversized_state", "crates/js/src/tests.rs::set_items_and_set_action_change_the_field", "crates/engine/src/document_actions_tests.rs::set_items_and_set_action_are_written_to_the_document", "crates/engine/src/document_actions_tests.rs::pointer_and_focus_triggers_run_the_widget_scripts", "crates/engine/src/document_actions_tests.rs::only_a_click_trigger_may_print", "crates/engine/src/document_actions_tests.rs::a_check_box_mouse_up_reads_the_value_its_click_stored", "crates/ui-egui/tests/it/field_triggers.rs::the_pointer_entering_and_leaving_a_widget_runs_its_scripts", "crates/ui-egui/tests/it/field_triggers.rs::a_check_box_mouse_up_script_sees_the_value_its_click_stored", "crates/automation/tests/it/timesheet_compat.rs::timesheet_keypad_geometry_icons_calculation_and_persistence", "crates/automation/tests/it/timesheet_compat.rs::popup_and_manual_response_resume_the_same_script_and_validate_choices", "crates/js/src/session.rs::document_realm_keeps_keypad_state_and_isolates_documents", "crates/js/src/tests.rs::calculate_scripts_read_fields_and_set_the_value", "crates/engine/src/tests.rs::form_javascript_validates_calculates_and_formats", "crates/automation/tests/it/automation.rs::javascript_through_tools", "crates/js/src/tests.rs::an_xfa_form_sees_the_xfa_plugin_installed", "crates/js/src/tests.rs::a_plain_form_sees_the_xfa_version_but_not_installed", "crates/engine/src/tests.rs::scripts_in_an_xfa_form_see_the_xfa_plugin_installed", "crates/js/src/tests.rs::scand_allows_separators_between_fields_but_nothing_before_or_after_them", "crates/js/src/tests.rs::app_alert_keeps_its_title_icon_and_buttons", "crates/js/src/tests.rs::app_alert_reads_the_object_form", "crates/js/src/tests.rs::app_alert_falls_back_on_bad_icon_and_button_numbers", "crates/js/src/tests.rs::app_alert_titles_are_clipped_and_charged", "crates/ui-egui/tests/it/javascript.rs::every_message_a_script_shows_takes_the_toast_in_turn", "crates/ui-egui/tests/it/forms.rs::a_form_button_opens_its_attached_instructions_in_a_new_tab", "crates/js/src/tests.rs::widget_rect_reads_and_writes_a_four_number_array", "crates/engine/src/tests.rs::javascript_field_rect_moves_first_widget_and_undoes"] -notes = "Document-scoped native Boa realms shared by button, console and field events; synchronous calculateNow in CO order; normal captions/icons; rect and appearance/tooltip writeback; effective page boxes; native explicit-button popup/response/alert continuation and viewer requests, including opening or saving attachments from form buttons. Headless js_run has deterministic ordered answers. A widget's Mouse Enter, Mouse Exit, Mouse Down, Focus and Blur JavaScript run in the app and through js_event (and form_focus for focus), and a check box's or radio button's Mouse Up runs after its click stored the new value (#247); field.setItems, field.setAction and a bounded Object.prototype.toSource (plain data only) are written back to the document (#269, ported from #344). Partial: web prompt UI, timers, annotation/layer APIs, non-normal button faces, widget-indexed Field access, and Will Close / Did Save / Did Print are not implemented. See docs/acroform-script-workflows.md for lifecycle, limits and validation scope." +notes = "Document-scoped native Boa realms shared by button, console and field events; synchronous calculateNow in CO order; normal captions/icons; rect and appearance/tooltip writeback; effective page boxes; native explicit-button popup/response/alert continuation and viewer requests, including opening or saving attachments from form buttons. Headless js_run has deterministic ordered answers. Where nobody can be asked (the web build, which has no worker), app.alert returns its buttons' safe default (OK alone 1, Yes/No 3, otherwise 2), as closing the dialog does, and app.response and app.popUpMenuEx return null (#4291). A widget's Mouse Enter, Mouse Exit, Mouse Down, Focus and Blur JavaScript run in the app and through js_event (and form_focus for focus), and a check box's or radio button's Mouse Up runs after its click stored the new value (#247); field.setItems, field.setAction and a bounded Object.prototype.toSource (plain data only) are written back to the document (#269, ported from #344). Partial: web prompt UI, timers, annotation/layer APIs, non-normal button faces, widget-indexed Field access, and Will Close / Did Save / Did Print are not implemented. See docs/acroform-script-workflows.md for lifecycle, limits and validation scope." [[feature]] id = "form.js-console" @@ -5447,8 +5447,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/tests.rs::rounded_corners_make_a_border_one_rounded_shape", "crates/xfa/src/tests.rs::a_rounded_box_cut_by_a_page_break_keeps_its_corners_on_each_page", "crates/xfa/src/tests.rs::rounded_boxes_are_written_as_curved_paths", "crates/xfa/src/tests.rs::a_flowed_subform_is_drawn_with_its_border_under_its_content", "crates/xfa/src/tests.rs::a_check_box_sits_where_its_margins_caption_and_alignment_put_it", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_takes_the_rest_of_the_field", "crates/xfa/src/tests.rs::a_radio_button_sits_where_a_check_box_would", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_is_measured_as_it_is_drawn", "crates/js/src/tests.rs::message_box_keeps_its_title_icon_and_buttons", "crates/js/src/tests.rs::app_alert_in_an_xfa_script_reads_app_alerts_arguments", "crates/engine/src/tests.rs::xfa_message_boxes_keep_their_title_icon_and_buttons", "crates/xfa/src/tests.rs::signature_fields_are_named_by_their_som_path", "crates/xfa/src/tests.rs::a_signature_on_a_laid_out_box_survives_a_new_layout", "crates/xfa/src/tests.rs::the_template_knows_its_floating_fields_and_sheet_roles", "crates/engine/src/tests.rs::text_shows_the_values_scripts_give_its_floating_fields", "crates/js/src/tests.rs::the_sheet_is_the_page_on_screen", "crates/xfa/src/tests.rs::embedded_text_shows_each_instances_data", "crates/xfa/src/tests.rs::an_embedded_sheet_number_counts_the_pages", "crates/engine/src/tests.rs::floating_fields_follow_their_data_whoever_writes_it", "crates/forms/src/af/tests.rs::xfa_date_fields_keep_and_show_what_their_pattern_does_not_read", "crates/automation/tests/it/automation.rs::xfa_date_fields_keep_typed_dates_as_another_viewer_does", "crates/xfa/src/tests.rs::relevant_and_presence_say_where_fields_and_draws_show", "crates/xfa/src/tests.rs::screen_only_and_print_only_objects_are_written_with_flags_and_layers", "crates/xfa/src/tests.rs::a_master_page_started_by_a_screen_only_subform_keeps_its_own_objects_everywhere", "crates/engine/src/tests.rs::xfa_screen_only_and_print_only_objects_show_and_print_where_the_form_says", "crates/xfa/src/tests.rs::links_in_screen_only_and_print_only_text_work_where_their_text_shows", "crates/engine/src/tests.rs::xfa_enter_and_exit_scripts_run_on_every_focus_change", "crates/engine/src/tests.rs::an_exit_the_fields_change_ran_does_not_run_twice", "crates/engine/src/tests.rs::a_radio_buttons_own_focus_scripts_run", "crates/automation/tests/it/automation.rs::xfa_focus_scripts_run_through_form_focus", "crates/ui-egui/tests/it/xfa.rs::xfa_enter_and_exit_scripts_run_whenever_the_focus_moves", "crates/engine/src/tests.rs::xfa_signing_scripts_run_before_and_after_signing", "crates/automation/tests/it/automation.rs::signing_an_xfa_box_runs_its_signing_scripts_through_tools", "crates/xfa/src/tests.rs::fields_that_must_be_filled_in_are_required", "crates/xfa/src/proto/tests.rs::fields_and_draws_take_size_border_fill_caption_and_font_from_a_style_sheet", "crates/xfa/src/proto/tests.rs::what_an_element_declares_overrides_what_it_inherits", "crates/xfa/src/proto/tests.rs::prototypes_inherit_from_prototypes", "crates/xfa/src/proto/tests.rs::prototype_loops_end_with_a_warning", "crates/xfa/src/proto/tests.rs::a_reference_to_nothing_or_another_document_is_left_as_it_is", "crates/xfa/src/proto/tests.rs::an_expansion_past_its_budget_leaves_the_template_unresolved_with_a_warning", "crates/xfa/src/proto/tests.rs::hostile_references_neither_panic_nor_run_away", "crates/xfa/src/tests.rs::a_caption_without_a_font_of_its_own_takes_its_fields", "crates/engine/src/tests.rs::xfa_initialize_scripts_that_hide_subforms_lay_the_form_out_once", "crates/engine/src/tests.rs::xfa_resets_in_a_row_reset_every_named_subform_and_nothing_else", "crates/js/src/tests.rs::hosts_given_the_same_form_reuse_its_flattened_copy_and_change_only_their_own", "crates/js/src/tests.rs::a_form_sent_again_does_not_carry_the_last_scripts_changes", "crates/xfa/src/tests.rs::corners_not_listed_follow_the_edge_pattern", "crates/js/src/xfa/props_tests.rs::unspecified_properties_read_as_the_spec_defaults", "crates/js/src/xfa/props_tests.rs::widget_border_and_validate_reads_throw_no_type_error", "crates/js/src/xfa/props_tests.rs::writes_are_read_back_in_the_run_and_have_no_effect", "crates/js/src/xfa/props_tests.rs::a_calculation_reads_its_override_script_and_message", "crates/js/src/xfa/props_tests.rs::a_fill_type_the_fill_does_not_have_throws_and_leaves_the_fill_as_it_was", "crates/xfa/src/props_tests.rs::a_calculation_is_kept_with_its_override_message_and_script", "crates/xfa/src/props_tests.rs::hostile_property_trees_are_cut_to_the_limits", "crates/engine/src/xfa.rs::a_click_script_reads_field_properties", "crates/engine/src/xfa.rs::snapshots_share_property_trees_across_runs_and_events"] -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. 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; a field or exclusion group that must be filled in, validate nullTest=\"error\", is Required, so field highlighting outlines it as another viewer does on a real form; a push button, which keeps no value, is not), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; usage rights the form carried (/Perms /UR3) are taken off with a note, as the layout voids them and a form with void usage rights opens with every field locked; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event, and property objects (XFA 3.3 ch. 3 p. 78, ch. 17), every property path the 367 inventoried forms read (the one known gap is value.text and value.exData, read by about 15 of them: a node's value stays its raw value, and changing what value returns is left to a follow-up with a full-corpus regression check): read as the template writes them, with the spec's defaults for what those forms read where it leaves them out (presence of border (hidden when the object has no border element, as readers read it), edge, corner and fill; an edge or corner past those the template lists, up to four (a border's fifth and later are out of reach, as the layout draws four), as the one drawn on that side (XFA 3.3 p. 38 says the last one listed is reused for the sides not listed; readers draw such a side from the edge or corner on the same side instead, two listed alternating, three reusing the second for the fourth, one serving every side, and reads follow the readers; with none listed, the defaults: thickness 0.5pt, solid, square cap, black, a corner's radius 0in, square join, not inverted, pp. 663, 687), made as a copy of it when a script reaches it so that a write changes only that side (copies have their own budget, apart from the script's writes); colours (a border fill white, a font fill, edges and corners black); font typeface, size and weight; para hAlign and vAlign; validate nullTest, scriptTest and formatTest; occur min, max and initial; a fill's type solid and a field's widget textEdit; margin insets; break before and after; bind ref; a comb's numberOfCells; a calculation's override, disabled where the template has no calculate element and error where it has one, pp. 641-642), other unspecified attributes reading as an empty value that compares as \"\" and never throws (further defaults are added as forms need them): border with its edges, corners and fill (colour, linear/radial/pattern/stipple/solid), font, para, margin, ui and its widget as oneOfChild (with the widget's own border and margin), validate with its message texts and picture, occur, break/breakBefore/breakAfter, assist with toolTip and speak, format with its picture, the value element's content type, caption, items, bind, desc, the object's extras, calculate with its script and message, and keep (intact, next, previous; intact defaults by container, pp. 762-763), with className, oneOfChild, children by name (desc.vMandatory, message.scriptTest) and by class (ui[\"#textEdit\"]), getElement(name, index), isPropertySpecified, getAttribute, setAttribute, rawValue (a desc's first text), a validate's script text, resolveNode(s), somExpression and nodes (length/item/namedItem) on them, SOM expressions from a node that run into its properties (resolveNode(\"ui.#textEdit\"), \"border.edge[1]\", \"extras.arrayGroup[*].groupName\", \"ui.*\"), getAttribute, getElement and isPropertySpecified on nodes, and a node's mandatory, validationMessage, formatMessage and mandatoryMessage read from its validate (a single unnamed message text serves every test, p. 782, and setting one overwrites it, as readers do; reading validate.message. where no such text exists raises a script error, as in readers), and fillColor, fontColor and borderColor from its border fill, font fill and edge colours (borderColor set colours all four edges); what a script writes to them is read back later in the same script but has no effect on the form yet. The caption (its value as text or rich text, read as its words, by name, class, resolveNode or oneOfChild, XFA 3.3 p. 643) and a field's items (each entry as the list or check button shows it, p. 758) are property objects too; a value content the element doesn't hold reads as null, and a fill type the fill doesn't have (its pattern when it is solid) raises an error the script can catch and leaves the fill as it was, as readers do; exData.loadXML and saveXML do nothing yet. PdfCraft's choice-list methods are not on main yet (addItem, clearItems and boundItem are missing, and selectedIndex reads give an object that takes anything); until they land, items reads follow the template. FormCalc reads none of these properties yet): initialize and calculate on open, exit, validate and calculate after a field changes, click for buttons (through js_run and the app), enter and exit each time a field gains or loses focus, changed or not (through form_focus and the app; a radio button runs its own; an exit its change already ran is not run again, and scripts that change nothing leave no edit; exit as measured on a synthetic form in another viewer, enter from the spec and not measured), preSign as signing a box begins, so what it changes (a date, a lock) and says shows before the signer confirms and is signed too, taken back if signing ends without a signature, and postSign once signed (in the app; through sign_document when run_form_scripts asks, with every field preSign changed listed), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed, and each script starting from a copy of one flattened form, shared until the form changes; resets in a row applied together), so hundreds of calculations, and a 1,300-script form's initialize scripts, run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. Opening lays the form out once, after its initialize and calculate scripts (which read the live form, not the pages), so a form whose initialize scripts hide many sections is initialized within the open budget and opens again as it was saved; a large form can still run out of that budget, and what it skips is reported. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: value.text and value.exData (a node's value is still its raw value, and value.#text on a draw resolves to null); property writes (border, colours, validate.nullTest, occur, toolTip) taking effect and being saved; node setAttribute, clone, createNode and nodes.append/insert/remove; property reads from FormCalc; a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; a radio group's own enter and exit scripts; the change event per keystroke; a postSign script that checks its signature through event.target.getField(...).signatureValidate() fails, as event.target isn't the document yet, and a preSign script's message is a notice, where another viewer asks for an answer before it goes on; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; text is measured at the exact standard-14 widths of the face it is drawn in (bold, italic and Times included), not in the template's own typefaces, and Acrobat fidelity is eyeballed on real forms, not measured (#60). xfa.host.messageBox keeps its title, icon and buttons, and app.alert in an XFA script reads its own argument order; every message box still answers OK (1) (#4291). Text that embeds a field (a floating field, XFA 3.3 p. 1222) shows the field's value from the data, so a value an initialize, click or calculate script gives it shows, and an event that changes one lays the form out again when it ends; xfa.layout.sheet (from 0) and sheetCount treat each page as a sheet, and an embedded sheet number or count shows as the page number or count does. A repeating row shows its own instance's value, a page area's field the value written under the area, and a typed value or a reset lays the text out again. Missing: floating fields set by layout:ready scripts (current date and time), as those scripts are not run yet, and fields inside an exclusion group (#6160)." +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/tests.rs::rounded_corners_make_a_border_one_rounded_shape", "crates/xfa/src/tests.rs::a_rounded_box_cut_by_a_page_break_keeps_its_corners_on_each_page", "crates/xfa/src/tests.rs::rounded_boxes_are_written_as_curved_paths", "crates/xfa/src/tests.rs::a_flowed_subform_is_drawn_with_its_border_under_its_content", "crates/xfa/src/tests.rs::a_check_box_sits_where_its_margins_caption_and_alignment_put_it", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_takes_the_rest_of_the_field", "crates/xfa/src/tests.rs::a_radio_button_sits_where_a_check_box_would", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_is_measured_as_it_is_drawn", "crates/js/src/tests.rs::message_box_keeps_its_title_icon_and_buttons", "crates/js/src/tests.rs::app_alert_in_an_xfa_script_reads_app_alerts_arguments", "crates/engine/src/tests.rs::xfa_message_boxes_keep_their_title_icon_and_buttons", "crates/js/src/tests.rs::message_box_returns_the_answer_given", "crates/engine/src/tests.rs::xfa_message_boxes_return_the_answers_given", "crates/engine/src/tests.rs::an_xfa_click_started_in_the_app_asks_and_waits_for_each_answer", "crates/engine/src/tests.rs::an_xfa_click_is_dropped_when_the_document_changes_while_it_asks", "crates/engine/src/tests.rs::an_xfa_click_asks_at_most_32_questions", "crates/engine/src/tests.rs::an_xfa_clicks_question_limit_holds_across_its_script_sessions", "crates/engine/src/tests.rs::a_dropped_xfa_click_that_ran_away_still_turns_the_scripts_off", "crates/ui-egui/tests/it/xfa.rs::an_xfa_click_is_kept_when_the_view_changes_while_it_asks", "crates/engine/src/tests.rs::waiting_for_an_answer_does_not_spend_the_events_time", "crates/js/src/tests.rs::a_session_that_can_ask_waits_for_the_answer_with_its_clock_stopped", "crates/automation/tests/it/automation.rs::js_run_answers_an_xfa_buttons_message_boxes", "crates/ui-egui/tests/it/xfa.rs::an_xfa_buttons_question_is_asked_and_its_answer_used", "crates/xfa/src/tests.rs::signature_fields_are_named_by_their_som_path", "crates/xfa/src/tests.rs::a_signature_on_a_laid_out_box_survives_a_new_layout", "crates/xfa/src/tests.rs::the_template_knows_its_floating_fields_and_sheet_roles", "crates/engine/src/tests.rs::text_shows_the_values_scripts_give_its_floating_fields", "crates/js/src/tests.rs::the_sheet_is_the_page_on_screen", "crates/xfa/src/tests.rs::embedded_text_shows_each_instances_data", "crates/xfa/src/tests.rs::an_embedded_sheet_number_counts_the_pages", "crates/engine/src/tests.rs::floating_fields_follow_their_data_whoever_writes_it", "crates/forms/src/af/tests.rs::xfa_date_fields_keep_and_show_what_their_pattern_does_not_read", "crates/automation/tests/it/automation.rs::xfa_date_fields_keep_typed_dates_as_another_viewer_does", "crates/xfa/src/tests.rs::relevant_and_presence_say_where_fields_and_draws_show", "crates/xfa/src/tests.rs::screen_only_and_print_only_objects_are_written_with_flags_and_layers", "crates/xfa/src/tests.rs::a_master_page_started_by_a_screen_only_subform_keeps_its_own_objects_everywhere", "crates/engine/src/tests.rs::xfa_screen_only_and_print_only_objects_show_and_print_where_the_form_says", "crates/xfa/src/tests.rs::links_in_screen_only_and_print_only_text_work_where_their_text_shows", "crates/engine/src/tests.rs::xfa_enter_and_exit_scripts_run_on_every_focus_change", "crates/engine/src/tests.rs::an_exit_the_fields_change_ran_does_not_run_twice", "crates/engine/src/tests.rs::a_radio_buttons_own_focus_scripts_run", "crates/automation/tests/it/automation.rs::xfa_focus_scripts_run_through_form_focus", "crates/ui-egui/tests/it/xfa.rs::xfa_enter_and_exit_scripts_run_whenever_the_focus_moves", "crates/engine/src/tests.rs::xfa_signing_scripts_run_before_and_after_signing", "crates/automation/tests/it/automation.rs::signing_an_xfa_box_runs_its_signing_scripts_through_tools", "crates/xfa/src/tests.rs::fields_that_must_be_filled_in_are_required", "crates/xfa/src/proto/tests.rs::fields_and_draws_take_size_border_fill_caption_and_font_from_a_style_sheet", "crates/xfa/src/proto/tests.rs::what_an_element_declares_overrides_what_it_inherits", "crates/xfa/src/proto/tests.rs::prototypes_inherit_from_prototypes", "crates/xfa/src/proto/tests.rs::prototype_loops_end_with_a_warning", "crates/xfa/src/proto/tests.rs::a_reference_to_nothing_or_another_document_is_left_as_it_is", "crates/xfa/src/proto/tests.rs::an_expansion_past_its_budget_leaves_the_template_unresolved_with_a_warning", "crates/xfa/src/proto/tests.rs::hostile_references_neither_panic_nor_run_away", "crates/xfa/src/tests.rs::a_caption_without_a_font_of_its_own_takes_its_fields", "crates/engine/src/tests.rs::xfa_initialize_scripts_that_hide_subforms_lay_the_form_out_once", "crates/engine/src/tests.rs::xfa_resets_in_a_row_reset_every_named_subform_and_nothing_else", "crates/js/src/tests.rs::hosts_given_the_same_form_reuse_its_flattened_copy_and_change_only_their_own", "crates/js/src/tests.rs::a_form_sent_again_does_not_carry_the_last_scripts_changes", "crates/xfa/src/tests.rs::corners_not_listed_follow_the_edge_pattern", "crates/js/src/xfa/props_tests.rs::unspecified_properties_read_as_the_spec_defaults", "crates/js/src/xfa/props_tests.rs::widget_border_and_validate_reads_throw_no_type_error", "crates/js/src/xfa/props_tests.rs::writes_are_read_back_in_the_run_and_have_no_effect", "crates/js/src/xfa/props_tests.rs::a_calculation_reads_its_override_script_and_message", "crates/js/src/xfa/props_tests.rs::a_fill_type_the_fill_does_not_have_throws_and_leaves_the_fill_as_it_was", "crates/xfa/src/props_tests.rs::a_calculation_is_kept_with_its_override_message_and_script", "crates/xfa/src/props_tests.rs::hostile_property_trees_are_cut_to_the_limits", "crates/engine/src/xfa.rs::a_click_script_reads_field_properties", "crates/engine/src/xfa.rs::snapshots_share_property_trees_across_runs_and_events"] +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. 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; a field or exclusion group that must be filled in, validate nullTest=\"error\", is Required, so field highlighting outlines it as another viewer does on a real form; a push button, which keeps no value, is not), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; usage rights the form carried (/Perms /UR3) are taken off with a note, as the layout voids them and a form with void usage rights opens with every field locked; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event, and property objects (XFA 3.3 ch. 3 p. 78, ch. 17), every property path the 367 inventoried forms read (the one known gap is value.text and value.exData, read by about 15 of them: a node's value stays its raw value, and changing what value returns is left to a follow-up with a full-corpus regression check): read as the template writes them, with the spec's defaults for what those forms read where it leaves them out (presence of border (hidden when the object has no border element, as readers read it), edge, corner and fill; an edge or corner past those the template lists, up to four (a border's fifth and later are out of reach, as the layout draws four), as the one drawn on that side (XFA 3.3 p. 38 says the last one listed is reused for the sides not listed; readers draw such a side from the edge or corner on the same side instead, two listed alternating, three reusing the second for the fourth, one serving every side, and reads follow the readers; with none listed, the defaults: thickness 0.5pt, solid, square cap, black, a corner's radius 0in, square join, not inverted, pp. 663, 687), made as a copy of it when a script reaches it so that a write changes only that side (copies have their own budget, apart from the script's writes); colours (a border fill white, a font fill, edges and corners black); font typeface, size and weight; para hAlign and vAlign; validate nullTest, scriptTest and formatTest; occur min, max and initial; a fill's type solid and a field's widget textEdit; margin insets; break before and after; bind ref; a comb's numberOfCells; a calculation's override, disabled where the template has no calculate element and error where it has one, pp. 641-642), other unspecified attributes reading as an empty value that compares as \"\" and never throws (further defaults are added as forms need them): border with its edges, corners and fill (colour, linear/radial/pattern/stipple/solid), font, para, margin, ui and its widget as oneOfChild (with the widget's own border and margin), validate with its message texts and picture, occur, break/breakBefore/breakAfter, assist with toolTip and speak, format with its picture, the value element's content type, caption, items, bind, desc, the object's extras, calculate with its script and message, and keep (intact, next, previous; intact defaults by container, pp. 762-763), with className, oneOfChild, children by name (desc.vMandatory, message.scriptTest) and by class (ui[\"#textEdit\"]), getElement(name, index), isPropertySpecified, getAttribute, setAttribute, rawValue (a desc's first text), a validate's script text, resolveNode(s), somExpression and nodes (length/item/namedItem) on them, SOM expressions from a node that run into its properties (resolveNode(\"ui.#textEdit\"), \"border.edge[1]\", \"extras.arrayGroup[*].groupName\", \"ui.*\"), getAttribute, getElement and isPropertySpecified on nodes, and a node's mandatory, validationMessage, formatMessage and mandatoryMessage read from its validate (a single unnamed message text serves every test, p. 782, and setting one overwrites it, as readers do; reading validate.message. where no such text exists raises a script error, as in readers), and fillColor, fontColor and borderColor from its border fill, font fill and edge colours (borderColor set colours all four edges); what a script writes to them is read back later in the same script but has no effect on the form yet. The caption (its value as text or rich text, read as its words, by name, class, resolveNode or oneOfChild, XFA 3.3 p. 643) and a field's items (each entry as the list or check button shows it, p. 758) are property objects too; a value content the element doesn't hold reads as null, and a fill type the fill doesn't have (its pattern when it is solid) raises an error the script can catch and leaves the fill as it was, as readers do; exData.loadXML and saveXML do nothing yet. PdfCraft's choice-list methods are not on main yet (addItem, clearItems and boundItem are missing, and selectedIndex reads give an object that takes anything); until they land, items reads follow the template. FormCalc reads none of these properties yet): initialize and calculate on open, exit, validate and calculate after a field changes, click for buttons (through js_run and the app), enter and exit each time a field gains or loses focus, changed or not (through form_focus and the app; a radio button runs its own; an exit its change already ran is not run again, and scripts that change nothing leave no edit; exit as measured on a synthetic form in another viewer, enter from the spec and not measured), preSign as signing a box begins, so what it changes (a date, a lock) and says shows before the signer confirms and is signed too, taken back if signing ends without a signature, and postSign once signed (in the app; through sign_document when run_form_scripts asks, with every field preSign changed listed), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed, and each script starting from a copy of one flattened form, shared until the form changes; resets in a row applied together), so hundreds of calculations, and a 1,300-script form's initialize scripts, run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. Opening lays the form out once, after its initialize and calculate scripts (which read the live form, not the pages), so a form whose initialize scripts hide many sections is initialized within the open budget and opens again as it was saved; a large form can still run out of that budget, and what it skips is reported. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: value.text and value.exData (a node's value is still its raw value, and value.#text on a draw resolves to null); property writes (border, colours, validate.nullTest, occur, toolTip) taking effect and being saved; node setAttribute, clone, createNode and nodes.append/insert/remove; property reads from FormCalc; a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; a radio group's own enter and exit scripts; the change event per keystroke; a postSign script that checks its signature through event.target.getField(...).signatureValidate() fails, as event.target isn't the document yet, and a preSign script's message is a notice, where another viewer asks for an answer before it goes on; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; text is measured at the exact standard-14 widths of the face it is drawn in (bold, italic and Times included), not in the template's own typefaces, and Acrobat fidelity is eyeballed on real forms, not measured (#60). xfa.host.messageBox keeps its title, icon and buttons, and app.alert in an XFA script reads its own argument order. Each returns the button picked (1 OK, 2 Cancel, 3 No, 4 Yes, #4291). A button clicked in the app runs on a worker, as an AcroForm button does (form.js-host): each message box of its click and the calculations after it shows in a dialog while the script waits, its time limits stopped, and the click is kept as one undo step once it ends (dropped if the document changed meanwhile); closing the dialog gives the buttons' safe default (OK alone 1, Yes/No 3, otherwise 2), and a click asks at most 32 times across all its scripts (past that within one script it fails, as an AcroForm script's prompts do; later scripts get the safe default); a click whose script runs away turns the form's scripts off even when the click is dropped. js_run takes the answers in order (every message box takes one), then the safe default. Missing: scripts that run on their own (open, calculate, validate, enter, exit, preSign) don't ask: their message boxes stay notices and get the safe default; the web build has no worker, so there nothing asks and every message box gets the safe default (a web version that can wait for an answer is left to a separate change). Text that embeds a field (a floating field, XFA 3.3 p. 1222) shows the field's value from the data, so a value an initialize, click or calculate script gives it shows, and an event that changes one lays the form out again when it ends; xfa.layout.sheet (from 0) and sheetCount treat each page as a sheet, and an embedded sheet number or count shows as the page number or count does. A repeating row shows its own instance's value, a page area's field the value written under the area, and a typed value or a reset lays the text out again. Missing: floating fields set by layout:ready scripts (current date and time), as those scripts are not run yet, and fields inside an exclusion group (#6160)." [[feature]] id = "form.xfa-formcalc" @@ -5459,8 +5459,8 @@ milestone = "M12" status = "partial" commands = ["file.open"] tools = ["doc_open", "form_fill", "js_run"] -evidence = ["crates/js/src/tests.rs::arithmetic_strings_and_comparisons_follow_formcalc_rules", "crates/js/src/tests.rs::built_in_functions_cover_the_common_set", "crates/js/src/tests.rs::control_flow_variables_and_functions_work", "crates/js/src/tests.rs::form_objects_resolve_assign_and_record_effects", "crates/js/src/tests.rs::hostile_formcalc_scripts_end_with_an_error_and_bounded_output", "crates/js/src/tests.rs::formcalc_values_results_and_errors_stay_bounded", "crates/js/src/tests.rs::a_two_digit_year_splits_its_century_at_30", "crates/engine/src/tests.rs::dynamic_xfa_forms_run_formcalc_scripts", "crates/engine/src/tests.rs::hostile_formcalc_scripts_cannot_hang_or_bloat_the_document", "crates/engine/src/tests.rs::a_formcalc_calculate_result_is_cut_before_it_is_saved", "crates/js/src/tests.rs::formcalc_message_box_keeps_its_title_icon_and_buttons"] -notes = "a native FormCalc interpreter (crates/js/src/formcalc.rs) over the same form table, effects and budgets as the XFA JavaScript model: expressions and FormCalc coercions, var, if/while/for/foreach/func, accessors ($, $host, $form, $record, $layout, $event, xfa., .., [n], [*], _name instance managers) and the arithmetic, logical, string, date/time, financial and unit built-ins. Bounded: steps and loop iterations, statement and expression nesting, operator/accessor chain length, strings (1 MiB; messages and thrown errors clipped to 4 KiB, field values and calculate results to 64 KiB, noted; copying and comparing long strings is charged to the step budget, so it ends on wasm, which has no clock), lists (each object once), clamped dates, the instance cap, and a deadline the script itself honours after the engine stops waiting. Missing: locale-aware pictures beyond simple number and date ones, Format/Parse time and text pictures, Get/Post/Put (refused), $template/$connectionSet, user-defined functions across scripts, a cap on a script's total memory (each string and list is capped, but many variables can each hold one), real Uuid() values (deterministic, from the step count) and the wall clock on wasm (Date() reads 1970-01-01 and Time() midnight there), and checking against Acrobat on real Designer forms beyond the fixtures. $host.messageBox keeps its title, icon and buttons; it answers OK (1) for now (#4291)." +evidence = ["crates/js/src/tests.rs::arithmetic_strings_and_comparisons_follow_formcalc_rules", "crates/js/src/tests.rs::built_in_functions_cover_the_common_set", "crates/js/src/tests.rs::control_flow_variables_and_functions_work", "crates/js/src/tests.rs::form_objects_resolve_assign_and_record_effects", "crates/js/src/tests.rs::hostile_formcalc_scripts_end_with_an_error_and_bounded_output", "crates/js/src/tests.rs::formcalc_values_results_and_errors_stay_bounded", "crates/js/src/tests.rs::a_two_digit_year_splits_its_century_at_30", "crates/engine/src/tests.rs::dynamic_xfa_forms_run_formcalc_scripts", "crates/engine/src/tests.rs::hostile_formcalc_scripts_cannot_hang_or_bloat_the_document", "crates/engine/src/tests.rs::a_formcalc_calculate_result_is_cut_before_it_is_saved", "crates/js/src/tests.rs::formcalc_message_box_keeps_its_title_icon_and_buttons", "crates/js/src/tests.rs::formcalc_message_box_returns_the_answer_given"] +notes = "a native FormCalc interpreter (crates/js/src/formcalc.rs) over the same form table, effects and budgets as the XFA JavaScript model: expressions and FormCalc coercions, var, if/while/for/foreach/func, accessors ($, $host, $form, $record, $layout, $event, xfa., .., [n], [*], _name instance managers) and the arithmetic, logical, string, date/time, financial and unit built-ins. Bounded: steps and loop iterations, statement and expression nesting, operator/accessor chain length, strings (1 MiB; messages and thrown errors clipped to 4 KiB, field values and calculate results to 64 KiB, noted; copying and comparing long strings is charged to the step budget, so it ends on wasm, which has no clock), lists (each object once), clamped dates, the instance cap, and a deadline the script itself honours after the engine stops waiting. Missing: locale-aware pictures beyond simple number and date ones, Format/Parse time and text pictures, Get/Post/Put (refused), $template/$connectionSet, user-defined functions across scripts, a cap on a script's total memory (each string and list is capped, but many variables can each hold one), real Uuid() values (deterministic, from the step count) and the wall clock on wasm (Date() reads 1970-01-01 and Time() midnight there), and checking against Acrobat on real Designer forms beyond the fixtures. $host.messageBox keeps its title, icon and buttons and returns the button picked, asked as JavaScript's is (form.xfa-dynamic, #4291)." [[feature]] id = "form.xfa-data" From a4fc3b16e7d18c54e5cc7ec1d4e98a46a9011b85 Mon Sep 17 00:00:00 2001 From: alehel Date: Wed, 11 Nov 2026 15:16:38 +0100 Subject: [PATCH 029/114] fix(js, engine, automation): review fixes for XFA message box answers (#4291) - A kept XFA click clears the document's runaway flag only when it ran away itself; a flag set by an overlapping click it makes stale stays for the next edit, which turns the scripts off. - FormCalc's $host.messageBox text and title are clipped before the viewer is asked, as the recorded message box is (JavaScript's already were). - js_run's description says an XFA button's responses take no answers. Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/tools.rs | 4 ++-- crates/engine/src/js.rs | 6 ++++-- crates/engine/src/tests.rs | 39 ++++++++++++++++++++++++++++++++++ crates/js/src/xfa/host.rs | 2 ++ 4 files changed, 47 insertions(+), 4 deletions(-) diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index b0998a86ca..d2caf7815f 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -1415,10 +1415,10 @@ pub fn tools() -> Vec { t("form_merge_data", "Merge data files into spreadsheet", "Collect the field values of form data files (FDF, XFDF) or filled-in PDF forms into one CSV file at path: a column per field name, a row per file. Returns the row and column counts.") .cmd("form.merge_data") .with(schema(json!({ "paths": { "type": "array", "items": { "type": "string" }, "minItems": 1 }, "path": { "type": "string" } }), &["paths", "path"])), - t("js_run", "Run JavaScript", "Run Acrobat JavaScript in the document, as the JavaScript console does (or as push button `field`'s Mouse Up script when field is given; on a laid-out XFA form, `field` runs that button's XFA click script instead, JavaScript or FormCalc, which can add and remove rows and show or hide subforms). The form object model is available: this/getField, event, app, util, console, display, color, and the document-level scripts (except the PDF container scripts when XFA layout is active; they remain available through js_document_scripts). Field changes and resetForm are applied as one undoable step; returns the script's and subsequent field scripts' alerts (each with its message, title, icon and buttons, in order; popups, responses and message boxes take the ordered answers, an XFA button's xfa.host.messageBox, $host.messageBox and app.alert included, each message box returning the button answered (1 OK, 2 Cancel, 3 No, 4 Yes); missing replies cancel input or give the message box's safe default: OK alone 1, Yes/No 3, otherwise 2), console output, requests (print, page, url, submit, attachment), error, and the errors of document-level scripts that failed (the rest still ran), plus warnings from applying the changes.") + t("js_run", "Run JavaScript", "Run Acrobat JavaScript in the document, as the JavaScript console does (or as push button `field`'s Mouse Up script when field is given; on a laid-out XFA form, `field` runs that button's XFA click script instead, JavaScript or FormCalc, which can add and remove rows and show or hide subforms). The form object model is available: this/getField, event, app, util, console, display, color, and the document-level scripts (except the PDF container scripts when XFA layout is active; they remain available through js_document_scripts). Field changes and resetForm are applied as one undoable step; returns the script's and subsequent field scripts' alerts (each with its message, title, icon and buttons, in order; popups, responses and message boxes take the ordered answers (on an XFA button only its message boxes do, xfa.host.messageBox, $host.messageBox and app.alert; its xfa.host.response and app.response return null and take none), each message box returning the button answered (1 OK, 2 Cancel, 3 No, 4 Yes); missing replies cancel input or give the message box's safe default: OK alone 1, Yes/No 3, otherwise 2), console output, requests (print, page, url, submit, attachment), error, and the errors of document-level scripts that failed (the rest still ran), plus warnings from applying the changes.") .cmd("tools.js_console") .with(schema( - json!({ "doc": doc(), "script": { "type": "string" }, "field": { "type": "string", "description": "Run as this button's Mouse Up event." }, "field_id": {"type":"integer","minimum":0,"maximum":281474976710655u64,"description":"Optional exact field identity from form_fields; requires matching field name and is scoped to this document."}, "answers": {"type":"array","maxItems":32,"items":{"type":["string","null"],"maxLength":4096},"description":"Ordered popup, response and message box answers (every message box takes one, OK-only ones too; \"1\" OK, \"2\" Cancel, \"3\" No, \"4\" Yes); strings are limited to 4096 UTF-8 bytes at runtime; null cancels a popup or response, and selects a message box's default (OK, Cancel or No, by button set)."} }), + json!({ "doc": doc(), "script": { "type": "string" }, "field": { "type": "string", "description": "Run as this button's Mouse Up event." }, "field_id": {"type":"integer","minimum":0,"maximum":281474976710655u64,"description":"Optional exact field identity from form_fields; requires matching field name and is scoped to this document."}, "answers": {"type":"array","maxItems":32,"items":{"type":["string","null"],"maxLength":4096},"description":"Ordered popup, response and message box answers (every message box takes one, OK-only ones too; an XFA button's responses take none; \"1\" OK, \"2\" Cancel, \"3\" No, \"4\" Yes); strings are limited to 4096 UTF-8 bytes at runtime; null cancels a popup or response, and selects a message box's default (OK, Cancel or No, by button set)."} }), &["doc", "script"], )), t( diff --git a/crates/engine/src/js.rs b/crates/engine/src/js.rs index 9fa96e100e..52b8dd7509 100644 --- a/crates/engine/src/js.rs +++ b/crates/engine/src/js.rs @@ -1791,9 +1791,11 @@ impl Session { } let ran = click.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); let Some((begun, checked)) = ran else { return Ok(Outcome { rc: true, ..Default::default() }) }; + let ran_away = begun.cx.xfa_ran_away; let ((), out) = self.with_own_js_output(p.id, |s| s.finish_edit(p.id, begun, checked).map(|_| ()))?; - // Kept, the click turned the scripts off itself (if they ran away): not again. - if let Some(d) = self.get(p.id) { + // Kept, a click that ran away turned the scripts off itself: not again. A flag another + // click set (one this commit makes stale) stays for the next edit. + if ran_away && let Some(d) = self.get(p.id) { d.xfa_ran_away.store(false, std::sync::atomic::Ordering::Relaxed); } return Ok(xfa_click_outcome(out)); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 18b815dfa8..9705ebabb6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -10077,6 +10077,45 @@ fn a_dropped_xfa_click_that_ran_away_still_turns_the_scripts_off() { assert!(s.take_js_output(id).errors.iter().any(|e| e.contains("scripts are off"))); } +/// Another click kept while a dropped one ran away leaves its signal for the next edit. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_click_kept_beside_one_that_ran_away_leaves_the_scripts_to_turn_off() { + use crate::js::InteractiveEvent; + let tpl = pdfcraft_xfa::fixtures::scripted_template().replace( + r#"xfa.host.messageBox("Hello " + qty.rawValue);"#, + "function f() { for (var j = 0; j < 99999; j++) {} } for (var k = 0; k < 5000; k++) f();", + ); + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("runaway.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens"); + let runaway = s.start_javascript_target(id, "", Some("hello"), None).unwrap(); + let kept = s.start_javascript_target(id, "", Some("addRow"), None).unwrap(); + let InteractiveEvent::Complete(ran) = next_event(&runaway) else { panic!("finishes") }; + let InteractiveEvent::Complete(out) = next_event(&kept) else { panic!("finishes") }; + assert_eq!(s.finish_javascript(kept, out).unwrap().error, None); + assert!(s.finish_javascript(runaway, ran).is_err(), "the document changed"); + s.apply(id, Edit::SetFieldValue { name: "price".into(), value: FieldValue::Text("7".into()) }).unwrap(); + assert!(s.get(id).unwrap().xfa_scripts_off(), "the next edit turns them off"); +} + +/// The viewer is asked with a FormCalc message clipped, as the message box kept is. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_formcalc_question_is_asked_clipped() { + use crate::js::{InteractiveEvent, Prompt}; + let tpl = pdfcraft_xfa::fixtures::scripted_template() + .replace(r#"$host.messageBox("FormCalc")"#, r#"var t = "x" while (Len(t) < 100000) do t = Concat(t, t) endwhile $host.messageBox(t, t)"#); + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("long.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens"); + let p = s.start_javascript_target(id, "", Some("legacy"), None).unwrap(); + let InteractiveEvent::Prompt(Prompt::Alert(m), reply) = next_event(&p) else { panic!("asks") }; + assert!(m.text.chars().count() <= 4_097, "{}", m.text.len()); + assert!(m.title.as_deref().is_some_and(|t| t.chars().count() <= 4_097)); + reply.send(None).unwrap(); + let InteractiveEvent::Complete(out) = next_event(&p) else { panic!("finishes") }; + assert_eq!(s.finish_javascript(p, out).unwrap().error, None); +} + /// The time a calculation waits for the user isn't the event's: the calculations after it still /// run, though the wait is longer than their whole budget. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/js/src/xfa/host.rs b/crates/js/src/xfa/host.rs index 2f1fc3f7e4..a0521f73a2 100644 --- a/crates/js/src/xfa/host.rs +++ b/crates/js/src/xfa/host.rs @@ -168,6 +168,8 @@ impl XHost { /// else the buttons' safe default. `Err`: an answer `m`'s buttons can't give, or the /// event's prompts are spent. pub(crate) fn message_box(&mut self, m: Message) -> Result { + // Clipped before the viewer is asked, as the effect is: the dialog shows no more than is kept. + let m = Message { text: clip(m.text), title: m.title.map(clip), ..m }; let at = self.messages; self.messages = self.messages.saturating_add(1); let invalid = |answer: Option<&str>| { From f42b8269b98e43527c03b831f4fa726c67932acb Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 15:25:24 +0100 Subject: [PATCH 030/114] form_merge_data: read the header as CSV so a quoted comma is not a second column Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 1 + crates/automation/Cargo.toml | 1 + crates/automation/src/a11y/form_tools.rs | 3 ++- crates/automation/tests/it/automation.rs | 24 ++++++++++++++++++++++++ 4 files changed, 28 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index b7596fa0f5..9be911f55c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4541,6 +4541,7 @@ version = "0.21.1" dependencies = [ "base64 0.23.1", "craft-cms", + "craft-csv", "craft-image-codecs", "craft-prc", "flate2", diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index eec9b172d9..f62fe67119 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -15,6 +15,7 @@ pdfcraft-render = { workspace = true } pdfcraft-organize = { workspace = true } pdfcraft-platform = { workspace = true } craft-prc = { workspace = true } +craft-csv = { workspace = true } pdfcraft-prc-render = { workspace = true } serde_json = { workspace = true } sha2 = "0.11" diff --git a/crates/automation/src/a11y/form_tools.rs b/crates/automation/src/a11y/form_tools.rs index 7ff433af63..76750e35fd 100644 --- a/crates/automation/src/a11y/form_tools.rs +++ b/crates/automation/src/a11y/form_tools.rs @@ -264,7 +264,8 @@ impl Automation { let csv = pdfcraft_engine::merge_data_files(&files).map_err(failed)?; let target = self.resolve(a.str("path")?, true)?; write_atomic(&target, csv.as_bytes())?; - let columns = csv.lines().next().map_or(0, |h| h.split(',').count()); + // The header is read as CSV: a name with a comma, a quote or a line break is one column. + let columns = craft_csv::records(&csv, ',', '"', 1, usize::MAX).first().map_or(0, Vec::len); Ok(json!({ "path": target.to_string_lossy(), "rows": files.len(), "columns": columns })) } diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 5141e02bc9..a9ff58d2a2 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -9651,6 +9651,30 @@ fn merging_form_data_into_a_spreadsheet() { assert_eq!(std::fs::read_to_string(dir.join("report.csv")).unwrap(), "City\nParis\nOslo\nOslo\n"); } +#[test] +fn merging_form_data_counts_a_quoted_header_as_one_column() { + let dir = workdir("merge-data-quoted-header"); + let mut a = auto(&dir); + let xfdf = |name: &str| { + format!( + r#"Checked"# + ) + }; + // A comma or a quote in a name makes it a quoted CSV cell, still one column. + for (file, name) in [("comma.xfdf", "Shipping, notes"), ("quote.xfdf", "Say "hi", ok"), ("plain.xfdf", "Shipping notes")] { + std::fs::write(dir.join(file), xfdf(name)).unwrap(); + let out = format!("{file}.csv"); + let r = ok(&mut a, "form_merge_data", json!({ "paths": [file], "path": out })); + assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(1), Some(1)), "{file}: {r}"); + } + // Two files with different names, one of them quoted: three columns in all. + std::fs::write(dir.join("a.xfdf"), xfdf("A, B")).unwrap(); + std::fs::write(dir.join("b.xfdf"), xfdf("C")).unwrap(); + std::fs::write(dir.join("c.xfdf"), xfdf("D")).unwrap(); + let r = ok(&mut a, "form_merge_data", json!({ "paths": ["a.xfdf", "b.xfdf", "c.xfdf"], "path": "three.csv" })); + assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(3), Some(3)), "{r}"); +} + #[test] fn field_actions_through_tools() { let dir = workdir("field-actions"); From fabfade4cdbba55b4c6f71cade15d3ddc02d1bbf Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 16:39:39 +0100 Subject: [PATCH 031/114] form_merge_data: no columns for files without fields; test names with line break and tab Co-Authored-By: Claude Sonnet 5.5 --- crates/automation/src/a11y/form_tools.rs | 3 ++- crates/automation/tests/it/automation.rs | 13 ++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/automation/src/a11y/form_tools.rs b/crates/automation/src/a11y/form_tools.rs index 76750e35fd..ede13d7b5d 100644 --- a/crates/automation/src/a11y/form_tools.rs +++ b/crates/automation/src/a11y/form_tools.rs @@ -265,7 +265,8 @@ impl Automation { let target = self.resolve(a.str("path")?, true)?; write_atomic(&target, csv.as_bytes())?; // The header is read as CSV: a name with a comma, a quote or a line break is one column. - let columns = craft_csv::records(&csv, ',', '"', 1, usize::MAX).first().map_or(0, Vec::len); + // Files without fields leave an empty header line: no columns. + let columns = if csv.starts_with('\n') { 0 } else { craft_csv::records(&csv, ',', '"', 1, usize::MAX).first().map_or(0, Vec::len) }; Ok(json!({ "path": target.to_string_lossy(), "rows": files.len(), "columns": columns })) } diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index a9ff58d2a2..c3f4e2b75e 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -9661,12 +9661,23 @@ fn merging_form_data_counts_a_quoted_header_as_one_column() { ) }; // A comma or a quote in a name makes it a quoted CSV cell, still one column. - for (file, name) in [("comma.xfdf", "Shipping, notes"), ("quote.xfdf", "Say "hi", ok"), ("plain.xfdf", "Shipping notes")] { + for (file, name) in [ + ("comma.xfdf", "Shipping, notes"), + ("quote.xfdf", "Say "hi", ok"), + ("plain.xfdf", "Shipping notes"), + ("lf.xfdf", "a b"), + ("tab.xfdf", "a b"), + ] { std::fs::write(dir.join(file), xfdf(name)).unwrap(); let out = format!("{file}.csv"); let r = ok(&mut a, "form_merge_data", json!({ "paths": [file], "path": out })); assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(1), Some(1)), "{file}: {r}"); } + // Files without fields: no column. + std::fs::write(dir.join("empty.xfdf"), r#""#) + .unwrap(); + let r = ok(&mut a, "form_merge_data", json!({ "paths": ["empty.xfdf"], "path": "empty.csv" })); + assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(1), Some(0)), "{r}"); // Two files with different names, one of them quoted: three columns in all. std::fs::write(dir.join("a.xfdf"), xfdf("A, B")).unwrap(); std::fs::write(dir.join("b.xfdf"), xfdf("C")).unwrap(); From bedafd5af28192e504ef81ce183991a48edb7e0c Mon Sep 17 00:00:00 2001 From: gmrmad1 Date: Sun, 15 Nov 2026 15:36:01 +0530 Subject: [PATCH 032/114] fix(ui): name a page's render warnings in a notice bar (#4340) --- crates/ui-egui/src/canvas.rs | 9 +++++- crates/ui-egui/src/canvas/bars.rs | 46 ++++++++++++++++++++++++++++++ crates/ui-egui/src/canvas/cache.rs | 16 +++++++++++ crates/ui-egui/src/canvas/tests.rs | 32 +++++++++++++++++++++ 4 files changed, 102 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index b835dd652c..37452b046c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -4,7 +4,7 @@ //! Page images come from the engine's render pool as whole-page rasters at the current zoom; //! stale rasters are shown stretched until the sharp one arrives (tiling comes in M3.3). -use std::collections::{BTreeSet, HashMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::ops::Range; use std::sync::Arc; @@ -558,6 +558,11 @@ pub struct DocView { cut_pages: std::collections::BTreeSet, /// Cut pages whose notice the reader dismissed: a page cut later shows it again. cut_notice_dismissed: std::collections::BTreeSet, + /// Pages with a render warning other than content truncation (#4340), by kind: the picture + /// may be missing a colour or an image, or a Type 3 font's spacing may be approximate. + warned_pages: BTreeMap>, + /// Warned pages whose notice the reader dismissed: a page warning later shows it again. + warn_notice_dismissed: std::collections::BTreeSet, /// When each still-missing page was first shown, to flag unusually slow renders. waiting_since: HashMap, thumbs: HashMap, @@ -1060,6 +1065,8 @@ impl DocView { errors: HashMap::new(), cut_pages: Default::default(), cut_notice_dismissed: Default::default(), + warned_pages: Default::default(), + warn_notice_dismissed: Default::default(), waiting_since: HashMap::new(), thumbs: HashMap::new(), thumb_demand: HashMap::new(), diff --git a/crates/ui-egui/src/canvas/bars.rs b/crates/ui-egui/src/canvas/bars.rs index 85807e28fe..0c0d03605a 100644 --- a/crates/ui-egui/src/canvas/bars.rs +++ b/crates/ui-egui/src/canvas/bars.rs @@ -131,6 +131,11 @@ pub(super) fn notices( if view.cut_pages.iter().any(|p| !view.cut_notice_dismissed.contains(p)) { cut_pages_bar(view, ui, t); } + // A page with any other render warning is named too (#4340), so a fallback colour or a + // missing image isn't mistaken for the page's real appearance. + if view.warned_pages.keys().any(|p| !view.warn_notice_dismissed.contains(p)) { + warned_pages_bar(view, ui, t); + } // A signature just placed with Fill & Sign is a comment others can move (#2149): offer to // lock it into the page now. `lock_offer` is false for a digitally signed document. if lock_offer && !view.lock_offer_dismissed { @@ -297,6 +302,47 @@ fn cut_pages_bar(view: &mut DocView, ui: &mut egui::Ui, t: &Tokens) { } } +/// The bar naming pages with a render warning other than content truncation (#4340): a colour +/// painted in a fallback colour, a malformed indexed image, or a Type 3 font spaced by its own +/// procedures. Dismissing it covers the pages warned so far; a page warned later shows it again. +fn warned_pages_bar(view: &mut DocView, ui: &mut egui::Ui, t: &Tokens) { + let Some((&first, kinds)) = view.warned_pages.iter().find(|(p, _)| !view.warn_notice_dismissed.contains(*p)) else { return }; + let page = first.saturating_add(1).to_string(); + let what = kinds + .iter() + .map(|kind| match kind { + pdfcraft_render::RenderWarning::ColourFallback => { + tl!("a colour couldn't be computed, so part of the page is painted in a fallback colour") + } + pdfcraft_render::RenderWarning::MalformedIndexedImage => { + tl!("an image's colour table is malformed, so it may be drawn wrongly or not at all") + } + pdfcraft_render::RenderWarning::Type3WidthsMissing => { + tl!("a Type 3 font has no widths, so its glyphs are spaced by their procedures") + } + // Content truncation has its own bar above, which also covers search and copy. + pdfcraft_render::RenderWarning::ContentTruncated => tl!("part of the content isn't drawn"), + }) + .collect::>() + .join("; "); + let n = view.warned_pages.len(); + let text = if n == 1 { + crate::i18n::fmt(tl!("Page {page}: {what}."), &[("page", &page), ("what", &what)]) + } else { + crate::i18n::fmt( + tl!("{n} pages have render warnings, page {page} first: {what}."), + &[("n", &n.to_string()), ("page", &page), ("what", &what)], + ) + }; + let mut dismiss = false; + notice_bar(ui, t, "triangle-alert", t.accent_text, text, |ui| { + dismiss = icons::button(ui, "x", 22.0, false, tl!("Dismiss")).clicked(); + }); + if dismiss { + view.warn_notice_dismissed.extend(view.warned_pages.keys().copied()); + } +} + /// One notice bar: an icon and a message on the left, `buttons` (added right to left) on the /// right. The buttons are laid out first, so the message only gets the width they leave: it /// wraps there (or, when very little is left, is cut short with the full text on hover) instead diff --git a/crates/ui-egui/src/canvas/cache.rs b/crates/ui-egui/src/canvas/cache.rs index 2b2e519f4c..6de3d3d43c 100644 --- a/crates/ui-egui/src/canvas/cache.rs +++ b/crates/ui-egui/src/canvas/cache.rs @@ -193,6 +193,7 @@ impl DocView { self.text_failed.clear(); self.errors.clear(); self.cut_pages.clear(); + self.warned_pages.clear(); self.slow_pages.clear(); self.waiting_since.clear(); self.last_queue.clear(); @@ -237,6 +238,7 @@ impl DocView { self.text_failed.remove(&page); self.errors.remove(&page); self.cut_pages.remove(&page); + self.warned_pages.remove(&page); self.last_queue.clear(); if self.selection.is_some_and(|s| s.page == page) { self.selection = None; @@ -668,6 +670,20 @@ impl DocView { if r.warnings.contains(&pdfcraft_render::RenderWarning::ContentTruncated) { self.cut_pages.insert(r.request.page); } + // Every other warning is named too (#4340): a colour painted in a fallback colour, a + // malformed indexed image, or a Type 3 font whose spacing came from its procedures. The + // whole-page raster speaks for the page; a tile or a text result carries no page warnings. + // A warning is kept until the page's content or view settings change: a later render of the + // same page reports it again, so clearing on one silent result would only flicker the bar. + if r.request.kind == RequestKind::Pixels && r.request.tile.is_none() { + let page = r.request.page; + for kind in r.warnings.iter().copied().filter(|w| *w != pdfcraft_render::RenderWarning::ContentTruncated) { + let listed = self.warned_pages.entry(page).or_default(); + if !listed.contains(&kind) { + listed.push(kind); + } + } + } if r.request.kind == RequestKind::Text { match r.text { Some(t) => { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index a04f6d2a35..4bbb59104c 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2152,6 +2152,38 @@ fn a_cut_page_is_named_beside_an_xfa_form_notice() { h.get_by_label_contains("XFA data are kept in step"); } +/// Every render warning but content truncation is kept per page for the notice bar until the +/// page's content is invalidated, so one silent render does not flicker it (#4340). +#[test] +fn render_warnings_are_kept_per_page_until_the_page_changes() { + use pdfcraft_render::{RenderRequest, RenderWarning, RenderedPage}; + + let mut v = view(1, PageLayout::Single, true); + let ctx = egui::Context::default(); + let request = RenderRequest { page: 0, kind: RequestKind::Pixels, tag: 7, ..Default::default() }; + let text_request = RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() }; + v.last_queue = vec![request, text_request]; + let result = |request, warnings| RenderedPage { + request, + width: 0, + height: 0, + rgba: Default::default(), + error: None, + text: None, + warnings, + millis: 0, + }; + v.receive_result(&ctx, result(request, vec![RenderWarning::ColourFallback, RenderWarning::ContentTruncated])); + assert!(v.cut_pages.contains(&0), "content truncation keeps its own bar"); + assert_eq!(v.warned_pages.get(&0), Some(&vec![RenderWarning::ColourFallback]), "the other warning is kept"); + v.receive_result(&ctx, result(text_request, Vec::new())); + assert_eq!(v.warned_pages.get(&0), Some(&vec![RenderWarning::ColourFallback]), "a text result does not clear the page's warning"); + v.receive_result(&ctx, result(request, Vec::new())); + assert_eq!(v.warned_pages.get(&0), Some(&vec![RenderWarning::ColourFallback]), "a silent render does not clear it"); + v.invalidate_content(); + assert!(v.warned_pages.get(&0).is_none(), "an edit or view change clears it with the page"); +} + /// Dismissing another notice doesn't hide a page found cut later (#623), and dismissing the /// cut-page notice lasts until another page is found cut (review on #2113). #[test] From 6a4d8f36c479fd80d69ee24857522acee6b33260 Mon Sep 17 00:00:00 2001 From: gmrmad1 Date: Sun, 15 Nov 2026 22:43:27 +0530 Subject: [PATCH 033/114] fix(ui): show a notice when a document script couldn't run (#7382) --- crates/ui-egui/src/workflows/js_ui.rs | 64 +++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/crates/ui-egui/src/workflows/js_ui.rs b/crates/ui-egui/src/workflows/js_ui.rs index 18f9bcb753..339a1dda70 100644 --- a/crates/ui-egui/src/workflows/js_ui.rs +++ b/crates/ui-egui/src/workflows/js_ui.rs @@ -43,6 +43,18 @@ pub(crate) fn scripts_off_notice() -> String { tl!("This form's scripts are turned off because one ran too long. Reopen the document to run them again.").to_string() } +/// The toast's shape of the first document-script error: the JavaScript console keeps the whole +/// text, so the notice names the script and its error within one short line. +fn short_doc_error(error: &str) -> String { + const MAX: usize = 200; + if error.chars().count() <= MAX { + return error.to_string(); + } + let mut short: String = error.chars().take(MAX).collect(); + short.push('…'); + short +} + impl PdfCraftApp { /// Act on what scripts produced in document `id`: alerts are shown, console output goes to /// the console, print and page requests are carried out, links wait for the user's permission @@ -61,6 +73,14 @@ impl PdfCraftApp { v.notice_dismissed = false; self.notify(scripts_off_notice()); } + // A document-level script failed or was skipped (today, one over the 256 KiB limit): + // say so where the user looks, not only in the JavaScript console. Field-script + // errors stay console-only. The console keeps the whole text; the toast names the + // first error, shortened. + if let Some(first) = out.doc_errors.first() { + let detail = short_doc_error(first); + self.notify_fmt("A document script couldn't run: {detail}", &[("detail", &detail)]); + } if out.is_empty() { return; } @@ -528,6 +548,50 @@ pub(crate) use crate::dialogs::preferences::{ PREFERENCES_BUTTON_ROW, PREFERENCES_MIN_SCROLL, date_language_picker_name, preferences_body, preferences_buttons, preferences_header, }; +#[cfg(test)] +mod doc_error_notice_tests { + use super::*; + + /// A native app with a visible synthetic blank document and no renderer. + fn app() -> (PdfCraftApp, DocId) { + let mut app = PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + let bytes = app.session.create_blank(200.0, 300.0, 1).unwrap(); + app.open_bytes("synthetic.pdf", None, bytes.to_vec()).unwrap(); + let id = app.active_ids().unwrap().1; + assert!(app.toast.is_none()); + (app, id) + } + + /// A document-level script that failed or was skipped (today, one over the 256 KiB + /// limit) shows a visible notice naming the script and its error; an ordinary + /// field-script error stays a JavaScript console line. The console keeps the error + /// either way, and an empty frame leaves the notice alone. + #[test] + fn a_failed_document_script_is_noticed_but_a_field_error_is_not() { + let (mut app, id) = app(); + app.handle_js(id, JsOutput { errors: vec!["TypeError: can't access property".into()], ..Default::default() }); + assert!(app.toast.is_none(), "a field-script error is console-only"); + assert!(app.js_console.log.iter().any(|l| l.contains("can't access property")), "{:?}", app.js_console.log); + let detail = "document script 1: the script is too long (270 KiB; the limit is 256 KiB)"; + app.handle_js(id, JsOutput { errors: vec![detail.into()], doc_errors: vec![detail.into()], ..Default::default() }); + let toast = app.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(toast.contains("document script"), "{toast}"); + assert!(toast.contains("too long"), "{toast}"); + assert!(app.js_console.log.iter().any(|l| l.contains(detail)), "{:?}", app.js_console.log); + app.handle_js(id, JsOutput::default()); + assert_eq!(app.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(), toast, "an empty frame repeats nothing"); + } + + #[test] + fn a_valid_document_shows_nothing() { + let (mut app, id) = app(); + app.handle_js(id, JsOutput::default()); + assert!(app.toast.is_none()); + assert!(app.js_console.log.is_empty()); + } +} + #[cfg(test)] mod tests { use super::*; From b942f8b2901fb561fe8228598d1d25cd1751fc72 Mon Sep 17 00:00:00 2001 From: alehel Date: Sun, 15 Nov 2026 23:35:45 +0100 Subject: [PATCH 034/114] test(engine): the runaway XFA click tests wait on a prompt Both tests relied on the main thread starting its next edit before the worker's script ran away. A worker that finished first set the runaway flag early, and that edit consumed it. The script now asks a question first, and the test answers it only once the other edit or click has begun. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/tests.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f5ca39f12a..cd8f4eb8a7 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -10040,12 +10040,15 @@ fn a_dropped_xfa_click_that_ran_away_still_turns_the_scripts_off() { use crate::js::InteractiveEvent; let tpl = pdfcraft_xfa::fixtures::scripted_template().replace( r#"xfa.host.messageBox("Hello " + qty.rawValue);"#, - "function f() { for (var j = 0; j < 99999; j++) {} } for (var k = 0; k < 5000; k++) f();", + "xfa.host.messageBox(\"Go\"); function f() { for (var j = 0; j < 99999; j++) {} } for (var k = 0; k < 5000; k++) f();", ); let mut s = Session::new().with_clock(|| 1_700_000_000); let id = s.open("runaway.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens"); let p = s.start_javascript_target(id, "", Some("hello"), None).unwrap(); + // The script waits on its question until the other edit is in, so it cannot run away first. + let InteractiveEvent::Prompt(_, reply) = next_event(&p) else { panic!("asks first") }; s.apply(id, Edit::SetFieldValue { name: "price".into(), value: FieldValue::Text("6".into()) }).unwrap(); + reply.send(Some("1".into())).unwrap(); let InteractiveEvent::Complete(out) = next_event(&p) else { panic!("finishes") }; assert!(s.finish_javascript(p, out).is_err(), "the document changed"); assert!(!s.get(id).unwrap().xfa_scripts_off()); @@ -10061,12 +10064,15 @@ fn a_click_kept_beside_one_that_ran_away_leaves_the_scripts_to_turn_off() { use crate::js::InteractiveEvent; let tpl = pdfcraft_xfa::fixtures::scripted_template().replace( r#"xfa.host.messageBox("Hello " + qty.rawValue);"#, - "function f() { for (var j = 0; j < 99999; j++) {} } for (var k = 0; k < 5000; k++) f();", + "xfa.host.messageBox(\"Go\"); function f() { for (var j = 0; j < 99999; j++) {} } for (var k = 0; k < 5000; k++) f();", ); let mut s = Session::new().with_clock(|| 1_700_000_000); let id = s.open("runaway.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens"); let runaway = s.start_javascript_target(id, "", Some("hello"), None).unwrap(); + // The runaway script waits on its question until the other click has begun. + let InteractiveEvent::Prompt(_, reply) = next_event(&runaway) else { panic!("asks first") }; let kept = s.start_javascript_target(id, "", Some("addRow"), None).unwrap(); + reply.send(Some("1".into())).unwrap(); let InteractiveEvent::Complete(ran) = next_event(&runaway) else { panic!("finishes") }; let InteractiveEvent::Complete(out) = next_event(&kept) else { panic!("finishes") }; assert_eq!(s.finish_javascript(kept, out).unwrap().error, None); From f6201cf1da906b44c3877d3fb639dbca803afd45 Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Mon, 16 Nov 2026 20:59:07 +0530 Subject: [PATCH 035/114] review: drop warning dismissals with their page indexes (coderabbitai/stale dismissal after reorder) --- crates/ui-egui/src/canvas/cache.rs | 4 ++++ crates/ui-egui/src/canvas/tests.rs | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/crates/ui-egui/src/canvas/cache.rs b/crates/ui-egui/src/canvas/cache.rs index 6de3d3d43c..943d89d197 100644 --- a/crates/ui-egui/src/canvas/cache.rs +++ b/crates/ui-egui/src/canvas/cache.rs @@ -194,6 +194,10 @@ impl DocView { self.errors.clear(); self.cut_pages.clear(); self.warned_pages.clear(); + // The dismissals name pages by index, and a page-list edit (insert, delete, move) gives + // those indexes to other pages: drop them with the warnings they dismissed, so the next + // warning on a reused index is not hidden. + self.warn_notice_dismissed.clear(); self.slow_pages.clear(); self.waiting_since.clear(); self.last_queue.clear(); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 4bbb59104c..0bf820dd44 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2180,8 +2180,12 @@ fn render_warnings_are_kept_per_page_until_the_page_changes() { assert_eq!(v.warned_pages.get(&0), Some(&vec![RenderWarning::ColourFallback]), "a text result does not clear the page's warning"); v.receive_result(&ctx, result(request, Vec::new())); assert_eq!(v.warned_pages.get(&0), Some(&vec![RenderWarning::ColourFallback]), "a silent render does not clear it"); + v.warn_notice_dismissed.insert(0); v.invalidate_content(); assert!(v.warned_pages.get(&0).is_none(), "an edit or view change clears it with the page"); + // The dismissal names page 0 by index; a page-list edit may put another page there, so it + // goes with the warning it dismissed rather than hiding that page's first warning. + assert!(v.warn_notice_dismissed.is_empty(), "a dismissed warning does not outlive its page list"); } /// Dismissing another notice doesn't hide a page found cut later (#623), and dismissing the From fde33900c0ec5df44e83010be2970659fc2ece48 Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Mon, 16 Nov 2026 21:00:17 +0530 Subject: [PATCH 036/114] review: queue a document-script error behind the run's submit notice (coderabbitai/toast replacement) --- crates/ui-egui/src/workflows/js_ui.rs | 39 +++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/workflows/js_ui.rs b/crates/ui-egui/src/workflows/js_ui.rs index 339a1dda70..7bd68844e9 100644 --- a/crates/ui-egui/src/workflows/js_ui.rs +++ b/crates/ui-egui/src/workflows/js_ui.rs @@ -75,13 +75,18 @@ impl PdfCraftApp { } // A document-level script failed or was skipped (today, one over the 256 KiB limit): // say so where the user looks, not only in the JavaScript console. Field-script - // errors stay console-only. The console keeps the whole text; the toast names the - // first error, shortened. + // errors stay console-only. The console keeps the whole text; the notice names the + // first error, shortened. It joins the form-message queue at the front: this run may + // also ask to submit, whose notice takes the toast, and a notice set now would be + // replaced before it was seen. + let empty = out.is_empty(); + let mut alerts = out.alerts; if let Some(first) = out.doc_errors.first() { let detail = short_doc_error(first); - self.notify_fmt("A document script couldn't run: {detail}", &[("detail", &detail)]); + let text = crate::i18n::fmt(tl!("A document script couldn't run: {detail}"), &[("detail", &detail)]); + alerts.insert(0, Message { text, icon: MessageIcon::Error, ..Default::default() }); } - if out.is_empty() { + if empty && alerts.is_empty() { return; } self.js_console.log.extend(out.console.iter().cloned()); @@ -138,7 +143,7 @@ impl PdfCraftApp { Request::Beep | Request::Reset(_) => {} } } - self.show_script_messages(out.alerts); + self.show_script_messages(alerts); } fn focus_script_field(&mut self, id: DocId, view: Option, name: &str, object_id: Option) { @@ -583,6 +588,30 @@ mod doc_error_notice_tests { assert_eq!(app.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(), toast, "an empty frame repeats nothing"); } + /// #7382: a failed document script's notice is not lost when the same output also asks to + /// submit: the submit notice takes the toast now and the error follows in the queue. + #[test] + fn a_document_script_error_waits_for_the_runs_submit_notice() { + let (mut app, id) = app(); + let detail = "document script 1: TypeError: boom"; + app.handle_js( + id, + JsOutput { + doc_errors: vec![detail.into()], + requests: vec![Request::Submit("https://example.test/form".into())], + ..Default::default() + }, + ); + let shown = app.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(shown.contains("form asks to be submitted"), "{shown}"); + assert_eq!(app.script_messages.len(), 1, "the error notice waits its turn"); + assert!(app.script_messages[0].text.contains("document script"), "{:?}", app.script_messages); + app.toast = None; + assert!(app.next_script_message()); + let after = app.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(after.contains("document script") && after.contains("boom"), "{after}"); + } + #[test] fn a_valid_document_shows_nothing() { let (mut app, id) = app(); From b0aa2857ae70bd41fc9b44597fe18f1a221a9913 Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Mon, 16 Nov 2026 23:12:46 +0530 Subject: [PATCH 037/114] review: use contains_key in the warning test (clippy) --- crates/ui-egui/src/canvas/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 0bf820dd44..3f6a99ca49 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2182,7 +2182,7 @@ fn render_warnings_are_kept_per_page_until_the_page_changes() { assert_eq!(v.warned_pages.get(&0), Some(&vec![RenderWarning::ColourFallback]), "a silent render does not clear it"); v.warn_notice_dismissed.insert(0); v.invalidate_content(); - assert!(v.warned_pages.get(&0).is_none(), "an edit or view change clears it with the page"); + assert!(!v.warned_pages.contains_key(&0), "an edit or view change clears it with the page"); // The dismissal names page 0 by index; a page-list edit may put another page there, so it // goes with the warning it dismissed rather than hiding that page's first warning. assert!(v.warn_notice_dismissed.is_empty(), "a dismissed warning does not outlive its page list"); From 034a00bd017cd15109c86195c3367e176b56712d Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Mon, 16 Nov 2026 23:27:18 +0530 Subject: [PATCH 038/114] review: rustfmt the doc-error queue test (coderabbitai/formatting) --- crates/ui-egui/src/workflows/js_ui.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/ui-egui/src/workflows/js_ui.rs b/crates/ui-egui/src/workflows/js_ui.rs index 7bd68844e9..d5220690c6 100644 --- a/crates/ui-egui/src/workflows/js_ui.rs +++ b/crates/ui-egui/src/workflows/js_ui.rs @@ -596,11 +596,7 @@ mod doc_error_notice_tests { let detail = "document script 1: TypeError: boom"; app.handle_js( id, - JsOutput { - doc_errors: vec![detail.into()], - requests: vec![Request::Submit("https://example.test/form".into())], - ..Default::default() - }, + JsOutput { doc_errors: vec![detail.into()], requests: vec![Request::Submit("https://example.test/form".into())], ..Default::default() }, ); let shown = app.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); assert!(shown.contains("form asks to be submitted"), "{shown}"); From 81a5737328e655657d1b7e81398c6bfa8463b71e Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Mon, 16 Nov 2026 23:36:18 +0530 Subject: [PATCH 039/114] review: rustfmt the warning retention test (coderabbitai/formatting) --- crates/ui-egui/src/canvas/tests.rs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 3f6a99ca49..87d2d5c9dc 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2163,16 +2163,8 @@ fn render_warnings_are_kept_per_page_until_the_page_changes() { let request = RenderRequest { page: 0, kind: RequestKind::Pixels, tag: 7, ..Default::default() }; let text_request = RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() }; v.last_queue = vec![request, text_request]; - let result = |request, warnings| RenderedPage { - request, - width: 0, - height: 0, - rgba: Default::default(), - error: None, - text: None, - warnings, - millis: 0, - }; + let result = + |request, warnings| RenderedPage { request, width: 0, height: 0, rgba: Default::default(), error: None, text: None, warnings, millis: 0 }; v.receive_result(&ctx, result(request, vec![RenderWarning::ColourFallback, RenderWarning::ContentTruncated])); assert!(v.cut_pages.contains(&0), "content truncation keeps its own bar"); assert_eq!(v.warned_pages.get(&0), Some(&vec![RenderWarning::ColourFallback]), "the other warning is kept"); From f971f876dd87c607104e3f0aff0161a120719ea8 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 22:03:38 +0100 Subject: [PATCH 040/114] Merge form data: write an empty field name as a quoted cell so it counts as a column --- crates/automation/tests/it/automation.rs | 4 ++++ crates/xfdf/src/lib.rs | 4 +++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 436dabdd4d..a50549fbff 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -9674,6 +9674,10 @@ fn merging_form_data_counts_a_quoted_header_as_one_column() { let r = ok(&mut a, "form_merge_data", json!({ "paths": [file], "path": out })); assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(1), Some(1)), "{file}: {r}"); } + // A field with an empty name is one column, not the empty header of a file without fields. + std::fs::write(dir.join("noname.xfdf"), xfdf("")).unwrap(); + let r = ok(&mut a, "form_merge_data", json!({ "paths": ["noname.xfdf"], "path": "noname.csv" })); + assert_eq!((r["rows"].as_u64(), r["columns"].as_u64()), (Some(1), Some(1)), "{r}"); // Files without fields: no column. std::fs::write(dir.join("empty.xfdf"), r#""#) .unwrap(); diff --git a/crates/xfdf/src/lib.rs b/crates/xfdf/src/lib.rs index a3c600c220..72652e7dbf 100644 --- a/crates/xfdf/src/lib.rs +++ b/crates/xfdf/src/lib.rs @@ -215,7 +215,9 @@ pub fn merge_csv(files: &[Vec<(String, Vec)>]) -> String { out } }; - let mut out = columns.iter().map(|c| q(c)).collect::>().join(","); + // An empty name is written as `""`, so a lone field with no name is still a column and not + // the empty header line of files without fields. + let mut out = columns.iter().map(|c| if c.is_empty() { "\"\"".to_string() } else { q(c) }).collect::>().join(","); out.push('\n'); for f in files { let row: Vec = columns.iter().map(|c| f.iter().find(|(k, _)| k == c).map_or(String::new(), |(_, v)| q(&v.join(", ")))).collect(); From d0cf3d22c6c4a1f149c4a7f206d31ac6bcafb4b9 Mon Sep 17 00:00:00 2001 From: jweaver3 <43688514+jweaver3@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:29:22 -0500 Subject: [PATCH 041/114] fix(edit): list every header add accepts, match redacted settings by value, number indices from 1 (#5785) - HeaderFooter::check refuses a box longer than the listing decodes (MAX_RECORDED_TEXT, measured as recorded), so every header that is added can be listed and updated, not only replaced page-wide. - Redaction takes /PCHeaderFooter off a shrink stream whose entry resolves or decodes to the redacted header's settings, so one stream storing it indirectly no longer leaves the template in the file. - doc_header_footers numbers index from 1, like pages and the other tools' indices; update takes that number and refuses 0. - The automation test also updates with explicit pages. --- crates/automation/src/documents.rs | 8 +++-- crates/automation/src/tools.rs | 2 +- crates/automation/tests/it/automation.rs | 23 +++++++++++---- crates/edit/src/lib.rs | 2 +- crates/edit/src/marks.rs | 12 ++++++++ crates/edit/src/tests.rs | 13 +++++++++ crates/redact/src/lib.rs | 14 ++++++++- crates/redact/src/tests.rs | 37 ++++++++++++++++++++++++ 8 files changed, 100 insertions(+), 11 deletions(-) diff --git a/crates/automation/src/documents.rs b/crates/automation/src/documents.rs index 449e3940ad..ff76933576 100644 --- a/crates/automation/src/documents.rs +++ b/crates/automation/src/documents.rs @@ -569,7 +569,7 @@ impl Automation { .iter() .enumerate() .map(|(i, m)| { - let mut out = json!({ "index": i, "pages": m.pages.iter().map(|p| p + 1).collect::>() }); + let mut out = json!({ "index": i + 1, "pages": m.pages.iter().map(|p| p + 1).collect::>() }); if copying { let boxes = ["header_left", "header_center", "header_right", "footer_left", "footer_center", "footer_right"]; let text: serde_json::Map = @@ -617,10 +617,12 @@ impl Automation { Some(_) if a.opt_bool("replace")?.is_some() => return Err(ToolError::InvalidArgs("give update or replace, not both".into())), Some(index) => { let found = self.doc(a)?.header_footers(); - let mark = usize::try_from(index).ok().and_then(|i| found.get(i)).cloned(); + // 1-based, as the listing numbers them and as `pages` are. + let mark = usize::try_from(index).ok().and_then(|i| i.checked_sub(1)).and_then(|i| found.get(i)).cloned(); let listed = found.len(); Some(mark.ok_or_else(|| { - ToolError::InvalidArgs(format!("update must be an index doc_header_footers lists ({listed} found), not {index}")) + let range = if listed == 0 { "it lists none".to_string() } else { format!("1 to {listed}") }; + ToolError::InvalidArgs(format!("update must be an index doc_header_footers lists ({range}), not {index}")) })?) } None => None, diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 6dc472ae80..8718f23304 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -1237,7 +1237,7 @@ pub fn tools() -> Vec { json!({ "doc": doc(), "pages": pages("to mark (default: all)"), - "update": { "type": "integer", "minimum": 0, "description": "The index doc_header_footers lists for the header and footer to change. Not with replace." }, + "update": { "type": "integer", "minimum": 1, "description": "The index doc_header_footers lists for the header and footer to change. Not with replace." }, "header_left": { "type": "string" }, "header_center": { "type": "string" }, "header_right": { "type": "string" }, "footer_left": { "type": "string" }, "footer_center": { "type": "string" }, "footer_right": { "type": "string" }, "font": { "type": "string", "enum": ["Helvetica", "Times", "Courier"] }, diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index cf902a8d69..ff38b96d79 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -3853,20 +3853,33 @@ fn header_footer_update_changes_the_one_named() { ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [2, 3], "header_left": "SECOND" })); let listed = ok(&mut a, "doc_header_footers", json!({ "doc": doc })); assert_eq!(listed["header_footers"][0]["pages"], json!([1])); - assert_eq!(listed["header_footers"][1], json!({ "index": 1, "pages": [2, 3], "text": { "header_left": "SECOND" } })); - // Added after listing, so index 0 is still FIRST; it shares page 1 with FIRST and must stay. + assert_eq!(listed["header_footers"][1], json!({ "index": 2, "pages": [2, 3], "text": { "header_left": "SECOND" } })); + // Indices count from 1, as pages do. Added after listing, so index 1 is still FIRST; it + // shares page 1 with FIRST and must stay. ok(&mut a, "doc_header_footer", json!({ "doc": doc, "pages": [1], "footer_left": "THIRD" })); - let updated = ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": 0, "header_left": "CHANGED" })); + let updated = ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": 1, "header_left": "CHANGED" })); assert_eq!(updated["header_footers"], ok(&mut a, "doc_header_footers", json!({ "doc": doc }))["header_footers"], "the indices that hold now"); let texts = page_text(&mut a, doc); assert!(texts[0].contains("CHANGED") && !texts[0].contains("FIRST"), "{texts:?}"); assert!(texts[0].contains("THIRD"), "the other one on that page stays: {texts:?}"); assert!(texts[1].contains("SECOND") && !texts[1].contains("CHANGED"), "{texts:?}"); - for bad in [json!({ "doc": doc, "update": 9, "header_left": "X" }), json!({ "doc": doc, "update": 0, "replace": true, "header_left": "X" })] { + // Given pages, the update goes there instead: it leaves every page the old one was on, and + // the other header and footer on those pages stays. + let changed = updated["header_footers"].as_array().unwrap().iter().find(|m| m["text"]["header_left"] == "CHANGED").unwrap()["index"].clone(); + ok(&mut a, "doc_header_footer", json!({ "doc": doc, "update": changed, "pages": [2], "header_left": "MOVED" })); + let texts = page_text(&mut a, doc); + assert!(!texts[0].contains("CHANGED") && !texts[0].contains("MOVED") && texts[0].contains("THIRD"), "{texts:?}"); + assert!(texts[1].contains("MOVED") && texts[1].contains("SECOND"), "{texts:?}"); + assert!(!texts[2].contains("MOVED") && texts[2].contains("SECOND"), "{texts:?}"); + for bad in [ + json!({ "doc": doc, "update": 9, "header_left": "X" }), + json!({ "doc": doc, "update": 0, "header_left": "X" }), + json!({ "doc": doc, "update": 1, "replace": true, "header_left": "X" }), + ] { assert!(matches!(a.call("doc_header_footer", &bad), Err(ToolError::InvalidArgs(_))), "{bad}"); } // The Update command changes a document: it must not run the read-only listing and report success. - let by_command = json!({ "id": "edit.header_footer.update", "params": { "doc": doc, "update": 0, "header_left": "VIA COMMAND" } }); + let by_command = json!({ "id": "edit.header_footer.update", "params": { "doc": doc, "update": 1, "header_left": "VIA COMMAND" } }); let listed = ok(&mut a, "doc_header_footers", json!({ "doc": doc })); assert!(a.call("command_run", &by_command).is_err()); assert_eq!(ok(&mut a, "doc_header_footers", json!({ "doc": doc })), listed); diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs index c6e0604701..232669263e 100644 --- a/crates/edit/src/lib.rs +++ b/crates/edit/src/lib.rs @@ -89,7 +89,7 @@ pub use apply::{ }; #[cfg(test)] use marks::bates_start; -pub use marks::{Background, Context, HeaderFooter, HeaderFooterMark, MarkKind, MarkSource, Watermark, expand}; +pub use marks::{Background, Context, HeaderFooter, HeaderFooterMark, MarkKind, MarkSource, Watermark, expand, recorded_header_footer}; use marks::{matrix_number, n}; pub(crate) use place::undrawable; #[cfg(test)] diff --git a/crates/edit/src/marks.rs b/crates/edit/src/marks.rs index 0dfc981719..2884b4cd9b 100644 --- a/crates/edit/src/marks.rs +++ b/crates/edit/src/marks.rs @@ -192,6 +192,11 @@ impl HeaderFooter { if self.text.iter().all(|t| t.trim().is_empty()) { return Err(EditError::Invalid("type the header or footer text first".into())); } + // Measured as recorded: a box the listing would refuse to decode must not be added, or it + // could never be listed and updated, only replaced page-wide. + if self.text.iter().any(|t| pdfcraft_cos::PdfString::text(t).bytes.len() > MAX_RECORDED_TEXT) { + return Err(EditError::Invalid(format!("a header or footer box can hold at most {} KB of text", MAX_RECORDED_TEXT / 1024))); + } if let Some(c) = self.first_undrawable() { return Err(super::place::undrawable(c)); } @@ -268,6 +273,13 @@ impl HeaderFooter { } } +/// The header and footer settings a [`SETTINGS_KEY`] entry records, if it records ones that +/// [`add_header_footer`](crate::add_header_footer) would accept: what redaction matches a +/// header's streams by, however each stores them. +pub fn recorded_header_footer(doc: &Document, value: &Object) -> Option { + HeaderFooter::from_object(doc, value) +} + /// The `cm` that shrinks a page's original content (user space) into the band `hf` leaves free, /// for a page shown `size` (display space) with view matrix `view` (display to user space): an /// even scale, centred across, the content's bottom on the footer's band. diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index 455e940eb1..03b6f96f74 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -420,6 +420,19 @@ fn settings_a_rewriting_tool_made_indirect_are_still_listed() { assert!(unrecorded_header_footer_pages(&doc).is_empty()); } +#[test] +fn a_header_too_long_to_be_listed_is_not_added() { + // Every header add accepts is one the listing can name, so Update never has to fall back to + // replacing it page-wide. + let mut doc = fixture(); + let too_long = with_text(&"x".repeat(16 * 1024 + 1)); + assert!(matches!(add_header_footer(&mut doc, &[0], &too_long, false, &cx()), Err(EditError::Invalid(_)))); + assert!(marks_present(&doc).is_empty(), "nothing drawn"); + let longest = with_text(&"x".repeat(16 * 1024)); + add_header_footer(&mut doc, &[0], &longest, false, &cx()).unwrap(); + assert_eq!(header_footers(&doc).len(), 1, "the longest box add accepts is listed"); +} + #[test] fn a_header_added_with_an_out_of_range_colour_can_be_updated() { let mut doc = fixture(); diff --git a/crates/redact/src/lib.rs b/crates/redact/src/lib.rs index 7ab5db1a3a..71224aaa40 100644 --- a/crates/redact/src/lib.rs +++ b/crates/redact/src/lib.rs @@ -35,6 +35,7 @@ mod pattern_guard; pub mod patterns; pub mod sanitize; mod tags; + #[cfg(test)] mod tests; #[cfg(test)] @@ -825,6 +826,13 @@ struct Applying { pruned_patterns: Vec, } +/// Whether a stream's `/PCHeaderFooter` entry `v` records the same header and footer as one of +/// the entries taken off redacted streams (`raw`, and those of them that decode, `decoded`). +fn same_settings(doc: &Document, raw: &[Object], decoded: &[pdfcraft_edit::HeaderFooter], v: &Object) -> bool { + let value = doc.resolve(v); + raw.iter().any(|r| *doc.resolve(r) == *value) || pdfcraft_edit::recorded_header_footer(doc, v).is_some_and(|hf| decoded.contains(&hf)) +} + /// Step 1 for one page: rewrites its content so nothing readable stays under a mark, and cleans the tags it no longer shows. fn redact_page_content( doc: &mut Document, @@ -896,10 +904,14 @@ fn redact_page_content( } // A shrinking header's `cm` stream records the same settings but draws no text, so it is // never rewritten above: take its copy of the templates away too. + // Matched by what the settings say, not how they are stored: a rewriting tool may make the + // entry indirect on one stream and leave it direct on the other. if !redacted_settings.is_empty() { + let decoded: Vec = + redacted_settings.iter().filter_map(|v| pdfcraft_edit::recorded_header_footer(doc, v)).collect(); for o in new_list.iter_mut() { let mut stream = match &*doc.resolve(o) { - Object::Stream(s) if s.dict.get(b"PCHeaderFooter").is_some_and(|v| redacted_settings.contains(v)) => s.clone(), + Object::Stream(s) if s.dict.get(b"PCHeaderFooter").is_some_and(|v| same_settings(doc, &redacted_settings, &decoded, v)) => s.clone(), _ => continue, }; stream.dict.remove(b"PCHeaderFooter"); diff --git a/crates/redact/src/tests.rs b/crates/redact/src/tests.rs index c99ae4d74a..d1ceab36c9 100644 --- a/crates/redact/src/tests.rs +++ b/crates/redact/src/tests.rs @@ -703,6 +703,43 @@ fn a_redacted_header_keeps_no_copy_of_its_text() { assert!(content(&doc, 0).contains("(AB)"), "the rest of the page stays"); } +#[test] +fn a_redacted_header_keeps_no_copy_of_its_text_however_its_streams_store_it() { + let mut doc = one_page(b"BT /F1 10 Tf 10 100 Td (AB) Tj ET", "", vec![]); + let mut hf = pdfcraft_edit::HeaderFooter { shrink: true, ..Default::default() }; + hf.text[1] = "SECRET9".into(); + pdfcraft_edit::add_header_footer(&mut doc, &[0], &hf, false, &pdfcraft_edit::Context { date: (2026, 10, 1) }).unwrap(); + // As a rewriting tool may: one stream's settings moved to an object of their own, the + // other's left in place, so the two entries are no longer the same value. + let page = doc.resolve(&Object::Ref(ObjRef::new(3, 0))).as_dict().unwrap().clone(); + let contents = doc.resolve(page.get(b"Contents").unwrap()).as_array().unwrap().to_vec(); + let recorded: Vec = contents + .iter() + .filter_map(|o| match o { + Object::Ref(r) => Some(*r), + _ => None, + }) + .filter(|r| matches!(&*doc.resolve(&Object::Ref(*r)), Object::Stream(s) if s.dict.get(b"PCHeaderFooter").is_some())) + .collect(); + assert_eq!(recorded.len(), 2, "the header's stream and its shrink's"); + for &moved in &recorded { + let mut doc = doc.clone(); + let settings = match &*doc.resolve(&Object::Ref(moved)) { + Object::Stream(s) => s.dict.get(b"PCHeaderFooter").unwrap().clone(), + _ => panic!("a content stream"), + }; + let indirect = doc.add(settings); + doc.update_dict(moved, |d| d.set(b"PCHeaderFooter".to_vec(), Object::Ref(indirect))).unwrap(); + mark(&mut doc, 0, &[[0.0, 240.0, 300.0, 300.0]], ""); + apply(&mut doc, None).unwrap(); + let page = doc.resolve(&Object::Ref(ObjRef::new(3, 0))).as_dict().unwrap().clone(); + let contents = doc.resolve(page.get(b"Contents").unwrap()).as_array().unwrap().to_vec(); + let left = contents.iter().filter(|o| matches!(&*doc.resolve(o), Object::Stream(s) if s.dict.get(b"PCHeaderFooter").is_some())).count(); + assert_eq!(left, 0, "a stream of the redacted header still records its settings ({moved:?} indirect)"); + assert!(content(&doc, 0).contains("(AB)"), "the rest of the page stays"); + } +} + #[test] fn operators_split_across_content_streams_are_redacted_whole() { // One content stream in three pieces, split between tokens: a marked-content dictionary From 62221477fb25e298ccbe6b2944c4b4e065a8056a Mon Sep 17 00:00:00 2001 From: jweaver3 <43688514+jweaver3@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:53:23 -0500 Subject: [PATCH 042/114] fix(edit, redact): read header settings in place, once per shared object, and keep a stripped stream's content (#5785) - HeaderFooter::from_object reads every value in place: a direct settings dictionary, array or string is no longer copied before its count and sizes are checked. - A scan of the headers and footers (header_footers and unrecorded_header_footer_pages) reads each stream and each settings entry given by reference once, however many pages share it, and converts at most 16 MiB of text in all. - Redaction keeps the content read for a stream it only takes the header settings off (it keeps its /Filter and /DecodeParms, perhaps by reference), instead of decoding it again without its parameters; a stream it rewrote that won't decode is an error, not empty content. An image only such a stream still draws keeps its resource. --- crates/edit/src/apply.rs | 105 +++++++++++++++++++++++++++++------ crates/edit/src/marks.rs | 110 +++++++++++++++++++++++-------------- crates/edit/src/tests.rs | 26 +++++++++ crates/redact/src/lib.rs | 22 +++++--- crates/redact/src/tests.rs | 38 +++++++++++++ 5 files changed, 235 insertions(+), 66 deletions(-) diff --git a/crates/edit/src/apply.rs b/crates/edit/src/apply.rs index 83f43d78ee..984f684e2f 100644 --- a/crates/edit/src/apply.rs +++ b/crates/edit/src/apply.rs @@ -2,13 +2,13 @@ use pdfcraft_fonts::shaped_text::{is_thai, thai_refusal, thai_width}; use super::marks::{ Background, Context, HeaderFooter, HeaderFooterMark, MarkKind, MarkText, SETTINGS_KEY, Watermark, add_picture_resource, bates_start, expand, - matrix_number, n, picture, rgb, shrink_matrix, + matrix_number, n, picture, read, rgb, shrink_matrix, }; use super::place::{ END, Isolation, add_page_resources, add_resources, begin, check, check_on_top, content_list, contents, free_font_name, isolation, page_fonts, page_list, place, place_inside_wrapper, stream_tag, undrawable, wrapper_role, }; -use super::{Document, EditError, Object, added, backdrop, helvetica_width}; +use super::{Document, EditError, ObjRef, Object, added, backdrop, helvetica_width}; /// Commit one complete mark operation only after every selected page succeeds. The snapshot /// shares original bytes, cross-references, caches and unchanged objects; only the overlay table @@ -45,26 +45,94 @@ fn recorded_settings(doc: &Document, stream: &Object) -> Option { if stream_tag(doc, stream).as_deref() != Some(MarkKind::HeaderFooter.tag()) { return None; } - let resolved = doc.resolve(stream); - HeaderFooter::from_object(doc, resolved.as_dict()?.get(SETTINGS_KEY)?) + read(doc, stream, |s| HeaderFooter::from_object(doc, s.as_dict()?.get(SETTINGS_KEY)?)) +} + +/// The most bytes of recorded text one scan of a document converts: the text of hundreds of +/// thousands of real headers, yet a bound on a file that repeats a large one in every stream. +const MAX_SCAN_TEXT: usize = 16 * 1024 * 1024; + +/// One scan of a document's headers and footers. A stream, or a settings entry, given by reference +/// is read once however many pages share it, and the text converted in all is bounded +/// ([`MAX_SCAN_TEXT`]): a file repeating its settings can't make listing them slow. +struct Scan { + found: Vec, + streams: std::collections::HashMap, + settings: std::collections::HashMap, + budget: usize, +} + +/// What a content stream records. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Recorded { + /// No header and footer, or one whose settings can't be read (from before they were recorded, + /// another tool's, unreadable, or past the scan's text budget). + Nothing, + /// Settings, listed as `found[k]`, or not listed (`None`) past [`MAX_HEADER_FOOTERS`]. + Settings(Option), +} + +impl Scan { + fn of(doc: &Document) -> Self { + let mut scan = Self { found: Vec::new(), streams: Default::default(), settings: Default::default(), budget: MAX_SCAN_TEXT }; + for (i, page) in page_list(doc).iter().enumerate() { + for o in content_list(doc, page).iter() { + if let Recorded::Settings(Some(k)) = scan.stream(doc, o) + && let Some(mark) = scan.found.get_mut(k) + && mark.pages.last() != Some(&i) + { + mark.pages.push(i); + } + } + } + scan + } + + fn stream(&mut self, doc: &Document, o: &Object) -> Recorded { + let Object::Ref(r) = o else { return self.read_stream(doc, o) }; + if let Some(known) = self.streams.get(r) { + return *known; + } + let recorded = self.read_stream(doc, o); + self.streams.insert(*r, recorded); + recorded + } + + fn read_stream(&mut self, doc: &Document, o: &Object) -> Recorded { + if stream_tag(doc, o).as_deref() != Some(MarkKind::HeaderFooter.tag()) { + return Recorded::Nothing; + } + read(doc, o, |s| Some(self.entry(doc, s.as_dict()?.get(SETTINGS_KEY)?))).unwrap_or(Recorded::Nothing) + } + + /// A stream's [`SETTINGS_KEY`] entry. + fn entry(&mut self, doc: &Document, value: &Object) -> Recorded { + let Object::Ref(r) = value else { return self.read_settings(doc, value) }; + if let Some(known) = self.settings.get(r) { + return *known; + } + let recorded = self.read_settings(doc, value); + self.settings.insert(*r, recorded); + recorded + } + + fn read_settings(&mut self, doc: &Document, value: &Object) -> Recorded { + let Some(settings) = HeaderFooter::from_object_within(doc, value, &mut self.budget) else { return Recorded::Nothing }; + if let Some(k) = self.found.iter().position(|m| m.settings == settings) { + return Recorded::Settings(Some(k)); + } + if self.found.len() >= MAX_HEADER_FOOTERS { + return Recorded::Settings(None); + } + self.found.push(HeaderFooterMark { pages: Vec::new(), settings }); + Recorded::Settings(Some(self.found.len() - 1)) + } } /// The headers and footers that record their settings, in page order, each with the pages it is /// on. Marks from before settings were recorded, or from another tool, are not listed. pub fn header_footers(doc: &Document) -> Vec { - let mut found: Vec = Vec::new(); - for (i, page) in page_list(doc).iter().enumerate() { - for settings in content_list(doc, page).iter().filter_map(|o| recorded_settings(doc, o)) { - if let Some(mark) = found.iter_mut().find(|m| m.settings == settings) { - if mark.pages.last() != Some(&i) { - mark.pages.push(i); - } - } else if found.len() < MAX_HEADER_FOOTERS { - found.push(HeaderFooterMark { pages: vec![i], settings }); - } - } - } - found + Scan::of(doc).found } /// The header and footer added last to page `page` (0-based): `Some(None)` when it records no @@ -82,10 +150,11 @@ pub fn newest_header_footer(doc: &Document, page: usize) -> Option Vec { let tagged = |o: &Object| stream_tag(doc, o).as_deref() == Some(MarkKind::HeaderFooter.tag()); + let mut scan = Scan::of(doc); page_list(doc) .iter() .enumerate() - .filter(|(_, page)| content_list(doc, page).iter().any(|o| tagged(o) && recorded_settings(doc, o).is_none())) + .filter(|(_, page)| content_list(doc, page).iter().any(|o| tagged(o) && scan.stream(doc, o) == Recorded::Nothing)) .map(|(i, _)| i) .collect() } diff --git a/crates/edit/src/marks.rs b/crates/edit/src/marks.rs index 2884b4cd9b..d6c47e620c 100644 --- a/crates/edit/src/marks.rs +++ b/crates/edit/src/marks.rs @@ -177,12 +177,22 @@ pub(crate) const SETTINGS_KEY: &[u8] = b"PCHeaderFooter"; /// what listing the headers and footers of a hostile file decodes. const MAX_RECORDED_TEXT: usize = 16 * 1024; +/// `f` of `o`, or of what it refers to: a direct value is read in place, never copied, so a large +/// one costs nothing until it has been checked. (`Document::resolve` copies a direct value whole.) +pub(crate) fn read(doc: &Document, o: &Object, f: impl FnOnce(&Object) -> Option) -> Option { + match o { + Object::Ref(_) => f(&doc.resolve(o)), + _ => f(o), + } +} + /// An array of exactly `N` numbers, each resolved: a rewriting tool may make any of them indirect. fn numbers(doc: &Document, o: &Object) -> Option<[f64; N]> { - let array = doc.resolve(o); - let items = array.as_array().filter(|a| a.len() == N)?; - let values: Vec = items.iter().map(|v| doc.resolve(v).as_f64()).collect::>()?; - <[f64; N]>::try_from(values).ok() + read(doc, o, |array| { + let items = array.as_array().filter(|a| a.len() == N)?; + let values: Vec = items.iter().map(|v| read(doc, v, Object::as_f64)).collect::>()?; + <[f64; N]>::try_from(values).ok() + }) } impl HeaderFooter { @@ -234,43 +244,63 @@ impl HeaderFooter { /// Settings back from a [`SETTINGS_KEY`] entry. `None` unless every value is one the dialog /// could have written: a file can say anything here. pub(crate) fn from_object(doc: &Document, o: &Object) -> Option { - let resolved = doc.resolve(o); - let d = resolved.as_dict()?; - // Every value resolved: a rewriting tool may make any of them indirect. - let value = |key: &[u8]| d.get(key).map(|v| doc.resolve(v)); - let flag = |key: &[u8]| match &*value(key)? { - Object::Bool(b) => Some(*b), - _ => None, - }; - // The count and each size are checked before anything is decoded or copied. - let texts = value(b"Text")?; - let texts = texts.as_array().filter(|a| a.len() == 6)?; - let text: Vec = texts - .iter() - .map(|t| { - let t = doc.resolve(t); - let s = t.as_string().filter(|s| s.bytes.len() <= MAX_RECORDED_TEXT)?; - Some(s.to_text()) - }) - .collect::>()?; - let hf = Self { - text: text.try_into().ok()?, - font: match value(b"Font")?.as_name()? { - b"Helvetica" => added::Family::Helvetica, - b"Times" => added::Family::Times, - b"Courier" => added::Family::Courier, - _ => return None, - }, - font_size: value(b"Size")?.as_f64()?, - color: numbers(doc, d.get(b"Color")?)?, - underline: flag(b"Underline")?, - margins: numbers(doc, d.get(b"Margins")?)?, - start_number: u32::try_from(value(b"Start")?.as_int()?).ok()?, - shrink: flag(b"Shrink")?, - }; - let sane = hf.check().is_ok() && hf.color.iter().all(|c| (0.0..=1.0).contains(c)); - sane.then_some(hf) + Self::from_object_within(doc, o, &mut usize::MAX) } + + /// [`from_object`](Self::from_object), converting at most `budget` bytes of text, which it + /// takes from: `None` once that is spent. Bounds what one scan of a document converts. + pub(crate) fn from_object_within(doc: &Document, o: &Object, budget: &mut usize) -> Option { + #[cfg(test)] + DECODED.with(|n| n.set(n.get() + 1)); + // Every value resolved, as a rewriting tool may make any of them indirect, and read in + // place: nothing is copied before it is checked. + read(doc, o, |o| { + let d = o.as_dict()?; + let flag = |key: &[u8]| { + read(doc, d.get(key)?, |v| match v { + Object::Bool(b) => Some(*b), + _ => None, + }) + }; + // The count and each size are checked before anything is decoded. + let text: Vec = read(doc, d.get(b"Text")?, |texts| { + let texts = texts.as_array().filter(|a| a.len() == 6)?; + texts + .iter() + .map(|t| { + read(doc, t, |t| { + let s = t.as_string().filter(|s| s.bytes.len() <= MAX_RECORDED_TEXT)?; + *budget = budget.checked_sub(s.bytes.len())?; + Some(s.to_text()) + }) + }) + .collect() + })?; + let hf = Self { + text: text.try_into().ok()?, + font: read(doc, d.get(b"Font")?, |v| match v.as_name()? { + b"Helvetica" => Some(added::Family::Helvetica), + b"Times" => Some(added::Family::Times), + b"Courier" => Some(added::Family::Courier), + _ => None, + })?, + font_size: read(doc, d.get(b"Size")?, Object::as_f64)?, + color: numbers(doc, d.get(b"Color")?)?, + underline: flag(b"Underline")?, + margins: numbers(doc, d.get(b"Margins")?)?, + start_number: read(doc, d.get(b"Start")?, |v| u32::try_from(v.as_int()?).ok())?, + shrink: flag(b"Shrink")?, + }; + let sane = hf.check().is_ok() && hf.color.iter().all(|c| (0.0..=1.0).contains(c)); + sane.then_some(hf) + }) + } +} + +#[cfg(test)] +thread_local! { + /// How many settings entries [`HeaderFooter::from_object_within`] has read on this thread. + pub(crate) static DECODED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// The header and footer settings a [`SETTINGS_KEY`] entry records, if it records ones that diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index 03b6f96f74..e9317c832a 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -400,6 +400,32 @@ fn settings_a_file_makes_up_are_not_listed() { } } +/// #6352 review: listing read a header's settings again for every stream that recorded them, so a +/// file repeating one shared entry (or one stream) across its pages could make it slow. A scan now +/// reads each stream and each settings entry given by reference once, and still finds every page. +#[test] +fn settings_shared_by_many_streams_are_read_once_in_a_scan() { + let (mut doc, mark) = one_recorded_header(); + let settings = doc.get(mark).as_dict().unwrap().get(b"PCHeaderFooter").cloned().unwrap(); + let shared = Object::Ref(doc.add(settings)); + doc.update_dict(mark, |d| d.set(b"PCHeaderFooter".to_vec(), shared)).unwrap(); + let Object::Stream(copy) = (*doc.get(mark)).clone() else { panic!("a stream") }; + // Page 0 draws the header's own stream 500 times; page 1 has 200 streams of its own, each + // recording the same settings by reference. + let mut first = vec![Object::Ref(pdfcraft_cos::ObjRef::new(7, 0))]; + first.extend(std::iter::repeat_n(Object::Ref(mark), 500)); + let mut second = vec![Object::Ref(pdfcraft_cos::ObjRef::new(7, 0))]; + second.extend((0..200).map(|_| Object::Ref(doc.add(Object::Stream(copy.clone()))))); + doc.update_dict(pdfcraft_cos::ObjRef::new(3, 0), |d| d.set(b"Contents".to_vec(), Object::Array(first))).unwrap(); + doc.update_dict(pdfcraft_cos::ObjRef::new(4, 0), |d| d.set(b"Contents".to_vec(), Object::Array(second))).unwrap(); + crate::marks::DECODED.with(|n| n.set(0)); + let found = header_footers(&doc); + assert_eq!(crate::marks::DECODED.with(std::cell::Cell::get), 1, "the shared entry is read once"); + assert_eq!(found.len(), 1); + assert_eq!((found[0].pages.as_slice(), found[0].settings.text[1].as_str()), (&[0, 1][..], "Real")); + assert!(unrecorded_header_footer_pages(&doc).is_empty()); +} + #[test] fn settings_a_rewriting_tool_made_indirect_are_still_listed() { let (mut doc, mark) = one_recorded_header(); diff --git a/crates/redact/src/lib.rs b/crates/redact/src/lib.rs index 71224aaa40..b0013c83d8 100644 --- a/crates/redact/src/lib.rs +++ b/crates/redact/src/lib.rs @@ -906,16 +906,19 @@ fn redact_page_content( // never rewritten above: take its copy of the templates away too. // Matched by what the settings say, not how they are stored: a rewriting tool may make the // entry indirect on one stream and leave it direct on the other. + // Only the entry goes: the stream's content is still what was read for it above. + let mut settings_only = Vec::new(); if !redacted_settings.is_empty() { let decoded: Vec = redacted_settings.iter().filter_map(|v| pdfcraft_edit::recorded_header_footer(doc, v)).collect(); - for o in new_list.iter_mut() { + for (i, o) in new_list.iter_mut().enumerate() { let mut stream = match &*doc.resolve(o) { Object::Stream(s) if s.dict.get(b"PCHeaderFooter").is_some_and(|v| same_settings(doc, &redacted_settings, &decoded, v)) => s.clone(), _ => continue, }; stream.dict.remove(b"PCHeaderFooter"); *o = Object::Ref(doc.add(Object::Stream(stream))); + settings_only.push(i); } } if changed || !out.xobjects.is_empty() || !out.replaced.is_empty() { @@ -933,14 +936,17 @@ fn redact_page_content( .iter() .zip(&list) .zip(&data) - .map(|((now, was), read)| match &*doc.resolve(now) { - // Left as it was: what was read above, with its parameters by reference. - _ if now == was => read.clone(), - // Written above by `Stream::flate`, which leaves no `/DecodeParms`. - Object::Stream(s) => s.decoded().unwrap_or_default(), - _ => Vec::new(), + .enumerate() + .map(|(i, ((now, was), read))| match &*doc.resolve(now) { + // Left as it was, or only its header settings taken off (keeping its + // `/Filter` and `/DecodeParms`, perhaps by reference): what was read above. + _ if now == was || settings_only.contains(&i) => Ok(read.clone()), + // Written above by `Stream::flate`. One that won't decode is an error, not + // empty content: `prune` would take that as drawing nothing. + Object::Stream(s) => doc.with_direct_parms(s).decoded(), + _ => Ok(Vec::new()), }) - .collect(); + .collect::>()?; interp::prune(doc, &mut budget, &mut xo, &out.replaced, &page_content)?; res.set(b"XObject".to_vec(), Object::Dict(xo)); } diff --git a/crates/redact/src/tests.rs b/crates/redact/src/tests.rs index d1ceab36c9..81d17c248c 100644 --- a/crates/redact/src/tests.rs +++ b/crates/redact/src/tests.rs @@ -245,6 +245,44 @@ fn an_image_drawn_again_in_content_with_parameters_by_reference_stays() { assert_eq!((image.dict.name(b"Subtype"), image.decoded().ok()), (Some(&b"Image"[..]), Some(vec![255; 4]))); } +/// #6352 review: a stream that only records a redacted header's settings keeps its `/Filter` +/// and `/DecodeParms` when the settings are taken off. Read again without its parameters (given by +/// reference), it seemed to draw nothing, so an image it draws, removed under the mark elsewhere on +/// the page, lost its resource while the stream still drew it. +#[test] +fn an_image_drawn_by_a_stream_keeping_header_settings_stays() { + use pdfcraft_cos::{Dict, ObjRef, Object}; + let img = stream("/Type /XObject /Subtype /Image /Width 4 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", [255, 255, 255, 255]); + let mut doc = one_page(b"q 10 0 0 10 10 270 cm /Im1 Do Q", "/XObject << /Im1 7 0 R >>", vec![img]); + let mut hf = pdfcraft_edit::HeaderFooter::default(); + hf.text[1] = "SECRET9".into(); + pdfcraft_edit::add_header_footer(&mut doc, &[0], &hf, false, &pdfcraft_edit::Context { date: (2026, 10, 1) }).unwrap(); + let page = doc.resolve(&Object::Ref(ObjRef::new(3, 0))).as_dict().unwrap().clone(); + let mut contents = doc.resolve(page.get(b"Contents").unwrap()).as_array().unwrap().to_vec(); + let settings = contents + .iter() + .find_map(|o| match &*doc.resolve(o) { + Object::Stream(s) => s.dict.get(b"PCHeaderFooter").cloned(), + _ => None, + }) + .unwrap(); + let mut again = predicted(&mut doc, Dict::new(), b"q 10 0 0 10 200 100 cm /Im1 Do Q"); + again.dict.set(b"PCHeaderFooter".to_vec(), settings); + contents.push(Object::Ref(doc.add(Object::Stream(again)))); + doc.update_dict(ObjRef::new(3, 0), |d| d.set(b"Contents".to_vec(), Object::Array(contents))).unwrap(); + // Over the header and the image drawn at the top, not the one drawn again below. + mark(&mut doc, 0, &[[0.0, 240.0, 300.0, 300.0]], ""); + let r = apply(&mut doc, None).unwrap(); + assert_eq!(r.images_removed, 1, "{r:?}"); + let doc = reopen(&doc); + assert!(content(&doc, 0).contains("200 100 cm /Im1 Do"), "{}", content(&doc, 0)); + let p = pdfcraft_model::pages(&doc).swap_remove(0); + let res = doc.resolve(p.dict.get(b"Resources").unwrap()).as_dict().cloned().unwrap(); + let xo = doc.resolve(res.get(b"XObject").unwrap()).as_dict().cloned().unwrap(); + let Some(Object::Stream(image)) = xo.reference(b"Im1").map(|r| (*doc.get(r)).clone()) else { panic!("no /Im1: {xo:?}") }; + assert_eq!((image.dict.name(b"Subtype"), image.decoded().ok()), (Some(&b"Image"[..]), Some(vec![255; 4]))); +} + /// #2130: a font with no /Widths is drawn with its embedded program's advances. Measured with a /// guess from its name instead (Courier's 600 units for "Mono"), the end of the line seemed to /// lie past a mark that covers all of it on screen, and was kept. From 77d4c308d2c3d747b88cfe478779d37ed539d7e6 Mon Sep 17 00:00:00 2001 From: jweaver3 <43688514+jweaver3@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:53:16 -0500 Subject: [PATCH 043/114] fix(edit): take no mutable reference to usize::MAX (#5785) clippy::const_item_mutation denies it under -D warnings: an unlimited budget is a local now. --- crates/edit/src/marks.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/edit/src/marks.rs b/crates/edit/src/marks.rs index d6c47e620c..19d853892f 100644 --- a/crates/edit/src/marks.rs +++ b/crates/edit/src/marks.rs @@ -244,7 +244,8 @@ impl HeaderFooter { /// Settings back from a [`SETTINGS_KEY`] entry. `None` unless every value is one the dialog /// could have written: a file can say anything here. pub(crate) fn from_object(doc: &Document, o: &Object) -> Option { - Self::from_object_within(doc, o, &mut usize::MAX) + let mut unlimited = usize::MAX; + Self::from_object_within(doc, o, &mut unlimited) } /// [`from_object`](Self::from_object), converting at most `budget` bytes of text, which it From 504595dfa849c182eab644bcbc7aaac63d97bbb5 Mon Sep 17 00:00:00 2001 From: alehel Date: Mon, 23 Nov 2026 18:56:44 +0100 Subject: [PATCH 044/114] fix(js): an XFA click past its 32 questions gets the safe default in every session Review on #6984: past the 32nd question, a click split across script sessions gave the later message boxes their buttons' safe default (the click-wide limiter answers nothing), but a single session failed with "too many interactive prompts" (interaction::reserve), so a form could take its error path in one case and go on in the other. XfaHost's message box now asks only while interaction::can_ask() and otherwise gives the safe default, as the PR describes; the 32-question bound is unchanged. FormCalc's $host.messageBox goes through the same path. AcroForm app.alert keeps its own limit. Test: an_xfa_click_asks_at_most_32_questions now asserts what the script receives: 32 asked and answered Yes, the other 28 get No without being asked, and the script completes (seen failing without the fix: "too many interactive prompts"). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/tests.rs | 12 +++++++----- crates/js/src/interaction.rs | 5 +++++ crates/js/src/xfa/host.rs | 8 +++++--- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c0ee5d35da..55c7c4d85c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -10238,15 +10238,16 @@ fn an_xfa_click_is_dropped_when_the_document_changes_while_it_asks() { assert_eq!(qty(&s, id), ["7"]); } -/// A click's prompts are limited as an AcroForm script's are: past 32 the script fails, and -/// keeps what it did before, as a failing script does. +/// A click asks at most 32 questions; every later message box gets its buttons' safe default (No +/// for Yes/No) without asking, and the script goes on, as it does when the click's questions are +/// spent across its script sessions (review on #6984). #[cfg(not(target_arch = "wasm32"))] #[test] fn an_xfa_click_asks_at_most_32_questions() { use crate::js::{InteractiveEvent, Prompt}; let tpl = pdfcraft_xfa::fixtures::scripted_template().replace( r#"xfa.host.messageBox("Hello " + qty.rawValue);"#, - r#"for (var i = 0; i < 1000; i++) { if (xfa.host.messageBox("Again?", "", 2, 2) == 4) qty.rawValue = i + 1; }"#, + r#"var yes = 0; var no = 0; for (var i = 0; i < 60; i++) { var a = xfa.host.messageBox("Again?", "", 2, 2); if (a == 4) yes++; else if (a == 3) no++; } qty.rawValue = yes * 10000 + no;"#, ); let mut s = Session::new().with_clock(|| 1_700_000_000); let id = s.open("many.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).expect("opens"); @@ -10264,8 +10265,9 @@ fn an_xfa_click_asks_at_most_32_questions() { }; assert_eq!(asked, 32); let o = s.finish_javascript(p, out).unwrap(); - assert!(o.error.as_deref().is_some_and(|e| e.contains("too many interactive prompts")), "{o:?}"); - assert_eq!(qty(&s, id), ["32"]); + assert!(o.error.is_none(), "the script goes on: {o:?}"); + // 32 answered Yes; the other 28 got No without being asked. + assert_eq!(qty(&s, id), ["320028"]); } /// The 32-question limit holds for the whole click, not for each script session: a script that diff --git a/crates/js/src/interaction.rs b/crates/js/src/interaction.rs index 7f146c1e55..18fc343aa6 100644 --- a/crates/js/src/interaction.rs +++ b/crates/js/src/interaction.rs @@ -33,6 +33,11 @@ pub(crate) fn has_host() -> bool { pub(crate) fn set_host(host: Option>) { HOST.with(|h| *h.borrow_mut() = host.map(|h| (h, 0))); } +/// Whether the invocation may still ask: it has a prompt channel and has asked fewer than +/// [`MAX_PROMPTS`] questions. +pub(crate) fn can_ask() -> bool { + HOST.with(|h| h.borrow().as_ref().is_some_and(|(_, n)| *n < MAX_PROMPTS)) +} /// Charge one prompt to the invocation's budget: the channel to send it on, if the worker has one. fn reserve() -> JsResult>> { HOST.with(|h| { diff --git a/crates/js/src/xfa/host.rs b/crates/js/src/xfa/host.rs index a0521f73a2..4c21776961 100644 --- a/crates/js/src/xfa/host.rs +++ b/crates/js/src/xfa/host.rs @@ -165,8 +165,10 @@ impl XHost { /// Show message box `m` and return the button picked: the next of the event's answers /// (headless runs); past them, the user's answer when the viewer can ask (an app's button /// click: the script waits on its thread, as an AcroForm script's `app.alert` does), or - /// else the buttons' safe default. `Err`: an answer `m`'s buttons can't give, or the - /// event's prompts are spent. + /// else the buttons' safe default. Past [`crate::interaction::MAX_PROMPTS`] questions nobody + /// is asked and the safe default is given, as it is when the click's questions are spent + /// across its script sessions: a form follows the same path either way. `Err`: an answer + /// `m`'s buttons can't give. pub(crate) fn message_box(&mut self, m: Message) -> Result { // Clipped before the viewer is asked, as the effect is: the dialog shows no more than is kept. let m = Message { text: clip(m.text), title: m.title.map(clip), ..m }; @@ -178,7 +180,7 @@ impl XHost { }; let reply = match self.answers.get(at) { Some(answer) => m.buttons.reply(answer.as_deref()).ok_or_else(|| invalid(answer.as_deref()))?, - None if crate::interaction::has_host() => { + None if crate::interaction::can_ask() => { let answer = crate::interaction::ask(crate::interaction::Prompt::Alert(m.clone())).map_err(|e| e.to_string())?; m.buttons.reply(answer.as_deref()).ok_or_else(|| invalid(answer.as_deref()))? } From a840e0787c8da2f4ba83e62f0f402f8e42240f31 Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Tue, 24 Nov 2026 05:12:05 -0800 Subject: [PATCH 045/114] Keep potential covers through glyph clips --- crates/audit/src/cover.rs | 51 +++++++++++++++++++++++++--------- crates/audit/src/lib.rs | 10 ++++--- crates/audit/src/tests.rs | 27 ++++++++++++++++-- crates/edit/src/lib.rs | 4 +-- crates/edit/src/text.rs | 2 +- crates/edit/src/text/interp.rs | 7 +++++ crates/edit/src/text/lines.rs | 36 +++++++++++++++++++++--- 7 files changed, 110 insertions(+), 27 deletions(-) diff --git a/crates/audit/src/cover.rs b/crates/audit/src/cover.rs index c614bdfa3c..739d8ac302 100644 --- a/crates/audit/src/cover.rs +++ b/crates/audit/src/cover.rs @@ -9,6 +9,8 @@ //! `G`/`RG`/`K`), the line width (`w`) and what ExtGState sets of them (`gs` reading `/ca`, //! `/CA` and `/LW`), rectangular and glyph clipping, form bounds, and default-off //! optional-content groups. Rotated rectangles are conservatively bounded in user space. +//! If only the source of a glyph clip is known, the audit excludes fills of that text object +//! from its own cover findings and retains potential covers on independently drawn text. //! Form XObjects are followed read-only with a depth and decode budget. Other filled paths, //! slanted or bent strokes, shadings and patterns remain out of scope. //! @@ -20,6 +22,7 @@ //! Positions compare lexicographically in paint order. use std::collections::HashSet; +use std::ops::Range; use pdfcraft_content::{Matrix, Op, Pieces, ops}; use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object}; @@ -43,6 +46,8 @@ pub struct FilledRect { /// Paint position: `(content-stream index, operator index in the joined stream)`. /// Rectangles inside a form XObject carry the `Do` operator's position. pub pos: (usize, usize), + /// Page operators of the text object whose own glyphs this paint fills. + pub glyph_source: Option>, } #[derive(Clone, Copy)] @@ -50,7 +55,6 @@ enum Clip { Unbounded, Rect([f64; 4]), Empty, - Glyphs, } impl Clip { @@ -61,15 +65,12 @@ impl Clip { let intersection = [rect[0].max(clip[0]), rect[1].max(clip[1]), rect[2].min(clip[2]), rect[3].min(clip[3])]; (intersection[0] < intersection[2] && intersection[1] < intersection[3]).then_some(intersection) } - Self::Empty | Self::Glyphs => None, + Self::Empty => None, } } fn intersect_rect(&mut self, rect: [f64; 4]) { - // Preserve an existing glyph clip. Its shape is already narrower than a rectangle. - if !matches!(self, Self::Glyphs) { - *self = self.visible_rect(rect).map_or(Self::Empty, Self::Rect); - } + *self = self.visible_rect(rect).map_or(Self::Empty, Self::Rect); } } @@ -82,6 +83,7 @@ struct Gs { stroke_alpha: f64, clip: Clip, glyph_clip_mode: bool, + glyph_source: Option>, /// Line width, in the space the path is drawn in. width: f64, /// Line cap (`J`, `/LC`): 0 butt, 1 round, 2 projecting square. @@ -178,6 +180,7 @@ impl Default for Gs { stroke_alpha: 1.0, clip: Clip::Unbounded, glyph_clip_mode: false, + glyph_source: None, width: 1.0, cap: 0, } @@ -193,6 +196,7 @@ struct Walker<'a> { /// fails the audit. budget: DecodeBudget, off_layers: HashSet, + blank_clips: &'a HashSet, } impl<'a> Walker<'a> { @@ -209,7 +213,7 @@ impl<'a> Walker<'a> { if alpha >= 1.0 && let Some(rect) = rect.and_then(|rect| gs.clip.visible_rect(rect)) { - self.out.push(FilledRect { rect, rgb, pos }); + self.out.push(FilledRect { rect, rgb, pos, glyph_source: gs.glyph_source.clone() }); } } @@ -239,6 +243,8 @@ impl<'a> Walker<'a> { let mut multiple_subpaths = false; let mut clip_next = false; let mut glyph_clip_pending = false; + let mut glyph_only_text = false; + let mut text_start = 0; let mut hidden_depth = 0usize; for (i, op) in ops.enumerate() { self.bump()?; @@ -362,16 +368,25 @@ impl<'a> Walker<'a> { multiple_subpaths = false; } b"c" | b"v" | b"y" => path = Path::Other, - b"BT" => glyph_clip_pending = false, + b"BT" => { + glyph_clip_pending = false; + glyph_only_text = true; + text_start = i; + } b"Tr" => { if let Some(mode) = op.num(0).filter(|v| (0.0..=7.0).contains(v) && v.fract() == 0.0) { gs.glyph_clip_mode = mode >= 4.0; } } - b"Tj" | b"TJ" | b"'" | b"\"" => glyph_clip_pending |= gs.glyph_clip_mode && hidden_depth == 0, + b"Tj" | b"TJ" | b"'" | b"\"" if shows_glyphs(op) => { + glyph_clip_pending |= gs.glyph_clip_mode && (at_do.is_some() || !self.blank_clips.contains(&i)); + glyph_only_text &= gs.glyph_clip_mode; + } b"ET" => { if std::mem::take(&mut glyph_clip_pending) { - gs.clip = Clip::Glyphs; + // Without glyph outlines, retain the rectangular bound as a conservative + // estimate. Paint through the clip can still cover independently drawn text. + gs.glyph_source = (glyph_only_text && at_do.is_none()).then_some(text_start..i); } } b"BDC" => { @@ -497,7 +512,17 @@ fn ext_state(doc: &Document, resources: &Dict, name: &[u8], gs: &mut Gs) { } } -/// Only explicit default-off groups suppress covers. Other configurations and +/// Empty shows and TJ positioning adjustments contribute no outline to a text clip. +fn shows_glyphs(op: &Op) -> bool { + let nonempty = |value: &Object| matches!(value, Object::String(text) if !text.bytes.is_empty()); + match op.operands.last() { + Some(Object::Array(items)) if op.is("TJ") => items.iter().any(nonempty), + Some(value) if !op.is("TJ") => nonempty(value), + _ => false, + } +} + +/// Only explicit groups in `/D /OFF` suppress covers. `/BaseState`, `/ON` and /// optional-content membership dictionaries stay visible to the audit. fn off_layers(doc: &Document) -> HashSet { let Some(root) = doc.trailer().get(b"Root").map(|value| doc.resolve(value)) else { return HashSet::new() }; @@ -517,7 +542,7 @@ fn off_layers(doc: &Document) -> HashSet { /// state set in an earlier stream is still in force in the later ones. Any content stream that /// cannot be decoded, or content and forms that decode or enter past one page's [`DecodeBudget`] /// in all, is an audit failure, never an empty result. -pub fn filled_rects(doc: &Document, page: &Dict) -> Result, AuditError> { +pub fn filled_rects(doc: &Document, page: &Dict, blank_clips: &HashSet) -> Result, AuditError> { let resources = page.get(b"Resources").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default(); let contents: Vec = match page.get(b"Contents") { None => Vec::new(), @@ -534,7 +559,7 @@ pub fn filled_rects(doc: &Document, page: &Dict) -> Result, Audi } } let pieces = Pieces::join(&streams); - let mut w = Walker { doc, pieces: &pieces, out: Vec::new(), ops_seen: 0, budget, off_layers: off_layers(doc) }; + let mut w = Walker { doc, pieces: &pieces, out: Vec::new(), ops_seen: 0, budget, off_layers: off_layers(doc), blank_clips }; let mut gs = Gs::default(); let mut stack = Vec::new(); // Read one operator at a time: the joined stream can hold millions of them within the diff --git a/crates/audit/src/lib.rs b/crates/audit/src/lib.rs index 2cc221d562..ca0030566d 100644 --- a/crates/audit/src/lib.rs +++ b/crates/audit/src/lib.rs @@ -234,10 +234,11 @@ fn audit(doc: &Document, limits: Limits) -> Result, AuditError for (n, page) in pdfcraft_model::pages(doc).iter().enumerate() { // The glyphs themselves: `/ActualText` is the file's own claim about them, and an empty // or substitute one must not hide text a cover sits on. - let lines = pdfcraft_edit::glyph_text_lines(doc, page).map_err(|e| AuditError::Text(n, e.to_string()))?; + let mut blank_clips = std::collections::HashSet::new(); + let lines = pdfcraft_edit::glyph_text_lines_with_blank_clips(doc, page, &mut blank_clips).map_err(|e| AuditError::Text(n, e.to_string()))?; budget.start_page(&lines); // 1. Opaque rectangles (filled, or painted by a thick stroke) over extractable text. - for r in cover::filled_rects(doc, &page.dict)? { + for r in cover::filled_rects(doc, &page.dict, &blank_clips)? { if let Some(covered) = budget.hidden_text(&lines, copying, std::slice::from_ref(&r.rect), |line| hides(&r, line))? { let covered_text = budget.report_text(covered, copying)?; out.push(AuditFinding { page: n, kind: rect_kind(&r), rect: r.rect, covered_text }); @@ -282,10 +283,11 @@ fn rect_kind(rect: &cover::FilledRect) -> FindingKind { /// Does `rect` hide `line`: painted after the start of the line and over it, and white or a cover /// ([`is_cover`]). Light covers in between (table shading) are not flagged. fn hides(rect: &cover::FilledRect, line: &TextLine) -> bool { - match rect_kind(rect) { + let hides = match rect_kind(rect) { FindingKind::HiddenUnderWhite => rect.pos > line.first_paint_pos() && covers(&rect.rect, line), _ => is_cover(rect, line), - } + }; + hides && !rect.glyph_source.as_ref().is_some_and(|source| line.drawn_within(source)) } /// Does `cover` hide a substantial part of what `line` draws? Three ways, any is enough: diff --git a/crates/audit/src/tests.rs b/crates/audit/src/tests.rs index 2e5074b84a..c94b497046 100644 --- a/crates/audit/src/tests.rs +++ b/crates/audit/src/tests.rs @@ -1091,7 +1091,7 @@ fn repeated_stream_references_share_one_decode_budget() { let mut doc = Document::new_empty(); let spaces = doc.add(Stream::flate(Dict::new(), &vec![b' '; 1 << 20])); let contents: Dict = [(b"Contents".to_vec(), Object::Array(vec![Object::Ref(spaces); 300]))].into_iter().collect(); - assert!(crate::cover::filled_rects(&doc, &contents).is_err(), "repeated content streams"); + assert!(crate::cover::filled_rects(&doc, &contents, &Default::default()).is_err(), "repeated content streams"); let form_dict: Dict = [(b"Subtype".to_vec(), Object::Name(b"Form".to_vec()))].into_iter().collect(); let form = doc.add(Stream::flate(form_dict, &vec![b' '; 1 << 20])); @@ -1099,7 +1099,7 @@ fn repeated_stream_references_share_one_decode_budget() { let xobjects: Dict = [(b"X".to_vec(), Object::Ref(form))].into_iter().collect(); let resources: Dict = [(b"XObject".to_vec(), Object::Dict(xobjects))].into_iter().collect(); let page: Dict = [(b"Contents".to_vec(), Object::Ref(draws)), (b"Resources".to_vec(), Object::Dict(resources))].into_iter().collect(); - assert!(crate::cover::filled_rects(&doc, &page).is_err(), "repeated form draws"); + assert!(crate::cover::filled_rects(&doc, &page, &Default::default()).is_err(), "repeated form draws"); } #[test] @@ -1113,7 +1113,7 @@ fn form_entries_past_the_page_allowance_fail_the_audit() { let xobjects: Dict = [(b"X".to_vec(), Object::Ref(form))].into_iter().collect(); let resources: Dict = [(b"XObject".to_vec(), Object::Dict(xobjects))].into_iter().collect(); let page: Dict = [(b"Contents".to_vec(), Object::Ref(draws)), (b"Resources".to_vec(), Object::Dict(resources))].into_iter().collect(); - assert!(matches!(crate::cover::filled_rects(&doc, &page), Err(crate::AuditError::TooManyForms))); + assert!(matches!(crate::cover::filled_rects(&doc, &page, &Default::default()), Err(crate::AuditError::TooManyForms))); } /// Copying a covered line's text walks all of it, padding included, so a long padded line under @@ -1272,6 +1272,27 @@ fn text_clipping_mode_fill_is_not_reported_as_cover() { assert!(findings[0].covered_text.contains("SECRET")); } +#[test] +fn glyph_clipping_keeps_covers_over_independent_text() { + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET q BT /F1 24 Tf 7 Tr 100 700 Td (MASK) Tj ET 0 g 100 688 220 32 re f Q"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert!(findings.iter().any(|finding| finding.covered_text.contains("SECRET")), "{findings:?}"); +} + +#[test] +fn empty_glyph_shows_leave_clipping_unchanged() { + let blank = r#"BT /F1 24 Tf 7 Tr () Tj [() 120 ()] TJ () ' 0 0 () " /F1 0 Tf (TEXT) Tj ET"#; + let fill = "0 g 100 688 220 32 re f"; + let content = format!("BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET {blank} {fill}"); + let findings = audit_redactions(&open(one_page(content.as_bytes(), ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "{findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); + + let content = format!("BT /F1 24 Tf 7 Tr 100 700 Td (MASK) Tj ET {blank} {fill}"); + let findings = audit_redactions(&open(one_page(content.as_bytes(), ""))).expect("audit must run"); + assert!(findings.is_empty(), "a blank show must preserve the previous text clip: {findings:?}"); +} + #[test] fn unclosed_oc_in_form_xobject_does_not_leak_to_parent() { let mut b = Builder::new(); diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs index 886bfc3522..876df14199 100644 --- a/crates/edit/src/lib.rs +++ b/crates/edit/src/lib.rs @@ -62,8 +62,8 @@ pub mod paragraph_align; pub mod text; pub use text::{ BlockKey, BlockStyle, LineEdit, MAX_FORM_DEPTH, MAX_FORM_VISITS, RangeStyle, ReadingBlocks, RunSources, TextBlock, TextLine, TextSession, - block_overlapping, clear_block, glyph_text_lines, reading_blocks, reading_blocks_checked, replace_block, replace_line, rewrite_block, - text_blocks, text_lines, + block_overlapping, clear_block, glyph_text_lines, glyph_text_lines_with_blank_clips, reading_blocks, reading_blocks_checked, replace_block, + replace_line, rewrite_block, text_blocks, text_lines, }; pub mod printer_marks; pub use printer_marks::{PrinterMarks, add_printer_marks}; diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rs index 0bcd48cc8e..3b938878f4 100644 --- a/crates/edit/src/text.rs +++ b/crates/edit/src/text.rs @@ -64,7 +64,7 @@ pub(crate) use lines::{ ContentStream, FormBudget, Read, content_streams, content_streams_within, dict_in_place, drawn_before_damage, dropped_advances, dropped_side_effects, first_op_after_damage, form_call, joined, reopen_text_object, resource_dict, rewritten_contents, splice, }; -pub use lines::{MAX_FORM_DEPTH, MAX_FORM_VISITS, glyph_text_lines, text_lines}; +pub use lines::{MAX_FORM_DEPTH, MAX_FORM_VISITS, glyph_text_lines, glyph_text_lines_with_blank_clips, text_lines}; use lines::{page_dict, word_lines}; pub use rewrite::{LineEdit, replace_line, rewrite_block}; use rewrite::{coincident_ops, rewrite_block_from}; diff --git a/crates/edit/src/text/interp.rs b/crates/edit/src/text/interp.rs index cf9e0beef2..7ada4a5182 100644 --- a/crates/edit/src/text/interp.rs +++ b/crates/edit/src/text/interp.rs @@ -449,6 +449,8 @@ pub(super) struct Shown { pub(super) extra_ops: Vec, /// Encoded glyphs, not bytes or Unicode characters (a ligature can represent several). pub(super) glyph_count: usize, + /// A glyph has an outline, or its font could not establish that it is empty. + pub(super) may_draw_outline: bool, /// Advance in text space, including spacing and TJ adjustments. pub(super) advance: f64, pub(super) tracking: f64, @@ -806,11 +808,15 @@ fn show_text(op: &Op, i: usize, state: &mut TextRunState<'_>) -> Result<(), Edit // before may have ended in one: a justified line can be split over `TJ` and `Tj`. let mut gap_space = std::mem::take(&mut carry.gap_space); let mut glyph_count = 0_usize; + let mut may_draw_outline = false; for p in &pieces { match p { Object::String(s) => { for (code, len) in m.codes(&s.bytes) { glyph_count = glyph_count.saturating_add(1); + if (4..=7).contains(&ts.render_mode) && ts.size != 0.0 && ts.scale != 0.0 { + may_draw_outline |= m.past_allowance || m.codespaces_dropped || m.has_outline(code) != Some(false); + } let shown = m.text_of(code); let blank = m.is_space(code, len) || shown.as_deref().is_some_and(|t| !t.is_empty() && t.chars().all(char::is_whitespace)); // A space glyph right after a gap that read as a space is that space: @@ -929,6 +935,7 @@ fn show_text(op: &Op, i: usize, state: &mut TextRunState<'_>) -> Result<(), Edit op: i, extra_ops: Vec::new(), glyph_count, + may_draw_outline, // Vertical text: the TJ adjustment that undoes the run is n = -1000 y / size; the // preview divides by size × `Tz`, so `Tz` is put back here. advance: if vertical.is_some() { y_text * ts.scale } else { x_text }, diff --git a/crates/edit/src/text/lines.rs b/crates/edit/src/text/lines.rs index 43b2c84d4e..1eb35c818e 100644 --- a/crates/edit/src/text/lines.rs +++ b/crates/edit/src/text/lines.rs @@ -19,6 +19,16 @@ impl TextLine { (self.stream, self.ops.iter().min().copied().unwrap_or(0)) } + /// Whether all the line's drawing operators are inside one text object in the joined + /// page stream. A line can join runs from several text objects. + pub fn drawn_within(&self, operators: &std::ops::Range) -> bool { + if self.actual_text { + return !self.ops.is_empty() && self.ops.iter().all(|op| operators.contains(op)); + } + // Glyph shows are appended in stream order. + self.ops.first().zip(self.ops.last()).is_some_and(|(first, last)| operators.contains(first) && operators.contains(last)) + } + /// The runs of text the line joins, in content order: each run's text as its glyphs show it, /// the boxes of its words (a part of `ink`), and whether joining put a space between it and /// the run before (`text` has one there; runs closer together join with none, so one word @@ -431,13 +441,13 @@ fn fill_color(fill: &[Op]) -> [f64; 3] { /// The lines of text on a page (0-based), in content order. pub fn text_lines(doc: &Document, page: usize) -> Result, EditError> { - text_lines_in(doc, &page_dict(doc, page)?, true, false) + text_lines_in(doc, &page_dict(doc, page)?, true, false, None) } /// [`text_lines`] with every show of invisible text a line of its own, however alike its /// neighbours: an OCR layer's words, which an edit can keep or change one by one. pub(crate) fn word_lines(doc: &Document, page: usize) -> Result, EditError> { - text_lines_in(doc, &page_dict(doc, page)?, true, true) + text_lines_in(doc, &page_dict(doc, page)?, true, true, None) } /// The lines `page`'s glyphs show, in content order, without `/ActualText` replacements: what the @@ -445,12 +455,27 @@ pub(crate) fn word_lines(doc: &Document, page: usize) -> Result, E /// not trust that metadata (the redaction audit). Takes the page itself, so a caller going /// through every page doesn't walk the page tree again for each. pub fn glyph_text_lines(doc: &Document, page: &pdfcraft_model::Page) -> Result, EditError> { - text_lines_in(doc, page, false, false) + text_lines_in(doc, page, false, false, None) +} + +/// Extracts the glyph lines and records text-clipping shows whose glyphs have no outlines. +pub fn glyph_text_lines_with_blank_clips( + doc: &Document, + page: &pdfcraft_model::Page, + blank_clips: &mut std::collections::HashSet, +) -> Result, EditError> { + text_lines_in(doc, page, false, false, Some(blank_clips)) } /// [`text_lines`] of `p`; with `actual_text`, `/ActualText` replaces the glyphs it spans, and with /// `invisible_apart`, no show of invisible text joins the one before it. -fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool, invisible_apart: bool) -> Result, EditError> { +fn text_lines_in( + doc: &Document, + p: &pdfcraft_model::Page, + actual_text: bool, + invisible_apart: bool, + blank_clips: Option<&mut std::collections::HashSet>, +) -> Result, EditError> { let res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default(); let mut cache = HashMap::new(); let mut lines: Vec = Vec::new(); @@ -461,6 +486,9 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool, in let ops = pieces.parse().ops; let properties = res.get(b"Properties").and_then(|o| doc.dict(o)).unwrap_or_default(); let shown = interpret(doc, &ops, &res, &mut cache, &mut carry, None, actual_text.then_some(&properties))?; + if let Some(blank_clips) = blank_clips { + blank_clips.extend(shown.iter().filter(|s| (4..=7).contains(&s.state.render_mode) && !s.may_draw_outline).map(|s| s.op)); + } let mut last: Option<(usize, Pen)> = None; // the stream piece and where its last run ended for mut s in shown { // A single RTL glyph's ActualText (e.g. lam-alef) is an inline ligature, not a From 843da52ceccc7e9cf5b1016ced549ca11a724b43 Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Tue, 24 Nov 2026 17:41:11 -0800 Subject: [PATCH 046/114] Distinguish painted glyphs from clip-only text in the audit --- crates/audit/src/cover.rs | 29 +++++++++++++++++++++-------- crates/audit/src/lib.rs | 9 +++++++-- crates/audit/src/tests.rs | 17 +++++++++++++++++ 3 files changed, 45 insertions(+), 10 deletions(-) diff --git a/crates/audit/src/cover.rs b/crates/audit/src/cover.rs index 739d8ac302..9bda6be30c 100644 --- a/crates/audit/src/cover.rs +++ b/crates/audit/src/cover.rs @@ -47,7 +47,13 @@ pub struct FilledRect { /// Rectangles inside a form XObject carry the `Do` operator's position. pub pos: (usize, usize), /// Page operators of the text object whose own glyphs this paint fills. - pub glyph_source: Option>, + pub glyph_source: Option, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct GlyphSource { + pub operators: Range, + pub painted: bool, } #[derive(Clone, Copy)] @@ -82,8 +88,8 @@ struct Gs { stroke: [f64; 3], stroke_alpha: f64, clip: Clip, - glyph_clip_mode: bool, - glyph_source: Option>, + text_render_mode: u8, + glyph_source: Option, /// Line width, in the space the path is drawn in. width: f64, /// Line cap (`J`, `/LC`): 0 butt, 1 round, 2 projecting square. @@ -179,7 +185,7 @@ impl Default for Gs { stroke: [0.0, 0.0, 0.0], stroke_alpha: 1.0, clip: Clip::Unbounded, - glyph_clip_mode: false, + text_render_mode: 0, glyph_source: None, width: 1.0, cap: 0, @@ -244,6 +250,7 @@ impl<'a> Walker<'a> { let mut clip_next = false; let mut glyph_clip_pending = false; let mut glyph_only_text = false; + let mut glyph_source_painted = false; let mut text_start = 0; let mut hidden_depth = 0usize; for (i, op) in ops.enumerate() { @@ -371,22 +378,28 @@ impl<'a> Walker<'a> { b"BT" => { glyph_clip_pending = false; glyph_only_text = true; + glyph_source_painted = false; text_start = i; } b"Tr" => { if let Some(mode) = op.num(0).filter(|v| (0.0..=7.0).contains(v) && v.fract() == 0.0) { - gs.glyph_clip_mode = mode >= 4.0; + gs.text_render_mode = mode as u8; } } b"Tj" | b"TJ" | b"'" | b"\"" if shows_glyphs(op) => { - glyph_clip_pending |= gs.glyph_clip_mode && (at_do.is_some() || !self.blank_clips.contains(&i)); - glyph_only_text &= gs.glyph_clip_mode; + let clips = gs.text_render_mode >= 4; + glyph_clip_pending |= clips && (at_do.is_some() || !self.blank_clips.contains(&i)); + glyph_only_text &= clips; + glyph_source_painted |= hidden_depth == 0 + && ((matches!(gs.text_render_mode, 4 | 6) && gs.alpha > 0.0) + || (matches!(gs.text_render_mode, 5 | 6) && gs.stroke_alpha > 0.0)); } b"ET" => { if std::mem::take(&mut glyph_clip_pending) { // Without glyph outlines, retain the rectangular bound as a conservative // estimate. Paint through the clip can still cover independently drawn text. - gs.glyph_source = (glyph_only_text && at_do.is_none()).then_some(text_start..i); + gs.glyph_source = + (glyph_only_text && at_do.is_none()).then_some(GlyphSource { operators: text_start..i, painted: glyph_source_painted }); } } b"BDC" => { diff --git a/crates/audit/src/lib.rs b/crates/audit/src/lib.rs index ca0030566d..de29fb27a6 100644 --- a/crates/audit/src/lib.rs +++ b/crates/audit/src/lib.rs @@ -283,11 +283,16 @@ fn rect_kind(rect: &cover::FilledRect) -> FindingKind { /// Does `rect` hide `line`: painted after the start of the line and over it, and white or a cover /// ([`is_cover`]). Light covers in between (table shading) are not flagged. fn hides(rect: &cover::FilledRect, line: &TextLine) -> bool { - let hides = match rect_kind(rect) { + let kind = rect_kind(rect); + let hides = match kind { FindingKind::HiddenUnderWhite => rect.pos > line.first_paint_pos() && covers(&rect.rect, line), _ => is_cover(rect, line), }; - hides && !rect.glyph_source.as_ref().is_some_and(|source| line.drawn_within(source)) + hides + && !rect + .glyph_source + .as_ref() + .is_some_and(|source| line.drawn_within(&source.operators) && !(source.painted && kind == FindingKind::HiddenUnderWhite)) } /// Does `cover` hide a substantial part of what `line` draws? Three ways, any is enough: diff --git a/crates/audit/src/tests.rs b/crates/audit/src/tests.rs index c94b497046..c7818365a6 100644 --- a/crates/audit/src/tests.rs +++ b/crates/audit/src/tests.rs @@ -1272,6 +1272,23 @@ fn text_clipping_mode_fill_is_not_reported_as_cover() { assert!(findings[0].covered_text.contains("SECRET")); } +#[test] +fn white_cover_distinguishes_painted_and_clip_only_glyph_sources() { + let doc = open(one_page(b"BT /F1 24 Tf 100 700 Td (Sample) Tj ET", "")); + let lines = pdfcraft_edit::glyph_text_lines(&doc, &pdfcraft_model::pages(&doc)[0]).expect("text"); + let line = &lines[0]; + let mut cover = crate::cover::FilledRect { + rect: line.rect, + rgb: [1.0; 3], + pos: (0, 10), + glyph_source: Some(crate::cover::GlyphSource { operators: 0..5, painted: false }), + }; + + assert!(!crate::hides(&cover, line)); + cover.glyph_source.as_mut().unwrap().painted = true; + assert!(crate::hides(&cover, line)); +} + #[test] fn glyph_clipping_keeps_covers_over_independent_text() { let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET q BT /F1 24 Tf 7 Tr 100 700 Td (MASK) Tj ET 0 g 100 688 220 32 re f Q"; From 8e52c9c3c37e5e5b2e9a7b96d6001b8599739f19 Mon Sep 17 00:00:00 2001 From: Thorsten Hirsch Date: Wed, 14 Oct 2026 19:45:09 +0200 Subject: [PATCH 047/114] M9: opt-in trust lists (a file of CA certificates, such as the EU Trusted Lists) A signer can be trusted through a list of CA certificates the user loads from a file: `sign_trust {"eu_trusted_list": ""}`, DER one after the other or PEM. Refs #775, #87, #824: the PDF attached to #775, a CAdES signature under a qualified service that Acrobat validates, is Unknown without the list and Valid with it. - The list is off until loaded, nothing is embedded, and it is kept apart from the user's own trusted certificates (`TrustStore::lists`). The details name the list that vouched. Chains through it still need CA certificates all the way (#620) and the signer's own certificate is held to #749's purpose rules. - A list vouches for signers, never for a time-stamp authority: a CA trusted to issue signing certificates is not thereby a source of trusted time, so trusted time still comes from the user's own certificates. - A cut-short or damaged list is refused instead of loading as a smaller one, and PEM that starts with text beginning with a "0" (DER's first byte) is read as PEM, in `x509::load_certificates` too. - `sign_trust` reads and checks every argument before it changes anything and revalidates the open documents once (`Session::update_trust`); the list path stays inside `--root` and the read is bounded. - `build_chain` takes its pool as an iterator, so a list's certificates are not copied for every signature. `TrustStore` gains `lists`: struct literals need `..TrustStore::default()`. Tests that fail without their change: the damaged-list and PEM cases (`trust.rs`), a list that holds a time-stamp authority's certificate not making its time trusted (`chain.rs`, with the shape of #775), and a bad `sign_trust` argument changing nothing (`automation.rs`). Co-Authored-By: Claude Sonnet 5.5 --- crates/automation/src/signing.rs | 44 +++++++- crates/automation/src/tools.rs | 4 +- crates/automation/tests/it/automation.rs | 53 ++++++++++ crates/engine/src/session.rs | 6 +- crates/engine/src/session/save.rs | 37 ++++++- crates/engine/src/tests.rs | 22 ++++ crates/sign/README.md | 9 ++ crates/sign/src/lib.rs | 5 +- crates/sign/src/pdf.rs | 2 +- crates/sign/src/pdf/types.rs | 42 +++++++- crates/sign/src/pdf/validate.rs | 12 ++- crates/sign/src/trust.rs | 125 +++++++++++++++++++++++ crates/sign/src/x509.rs | 18 +++- crates/sign/tests/it/chain.rs | 101 +++++++++++++++++- crates/sign/tests/it/pdf.rs | 72 +++++++------ parity/acrobat-features.toml | 8 +- 16 files changed, 496 insertions(+), 64 deletions(-) create mode 100644 crates/sign/src/trust.rs diff --git a/crates/automation/src/signing.rs b/crates/automation/src/signing.rs index f2b583c070..40fabc1e71 100644 --- a/crates/automation/src/signing.rs +++ b/crates/automation/src/signing.rs @@ -2,6 +2,8 @@ //! document, and manage trusted certificates. Rectangles are points from the top-left of the //! displayed page. +use std::io::Read; + use pdfcraft_engine::js::SignEvent; use pdfcraft_engine::sign::{self, Certificate, DigitalId, Modification, Name, PrivateKey}; use pdfcraft_engine::{SignOptions, SignatureInfo, SignatureStatus}; @@ -9,6 +11,9 @@ use serde_json::{Value, json}; use crate::{Args, Automation, Result, ToolError, failed, write_atomic}; +/// The name the EU Trusted List file is loaded under (`sign_trust eu_trusted_list`). +const EU_LIST: &str = "EU Trusted List"; + fn bad(m: impl Into) -> ToolError { ToolError::InvalidArgs(m.into()) } @@ -377,8 +382,10 @@ impl Automation { } pub(crate) fn sign_trust(&mut self, a: &Args) -> Result { - let mut certs: Vec = - if a.opt_bool("clear")?.unwrap_or(false) { Vec::new() } else { self.session.trusted_certificates().to_vec() }; + // Every argument is read and checked first, so a bad one changes nothing, and the changes + // are applied together: the open documents are revalidated once, not once per change. + let clear = a.opt_bool("clear")?.unwrap_or(false); + let mut certs: Vec = if clear { Vec::new() } else { self.session.trusted_certificates().to_vec() }; // Which certificates are already in, by their bytes: a set, so a bundle of many distinct // certificates isn't compared against every one before it. let mut known: std::collections::HashSet> = certs.iter().map(|c| c.raw.clone()).collect(); @@ -391,6 +398,7 @@ impl Automation { .map(|p| p.as_str().map(str::to_string).ok_or_else(|| bad("paths must be strings"))) .collect::>()?, }; + let certs_changed = clear || !paths.is_empty(); for p in paths { let path = self.resolve(&p, false)?; let bytes = crate::read_input(&path)?; @@ -407,7 +415,35 @@ impl Automation { } } } - self.session.set_trusted_certificates(certs); - Ok(json!({ "trusted": self.session.trusted_certificates().iter().map(cert_json).collect::>() })) + // The trust list, off until asked for. `None`: not mentioned, left alone. + let eu_list = match a.get("eu_trusted_list") { + None => None, + Some(Value::Bool(false) | Value::Null) => Some(None), + Some(Value::String(p)) => { + let path = self.resolve(p, false)?; + // One byte more than allowed is read, so an oversize file (or one that grows, or a + // device) is refused by `from_bytes` instead of being read whole. + let mut bytes = Vec::new(); + std::fs::File::open(&path) + .and_then(|f| f.take(sign::trust::MAX_LIST_BYTES as u64 + 1).read_to_end(&mut bytes)) + .map_err(|e| failed(format!("{}: {e}", path.display())))?; + Some(Some(sign::trust::TrustList::from_bytes(EU_LIST, &bytes).map_err(failed)?)) + } + Some(_) => return Err(bad("eu_trusted_list must be the path of a trust list file, or false")), + }; + if certs_changed || eu_list.is_some() { + self.session.update_trust(|trust| { + if certs_changed { + trust.certs = certs; + } + if let Some(list) = eu_list { + trust.set_list(EU_LIST, list); + } + }); + } + Ok(json!({ + "trusted": self.session.trusted_certificates().iter().map(cert_json).collect::>(), + "trust_lists": self.session.trust_lists().iter().map(|l| json!({ "name": l.name, "certificates": l.certs.len() })).collect::>(), + })) } } diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index b9da1dbed5..36c4e98884 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -1086,8 +1086,8 @@ pub fn tools() -> Vec { }), &["doc", "id", "out"], )), - t("sign_trust", "Trust certificates", "Add certificates (.cer/.crt/.pem/.der, a .p7b/.p7c bundle, or the certificates in a .p12 with `password`) to the trusted certificates used to validate signatures, or clear the list (clear: true). Every open document is revalidated. Returns the trusted list.").with(schema( - json!({ "paths": { "type": "array", "items": { "type": "string" } }, "password": { "type": "string" }, "clear": { "type": "boolean" } }), + t("sign_trust", "Trust certificates", "Add certificates (.cer/.crt/.pem/.der, a .p7b/.p7c bundle, or the certificates in a .p12 with `password`) to the trusted certificates used to validate signatures, or clear the list (clear: true). `eu_trusted_list` loads a trust list kept apart from them, off until asked for: the path of a file of CA certificates (DER one after the other, or PEM; the EU Trusted Lists' qualified CAs, say), whose CAs may vouch for signers but never for a time-stamp authority; false removes it. The changes of one call are applied together, or not at all if an argument is bad, and every open document is revalidated once. Returns the trusted list and the loaded trust lists.").with(schema( + json!({ "paths": { "type": "array", "items": { "type": "string" } }, "password": { "type": "string" }, "clear": { "type": "boolean" }, "eu_trusted_list": { "type": ["string", "boolean"] } }), &[], )), t("comment_mark", "Mark a comment with a checkmark", "Mark or unmark a comment with a checkmark (Acrobat: Mark with checkmark), recorded as a private reply. Undoable.").with(schema( diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index f1ccd7ea73..50a92f822b 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -8899,6 +8899,59 @@ fn optimizing_discards_an_embedded_search_index_through_tools() { assert_eq!(piece_info("small.pdf"), ["Illustrator"]); } +#[test] +fn a_trust_list_is_off_until_loaded_through_sign_trust() { + let dir = workdir("trust_list"); + let mut a = auto(&dir); + ok(&mut a, "sign_id_create", json!({ "name": "Ada Lovelace", "country": "GB", "key": "p256", "password": "secret12", "path": "ada.p12" })); + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "sign_document", json!({ "doc": doc, "id": "ada.p12", "password": "secret12", "out": "signed.pdf" })); + let status = |a: &mut Automation| ok(a, "sign_list", json!({ "doc": doc }))["signatures"][0]["status"].as_str().unwrap().to_string(); + assert_eq!(status(&mut a), "unknown", "nothing trusted by default"); + + // Default: no list. + let t = ok(&mut a, "sign_trust", json!({})); + assert_eq!(t["trust_lists"].as_array().map(Vec::len), Some(0)); + + // A trust list file (the certificate as DER), loaded by path. + let ada = pdfcraft_engine::sign::pkcs12::open(&std::fs::read(dir.join("ada.p12")).unwrap(), "secret12").unwrap(); + std::fs::write(dir.join("list.der"), &ada.certificate.raw).unwrap(); + let t = ok(&mut a, "sign_trust", json!({ "eu_trusted_list": "list.der" })); + assert_eq!(t["trust_lists"][0]["name"], "EU Trusted List"); + assert_eq!(t["trust_lists"][0]["certificates"], 1); + assert_eq!(t["trusted"].as_array().unwrap().len(), 0, "the list is kept apart from the user's certificates"); + assert_eq!(status(&mut a), "valid"); + // Bad input is refused and leaves the list as it was. + std::fs::write(dir.join("junk.der"), b"not certificates").unwrap(); + assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "junk.der" })), Err(ToolError::Failed(_)))); + assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "missing.der" })), Err(ToolError::Failed(_)))); + // A file over the size limit (sparse, so cheap) is refused without being read whole. + let big = std::fs::File::create(dir.join("big.der")).unwrap(); + big.set_len(pdfcraft_engine::sign::trust::MAX_LIST_BYTES as u64 + 1).unwrap(); + assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "big.der" })), Err(ToolError::Failed(_)))); + assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": 5 })), Err(ToolError::InvalidArgs(_)))); + assert!(a.call("sign_trust", &json!({ "eu_trusted_list": "../outside.der" })).is_err(), "paths stay inside the root"); + assert_eq!(status(&mut a), "valid"); + // Removing it makes the signer unknown again. + assert_eq!(ok(&mut a, "sign_trust", json!({ "eu_trusted_list": false }))["trust_lists"].as_array().map(Vec::len), Some(0)); + assert_eq!(status(&mut a), "unknown"); + + // One call can change everything at once (and revalidates once). + let t = ok(&mut a, "sign_trust", json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": "list.der" })); + assert_eq!((t["trusted"].as_array().map(Vec::len), t["trust_lists"].as_array().map(Vec::len)), (Some(1), Some(1))); + // A bad argument changes nothing, not even what came before it in the same call. + ok(&mut a, "sign_trust", json!({ "clear": true, "eu_trusted_list": false })); + for bad in [ + json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": "junk.der" }), + json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": 5 }), + ] { + assert!(a.call("sign_trust", &bad).is_err(), "{bad}"); + let t = ok(&mut a, "sign_trust", json!({})); + assert_eq!((t["trusted"].as_array().map(Vec::len), t["trust_lists"].as_array().map(Vec::len)), (Some(0), Some(0)), "{bad}"); + } + assert_eq!(status(&mut a), "unknown"); +} + #[test] fn optimizing_through_tools() { let dir = workdir("optimize"); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 8b084c728b..0b175891d6 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -35,10 +35,14 @@ pub struct Session { /// injected time AS local time and zeroes the zone, so injecting only it leaves either the /// local dates or the UTC ones wrong by the zone's offset. utc_offset: Option i64>, - /// Certificates trusted for signing (Acrobat: Trusted Certificates). + /// What is trusted for signing: the user's certificates (Acrobat: Trusted Certificates) and the + /// trust lists they loaded. pub(crate) trust: Arc, /// The words signature status layers are drawn with, in the interface language. pub(crate) captions: Arc, + /// How often every open document's signatures were validated again after a trust change. + #[cfg(test)] + pub(crate) revalidations: usize, /// Preferences ▸ JavaScript ▸ Enable Acrobat JavaScript, inverted (on by default). pub(crate) js_off: bool, /// Preferences ▸ Date format, when not the default (see [`dates`]). diff --git a/crates/engine/src/session/save.rs b/crates/engine/src/session/save.rs index a8770bc007..1de07acc6b 100644 --- a/crates/engine/src/session/save.rs +++ b/crates/engine/src/session/save.rs @@ -252,11 +252,40 @@ impl Session { &self.trust.certs } - /// Replace the trusted certificates, revalidate every open document's signatures, - /// and rebuild its display copy and renderer to match (working file untouched, - /// generation/dirty unchanged: trust alone is not an edit). + /// Change the trust store, revalidate every open document's signatures, and rebuild its + /// display copy and renderer to match (working file untouched, generation/dirty unchanged: + /// trust alone is not an edit). This happens once, however many changes `change` makes: + /// revalidating runs chain building and signature verification for every signature, against + /// every certificate of every trust list. + pub fn update_trust(&mut self, change: impl FnOnce(&mut TrustStore)) { + let mut trust = (*self.trust).clone(); + change(&mut trust); + self.trust = Arc::new(trust); + self.revalidate_signatures(); + } + + /// Replace the trusted certificates (see [`Session::update_trust`]). pub fn set_trusted_certificates(&mut self, certs: Vec) { - self.trust = Arc::new(TrustStore { certs }); + self.update_trust(|trust| trust.certs = certs); + } + + /// The trust lists the user loaded (e.g. the EU Trusted Lists' qualified CAs), none by default. + /// They are not part of [`Session::trusted_certificates`]. + pub fn trust_lists(&self) -> &[pdfcraft_sign::trust::TrustList] { + &self.trust.lists + } + + /// Load `list` (replacing a list of the same name), or with `None` remove the list called + /// `name`, and revalidate every open document. + pub fn set_trust_list(&mut self, name: &str, list: Option) { + self.update_trust(|trust| trust.set_list(name, list)); + } + + fn revalidate_signatures(&mut self) { + #[cfg(test)] + { + self.revalidations += 1; + } for doc in &mut self.docs { Self::revalidate(doc, self.trust.clone()); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 13696f531b..b7098e86a5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5798,6 +5798,28 @@ fn reading_colors_set_and_invalidated() { assert!(!s.set_reading_colors(DocId(u64::MAX), ReadingColors::WHITE_ON_BLACK)); } +#[test] +fn several_trust_changes_revalidate_the_open_documents_once() { + let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap(); + let cert = sign::pkcs12::open(&p12, "test").unwrap().certificate; + let mut s = Session::default(); + // Each setter changes one thing and revalidates. + s.set_trusted_certificates(vec![cert.clone()]); + s.set_trusted_certificates(Vec::new()); + assert_eq!(s.revalidations, 2); + // One `update_trust` changes any number of things and revalidates once. + let list = sign::trust::TrustList::from_bytes("Test list", &cert.raw).unwrap(); + s.update_trust(|trust| { + trust.certs = vec![cert.clone()]; + trust.set_list("Test list", Some(list)); + }); + assert_eq!(s.revalidations, 3); + assert_eq!((s.trusted_certificates().len(), s.trust_lists().len()), (1, 1)); + // Replacing a list by name, and removing it. + s.set_trust_list("Test list", None); + assert!(s.trust_lists().is_empty()); +} + #[test] fn signing_saving_trusting_and_commenting_afterwards() { let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap(); diff --git a/crates/sign/README.md b/crates/sign/README.md index a5289cbe30..c41d66eaf0 100644 --- a/crates/sign/README.md +++ b/crates/sign/README.md @@ -114,6 +114,15 @@ needs a prompt to open is listed and asks at signing (issue #179). - **Weak algorithms still validate, and say so.** SHA-1 and RIPEMD-160 signatures are common in documents signed years ago, so they validate (new signatures never use SHA-1), but the signature's details say that the algorithm is weak and shouldn't be relied on. +- **Trust is the user's decision.** Only the user's own list (`TrustStore::certs`) is trusted by + default. A trust list the user loads from a file (`sign_trust eu_trusted_list`, the EU Trusted + Lists' qualified CAs, say) is kept apart from it (`TrustStore::lists`), off until loaded, and + named in the details when it vouches. Nothing of the kind is embedded. A list vouches for + signers, never for a time-stamp authority: trusted time comes from the user's own certificates. +- **Not Adobe's list.** Adobe's AATL is not used: Adobe-authored data outside the closed list in + AGENTS.md §1.1 needs the owner's explicit approval, and the EU Trusted Lists (and, planned, the + operating system's store) cover the same ground. A signer that chains only to an AATL root stays + "unknown" until the user trusts that root. - **Validation algorithms:** digests SHA-1, SHA-224/256/384/512, SHA-512/224, SHA-512/256, SHA3-224/256/384/512 and RIPEMD-160. RSA PKCS #1 v1.5 and RSASSA-PSS (the hash, MGF1 hash and salt length the signature declares), ECDSA on P-256, P-384, P-521, brainpoolP256r1, P384r1 and diff --git a/crates/sign/src/lib.rs b/crates/sign/src/lib.rs index a34c1f2f1c..94e3e1d259 100644 --- a/crates/sign/src/lib.rs +++ b/crates/sign/src/lib.rs @@ -21,6 +21,7 @@ pub mod pkcs12; pub mod revocation; pub mod status_layers; pub mod timestamp; +pub mod trust; #[cfg(target_os = "windows")] pub mod windows; pub mod x509; @@ -29,8 +30,8 @@ pub use der::Time; pub use graphic::Graphic; pub use keys::{DigestAlg, PrivateKey, PublicKey}; pub use pdf::{ - Appearance, AppearanceLabels, Detail, DigestCache, Fill, Modification, SignOptions, SignatureInfo, Status, TrustStore, WORDINGS, Words, - has_signatures, in_english, kind, list as signatures, sign, sign_with_timestamp, timestamp_document, validate, + Appearance, AppearanceLabels, Detail, DigestCache, Fill, Modification, SignOptions, SignatureInfo, Status, TrustSource, TrustStore, WORDINGS, + Words, has_signatures, in_english, kind, list as signatures, sign, sign_with_timestamp, timestamp_document, validate, }; pub use pkcs12::DigitalId; pub use status_layers::{StatusCaptions, has_status_layers, show_status_layers, status_rgb}; diff --git a/crates/sign/src/pdf.rs b/crates/sign/src/pdf.rs index a491f15054..8e5206198b 100644 --- a/crates/sign/src/pdf.rs +++ b/crates/sign/src/pdf.rs @@ -40,7 +40,7 @@ pub use listing::{DigestCache, list, list_cached}; pub(crate) use listing::{walk_sig_fields, widget_shown}; pub(crate) use signing::fmt; pub use signing::{Appearance, AppearanceLabels, SignOptions, display_date, has_signatures, sign, sign_with_timestamp, timestamp_document}; -pub use types::{Detail, Fill, Modification, Status, TrustStore, WORDINGS, Words, in_english, kind}; +pub use types::{Detail, Fill, Modification, Status, TrustSource, TrustStore, WORDINGS, Words, in_english, kind}; pub(crate) use validate::signature_contents; pub use validate::validate; #[cfg(test)] diff --git a/crates/sign/src/pdf/types.rs b/crates/sign/src/pdf/types.rs index 5691761d13..5ee8a0210c 100644 --- a/crates/sign/src/pdf/types.rs +++ b/crates/sign/src/pdf/types.rs @@ -1,12 +1,46 @@ use super::Certificate; -/// Certificates the user trusts for signing (Acrobat: Trusted Certificates). +/// Certificates trusted for signing (Acrobat: Trusted Certificates). Only `certs`, the user's own +/// list, is trusted by default; a trust list has to be loaded. #[derive(Clone, Debug, Default)] pub struct TrustStore { pub certs: Vec, + /// Lists of CA certificates the user loaded (e.g. the EU Trusted Lists' qualified CAs). They + /// vouch for signers, never for a time-stamp authority: trusted time comes from `certs` alone. + pub lists: Vec, +} + +/// Why a certificate in a chain is trusted. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum TrustSource { + /// The user's own list of trusted certificates. + User, + /// The named list the user loaded. + List(String), } impl TrustStore { + /// Load `list`, replacing a list of the same name, or with `None` remove the list `name`. + pub fn set_list(&mut self, name: &str, list: Option) { + self.lists.retain(|l| l.name != name); + self.lists.extend(list); + } + + /// Every certificate that can anchor a signer's chain: the user's, then the loaded lists'. + pub(super) fn anchors(&self) -> impl Iterator + Clone { + self.certs.iter().chain(self.lists.iter().flat_map(|l| l.certs.iter())) + } + + /// What makes `c` trusted to vouch for a signer, if anything. The user's own list wins. + pub fn source_of(&self, c: &Certificate) -> Option { + if self.trusts(c) { + Some(TrustSource::User) + } else { + self.lists.iter().find(|l| l.certs.iter().any(|t| t.raw == c.raw)).map(|l| TrustSource::List(l.name.clone())) + } + } + + /// Whether the user's own list holds `c`. Only that vouches for a time-stamp authority. pub(super) fn trusts(&self, c: &Certificate) -> bool { self.certs.iter().any(|t| t.raw == c.raw) } @@ -92,8 +126,9 @@ pub enum Fill { /// A value out of the signature itself — a time, the evidence a revocation came from — written /// as it stands, the way a certificate's name or date is. Value(String), - /// Two certificates' own names, for the wording that says one was not used to vouch for the - /// other. They go in the order the wording puts its two holes in, which a language may reverse. + /// Two names, for the wording with two holes: that one certificate was not used to vouch for + /// another, or which trust list vouched through which certificate. They go in the order the + /// wording puts its two holes in, which a language may reverse. Names(String, String), } @@ -199,6 +234,7 @@ pub const WORDINGS: &[&str] = &[ "The certificate of {} was not valid at the time of signing, so it is not used to vouch for {}.", "The signer's identity is unknown because it has not been included in your list of trusted certificates and none of its parent certificates are trusted certificates.", "The signer's identity is valid.", + "Its certificate chains to {} in the trust list “{}”.", "The signature includes an embedded timestamp.", "Signing time is from the clock on the signer's computer.", // What the signature's own timestamp token proves, if it carries one. diff --git a/crates/sign/src/pdf/validate.rs b/crates/sign/src/pdf/validate.rs index 32874b81c8..148580294c 100644 --- a/crates/sign/src/pdf/validate.rs +++ b/crates/sign/src/pdf/validate.rs @@ -337,13 +337,13 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu let SignatureValidation { doc, bytes, trust, info, cache, .. } = context; let VerifiedSignature { covered, certificate: cert, embedded, cms_time, unverified_time } = verified; info.signing_time = cms_time.or_else(|| info.date.as_deref().and_then(Time::from_pdf)); - let mut pool = embedded.to_vec(); - pool.extend(trust.certs.iter().cloned()); // The time the chain is judged at: trusted timestamp, else the signer's claimed time. let at = info.timestamp_time.or(info.signing_time); - let (chain, refused) = build_chain_noted(&cert, &pool, at); + let (chain, refused) = build_chain_noted(&cert, embedded.iter().chain(trust.anchors()), at); let chain: Vec = chain.into_iter().cloned().collect(); - let trusted = chain.iter().any(|c| trust.trusts(c)); + // The first trusted certificate going up the chain, and what makes it trusted. + let anchor = chain.iter().find_map(|c| trust.source_of(c).map(|s| (c.display_name(), s))); + let trusted = anchor.is_some(); info.chain = chain; info.certificate = Some(cert.clone()); if let Some(why) = refused @@ -474,6 +474,10 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu } } else { info.details.push(Detail::plain("The signer's identity is valid.")); + // Which list vouched, when one did: the user's own list is the plain case and says nothing. + if let Some((root, TrustSource::List(list))) = anchor { + info.details.push(Detail::of("Its certificate chains to {} in the trust list “{}”.", Fill::Names(root, list))); + } if !problems && !revoked { info.status = Status::Valid; } diff --git a/crates/sign/src/trust.rs b/crates/sign/src/trust.rs new file mode 100644 index 0000000000..48661f2dde --- /dev/null +++ b/crates/sign/src/trust.rs @@ -0,0 +1,125 @@ +//! Trust lists: sets of CA certificates the user loads from a file, kept apart from the +//! certificates they trust themselves. +//! +//! Nothing here is trusted unless the user loads it (`TrustStore::lists`): which authorities a PDF +//! reader vouches for is the user's decision, not ours, so no list is embedded in PdfCraft. The +//! first intended source is the EU Trusted Lists' qualified CA services. Chain building +//! ([`crate::x509::build_chain`]) still applies to a list: a certificate in it only vouches for what +//! a chain of CA certificates under it leads to. +//! +//! A list vouches for signers. It never vouches for a time-stamp authority: a CA that is trusted +//! to issue signing certificates is not thereby a source of trusted time, so trusted time still +//! comes only from the user's own certificates. +//! +//! Adobe's AATL is not used in any form: Adobe-authored data outside the closed list in AGENTS.md §1.1 +//! needs the owner's explicit approval, and the EU Trusted Lists cover the same ground. + +use std::sync::Arc; + +use crate::SignError; +use crate::der::Tlv; +use crate::x509::Certificate; + +/// Certificates as DER one after the other. A certificate that doesn't parse (a key type PdfCraft +/// doesn't read, say) is skipped. Bytes that aren't a DER element at all, as in a file cut short, +/// are an error, so a damaged list doesn't load as a smaller one without a word. +fn parse_concatenated(mut rest: &[u8]) -> Result, SignError> { + let mut out = Vec::new(); + while !rest.iter().all(u8::is_ascii_whitespace) { + let Ok((t, r)) = Tlv::parse(rest) else { + return Err(SignError::Malformed(format!("the trust list is damaged after {} certificates ({} bytes left)", out.len(), rest.len()))); + }; + if let Ok(c) = Certificate::parse(t.raw) { + out.push(c); + } + rest = r; + } + Ok(out) +} + +/// The most a list file may hold: far above the roughly 1.5 MB of the EU qualified CAs. +pub const MAX_LIST_BYTES: usize = 32 << 20; + +/// A named set of trusted CA certificates the user loaded from a file, e.g. "EU Trusted List". +#[derive(Clone, Debug)] +pub struct TrustList { + pub name: String, + pub certs: Arc>, +} + +impl TrustList { + /// A list from a file's bytes: certificates as DER one after the other, or a PEM bundle. + /// Certificates that don't parse are skipped; a file with none, a damaged one, or one over + /// [`MAX_LIST_BYTES`], is an error. + pub fn from_bytes(name: &str, bytes: &[u8]) -> Result { + if bytes.len() > MAX_LIST_BYTES { + return Err(SignError::Malformed(format!("trust list over {} MiB", MAX_LIST_BYTES >> 20))); + } + let mut certs = if bytes.first() == Some(&0x30) && !crate::x509::is_pem(bytes) { + parse_concatenated(bytes)? + } else { + crate::x509::load_certificates(bytes)? + }; + let mut seen = std::collections::HashSet::new(); + certs.retain(|c| seen.insert(c.raw.clone())); + if certs.is_empty() { + return Err(SignError::Malformed("no certificates in the trust list".into())); + } + Ok(TrustList { name: name.to_string(), certs: Arc::new(certs) }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A few self-made certificates to load: the lists are tested without any real CA's data. + fn certificates(n: usize) -> Vec> { + (0..n) + .map(|i| { + let key = crate::PrivateKey::generate_p256().unwrap(); + let name = crate::x509::Name::build(&format!("List Test {i}"), "", "Trust Tests", "", "US"); + let alg = key.preferred_digest(); + let sig_alg = key.signature_algorithm(alg); + let tbs = crate::der::seq(&[ + &crate::der::uint(&[1 + i as u8]), + &sig_alg, + &name.raw, + &crate::der::seq(&[ + &crate::der::Time { year: 2020, month: 1, day: 1, hour: 0, minute: 0, second: 0 }.encode(), + &crate::der::Time { year: 2040, month: 1, day: 1, hour: 0, minute: 0, second: 0 }.encode(), + ]), + &name.raw, + &key.public_key().spki(), + ]); + let signature = key.sign(alg, &tbs).unwrap(); + crate::der::seq(&[&tbs, &sig_alg, &crate::der::bit_string(&signature)]) + }) + .collect() + } + + #[test] + fn a_list_reads_concatenated_der_and_rejects_garbage() { + let certs = certificates(3); + let file = certs.concat(); + let list = TrustList::from_bytes("Test list", &file).unwrap(); + assert_eq!((list.name.as_str(), list.certs.len()), ("Test list", 3)); + // The same as a PEM bundle. + let pem: String = list.certs.iter().map(crate::x509::to_pem).collect(); + assert_eq!(TrustList::from_bytes("pem", pem.as_bytes()).unwrap().certs.len(), 3); + assert!(TrustList::from_bytes("none", b"not certificates").is_err()); + assert!(TrustList::from_bytes("none", &[]).is_err()); + assert!(TrustList::from_bytes("big", &vec![0x30; MAX_LIST_BYTES + 1]).is_err()); + // A file cut short is refused, not loaded as the certificates before the cut. + assert!(TrustList::from_bytes("cut", &file[..file.len() - 5]).is_err()); + // Whitespace after the last certificate is not damage. + let spaced = [file.as_slice(), b"\n"].concat(); + assert_eq!(TrustList::from_bytes("spaced", &spaced).unwrap().certs.len(), 3); + // PEM that follows a note starting with "0" (the first byte DER starts with) is still PEM. + let noted = format!("0 certificates have been revoked in this bundle\n{pem}"); + assert_eq!(TrustList::from_bytes("noted", noted.as_bytes()).unwrap().certs.len(), 3); + // A certificate listed twice, even apart, is one entry. + let repeated = [certs[0].clone(), certs[1].clone(), certs[0].clone()].concat(); + assert_eq!(TrustList::from_bytes("dups", &repeated).unwrap().certs.len(), 2); + } +} diff --git a/crates/sign/src/x509.rs b/crates/sign/src/x509.rs index 91f74ff214..e08dbe1966 100644 --- a/crates/sign/src/x509.rs +++ b/crates/sign/src/x509.rs @@ -569,7 +569,7 @@ pub fn subject_of(raw: &[u8]) -> Option { /// `pathLenConstraint` allows the CA certificates below it, and (when `at` is given) it was valid /// then. Stops at a self-signed certificate. Certificates embedded in a document are in `pool` /// too, so an ordinary end-entity certificate must never be accepted as an issuer. -pub fn build_chain<'a>(leaf: &'a Certificate, pool: &'a [Certificate], at: Option