diff --git a/Cargo.lock b/Cargo.lock index 3ed3003d45..1c15e7ec8b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6707,6 +6707,7 @@ dependencies = [ "pdfcraft-ocr", "pdfcraft-platform", "pdfcraft-render", + "pdfcraft-testkit", "pdfcraft-xfa", "plist", "proptest", diff --git a/ROADMAP.md b/ROADMAP.md index e42f364f8a..417071098a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -360,6 +360,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md - **2026-10-26 (M3, view.text-select):** Text selection runs across pages: dragging onto another page (also a quick flick off the page, and the edge and wheel scrolling of #721/#1670) or ⇧-clicking there selects the rest of the first page, the pages between and the last page up to the pointer. Copy has each page's part on a line of its own, reading pages not yet read off the UI thread; highlight, underline, strikethrough and Redact put one mark on each page in one undo step (a tool that finishes first marks once the pages are read; Redact refuses a selection over a page whose text could not be read); Add comment and Replace text stay one-page. A drag from one page's text that is already over the next when it starts no longer begins a Redact or area-highlight box there. 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 (M7, #2750):** Single-style Keep source fonts edits retain source glyphs and batch only missing glyphs in fallback fonts. Per-rewrite character eligibility and widths are cached; source and fallback edge spaces stay extractable. 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-25 (M10, #4399):** The printer picker has a wider searchable list, wrapped device names, stable selection while filtering, and Search and Save as PDF kept visible. Synthetic fleet UI regressions cover long lists and a smaller window. Estimates unchanged. - **2026-10-25 (web, same-document host mode):** A page that loads the PdfCraft web module into its own document (no iframe) can opt into the host bridge with `data-host="page"` on the app's canvas — the exact value `page`; any other value keeps the normal app with downloads, unless a same-origin framed `?host=parent` selects the parent bridge (unframed or cross-origin, `?host=parent` also keeps the normal app). It is the `?host=parent` bridge with the transport swapped: the same five messages travel as non-bubbling `CustomEvent`s on the canvas (`detail` holds the parent messages' fields without `type`; the host answers with a `pdfcraft:open` event), so saves reach the host instead of downloading and dirty and start-up-failure reporting are unchanged. Unit tests cover the opt-in rule; no parity or estimate changes. - **2026-10-25 (M10):** Vector printing keeps field and comment artwork whose rectangle coordinates are indirect, requiring exactly four finite resolved values. 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"])); } diff --git a/crates/audit/src/cover.rs b/crates/audit/src/cover.rs index 78b16e57ea..9bda6be30c 100644 --- a/crates/audit/src/cover.rs +++ b/crates/audit/src/cover.rs @@ -7,9 +7,12 @@ //! out ("marker" style), counts as the rectangle the stroke paints (#2385). Graphics state tracked //! here is deliberately small: the CTM stack (`q`/`Q`/`cm`), the colors (`g`/`rg`/`k` and //! `G`/`RG`/`K`), the line width (`w`) and what ExtGState sets of them (`gs` reading `/ca`, -//! `/CA` and `/LW`). Form XObjects are followed read-only with a depth cap. Anything fancier -//! (other filled paths, slanted or bent strokes, shadings, patterns) is out of scope and -//! documented as such. +//! `/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. //! //! 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 @@ -18,8 +21,11 @@ //! 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 std::ops::Range; + use pdfcraft_content::{Matrix, Op, Pieces, ops}; -use pdfcraft_cos::{DecodeBudget, Dict, Document, Object}; +use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object}; use crate::AuditError; @@ -40,6 +46,38 @@ 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, Debug, PartialEq)] +pub struct GlyphSource { + pub operators: Range, + pub painted: bool, +} + +#[derive(Clone, Copy)] +enum Clip { + Unbounded, + Rect([f64; 4]), + Empty, +} + +impl Clip { + fn visible_rect(self, rect: [f64; 4]) -> Option<[f64; 4]> { + match self { + Self::Unbounded => Some(rect), + Self::Rect(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 => None, + } + } + + fn intersect_rect(&mut self, rect: [f64; 4]) { + *self = self.visible_rect(rect).map_or(Self::Empty, Self::Rect); + } } #[derive(Clone)] @@ -49,6 +87,9 @@ struct Gs { alpha: f64, stroke: [f64; 3], stroke_alpha: f64, + clip: Clip, + 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. @@ -68,9 +109,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, } @@ -110,13 +151,11 @@ 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 pts = if pts.len() == 5 && same(pts[0][0], pts[4][0]) && same(pts[0][1], pts[4][1]) { &pts[..4] } else { pts }; let [a, b, c, d] = <[[f64; 2]; 4]>::try_from(pts).ok()?; let fits = |first_horizontal: bool| { [(a, b), (b, c), (c, d), (d, a)] @@ -139,7 +178,18 @@ fn lines_rect(mut pts: Vec<[f64; 2]>) -> Option<[f64; 4]> { impl Default for Gs { fn default() -> Self { - Gs { ctm: Matrix::IDENTITY, fill: [0.0, 0.0, 0.0], alpha: 1.0, stroke: [0.0, 0.0, 0.0], stroke_alpha: 1.0, width: 1.0, cap: 0 } + Gs { + ctm: Matrix::IDENTITY, + fill: [0.0, 0.0, 0.0], + alpha: 1.0, + stroke: [0.0, 0.0, 0.0], + stroke_alpha: 1.0, + clip: Clip::Unbounded, + text_render_mode: 0, + glyph_source: None, + width: 1.0, + cap: 0, + } } } @@ -151,6 +201,8 @@ struct Walker<'a> { /// Decoded bytes and form entries left for the page, its forms included: spending either /// fails the audit. budget: DecodeBudget, + off_layers: HashSet, + blank_clips: &'a HashSet, } impl<'a> Walker<'a> { @@ -162,6 +214,24 @@ impl<'a> Walker<'a> { Ok(()) } + fn push_cover(&mut self, rect: Option<[f64; 4]>, gs: &Gs, stroke: bool, pos: (usize, usize)) { + let (alpha, rgb) = if stroke { (gs.stroke_alpha, gs.stroke) } else { (gs.alpha, gs.fill) }; + if alpha >= 1.0 + && let Some(rect) = rect.and_then(|rect| gs.clip.visible_rect(rect)) + { + self.out.push(FilledRect { rect, rgb, pos, glyph_source: gs.glyph_source.clone() }); + } + } + + fn paint_path(&mut self, path: &Path, operator: &[u8], gs: &Gs, pos: (usize, usize)) { + if matches!(operator, b"B" | b"B*" | b"b" | b"b*" | b"S" | b"s") { + self.push_cover(path.stroked_rect(gs), gs, true, pos); + } + if !matches!(operator, b"S" | b"s" | b"n") { + self.push_cover(path.rect(), gs, false, pos); + } + } + /// Walk one stream's operators, read one at a time (a stream of millions of short operators /// is never held whole), with the given graphics state. `at_do` is the `Do` position to /// stamp on rectangles found inside a form XObject, or `None` at page level (where each @@ -176,6 +246,13 @@ impl<'a> Walker<'a> { at_do: Option<(usize, usize)>, ) -> Result<(), AuditError> { let mut path = Path::Empty; + let mut multiple_subpaths = false; + 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() { self.bump()?; let op = &op; @@ -245,6 +322,7 @@ impl<'a> Walker<'a> { } } b"re" => { + multiple_subpaths |= !matches!(path, Path::Empty); 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 { let r = gs.ctm.bbox([x.min(x + w), y.min(y + h), x.max(x + w), y.max(y + h)]); @@ -256,6 +334,7 @@ impl<'a> Walker<'a> { path = rect.map_or(Path::Other, Path::Rect); } b"m" => { + multiple_subpaths |= !matches!(path, Path::Empty); path = match (path, user_point(gs, op)) { (Path::Empty, Some(p)) => Path::Lines(vec![p], false), _ => Path::Other, @@ -279,38 +358,67 @@ impl<'a> Walker<'a> { _ => Path::Other, }; } - // `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*" => { + b"W" | b"W*" => clip_next = true, + b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" | b"S" | b"s" | b"n" => { let done = std::mem::replace(&mut path, Path::Empty); - if matches!(op.op.as_slice(), b"B" | b"B*" | b"b" | b"b*") - && let Some(r) = done.stroked_rect(gs) - && gs.stroke_alpha >= 1.0 - { - self.out.push(FilledRect { rect: r, rgb: gs.stroke, pos }); + if hidden_depth == 0 { + self.paint_path(&done, op.op.as_slice(), gs, pos); } - if let Some(r) = done.rect() - && gs.alpha >= 1.0 + // A clipping operator takes effect after the path-ending paint. + if clip_next + && !multiple_subpaths + && let Some(rect) = done.rect() { - self.out.push(FilledRect { rect: r, rgb: gs.fill, pos }); + gs.clip.intersect_rect(rect); + } + clip_next = false; + multiple_subpaths = false; + } + b"c" | b"v" | b"y" => path = Path::Other, + 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.text_render_mode = mode as u8; } } - b"S" | b"s" => { - if let Some(r) = std::mem::replace(&mut path, Path::Empty).stroked_rect(gs) - && gs.stroke_alpha >= 1.0 - { - self.out.push(FilledRect { rect: r, rgb: gs.stroke, pos }); + b"Tj" | b"TJ" | b"'" | b"\"" if shows_glyphs(op) => { + 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(GlyphSource { operators: text_start..i, painted: glyph_source_painted }); } } - b"n" => path = Path::Empty, - b"c" | b"v" | b"y" | b"W" | b"W*" => path = Path::Other, + b"BDC" => { + if hidden_depth > 0 || (op.name(0) == Some(b"OC") && self.layer_is_off(resources, op.operands.get(1))) { + hidden_depth += 1; + } + } + b"BMC" if hidden_depth > 0 => hidden_depth += 1, + b"EMC" => hidden_depth = hidden_depth.saturating_sub(1), b"Do" => { - if let Some(name) = op.name(0) { + if let Some(name) = op.name(0).filter(|_| hidden_depth == 0) { if depth >= MAX_DEPTH { return Err(AuditError::TooDeep); } self.walk_xobject(name, gs, resources, depth, pos)?; } path = Path::Empty; + clip_next = false; + multiple_subpaths = false; } _ => {} } @@ -318,6 +426,15 @@ impl<'a> Walker<'a> { Ok(()) } + fn layer_is_off(&self, resources: &Dict, property: Option<&Object>) -> bool { + let Object::Name(name) = property.unwrap_or(&Object::Null) else { + return matches!(property, Some(Object::Ref(id)) if self.off_layers.contains(id)); + }; + let props = resources.get(b"Properties").map(|value| self.doc.resolve(value)); + let layer = props.as_deref().and_then(Object::as_dict).and_then(|dict| dict.get(name)); + matches!(layer, Some(Object::Ref(id)) if self.off_layers.contains(id)) + } + /// Follow a form XObject read-only, composing its matrix onto the current CTM. State /// changes inside never leak out; every rectangle found is stamped with the `Do` /// position `pos`. @@ -331,6 +448,9 @@ impl<'a> Walker<'a> { if crate::subtype(self.doc, dict)?.as_deref() != Some(b"Form") { return Ok(()); } + if matches!(dict.get(b"OC"), Some(Object::Ref(id)) if self.off_layers.contains(id)) { + return Ok(()); + } let matrix = dict .get(b"Matrix") .map(|o| self.doc.resolve(o)) @@ -350,6 +470,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); + let bbox = dict.get(b"BBox").map(|value| self.doc.resolve(value)); + if let Some([x0, y0, x1, y1]) = + bbox.as_deref().and_then(Object::as_array).and_then(|operands| <&[Object; 4]>::try_from(operands.as_slice()).ok()).and_then(|values| { + let [x0, y0, x1, y1] = values.each_ref().map(|value| self.doc.resolve(value).as_f64()); + Some([x0?, y0?, x1?, y1?]).filter(|values| values.iter().all(|v| v.is_finite())) + }) + { + let bounds = [x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)]; + let bbox = sub_gs.ctm.bbox(bounds); + if bbox.iter().all(|v| v.is_finite()) { + sub_gs.clip.intersect_rect(bbox); + } + } let mut sub_stack = Vec::new(); self.walk_ops(ops(&data), &mut sub_gs, &mut sub_stack, sub_resources, depth + 1, Some(pos)) } @@ -392,12 +525,37 @@ fn ext_state(doc: &Document, resources: &Dict, name: &[u8], gs: &mut Gs) { } } +/// 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() }; + let props = root.as_dict().and_then(|dict| dict.get(b"OCProperties")).map(|value| doc.resolve(value)); + let configuration = props.as_deref().and_then(Object::as_dict).and_then(|dict| dict.get(b"D")).map(|value| doc.resolve(value)); + let off = configuration.as_deref().and_then(Object::as_dict).and_then(|dict| dict.get(b"OFF")).map(|value| doc.resolve(value)); + off.as_deref() + .and_then(Object::as_array) + .into_iter() + .flatten() + .filter_map(|value| if let Object::Ref(id) = value { Some(*id) } else { None }) + .collect() +} + /// 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 /// 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(), @@ -414,7 +572,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 }; + 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..de29fb27a6 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,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 { - 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.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 436b2fc8c9..c7818365a6 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 @@ -1164,3 +1164,201 @@ fn every_finding_record_counts_against_the_output_bound() { let short = crate::Limits { covered_text: 3 * one - 1, ..exact }; assert!(matches!(crate::audit(&doc, short), Err(crate::AuditError::TooMuchOutput))); } + +#[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 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"; + 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(); + 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 rotation: keep the conservative bounding-box result. + 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_eq!(findings.len(), 1, "the rotated cover must still be reported: {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:?}"); +} diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs index 365d06d776..64ff26c164 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 01a736ef9f..0a1714d761 100644 --- a/crates/edit/src/text.rs +++ b/crates/edit/src/text.rs @@ -69,7 +69,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 284914d4fa..166ffcd327 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, @@ -819,11 +821,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: @@ -942,6 +948,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 12f560a550..8e0d258ec6 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(); @@ -462,6 +487,9 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool, in let properties = res.get(b"Properties").and_then(|o| doc.dict(o)).unwrap_or_default(); carry.containers = std::rc::Rc::new(super::containers::Containers::collect(doc, &ops, &res)); 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 diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index eb9102eb27..5a001a1100 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -92,6 +92,9 @@ js-sys = "0.3" web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "HtmlIFrameElement", "HtmlImageElement", "HtmlCollection", "Node", "EventTarget", "Navigator", "RequestCache", "RequestInit", "Response", "Worker", "WorkerOptions", "WorkerType", "MessageEvent"] } [dev-dependencies] +# Exercise preference round-trips in the persisted config.toml format. +toml = "1" +pdfcraft-testkit = { workspace = true } # The fixture and suite runner the component trials drive the app's components with. craft = { workspace = true, features = ["ui-testing", "zip"] } pdfcraft-xfa = { workspace = true } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index b4c07d5b03..d6d4a5fb57 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -299,6 +299,7 @@ impl PdfCraftApp { mode: Mode::AllTools, default_mode: Mode::AllTools, view_defaults: Default::default(), + show_form_field_reminder: true, highlight_fields: true, units: Default::default(), blank_paper: crate::paper::Paper::system(), diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 22f3b718dd..17ca59a4c8 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -90,6 +90,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)?; self.sync_open_date_format(); diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs index 2c53ba1b2a..ca53c89ea6 100644 --- a/crates/ui-egui/src/app/prefs.rs +++ b/crates/ui-egui/src/app/prefs.rs @@ -180,6 +180,7 @@ impl PdfCraftApp { full_screen_escape_exits: Some(self.full_screen_escape_exits), units: Some(self.units), always_default_view: Some(self.always_default_view), + show_form_field_reminder: Some(self.show_form_field_reminder), highlight_fields: Some(self.highlight_fields), comments_panel_closed: Some(self.comments_panel_closed), right_panel_closed: Some(self.right_panel_closed), @@ -479,6 +480,9 @@ impl PdfCraftApp { if let Some(on) = b.always_default_view { self.always_default_view = on; } + if let Some(show) = b.show_form_field_reminder { + self.show_form_field_reminder = show; + } if let Some(on) = b.highlight_fields { self.highlight_fields = on; } diff --git a/crates/ui-egui/src/app/settings.rs b/crates/ui-egui/src/app/settings.rs index aff2984134..7608e2aedb 100644 --- a/crates/ui-egui/src/app/settings.rs +++ b/crates/ui-egui/src/app/settings.rs @@ -85,6 +85,7 @@ pub struct Behavior { pub full_screen_escape_exits: Option, pub units: Option, pub always_default_view: Option, + pub show_form_field_reminder: Option, pub highlight_fields: Option, pub comments_panel_closed: Option, pub right_panel_closed: Option, @@ -661,6 +662,7 @@ pub fn import_json(text: &str) -> (PdfCraftSettings, Vec) { full_screen_escape_exits: r.bool("full_screen_escape_exits"), units: r.typed("units"), always_default_view: r.bool("always_default_view"), + show_form_field_reminder: r.bool("show_form_field_reminder"), highlight_fields: r.bool("highlight_fields"), comments_panel_closed: r.bool("comments_panel_closed"), right_panel_closed: r.bool("right_panel_closed"), diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 78f28bce15..bd1a061816 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -787,6 +787,7 @@ fn apply_notice(app: &mut PdfCraftApp, ctx: &egui::Context, index: usize, notice } } Some(Notice::Signatures) => crate::side_panels::set_panel_visible(app, RightPanel::Signatures.into(), true), + Some(Notice::DismissFormReminder) => app.show_form_field_reminder = false, Some(Notice::FieldHighlights(on)) => app.highlight_fields = on, Some(Notice::Console) => crate::js_dialogs::open_console(app), // Back on in Preferences ▸ General. @@ -1675,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, 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 cc686c1b20..7f37802d45 100644 --- a/crates/ui-egui/src/canvas/bars.rs +++ b/crates/ui-egui/src/canvas/bars.rs @@ -52,6 +52,8 @@ pub(super) enum Notice { Close, /// Stop showing the secured-document notice, in every document (#4035). HideSecured, + /// Dismiss only the ordinary AcroForm reminder across sessions. + DismissFormReminder, /// Lock the placed signatures into the page (#2149). LockSignatures, } @@ -62,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, @@ -70,12 +85,11 @@ fn bar(_tone: Tone, icon: IconId, text: String) -> Bar<'static> { pub(super) fn notices( view: &mut DocView, 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() { @@ -151,12 +165,14 @@ pub(super) fn notices( .show(ui); return (out.action == Some(0)).then_some(Notice::Signatures); } - if view.notice_dismissed { - return None; - } // 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(); + let fillable_form = info.fields.iter().any(|f| f.kind != pdfcraft_render::FieldKind::PushButton); + let ordinary = show_form_field_reminder && fillable_form && !scripts_off && !secured && xfa.is_none() && info.xfa.is_none(); + if view.notice_dismissed && !ordinary { + 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(); @@ -188,7 +204,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(( IconId::new("text-cursor-input"), @@ -257,6 +273,9 @@ pub(super) fn notices( } let out = notice.show(ui); if out.dismissed { + if ordinary { + return Some(Notice::DismissFormReminder); + } view.notice_dismissed = true; } let taken = results.into_iter().nth(out.action?)?; diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index b5683d9b19..f79d2a1729 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -35,6 +35,7 @@ //! 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` persists ordinary form reminders. `ui.state.show_form_field_reminder` reports the setting. //! `show_page_edge_shadows=true|false` controls page decoration app-wide. //! `comment-tool-pinned=true|false` remembers the annotation quick bar's pin across restarts. //! `folder-collapsed==on|off` folds a pinned folder on Home down to its heading or diff --git a/crates/ui-egui/src/control/host.rs b/crates/ui-egui/src/control/host.rs index 01151e3556..39f04746e3 100644 --- a/crates/ui-egui/src/control/host.rs +++ b/crates/ui-egui/src/control/host.rs @@ -139,6 +139,7 @@ impl 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": { "tools": self.hotbar.tools }, "comment_tool_pinned": self.comment_prefs.pinned, // Home's pinned folders, in order, and whether each is folded down to its heading. diff --git a/crates/ui-egui/src/dialogs/preferences.rs b/crates/ui-egui/src/dialogs/preferences.rs index 95448331ce..f82e2bd572 100644 --- a/crates/ui-egui/src/dialogs/preferences.rs +++ b/crates/ui-egui/src/dialogs/preferences.rs @@ -79,6 +79,7 @@ struct PrefsDraft { view_defaults: ViewDefaults, full_screen_fill: bool, full_screen_escape_exits: bool, + show_form_field_reminder: bool, highlight_fields: bool, always_default_view: bool, text_links: bool, @@ -116,6 +117,7 @@ impl PrefsDraft { view_defaults: app.view_defaults, full_screen_fill: app.full_screen_fill, full_screen_escape_exits: app.full_screen_escape_exits, + show_form_field_reminder: app.show_form_field_reminder, highlight_fields: app.highlight_fields, always_default_view: app.always_default_view, text_links: app.text_links, @@ -158,6 +160,7 @@ impl PrefsDraft { view_defaults: ViewDefaults::default(), full_screen_fill: true, full_screen_escape_exits: true, + show_form_field_reminder: true, highlight_fields: true, always_default_view: false, text_links: true, @@ -437,6 +440,7 @@ impl PreferencesModel for Prefs<'_> { ("general.recent", PrefValue::Int(v)) => d.recent_limit = usize::try_from(v).unwrap_or(0).min(crate::RECENT_FILES_MAX), ("general.title_bar", PrefValue::Bool(v)) => d.system_title_bar = v, ("appearance.edge_shadows", PrefValue::Bool(v)) => d.show_page_edge_shadows = v, + ("view.form_reminder", PrefValue::Bool(v)) => d.show_form_field_reminder = v, ("appearance.highlight_fields", PrefValue::Bool(v)) => d.highlight_fields = v, ("appearance.reading.mode", PrefValue::Choice(id)) => { if id == "custom" { @@ -573,6 +577,7 @@ impl PreferencesModel for Prefs<'_> { d.full_screen_fill = fresh.full_screen_fill; d.full_screen_escape_exits = fresh.full_screen_escape_exits; d.always_default_view = fresh.always_default_view; + d.show_form_field_reminder = fresh.show_form_field_reminder; d.text_links = fresh.text_links; d.units = fresh.units; d.scroll_speed = fresh.scroll_speed; @@ -653,6 +658,7 @@ impl PreferencesDraft for Prefs<'_> { self.app.view_defaults = d.view_defaults; self.app.full_screen_fill = d.full_screen_fill; self.app.full_screen_escape_exits = d.full_screen_escape_exits; + self.app.show_form_field_reminder = d.show_form_field_reminder; self.app.highlight_fields = d.highlight_fields; self.app.always_default_view = d.always_default_view; self.app.text_links = d.text_links; @@ -778,6 +784,7 @@ impl Prefs<'_> { let rows = vec![ choice_row("view.mode", tl!("Default workspace mode"), d.default_mode, &mode_table()) .help(tl!("Used when opening PDFs. An explicit launch or control mode takes precedence for the session.")), + RowSpec::new("view.form_reminder", tl!("Show form field reminder"), RowKind::Bool(d.show_form_field_reminder)), choice_row("view.layout", tl!("Default page display"), v.display, &layout_table()), RowSpec::new("view.continuous", tl!("Continuous scrolling"), RowKind::Bool(v.continuous)), RowSpec::new("view.gaps", tl!("Show gaps between pages"), RowKind::Bool(v.page_gaps)) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bd0a0901b4..c53d47240d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -287,6 +287,8 @@ pub struct PdfCraftApp { /// Documents and view). Continuous scrolling at fit width by default, which never snaps /// between pages. pub view_defaults: canvas::ViewDefaults, + /// Whether to show ordinary AcroForm reminders across documents and restarts. + pub show_form_field_reminder: bool, /// Preferences ▸ Highlight fields for newly opened forms (saved as `highlight_fields`). pub(crate) highlight_fields: bool, /// The unit page sizes and margins are shown in (Preferences ▸ Documents and view). 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..ab7503539f --- /dev/null +++ b/crates/ui-egui/tests/it/form_reminder.rs @@ -0,0 +1,286 @@ +//! Persistent dismissal of the ordinary AcroForm reminder (#2725). + +use egui_kittest::{Harness, kittest::Queryable}; +use pdfcraft_testkit::Pdf; +use pdfcraft_ui_egui::{PdfCraftApp, settings::PdfCraftSettings}; + +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() +} + +/// Serialize and reload the current preferences in the format of config.toml. +fn snapshot(app: &PdfCraftApp) -> PdfCraftSettings { + toml::from_str(&toml::to_string(&app.settings_snapshot()).unwrap()).unwrap() +} + +fn legacy(json: &str) -> PdfCraftSettings { + pdfcraft_ui_egui::settings::import_json(json).0 +} + +/// 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| { + crate::support::install_runtime(&cc.egui_ctx); + let mut app = crate::control::new_app(); + if let Some(settings) = saved { + app.apply_settings(&settings); + } + app.set_option(&cc.egui_ctx, "language", "en").unwrap(); + app.open_bytes(&cc.egui_ctx, "synthetic-form.pdf", None, bytes).unwrap(); + app.set_option(&cc.egui_ctx, "left", "closed").unwrap(); + app.set_option(&cc.egui_ctx, "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].session.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].session.highlight_fields, highlights); + assert_eq!(h.state().session.get(id).unwrap().bytes, original, "a UI preference must not change PDF bytes"); + let saved = snapshot(h.state()); + let ctx = h.ctx.clone(); + h.state_mut().open_bytes(&ctx, "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"); + let ctx = h.ctx.clone(); + h.state_mut().set_option(&ctx, "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().dialogs.is_empty(), "Preferences must actually close before checking the restored reminder"); + h.get_by_label(REMINDER); + shot(&mut h, "reminder-restored"); + let saved = snapshot(h.state()); + 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(legacy(saved)), 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 = legacy(r#"{"show_form_field_reminder":false}"#); + 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(snapshot(h.state())), 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(legacy(r#"{"show_form_field_reminder":false}"#)), 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"); + let ctx = h.ctx.clone(); + h.state_mut().set_option(&ctx, "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 = legacy(&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].session.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].session.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 = snapshot(h.state()); + assert_eq!(h.state().settings_snapshot().behavior.show_form_field_reminder.unwrap(), 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(legacy(&settings)), bytes.clone()); + let settings = snapshot(h.state()); + 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(legacy(r#"{"show_form_field_reminder":false}"#)), 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(legacy(r#"{"show_form_field_reminder":false}"#)), pdfcraft_xfa::fixtures::shell(&template)); + let id = h.state().views[0].id; + assert!(h.state().session.get(id).unwrap().xfa_scripts_off()); + for card in craft::ui::runtime::toast::cards(&h.ctx, &craft::ui::runtime::env::WindowKey::main()) { + craft::ui::runtime::toast::dismiss(&h.ctx, card.id); + } + 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 (client, rx) = std::sync::mpsc::channel(); + h.state_mut().attach_control(craft::automation::ControlChannel::new(rx), None); + let call = |h: &mut Harness<'static, PdfCraftApp>, method: &str, params| crate::control::call(h, &client, method, params); + 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 = snapshot(h.state()); + let h = harness(Some(saved), form()); + 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!(!app.settings_snapshot().behavior.show_form_field_reminder.unwrap()); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 8d08456bb7..0026a12fc8 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -49,6 +49,7 @@ mod fill_sign; mod find_replace; mod folders; mod fonts; +mod form_reminder; mod forms; mod identity; mod javascript; 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); diff --git a/docs/development.md b/docs/development.md index 50a6df1b19..c62e15f398 100644 --- a/docs/development.md +++ b/docs/development.md @@ -144,6 +144,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 9903492d6d..c63c4d46a6 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -268,7 +268,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). Insert from File retains catalog attachments in the same undo step, preserving existing destination name trees and duplicate-key encoding. 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). Document Properties dismisses stale drafts after edits, reloads or tab changes; JSONL replay covers commit, cancellation and save/reopen. Missing: page transitions, recovery on the web. Maintainers are reviewing the vendored Document Properties runtime and the optional local scenario replay. | +| M4 | Engine, history, save, organize | 100–180 | 95% | 8–15 | Done:
- command registry (menus, shortcuts and palette all use it);
- undo/redo; incremental, atomic and encrypted saves;
- autosave and crash recovery;
- organize, combine, extract, split and insert-from-file, with identical fonts and images stored once;
- CLI `edit/combine/extract/split`.
Done since: Organize opens directly into the page overview, with checkbox selection, an editable page-range selection (#1092), and per-page rotate/delete controls; Combine files in its own tab (sortable, resizable columns; folders; early warnings; unlocking protected files), bookmark editing, page labels (Number pages), CLI `run`, Set Page Boxes, Crop tool, Duplicate pages, Ctrl+A / Cmd+A to select all pages in Organize, Replace pages, bookmarks from tagged headings. Extract and Split preserve shared Type 3 glyph resource graphs, retaining conservative pruning limits. Undo back to the opened or last saved file is clean; Revert opens that saved file after an undo; a later save appends to it so the saved revision stays in the file (#1310, #1311, #1312). Insert from File retains catalog attachments in the same undo step, preserving existing destination name trees and duplicate-key encoding. 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). Document Properties dismisses stale drafts after edits, reloads or tab changes; JSONL replay covers commit, cancellation and save/reopen. Missing: page transitions, recovery on the web. Maintainers are reviewing the vendored Document Properties runtime and the optional local scenario replay. 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 dfa966a679..1eecaf89bf 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -10172,11 +10172,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"