PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M1: reject partial resource-fork copies and integrate current main
PerchAntone75551ce62c4
diff --cc ROADMAP.mdindex 3f628ab69,3eb8e6aaa..7cca8d558--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -36,6 -38,6 +38,7 @@@> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (#594 paragraph drags validated in the Linux test environment; localized shortcut labels, #496; readiness table with hours per audience; full number as weighted sum 49%; earlier: second look: ready 40% → 47%, mainstream 55% added; core-workflow gate applied → alpha) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (architectural paper controls from #599; localized shortcut labels, #496; readiness table with hours per audience; full number as weighted sum 49%; earlier: second look: ready 40% → 47%, mainstream 55% added; core-workflow gate applied → alpha) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (closed issues synced: #774, #756 and the #799–#821 batch; earlier: localized shortcut labels, #496; readiness table with hours per audience; full number as weighted sum 49%; earlier: second look: ready 40% → 47%, mainstream 55% added; core-workflow gate applied → alpha) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)++> **Last reviewed:** 2026-10-18 - **Last updated:** 2026-10-18 - **Change:** minor (M1 #2658: macOS atomic saves retain destination extended attributes, including Finder tags, and reject partial resource-fork reads after size changes. Metadata failures retain the original PDF and unsaved edit. Estimates unchanged)PdfCraft's one-page summary: how close it is to Adobe Acrobat Pro's offline feature set, and whatcomes next. Adobe's cloud services (Document Cloud, Acrobat Sign requests, shared review, the AI@@@ -166,7 -168,6 +169,8 @@@ Ranked; detail and the full milestone t| 8 | 1.0 polish: performance, right-to-left, missing languages, keyboard-only (M14) | 55–95 |## Progress log+++- **2026-10-18 (M1, #2658):** macOS atomic saves retain destination extended attributes, including Finder tags, and reject partial resource-fork reads after size changes. Metadata failures retain the original PDF and unsaved edit. Estimates unchanged.- **2026-10-15 (M7, Edit text caret):** In a text region that mixes sizes (a 24 pt title over 12 pt lines), the inline editor's caret on a small row was as tall as the region's first size and reached into the row below: egui draws the caret at least one row of the text field's font tall, and that font had the paragraph's first size. The field's font is now half the region's smallest size, so each row's own height decides. Kittest regression; checked in the app on a real document. Estimates unchanged.- **2026-10-16 (M3, #2781):** The Pages panel follows the current page, as Acrobat's page thumbnails do: going to a page whose thumbnail is out of sight (scrolling, Page Down, Go to page, a bookmark) scrolls the panel just enough to show it. A thumbnail already in view, or clicked, leaves the panel where it is, and a page change while the user scrolls the panel or drags thumbnails does not move it. Estimates unchanged.- **2026-10-16 (M12, #1645):** CLI info, text and render use the engine's dynamic XFA layout rather than placeholder pages. Synthetic two-page and encrypted-form regressions cover counts, text, pixels, copy permissions and unchanged input bytes. Estimates unchanged.diff --cc crates/platform/src/staging.rsindex 71bc19f59,2cee86c5e..fdf088c0f--- a/crates/platform/src/staging.rs+++ b/crates/platform/src/staging.rs@@@ -69,9 -97,9 +97,11 @@@ pub fn staging_suffixes() -> impl Itera/// crash, a full disk or a refused flush never leaves a half-written file where a good one was,/// and the target is untouched until the new file is complete. The target's folder must exist;/// a folder at the target is refused by the rename. Flushing is the staging file's own- /// (`sync_all`); parent-directory durability after a power loss is not promised.+ /// (`sync_all`); parent-directory durability after a power loss is not promised. On Unix a file+ /// that is replaced keeps its permissions, so a private file stays private; a new file gets the+ /// usual mode for a new file.+/// On macOS, accessible extended attributes of an existing regular destination are copied+/// before flushing; a copy failure refuses the save rather than losing metadata (#2658).pub fn write_atomically(path: &Path, bytes: &[u8], form: StagingName) -> std::io::Result<()> {write_atomically_with(path, bytes, form, staging_suffixes(), std::fs::File::sync_all)}@@@ -289,171 -284,33 +357,201 @@@ mod testslet _ = std::fs::remove_dir_all(&dir);}+ #[cfg(target_os = "macos")]+ #[test]+ fn atomic_saves_keep_finder_tags_and_binary_extended_attributes() {+ use rustix::fs::{XattrFlags, fgetxattr, setxattr};+ let dir = test_dir("xattrs");+ let target = dir.join("out.pdf");+ let attributes: &[(&str, &[u8])] = &[+ ("com.apple.metadata:_kMDItemUserTags", b"<plist version=\"1.0\"><array><string>PdfCraft\n6</string></array></plist>"),+ ("com.pdfcraft.test.binary", b"\0\xff\x80original\0"),+ ("com.pdfcraft.test.empty", b""),+ ];+ std::fs::write(&target, b"OLD").unwrap();+ for (name, value) in attributes {+ setxattr(&target, *name, value, XattrFlags::empty()).unwrap();+ }+ // Both desktop and automation name forms, including a second save of the replacement.+ for form in [StagingName::TagThenSuffix, StagingName::SuffixThenTag] {+ write_atomically_with(&target, b"NEW", form, [7], |staged| {+ for (name, value) in attributes {+ let mut bytes = [0u8; 256];+ let len = fgetxattr(staged, *name, &mut bytes[..]).unwrap();+ assert_eq!(&bytes[..len], *value, "metadata must be present before flush: {name}");+ }+ Ok(())+ })+ .unwrap();+ let saved = std::fs::File::open(&target).unwrap();+ for (name, value) in attributes {+ let mut bytes = [0u8; 256];+ let len = fgetxattr(&saved, *name, &mut bytes[..]).unwrap();+ assert_eq!(&bytes[..len], *value);+ }+ assert_eq!(std::fs::read(&target).unwrap(), b"NEW");+ assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);+ }+ std::fs::remove_dir_all(dir).unwrap();+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn a_failed_flush_keeps_the_original_extended_attributes() {+ use rustix::fs::{XattrFlags, getxattr, setxattr};+ let dir = test_dir("xattrs-flush");+ let target = dir.join("out.pdf");+ std::fs::write(&target, b"OLD").unwrap();+ setxattr(&target, "com.pdfcraft.test", b"original", XattrFlags::empty()).unwrap();+ let e = write_atomically_with(&target, b"NEW", StagingName::TagThenSuffix, [9], |_| Err(std::io::Error::other("flush refused"))).unwrap_err();+ assert!(e.to_string().contains("flush refused"));+ assert_eq!(std::fs::read(&target).unwrap(), b"OLD");+ let mut value = [0u8; 64];+ let len = getxattr(&target, "com.pdfcraft.test", &mut value[..]).unwrap();+ assert_eq!(&value[..len], b"original");+ assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);+ std::fs::remove_dir_all(dir).unwrap();+ }++ /// Model an HFS-style partial read while using real macOS metadata and the atomic writer.+ /// The shared read validator must reject growth before the staging file can be published.+ #[cfg(target_os = "macos")]+ #[test]+ fn a_growing_resource_fork_refuses_publication_and_keeps_original() {+ use rustix::fs::{XattrFlags, fgetxattr, fsetxattr, getxattr, setxattr};+ let dir = test_dir("xattrs-growing-fork");+ let target = dir.join("out.pdf");+ let name = "com.apple.ResourceFork";+ for form in [StagingName::TagThenSuffix, StagingName::SuffixThenTag] {+ std::fs::write(&target, b"ORIGINAL PDF").unwrap();+ setxattr(&target, name, b"ABC", XattrFlags::empty()).unwrap();+ let source = std::fs::File::open(&target).unwrap();+ let result = write_atomically_with(&target, b"REPLACEMENT PDF", form, [23], |staged| {+ let size = fgetxattr(&source, name, &mut [] as &mut [u8])?;+ let value = read_xattr_value(size, |buffer| {+ if buffer.is_empty() {+ return Ok(fgetxattr(&source, name, buffer)?);+ }+ // HFS can return the prefix that fits instead of ERANGE. APFS need not+ // have that behaviour: model the kernel response, not a timing race.+ setxattr(&target, name, b"ABCD", XattrFlags::empty())?;+ buffer.get_mut(..3).unwrap().copy_from_slice(b"ABC");+ Ok(3)+ })?;+ fsetxattr(staged, name, &value, XattrFlags::empty())?;+ Ok(())+ });+ let error = result.expect_err("a short prefix of the grown fork must not be published");+ assert!(error.to_string().contains("changed size"), "{error}");+ assert_eq!(std::fs::read(&target).unwrap(), b"ORIGINAL PDF");+ let mut bytes = [0u8; 8];+ let len = getxattr(&target, name, &mut bytes[..]).unwrap();+ assert_eq!(&bytes[..len], b"ABCD", "the original's grown fork must remain intact");+ assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "staging files are removed on refusal");+ }+ std::fs::remove_dir_all(dir).unwrap();+ }++ /// Stable empty/binary values are accepted; short reads, growth and failed rechecks are refused.+ #[cfg(target_os = "macos")]+ #[test]+ fn attribute_reads_require_a_complete_value_and_stable_size() {+ for bytes in [&b""[..], &b"\0\xffB"[..]] {+ let value = read_xattr_value(bytes.len(), |buffer| {+ if !buffer.is_empty() {+ buffer.get_mut(..bytes.len()).unwrap().copy_from_slice(bytes);+ }+ Ok(bytes.len())+ })+ .unwrap();+ assert_eq!(value, bytes);+ }+ for (before, read_len, after) in [(3, 2, 3), (3, 3, 4), (0, 1, 1), (3, 2, 2)] {+ let result = read_xattr_value(before, |buffer| Ok(if buffer.is_empty() { after } else { read_len }));+ assert!(result.unwrap_err().to_string().contains("changed size"));+ }+ let result = read_xattr_value(3, |buffer| {+ if buffer.is_empty() { Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "size recheck refused")) } else { Ok(3) }+ });+ assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::PermissionDenied);+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn oversized_extended_attributes_refuse_the_save_without_replacing_the_target() {+ use rustix::fs::{XattrFlags, getxattr, setxattr};+ let dir = test_dir("xattrs-limit");+ let target = dir.join("out.pdf");+ std::fs::write(&target, b"OLD").unwrap();+ // A resource fork can exceed the ordinary attribute limit on macOS. No fixture file+ // is committed; only the OS metadata of this temporary synthetic file holds the bytes.+ let fork = vec![42u8; 16 * 1024 * 1024 + 1];+ setxattr(&target, "com.apple.ResourceFork", &fork, XattrFlags::empty()).unwrap();+ let mut flushed = false;+ let e = write_atomically_with(&target, b"NEW", StagingName::TagThenSuffix, [10], |_| {+ flushed = true;+ Ok(())+ })+ .unwrap_err();+ assert!(e.to_string().contains("extended attributes"), "{e}");+ assert!(e.to_string().contains("Save As"), "{e}");+ assert!(!flushed, "metadata failure must stop before flush and rename");+ assert_eq!(std::fs::read(&target).unwrap(), b"OLD");+ let size = getxattr(&target, "com.apple.ResourceFork", &mut [] as &mut [u8]).unwrap();+ assert_eq!(size, fork.len());+ assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);+ std::fs::remove_dir_all(dir).unwrap();+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn replacing_a_symlink_does_not_copy_attributes_from_its_referent() {+ use rustix::fs::{XattrFlags, getxattr, setxattr};+ let dir = test_dir("xattrs-symlink");+ let outside = test_dir("xattrs-outside").join("private.pdf");+ std::fs::write(&outside, b"PRIVATE").unwrap();+ setxattr(&outside, "com.pdfcraft.test", b"private metadata", XattrFlags::empty()).unwrap();+ let target = dir.join("out.pdf");+ std::os::unix::fs::symlink(&outside, &target).unwrap();+ write_atomically(&target, b"NEW", StagingName::TagThenSuffix).unwrap();+ assert_eq!(std::fs::read(&outside).unwrap(), b"PRIVATE");+ assert_eq!(std::fs::read(&target).unwrap(), b"NEW");+ assert!(!target.symlink_metadata().unwrap().file_type().is_symlink());+ let mut bytes = [0u8; 64];+ assert_eq!(getxattr(&target, "com.pdfcraft.test", &mut bytes[..]).unwrap_err(), rustix::io::Errno::NOATTR);+ let len = getxattr(&outside, "com.pdfcraft.test", &mut bytes[..]).unwrap();+ assert_eq!(&bytes[..len], b"private metadata");+ std::fs::remove_dir_all(dir).unwrap();+ std::fs::remove_dir_all(outside.parent().unwrap()).unwrap();+ }+++ /// #1790: a replaced file keeps its permissions, and its staging file already has them while+ /// it is written; a new file gets the same mode as any other new file.+ #[cfg(unix)]+ #[test]+ fn a_replaced_file_keeps_its_permissions() {+ use std::os::unix::fs::PermissionsExt as _;+ let dir = test_dir("modes");+ let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;+ let target = dir.join("out.pdf");+ for keep in [0o600, 0o640, 0o664] {+ std::fs::write(&target, b"OLD").unwrap();+ std::fs::set_permissions(&target, std::fs::Permissions::from_mode(keep)).unwrap();+ let mut staged = 0;+ write_atomically_with(&target, b"NEW", StagingName::SuffixThenTag, [keep as u64], |f| {+ staged = f.metadata()?.permissions().mode() & 0o777;+ Ok(())+ })+ .unwrap();+ assert_eq!(staged, keep, "the staging file has the target's mode before it is flushed");+ assert_eq!(mode(&target), keep, "the saved file keeps mode {keep:o}");+ assert_eq!(std::fs::read(&target).unwrap(), b"NEW");+ }+ let fresh = dir.join("new.pdf");+ write_atomically(&fresh, b"NEW", StagingName::TagThenSuffix).unwrap();+ let plain = dir.join("plain");+ std::fs::write(&plain, b"").unwrap();+ assert_eq!(mode(&fresh), mode(&plain), "a new file is not made private");+ let _ = std::fs::remove_dir_all(&dir);+ }}diff --cc docs/roadmap.mdindex 97416da7e,c76936a7e..9e97a9503--- a/docs/roadmap.md+++ b/docs/roadmap.md@@@ -43,6 -43,6 +43,7 @@@> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (M13: reject malformed CLI --root options before dispatch; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (Traditional Chinese accessibility semantics and Taiwan form/table terminology; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** patch (M1 #1337: exhausted xref hints are repaired; allocation avoids overflow; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)++> **Last reviewed:** 2026-10-18 - **Last updated:** 2026-10-18 - **Change:** minor (M1 #2658: macOS atomic saves retain destination extended attributes, including Finder tags, and reject partial resource-fork reads after size changes. Metadata failures retain the original PDF and unsaved edit. Estimates unchanged)Forward-looking: the milestones, the current focus and what comes next. The parity numbers behindit are in [target-app-parity.md](target-app-parity.md), the ranked work list in [gaps.md](gaps.md),@@@ -107,7 -107,7 +108,7 @@@ total matches the parity estimate| M | Milestone | Plan size (h) | Done | Remaining (h, 2026-10-10) | Notes ||---|---|---|---|---|---|| 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). A full rewrite keeps unknown trailer entries, including objects reachable only from them (#1338). Fuzzing runs nightly (`xtask fuzz`). Raw-deflate fallback preserves decoding-limit errors, including through tolerant COS stream decoding. Refreshed against upstream `99941daa` (2026-10-15). Done since: macOS atomic saves retain accessible destination xattrs, including Finder tags; a metadata failure keeps the original and the unsaved edit (#2658, metadata only). Done since: Post-read size checks refuse partial resource-fork copies when metadata changes during a save. Missing: ≥ 250 tests, own image codecs |-| 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). A full rewrite keeps unknown trailer entries, including objects reachable only from them (#1338). Fuzzing runs nightly (`xtask fuzz`). Raw-deflate fallback preserves decoding-limit errors, including through tolerant COS stream decoding. Missing: ≥ 250 tests, own image codecs |++| 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). A full rewrite keeps unknown trailer entries, including objects reachable only from them (#1338). Fuzzing runs nightly (`xtask fuzz`). Raw-deflate fallback preserves decoding-limit errors, including through tolerant COS stream decoding. Done since: macOS atomic saves retain destination extended attributes, including Finder tags, and reject partial resource-fork reads after size changes. Metadata failures retain the original PDF and unsaved edit. (#2658). 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. 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. Packed TIFF-predictor RGB rows retain later rows in decoding and rendering. The renderer keeps its one-point crop-size floor in physical points after UserUnit scaling, with regression coverage for crop origins, rotations and f32 reciprocal rounding. Existing unit policy and nearly-zero fallback are retained. || 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 |