From bd3a9d318ed46f13ac4eb5b27578becd4122a3e7 Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Sat, 17 Oct 2026 21:22:19 -0700 Subject: [PATCH 1/7] 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 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 2/7] 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 a840e0787c8da2f4ba83e62f0f402f8e42240f31 Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Tue, 24 Nov 2026 05:12:05 -0800 Subject: [PATCH 3/7] 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 4/7] 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 9b2c9e10336248f816f2876aa92393ab29a6f169 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:54:21 +0100 Subject: [PATCH 5/7] Pass the notice flags to notices() as one struct After main was merged in, notices() takes eight arguments and clippy's too_many_arguments fails the gate. AGENTS.md asks to fix the code a lint reports rather than silence it, so the four booleans that decide which notices show (form-field reminder, secured, repaired, lock offer) now travel as NoticeFlags. Behaviour is unchanged. Also use assert!(!..) in the form reminder test, which the newer clippy flags (bool_assert_comparison); the assertion is the same. --- crates/ui-egui/src/canvas.rs | 8 +++++++- crates/ui-egui/src/canvas/bars.rs | 19 +++++++++++++++---- crates/ui-egui/tests/it/form_reminder.rs | 2 +- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index a2a833df2b..bd1a061816 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1676,7 +1676,13 @@ pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mu // PLAN: assumed `notices(view, doc, secured, repaired, lock_offer, banner, ui)`: pdf-canvas-w16 drops the tokens // argument and gives no other change. let bars_top = ui.available_rect_before_wrap().top(); - let notice = notices(view, app.show_form_field_reminder, doc, secured, repaired, lock_offer, crate::sign_ui::banner(&doc.signatures), ui); + let notice = notices( + view, + doc, + bars::NoticeFlags { show_form_field_reminder: app.show_form_field_reminder, secured, repaired, lock_offer }, + crate::sign_ui::banner(&doc.signatures), + ui, + ); // The notice bars' height keeps the floating toolbar below them (the dock's top inset, next pass). let inset = (ui.available_rect_before_wrap().top() - bars_top).max(0.0); if (inset - app.notice_inset).abs() > 0.5 { diff --git a/crates/ui-egui/src/canvas/bars.rs b/crates/ui-egui/src/canvas/bars.rs index 7499f1d2a0..7f37802d45 100644 --- a/crates/ui-egui/src/canvas/bars.rs +++ b/crates/ui-egui/src/canvas/bars.rs @@ -64,6 +64,19 @@ fn bar(_tone: Tone, icon: IconId, text: String) -> Bar<'static> { Bar::new(Tone::Info, text).layout(NoticeLayout::Bar).icon(NoticeIcon::Custom(icon.into())) } +/// What decides which notices [`notices`] shows, besides the document itself. +#[derive(Clone, Copy)] +pub(super) struct NoticeFlags { + /// The form-field reminder is on in Preferences. + pub show_form_field_reminder: bool, + /// Opened without the owner password and something is restricted, and the notice is not turned off (#4035). + pub secured: bool, + /// The file was damaged and has been repaired. + pub repaired: bool, + /// Offer to lock a signature just placed into the page; false for a digitally signed document. + pub lock_offer: bool, +} + /// The notices above the pages, one after another: a file changed on disk first, then what a historical /// snapshot is, then pages cut at the renderer's limits, then the offer to lock a signature just /// placed, then the signature status bar, a form's scripts having been turned off, security, @@ -71,14 +84,12 @@ fn bar(_tone: Tone, icon: IconId, text: String) -> Bar<'static> { #[allow(clippy::cognitive_complexity)] pub(super) fn notices( view: &mut DocView, - show_form_field_reminder: bool, doc: &pdfcraft_engine::Document, - secured: bool, - repaired: bool, - lock_offer: bool, + flags: NoticeFlags, signed: Option<(&'static str, Tone, &str, String)>, ui: &mut egui::Ui, ) -> Option { + let NoticeFlags { show_form_field_reminder, secured, repaired, lock_offer } = flags; // Full screen shows the page and nothing else (#1459), so the notice bar above the pages waits // until it is left; filling the screen, a bar would push the page past its bottom (#576). if view.presenting() { diff --git a/crates/ui-egui/tests/it/form_reminder.rs b/crates/ui-egui/tests/it/form_reminder.rs index 09b7b96773..ab7503539f 100644 --- a/crates/ui-egui/tests/it/form_reminder.rs +++ b/crates/ui-egui/tests/it/form_reminder.rs @@ -282,5 +282,5 @@ fn control_form_reminder_is_persistent_and_rejects_invalid_values() { assert!(h.query_by_label(REMINDER).is_none()); let mut app = crate::control::new_app(); app.set_option(&egui::Context::default(), "form-reminder", "off").unwrap(); - assert_eq!(app.settings_snapshot().behavior.show_form_field_reminder.unwrap(), false); + assert!(!app.settings_snapshot().behavior.show_form_field_reminder.unwrap()); } From 7cce4ce1733e8995acb4d3529beea313a4f6ab71 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:27:50 +0100 Subject: [PATCH 6/7] test: resolve nightly launches in the socket tests without installing the profile cargo test runs the pdfcraft binary's unit tests in one process. The single-instance socket tests called launch_profile::prepare, which installs the nightly profile in craft_nightly's process-wide OnceLock, so tests that ran after them saw a nightly launch: the window icon test compared the nightly icon with the stable one, and stable_defaults_and_nightly_version_line found is_nightly() true. The FreeBSD workflow runs plain cargo test and failed this way. The socket tests now parse and validate the launch the same way, without installing it. --- apps/pdfcraft/src/launch_profile.rs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/apps/pdfcraft/src/launch_profile.rs b/apps/pdfcraft/src/launch_profile.rs index 21f6e039cf..fd1df09247 100644 --- a/apps/pdfcraft/src/launch_profile.rs +++ b/apps/pdfcraft/src/launch_profile.rs @@ -67,6 +67,19 @@ mod tests { args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]) } + /// What [`super::prepare`] returns for `argv`, without installing the profile process-wide. + /// `cargo test` runs every unit test of the binary in one process, and an installed nightly + /// profile would make the stable icon, app id and title tests that run after it see nightly. + #[cfg(any(windows, all(unix, not(target_os = "macos"))))] + fn prepare_without_installing(argv: Vec) -> Result { + let spec = profile_root::spec(); + let mut launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new())?; + if let Profile::NightlyV1(root) = &launch.profile { + launch.profile = Profile::NightlyV1(craft_nightly::validate_and_prepare_root(root, &spec)?); + } + Ok(launch) + } + #[test] fn stable_arguments_and_directory_policy_are_unchanged() { let spec = profile_root::spec(); @@ -158,14 +171,14 @@ mod tests { let listener = UnixListener::bind(&sock_path).unwrap(); // Live listener socket already present inside /single-instance/. - let live_launch = super::prepare(BuildFlavor::NightlyV1, launch_arguments(&profile, &args(&["doc.pdf"]))).unwrap(); + let live_launch = prepare_without_installing(launch_arguments(&profile, &args(&["doc.pdf"]))).unwrap(); assert_eq!(live_launch.profile, Profile::NightlyV1(expected_root.clone())); assert_eq!(live_launch.passthrough_args, args(&["doc.pdf"])); // Leftover/stale socket remaining after the previous instance exits. drop(listener); assert!(std::fs::symlink_metadata(&sock_path).is_ok(), "stale socket remains on disk"); - let stale_launch = super::prepare(BuildFlavor::NightlyV1, launch_arguments(&profile, &args(&["after-exit.pdf"]))).unwrap(); + let stale_launch = prepare_without_installing(launch_arguments(&profile, &args(&["after-exit.pdf"]))).unwrap(); assert_eq!(stale_launch.profile, Profile::NightlyV1(expected_root)); assert_eq!(stale_launch.passthrough_args, args(&["after-exit.pdf"])); } @@ -183,14 +196,14 @@ mod tests { let listener = uds_windows::UnixListener::bind(&sock_path).unwrap(); // Live AF_UNIX listener socket already present inside \single-instance\. - let live_launch = super::prepare(BuildFlavor::NightlyV1, launch_arguments(&profile, &args(&["doc.pdf"]))).unwrap(); + let live_launch = prepare_without_installing(launch_arguments(&profile, &args(&["doc.pdf"]))).unwrap(); assert_eq!(live_launch.profile, Profile::NightlyV1(expected_root.clone())); assert_eq!(live_launch.passthrough_args, args(&["doc.pdf"])); // Leftover/stale socket remaining after the previous instance exits. drop(listener); assert!(std::fs::symlink_metadata(&sock_path).is_ok(), "stale socket remains on disk"); - let stale_launch = super::prepare(BuildFlavor::NightlyV1, launch_arguments(&profile, &args(&["after-exit.pdf"]))).unwrap(); + let stale_launch = prepare_without_installing(launch_arguments(&profile, &args(&["after-exit.pdf"]))).unwrap(); assert_eq!(stale_launch.profile, Profile::NightlyV1(expected_root)); assert_eq!(stale_launch.passthrough_args, args(&["after-exit.pdf"])); } From e8c6624960800ee8ac9fd5957e71f2f7067e35ed Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:13:10 +0100 Subject: [PATCH 7/7] test(ui): wait for an encrypted document's view before reading its text layer harness_clip's wait read app.views[0] on its first check. An encrypted document opens in the background after setup submits its password, so on a slow or busy machine the view did not exist yet and the closure panicked with an index out of bounds instead of waiting. --- crates/ui-egui/tests/it/text_select.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/tests/it/text_select.rs b/crates/ui-egui/tests/it/text_select.rs index 064bd0d956..251f822b37 100644 --- a/crates/ui-egui/tests/it/text_select.rs +++ b/crates/ui-egui/tests/it/text_select.rs @@ -59,8 +59,11 @@ fn harness_clip( app } }); - // Wait for the text layer itself (#1277), not for a fixed second. - crate::support::wait_until(&mut h, "the page's text layer", |app| app.views[0].glyph_screen_pos(0, 5).is_some() && !app.render_pending()); + // Wait for the text layer itself (#1277), not for a fixed second. An encrypted document opens + // in the background after `setup` submits its password, so its view may not exist yet. + crate::support::wait_until(&mut h, "the page's text layer", |app| { + app.views.first().is_some_and(|view| view.glyph_screen_pos(0, 5).is_some()) && !app.render_pending() + }); let at = h.state().views[0].glyph_screen_pos(0, 5).expect("text layer loaded"); h.hover_at(at); h.run_steps(1);