PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M2: preserve precision when writing page transforms (#946)
sanyamsingh001dbef872ed77b
diff --git a/ROADMAP.md b/ROADMAP.mdindex b4ab4ea8a..309d4dccd 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -149,6 +149,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md## Progress log+- **2026-10-13 (M2, page-unit transform precision):** Preserve small transform coefficients in page marks, added content and print output. Regression cases cover accepted page units of 4096 and 75000; existing page-unit interpretation and estimates are unchanged.- **2026-10-13 (M3, native-opening candidate):** Chosen tools survive preparation, conversion and password retries; startup intake waits for pending preparation. Regression tests cover completion, cancellation and document identity. Estimates unchanged.- **2026-10-12 (M10, Windows printing without PowerShell, #1107):** craft-print now prints on Windows in-process: printers from EnumPrinters/GetDefaultPrinter, jobs drawn as vectors by Windows.Data.Pdf into the XPS print API with a driver-validated PrintTicket (exact paper, orientation, no scaling), so printing works where App Control for Business or AppLocker run PowerShell in Constrained Language Mode. Portrait and landscape sheets still print as one job (turned with /Rotate); a sheet size the driver lacks is refused rather than shrunk. Pins craft-libs f03ec27 (craft-libs#28); deny.toml allows the storytold/winprint.rs fork and adds a webpki-root-certs licence exception and a RUSTSEC-2024-0370 ignore for winprint's build-dependencies. An earlier craft-print revision was checked in Windows Sandbox under enforced WDAC: printers listed, CLI and desktop jobs spooled, and no powershell.exe in the 4688 audit. The final pinned revision passed craft-libs Windows CI, including a real paused-queue job; that Sandbox run has not been repeated. Estimates unchanged.- **2026-10-12 (M13, CLI robustness scans):** `pdfcraft-cli check` visits a directory once even when input roots overlap or directory symlinks lead back into the tree. PDFs reached through file symlinks remain accepted. Three real CLI regressions cover overlapping roots, a directory cycle and directory/file aliases. Estimates unchanged.diff --git a/crates/edit/src/added.rs b/crates/edit/src/added.rsindex 9f13047b0..12008dee8 100644--- a/crates/edit/src/added.rs+++ b/crates/edit/src/added.rs@@ -14,7 +14,7 @@ use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, Stream};use pdfcraft_fonts::{GlyphError, GlyphOutline, ShapedCluster, ShapedScript, Std14, literal, shape_arabic, shape_thai, shaped_glyph, win_ansi};use unicode_bidi::{Level, ParagraphBidiInfo};-use crate::{EditError, MarkKind, check, contents, n, page_list, place_tagged};+use crate::{EditError, MarkKind, check, contents, matrix_number, n, page_list, place_tagged};const TAG: &str = "Added";@@ -701,7 +701,16 @@ fn type3_shaped(doc: &mut Document, clusters: &[&ShapedCluster], outlines: &Hash/// keeps drawing its Arabic as `?`, as before Arabic was supported, rather than refusing to move it.fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict, existing: bool) -> Result<(Vec<u8>, Dict), EditError> {let mut res = Dict::new();- let mut out = format!("q {} {} {} {} {} {} cm\n", n(view[0]), n(view[1]), n(view[2]), n(view[3]), n(view[4]), n(view[5])).into_bytes();+ let mut out = format!(+ "q {} {} {} {} {} {} cm\n",+ matrix_number(view[0]),+ matrix_number(view[1]),+ matrix_number(view[2]),+ matrix_number(view[3]),+ matrix_number(view[4]),+ matrix_number(view[5])+ )+ .into_bytes();match c {Content::Text(t) => {let base = t.family.base_font(t.bold, t.italic);diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rsindex d92f28405..336e948ae 100644--- a/crates/edit/src/lib.rs+++ b/crates/edit/src/lib.rs@@ -172,6 +172,13 @@ pub struct Context {pub date: (i64, u32, u32),}+// Model-derived transforms can contain tiny scale factors; retain their PDF decimal precision.+fn matrix_number(value: f64) -> String {+ let mut bytes = Vec::new();+ pdfcraft_cos::serialize(&Object::Real(value), &mut bytes);+ String::from_utf8_lossy(&bytes).into_owned()+}+fn n(v: f64) -> String {let s = format!("{:.3}", if v.abs() < 5e-4 { 0.0 } else { v });let s = s.trim_end_matches('0').trim_end_matches('.');@@ -365,12 +372,12 @@ fn begin(kind: MarkKind, subtype: &str, matrix: [f64; 6]) -> String {format!("q\n/Artifact <</Type /Pagination /Subtype /{subtype} /PCMark /{}>> BDC\n{} {} {} {} {} {} cm\n",kind.tag(),- n(matrix[0]),- n(matrix[1]),- n(matrix[2]),- n(matrix[3]),- n(matrix[4]),- n(matrix[5])+ matrix_number(matrix[0]),+ matrix_number(matrix[1]),+ matrix_number(matrix[2]),+ matrix_number(matrix[3]),+ matrix_number(matrix[4]),+ matrix_number(matrix[5]))}diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rsindex fce7d5e10..ecbedb9b4 100644--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@ -3443,3 +3443,49 @@ fn an_items_measured_face_is_the_face_it_is_written_as() {let courier = |italic| Family::Courier.width("Anna", 12.0, false, italic);assert_eq!(courier(false), courier(true));}++#[test]+fn page_marks_and_added_content_preserve_fractional_user_unit_matrices() {+ for rotation in [0, 90] {+ let mut doc = fixture();+ let page = pdfcraft_model::pages(&doc)[2].obj;+ doc.update_dict(page, |d| {+ let bounds = Object::Array([0.0, 0.0, 0.1, 0.1].into_iter().map(Object::Real).collect());+ d.set(b"MediaBox".to_vec(), bounds.clone());+ d.set(b"CropBox".to_vec(), bounds);+ d.set(b"UserUnit".to_vec(), Object::Int(4096));+ d.set(b"Rotate".to_vec(), Object::Int(rotation));+ })+ .unwrap();+ let mut hf = HeaderFooter::default();+ hf.text[0] = "Matrix header".into();+ add_header_footer(&mut doc, &[2], &hf, false, &cx()).unwrap();+ let text = AddedText { rect: [72.0, 100.0, 200.0, 144.0], text: "Matrix text".into(), size: 12.0, ..AddedText::default() };+ add_content(&mut doc, 2, &Content::Text(text)).unwrap();+ let saved = reopen(&doc);+ let contents = streams(&saved, 2);+ for marker in ["/PCMark /HeaderFooter", "(Matrix text) Tj"] {+ let matching: Vec<_> = contents.iter().filter(|s| s.contains(marker)).collect();+ assert_eq!(matching.len(), 1, "{contents:?}");+ let stream = matching[0];+ let parsed = pdfcraft_content::parse(stream.as_bytes());+ assert_eq!(parsed.skipped, 0);+ let cm = parsed.ops.iter().find(|op| op.is("cm")).unwrap();+ assert_eq!(cm.operands.len(), 6);+ assert!(!stream[cm.span.clone()].contains('e') && !stream[cm.span.clone()].contains('E'), "PDF numbers cannot use exponents");+ let matrix = cm.nums::<6>().unwrap();+ let expected = if rotation == 0 {+ [0.000244140625, 0.0, 0.0, 0.000244140625, 0.0, 0.0]+ } else {+ [0.0, 0.000244140625, -0.000244140625, 0.0, 0.1, 0.0]+ };+ assert_eq!(matrix, expected, "rotation={rotation}, stream={stream}");+ // A fixed physical display point must remain at its intended raw page position.+ let raw = [matrix[0] * 72.0 + matrix[2] * 144.0 + matrix[4], matrix[1] * 72.0 + matrix[3] * 144.0 + matrix[5]];+ let expected_raw = if rotation == 0 { [0.017578125, 0.03515625] } else { [0.06484375, 0.017578125] };+ for (actual, expected) in raw.into_iter().zip(expected_raw) {+ assert!((actual - expected).abs() < 1e-12);+ }+ }+ }+}diff --git a/crates/print/src/lib.rs b/crates/print/src/lib.rsindex b4ed59959..cbffdc4e2 100644--- a/crates/print/src/lib.rs+++ b/crates/print/src/lib.rs@@ -506,6 +506,13 @@ pub fn layout(sizes: &[(f64, f64)], settings: &Settings) -> Result<Vec<Sheet>, POk(sheets)}+// Model-derived transforms and clipping bounds need their full PDF decimal precision.+fn geometry_number(value: f64) -> String {+ let mut bytes = Vec::new();+ pdfcraft_cos::serialize(&Object::Real(value), &mut bytes);+ String::from_utf8_lossy(&bytes).into_owned()+}+fn n(v: f64) -> String {let s = format!("{v:.4}");let s = s.trim_end_matches('0').trim_end_matches('.');@@ -669,22 +676,22 @@ pub fn impose(src: &Document, settings: &Settings) -> Result<Vec<u8>, PrintErrorlet [x0, y0, x1, y1] = pl.clip;c.push_str(&format!("q {} {} {} {} {} {} cm {} {} {} {} re W n {} {} {} {} {} {} cm /{name} Do Q\n",- n(a),- n(b),- n(cc),- n(d),- n(e),- n(f),- n(x0),- n(y0),- n(x1 - x0),- n(y1 - y0),- n(ua),- n(ub),- n(uc),- n(ud),- n(ue),- n(uf)+ geometry_number(a),+ geometry_number(b),+ geometry_number(cc),+ geometry_number(d),+ geometry_number(e),+ geometry_number(f),+ geometry_number(x0),+ geometry_number(y0),+ geometry_number(x1 - x0),+ geometry_number(y1 - y0),+ geometry_number(ua),+ geometry_number(ub),+ geometry_number(uc),+ geometry_number(ud),+ geometry_number(ue),+ geometry_number(uf)));}if !sheet.borders.is_empty() || !sheet.lines.is_empty() {diff --git a/crates/print/src/tests.rs b/crates/print/src/tests.rsindex ee21c2706..e87862408 100644--- a/crates/print/src/tests.rs+++ b/crates/print/src/tests.rs@@ -643,3 +643,52 @@ fn paper_matching_accepts_rounded_metric_sizes_but_not_custom_or_invalid_sizes()assert_eq!(matching_paper(size), None);}}++#[test]+fn imposed_pages_preserve_large_user_unit_matrices() {+ let (unit, mode) = (75000.0, SizeMode::Fit);+ let mut doc = fixture(1);+ let page = pdfcraft_model::pages(&doc)[0].obj;+ doc.update_dict(page, |d| d.set(b"UserUnit".to_vec(), Object::Real(unit))).unwrap();+ let out = impose(&doc, &Settings { content: Content::Document, ..settings(vec![0], Layout::Size(mode)) }).unwrap();+ let printed = Document::open(Arc::new(out)).unwrap();+ let page = &pdfcraft_model::pages(&printed)[0];+ let contents = printed.resolve(page.dict.get(b"Contents").unwrap());+ let Object::Stream(stream) = &*contents else { panic!("sheet content") };+ let bytes = stream.decoded().unwrap();+ let parsed = pdfcraft_content::parse(&bytes);+ assert_eq!(parsed.skipped, 0);+ let cms: Vec<_> = parsed.ops.iter().filter(|op| op.is("cm")).collect();+ assert_eq!(cms.len(), 2, "placement and source-to-display matrices");+ let normalized = f64::from(unit as f32);+ let scale = if mode == SizeMode::Actual { 1.0 } else { 756.0 / (300.0 * normalized) };+ let expected = [+ [scale, 0.0, 0.0, scale, 306.0 - 100.0 * normalized * scale, 396.0 - 150.0 * normalized * scale],+ [normalized, 0.0, 0.0, normalized, 0.0, 0.0],+ ];+ for (cm, expected) in cms.iter().zip(expected) {+ assert_eq!(cm.operands.len(), 6);+ assert!(!bytes[cm.span.clone()].contains(&b'e') && !bytes[cm.span.clone()].contains(&b'E'));+ for (actual, expected) in cm.nums::<6>().unwrap().into_iter().zip(expected) {+ assert!((actual - expected).abs() <= 1e-12 * expected.abs(), "unit={unit}: {actual} != {expected}");+ }+ }+ let clip = parsed.ops.iter().find(|op| op.is("re")).unwrap();+ assert_eq!(clip.operands.len(), 4);+ let rect = clip.nums::<4>().unwrap();+ assert_eq!(rect, [0.0, 0.0, 200.0 * normalized, 300.0 * normalized]);+ assert!(rect[2] > 0.0 && rect[3] > 0.0, "the clip must retain the visible page");+ let clip_tokens = std::str::from_utf8(&bytes[clip.span.clone()]).unwrap();+ assert!(clip_tokens.split_whitespace().take(4).all(|token| !token.contains('e') && !token.contains('E')));+ let apply = |m: [f64; 6], p: [f64; 2]| [m[0] * p[0] + m[2] * p[1] + m[4], m[1] * p[0] + m[3] * p[1] + m[5]];+ let to_sheet = |p| apply(cms[0].nums::<6>().unwrap(), apply(cms[1].nums::<6>().unwrap(), p));+ let mut anchors = vec![([100.0, 150.0], [306.0, 396.0])];+ if mode == SizeMode::Fit {+ anchors.extend([([0.0, 0.0], [54.0, 18.0]), ([200.0, 300.0], [558.0, 774.0])]);+ }+ for (raw, expected) in anchors {+ for (actual, expected) in to_sheet(raw).into_iter().zip(expected) {+ assert!((actual - expected).abs() < 1e-9, "unit={unit}: {actual} != {expected}");+ }+ }+}diff --git a/docs/roadmap.md b/docs/roadmap.mdindex fabb5e603..95e9142ef 100644--- a/docs/roadmap.md+++ b/docs/roadmap.md@@ -89,7 +89,7 @@ total matches the parity estimate.|---|---|---|---|---|---|| M0 | Skeleton: workspace, xtask gates, CI | 15–30 | 98% | 1–2 | GitHub workflow, `deny.toml` (licence audit of every dependency), parity checklist (826 features, `xtask parity`) done. Missing: remaining crate stubs, testkit/oracle crates || M1 | COS: filters, crypt, parser, xref, writer | 120–200 | 80% | 20–40 | Done:<br>- filters and crypt: every standard-security revision R2–R6 (RC4, AES-128/256), SASLprep, permissions, creating encryption;<br>- cos: parse and repair (including invalid xref object-number ranges), decoded-stream limits including unfiltered data, decrypt on load, re-encrypt on save, incremental and full writing.<br>Corpus: open/edit/save passes on 958 files, and all 7 password-protected files open.<br>Full saves now pack objects into compressed object streams. An unchanged incremental save of a classic table writes a zero-length cross-reference subsection instead of a section with no subsections (#1339). Fuzzing runs nightly (`xtask fuzz`). Missing: ≥ 250 tests, own image codecs |-| 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. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Packed TIFF-predictor RGB rows retain later rows in decoding and rendering. |+| 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. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Packed TIFF-predictor RGB rows retain later rows in decoding and rendering. Page marks, added content and print output retain small page-unit transform coefficients when serialized. || 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. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings || 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<br>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). #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. || 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 |