PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge r2 track t11: redaction, mixed: combine, compare, crate:edit, measure, ocr
aiongg15f558aaa866
diff --cc ROADMAP.mdindex 43d8fc907,33480c6e1..270f1f791--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -244,7 -205,7 +244,8 @@@ Ranked; detail and the full milestone t- **2026-10-16 (M10, #1201 partial):** Lossless image export applies each component's Decode pair. Indexed values round and clip before palette lookup. Color-key masks keep raw samples. The existing 16-bit precision limit remains. JPEG and mask Decode, ICC transforms, and calibrated colors remain outside this fix. Estimates unchanged.- **2026-10-16 (M3, #2739):** Wrapped revision buttons stay above Binding in Document Properties. A synthetic regression checks control bounds and opens a saved revision at two viewport widths. Estimates unchanged.- **2026-10-19 (M7, tracked text):** Editable paragraphs and object labels distinguish repeated glyph tracking from word gaps in TJ arrays and separately positioned glyphs. Synthetic regressions cover character spacing, horizontal scaling, rotated baselines, larger word gaps, and rows of one-glyph words or cells (inferred tracking is capped at half an em, so `a b c` and digit or Y/N columns keep their spaces). Estimates unchanged.+- **2026-10-16 (M5, #2669, item 5):** The Comments panel groups replies by name and counts all page roots once per frame. Estimates unchanged.+ - **2026-10-16 (M7, #2140):** Header & footer (and Bates numbering, which uses the same dialog) can shrink the page content so the header and footer don't cover it: the original content is scaled evenly into the band they leave free, centred across, also on rotated pages; Remove and Update take the scaling away, and margins that leave no room are refused. Dialog checkbox with a preview of the band, `shrink` on `doc_header_footer`, all catalogs. Annotations and added text and images are not moved yet. Estimates unchanged.- **2026-10-15 (M2, gap 12):** `cargo xtask text-oracle` scores reading order as well as word F1: the longest common subsequence of the two word sequences over the longer one. F1 is a bag of words and cannot see order at all -- measuring #2431, a change that moves text and nothing else, it called 26 of the 29 files whose output changed identical, where the order score separated 18 improvements from 6 regressions. Reports, does not gate; a disagreement with Poppler, not a verdict. Estimates unchanged.- **2026-10-15 (M2, #2305 follow-up):** WinAnsiEncoding 0xA0 and 0xAD and MacRomanEncoding 0xCA extract as the ordinary space and hyphen Annex D.2 names them, in the vendored hayro tables (patch 30) as well as `crates/fonts`, so search, copy and redaction see characters that were hidden behind U+00A0 and U+00AD. Across the pdf.js corpus the soft hyphens we extract fall 117 to 13 and the non-breaking spaces 30 to 26; the rest come from `/ToUnicode`. An explicit `/Differences` name keeps its glyph list value, as pdftotext does. Estimates unchanged.- **2026-10-15 (M12, XFA, #2574):** A `pageArea` with no `<occur>` repeats without limit instead of taking a subform's default of one use, so a later page area with `occur max="1"` is no longer drawn (with a copy of its fields) over every body page. A page area's `occur min` is honoured too: one the body never reached gets the pages it still needs after the body (the once-only closing page of a form, with its button, comes last). Acrobat Pro also puts that page last, and when printing keeps it but leaves it blank (`relevant="-print"` on the page area), which PdfCraft does not do yet; both re-observed on a synthetic fixture, see the 2026-10-19 line. Synthetic regression tests. Estimates unchanged.diff --cc crates/automation/src/tools.rsindex 5b0b093f9,5c8383fdb..551510461--- a/crates/automation/src/tools.rs+++ b/crates/automation/src/tools.rs@@@ -889,7 -875,7 +889,7 @@@ pub fn tools() -> Vec<ToolDef>t("doc_header_footer","Add header and footer",- "Add a header and/or footer to pages. Text boxes: header_left/center/right, footer_left/center/right. Tokens: <<1>> page number, <<n>> page count, <<1 of n>>, <<Page 1 of n>>, <<1/n>>, dates <<m/d/yyyy>> <<yyyy-mm-dd>> <<mmmm d, yyyy>> (and more), Bates <<Bates Number#6#1#PREFIX#SUFFIX>>. font: Helvetica (default), Times or Courier. replace: true swaps out existing ones (Update). Undoable.",- "Add a header and/or footer to pages. Text boxes: header_left/center/right, footer_left/center/right. Tokens: <<1>> page number, <<n>> page count, <<1 of n>>, <<Page 1 of n>>, <<1/n>>, dates <<m/d/yyyy>> <<yyyy-mm-dd>> <<mmmm d, yyyy>> (and more), Bates <<Bates Number#6#1#PREFIX#SUFFIX>>. shrink: true scales the page content down evenly into the room the header and footer leave free, so they don't cover it. replace: true swaps out existing ones (Update). Undoable.",++ "Add a header and/or footer to pages. Text boxes: header_left/center/right, footer_left/center/right. Tokens: <<1>> page number, <<n>> page count, <<1 of n>>, <<Page 1 of n>>, <<1/n>>, dates <<m/d/yyyy>> <<yyyy-mm-dd>> <<mmmm d, yyyy>> (and more), Bates <<Bates Number#6#1#PREFIX#SUFFIX>>. shrink: true scales the page content down evenly into the room the header and footer leave free, so they don't cover it. font: Helvetica (default), Times or Courier. replace: true swaps out existing ones (Update). Undoable.",).cmd("edit.header_footer").with(schema(diff --cc crates/automation/tests/automation.rsindex 5b0ec94ae,461faa1e0..066c6feed--- a/crates/automation/tests/automation.rs+++ b/crates/automation/tests/automation.rs@@@ -2239,22 -2239,45 +2239,59 @@@ fn headers_watermarks_and_backgrounds_tassert!(matches!(a.call("doc_remove_marks", &json!({ "doc": doc, "kind": "watermark" })), Err(ToolError::Failed(_))));assert!(matches!(a.call("doc_header_footer", &json!({ "doc": doc })), Err(ToolError::Failed(_))), "no text");ok(&mut a, "doc_save", json!({ "doc": doc, "path": "marked.pdf" }));+ // A standard face other than Helvetica (#3754), kept through save and reopen; one it doesn't+ // offer is refused with the faces it does.+ let mono = ok(&mut a, "doc_open", json!({ "path": "b.pdf" }))["doc"].as_u64().unwrap();+ ok(&mut a, "doc_header_footer", json!({ "doc": mono, "header_left": "MONO", "font": "Courier" }));+ assert!(page_text(&mut a, mono)[0].contains("MONO"));+ ok(&mut a, "doc_save", json!({ "doc": mono, "path": "courier.pdf" }));+ let saved = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join("courier.pdf")).unwrap())).unwrap();+ let page = &pdfcraft_model::pages(&saved)[0];+ let res = saved.resolve(page.dict.get(b"Resources").unwrap());+ let fonts = saved.resolve(res.as_dict().unwrap().get(b"Font").unwrap()).as_dict().cloned().unwrap();+ let face = saved.resolve(fonts.get(b"PCCour").expect("Courier is added")).as_dict().cloned().unwrap();+ assert_eq!(face.name(b"BaseFont"), Some(&b"Courier"[..]));+ let refused = a.call("doc_header_footer", &json!({ "doc": mono, "header_left": "X", "font": "Arial" }));+ assert!(matches!(refused, Err(ToolError::InvalidArgs(e)) if e.contains("Courier")));}+ #[test]+ fn a_shrinking_header_and_footer_moves_the_page_content_out_of_their_way_through_tools() {+ let dir = workdir("hf-shrink");+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();+ // The box of "Page 1" (left, top, width, height in points), read back from a saved copy.+ let mut saved = 0;+ let mut text_box = |a: &mut Automation| -> [f64; 4] {+ saved += 1;+ let path = format!("shrunk{saved}.pdf");+ ok(a, "doc_save", json!({ "doc": doc, "path": path }));+ let copy = ok(a, "doc_open", json!({ "path": path }))["doc"].as_u64().unwrap();+ let found = ok(a, "text_find", json!({ "doc": copy, "query": "Page 1" }));+ let r = found["matches"][0]["rects"][0].as_array().unwrap_or_else(|| panic!("Page 1 is on the page: {found}"));+ let v: Vec<f64> = r.iter().map(|x| x.as_f64().unwrap()).collect();+ [v[0], v[1], v[2] - v[0], v[3] - v[1]]+ };+ let before = text_box(&mut a);+ ok(+ &mut a,+ "doc_header_footer",+ json!({ "doc": doc, "pages": [1], "header_center": "ACME", "footer_right": "<<Bates Number#6#1##>>", "shrink": true }),+ );+ let after = text_box(&mut a);+ // 200 × 300 page, 8 pt text and 36 pt margins: the header takes 48 pt, the footer 46.4 pt.+ let k = (300.0 - 48.0 - 46.4) / 300.0;+ assert!((after[2] / before[2] - k).abs() < 0.02 && (after[3] / before[3] - k).abs() < 0.02, "scaled by {k}: {before:?} → {after:?}");+ assert!((after[0] - (20.0 * k + (200.0 - 200.0 * k) / 2.0)).abs() < 1.0, "centred across: {before:?} → {after:?}");+ assert!(page_text(&mut a, doc)[0].contains("000001"), "the Bates number is drawn");+ // Margins that leave no room are refused; Remove brings the content back to full size.+ let full = json!({ "doc": doc, "header_center": "X", "margins": [295, 36, 72, 72], "shrink": true, "replace": true });+ assert!(matches!(a.call("doc_header_footer", &full), Err(ToolError::Failed(_))), "no room");+ ok(&mut a, "doc_remove_marks", json!({ "doc": doc, "kind": "header_footer" }));+ let restored = text_box(&mut a);+ assert!(restored.iter().zip(before).all(|(r, b)| (r - b).abs() < 0.01), "{before:?} → {restored:?}");+ }+#[test]fn watermarks_move_from_the_page_centre_through_tools() {let dir = workdir("wm-offset");diff --cc crates/edit/src/lib.rsindex e2d69a97b,b86cabdc5..e321937e4--- a/crates/edit/src/lib.rs+++ b/crates/edit/src/lib.rs@@@ -740,12 -741,14 +798,17 @@@ pub fn add_header_footer(doc: &mut Doculet mut content = begin(MarkKind::HeaderFooter, "Header", page.view_matrix(doc)).into_bytes();content.extend(body);content.extend_from_slice(END.as_bytes());- add_resources(doc, page, None, None)?;+ // A name already there is that very font (see `free_font_name`): left as it is.+ if !page_fonts(doc, page).contains(resource.as_bytes()) {+ add_page_resources(doc, page, None, &[(resource.into_bytes(), base)])?;+ }let page = &page_list(doc)[i];place(doc, page, MarkKind::HeaderFooter, content, false)?;+ if let Some(Some(m)) = shrinks.get(k) {+ let cm = format!("{} cm\n", m.map(matrix_number).join(" "));+ let page = &page_list(doc)[i];+ place_inside_wrapper(doc, page, MarkKind::HeaderFooter.tag(), cm.into_bytes())?;+ }}Ok(())}diff --cc crates/ui-egui/tests/compare.rsindex e0ba29f6d,a6fd03596..22f65dfab--- a/crates/ui-egui/tests/compare.rs+++ b/crates/ui-egui/tests/compare.rs@@@ -59,44 -59,69 +59,107 @@@ fn compare_two_versions()assert_eq!(h.state().session.get(h.state().active_ids().unwrap().1).unwrap().name, "Compare Report.pdf");}+/// Two versions compared side by side (old `v1.pdf` left, new `v2.pdf` right).+fn side_by_side() -> Harness<'static, PdfCraftApp> {+ let s = Session::new();+ let v1 = s.create_from_text("t", "Delivery within five days. Returns accepted.").unwrap().to_vec();+ let v2 = s.create_from_text("t", "Delivery within three days. Returns accepted for a week.").unwrap().to_vec();+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {+ let mut app = PdfCraftApp::new();+ app.set_option("language", "en").unwrap();+ app.open_bytes("v1.pdf", None, v1.clone()).unwrap();+ app.open_bytes("v2.pdf", None, v2.clone()).unwrap();+ app+ });+ h.run_steps(4);+ assert!(h.state_mut().execute("doc.compare"));+ h.run_steps(2);+ h.get_by_label("Compare").click();+ h.run_steps(3);+ assert!(h.state().compare.as_ref().unwrap().side_by_side);+ h+}++/// #3915: a half that closes its own tab while it draws (its snapshot bar's Close sets+/// `close_requested`) must not leave the frame indexing the closed tab. Either half.+#[test]+fn closing_either_half_of_a_side_by_side_comparison_keeps_the_app_running() {+ for (half, name) in [(1, "v2.pdf"), (0, "v1.pdf")] {+ let mut h = side_by_side();+ let c = h.state().compare.as_ref().unwrap();+ let id = if half == 1 { c.new } else { c.old };+ let i = h.state().views.iter().position(|v| v.id == id).unwrap();+ h.state_mut().views[i].close_requested = true;+ h.run_steps(3);+ let s = h.state();+ assert_eq!(s.views.len(), 1, "the {name} tab closed");+ assert!(s.views.iter().all(|v| v.id != id));+ }+}++ /// Two versions whose differences are of both kinds: a replaced word (text) and a rectangle+ /// drawn far below the text (visual only, no text change explains it).+ fn text_and_visual_versions() -> (Vec<u8>, Vec<u8>) {+ let mut s = Session::new();+ let v1 = s.create_from_text("t", "Delivery within five days. Returns accepted.").unwrap().to_vec();+ let text = s.create_from_text("t", "Delivery within three days. Returns accepted.").unwrap();+ let id = s.open("v2.pdf", None, text, None).unwrap();+ let square = pdfcraft_engine::Shape::Rectangle { rect: [100.0, 80.0, 300.0, 200.0] };+ let style = pdfcraft_engine::Style::default_for(&square);+ let new = pdfcraft_engine::NewAnnotation { page: 0, shape: square, style, contents: String::new(), author: "Ada".into() };+ s.apply(id, pdfcraft_engine::Edit::AddAnnotation(new)).unwrap();+ (v1, s.save_bytes(id).unwrap().to_vec())+ }++ /// The Compare panel's Show: Text / Visual filter, on both halves: Text takes the text changes+ /// out of the list and the shading, Visual takes the visual differences (counted, never listed)+ /// out of the shading, and each brings them back.+ #[test]+ fn compare_filters_hide_text_or_visual_changes() {+ let (v1, v2) = text_and_visual_versions();+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {+ let mut app = PdfCraftApp::new();+ app.set_option("language", "en").unwrap();+ app.open_bytes("v1.pdf", None, v1.clone()).unwrap();+ app.open_bytes("v2.pdf", None, v2.clone()).unwrap();+ app+ });+ h.run_steps(4);+ h.state_mut().compare_old = h.state().views.first().map(|v| v.id);+ h.state_mut().run_compare();+ h.run_steps(3);+ let new_i = h.state().active_ids().unwrap().0;+ let old_i = h.state().views.iter().position(|v| v.id == h.state().compare.as_ref().unwrap().old).unwrap();+ // Visual differences are shaded orange (compare_ui::VISUAL), text changes in their kind's colour.+ let visual = egui::Color32::from_rgb(0xF0, 0x8C, 0x1A);+ let kinds = |h: &Harness<'_, PdfCraftApp>, i: usize| {+ let marks = &h.state().views[i].compare_marks;+ (marks.iter().filter(|m| m.2 != visual).count(), marks.iter().filter(|m| m.2 == visual).count())+ };+ let (text_new, visual_new) = kinds(&h, new_i);+ let (text_old, visual_old) = kinds(&h, old_i);+ assert!(text_new > 0 && visual_new > 0, "the fixture has both kinds on the new file: {text_new} text, {visual_new} visual");+ assert!(text_old > 0 && visual_old > 0, "and on the old file: {text_old} text, {visual_old} visual");+ h.get_by_label("\"five\" → \"three\"");++ h.get_by_label("Text").click();+ h.run_steps(2);+ assert!(h.query_by_label("\"five\" → \"three\"").is_none(), "text changes leave the list");+ assert_eq!(kinds(&h, new_i), (0, visual_new), "and the new file's shading");+ assert_eq!(kinds(&h, old_i), (0, visual_old), "and the old file's");++ h.get_by_label("Visual").click();+ h.run_steps(2);+ assert_eq!(kinds(&h, new_i), (0, 0));+ assert_eq!(kinds(&h, old_i), (0, 0));++ h.get_by_label("Text").click();+ h.run_steps(2);+ h.get_by_label("\"five\" → \"three\"");+ assert_eq!(kinds(&h, new_i), (text_new, 0), "text back, visual still hidden");+ assert_eq!(kinds(&h, old_i), (text_old, 0));+ }+/// Writes a screenshot of the Compare panel when PDFCRAFT_SHOT is set (for review).#[test]fn compare_panel_screenshot() {diff --cc crates/ui-egui/tests/ui_group/marks.rsindex e0d86c4ab,4b71d3bf7..d94594be0--- a/crates/ui-egui/tests/ui_group/marks.rs+++ b/crates/ui-egui/tests/ui_group/marks.rs@@@ -58,33 -58,21 +58,48 @@@ fn header_and_footer_dialog_inserts_tokassert!(marks(&h).is_empty());}+#[test]+fn header_and_footer_dialog_draws_in_the_chosen_face() {+ // #3754: the dialog offers Helvetica, Times and Courier (it only said "Font: Helvetica"),+ // and the face chosen is the one the page's header is drawn in.+ let mut h = harness();+ assert!(h.state_mut().execute("edit.header_footer"));+ h.run_steps(3);+ h.get_by_label("Font:");+ h.get_by_value("Helvetica").click();+ h.run_steps(2);+ h.get_by_label("Times").click();+ h.run_steps(2);+ assert_eq!(h.state().marks_draft.hf.font, pdfcraft_engine::FontFamily::Times);+ h.state_mut().marks_draft.hf.text[0] = "Serif".into();+ h.run_steps(2);+ h.get_by_label("OK").click();+ h.run_steps(4);+ assert_eq!(marks(&h), [MarkKind::HeaderFooter]);+ let s = h.state();+ let doc = pdfcraft_cos::Document::open(s.session.get(s.views[0].id).unwrap().bytes.clone()).unwrap();+ let page = &pdfcraft_model::pages(&doc)[0];+ let res = doc.resolve(page.dict.get(b"Resources").unwrap());+ let fonts = doc.resolve(res.as_dict().unwrap().get(b"Font").unwrap()).as_dict().cloned().unwrap();+ let face = doc.resolve(fonts.get(b"PCTimes").expect("Times is added")).as_dict().cloned().unwrap();+ assert_eq!(face.name(b"BaseFont"), Some(&b"Times-Roman"[..]));+}++ #[test]+ fn header_and_footer_dialog_can_shrink_the_page_content() {+ let mut h = harness();+ assert!(h.state_mut().execute("edit.bates"));+ h.run_steps(3);+ assert!(!h.state().marks_draft.hf.shrink, "off by default, as in Acrobat");+ h.get_by_label("Shrink the page content to make room for the header and footer").click();+ h.run_steps(2);+ assert!(h.state().marks_draft.hf.shrink);+ h.get_by_label("OK").click();+ h.run_steps(4);+ assert_eq!(h.state().dialog, None);+ assert_eq!(marks(&h), [MarkKind::HeaderFooter]);+ }+#[test]fn watermark_and_background_dialogs() {let mut h = harness();diff --cc docs/gaps.mdindex 3c74282af,933a3515c..494de43fa--- a/docs/gaps.md+++ b/docs/gaps.md@@@ -383,7 -386,7 +387,8 @@@ update the numbers| Date | Change | Summary ||---|---|---|+| 2026-10-19 | minor | Gap 2: a Type 0 font whose `/ToUnicode` is the name `/Identity-H` or `/Identity-V` (WSCAD) reads its codes as Unicode, so such pages have text to select, find and edit (hayro-interpret patch 44, `view.render-cid-fonts`). Estimates unchanged. |+ | 2026-10-15 | minor | Gap 21: the side-by-side view had already shipped; the Compare panel filters text changes and visual differences. Estimate 10–20 h → 8–16 h || 2026-10-15 | minor | Gap 12: the text oracle scores reading order as well as word F1, which is a bag of words and cannot see order; the first measurement separated 18 improvements from 6 regressions in a change F1 called unchanged on 26 of 29 files. Estimates unchanged. || 2026-10-14 | minor | M1: raw-deflate fallback preserves decoding-limit errors in strict and tolerant decoding; synthetic filter and COS stream regressions. Estimates unchanged. || 2026-10-15 | patch | Gap 24: record localization and installers as partial (unusable Chinese, Telugu and Arabic; unsigned Linux packages) |