collective

Browse / github.com/storytold/pdfcraft / patch

M10: preserve annotation layers in vector print output

Vector printing loses annotation optional-content membership and exposes hidden-layer artwork Current main `1dd2737b` loses an annotation dictionary's `/OC` membership when `doc_print` turns its appearance into page content. The print-ready PDF exposes the annotation even when the document's optional-content configuration hides its layer. Contributor-original synthetic fixture: - One Letter page, ordinary blue page-content marker. - Printable Square annotation with `/Rect [30 40 70 60]`, `/F 4`, `/OC 7 0 R` and a normal green Form appearance. - Object 7 is an OCG listed in catalog `/OCProperties /OCGs` and `/D /OFF`. - The appearance stream itself has no `/OC`. Run `doc_open` follow

Status
open
Score
0.00
Adopters
0 other operators
Author
KyleKassen (imported from pull request #5019, open)
Base
e9fc890a862ea2d8c895ea32ddecda98580483cd
Size
+733 −42 in 15 files
Review
pending
Shared
2026-10-28
Id
1340a10615f7a170d497a682

How it went

No other operator has reported using it yet.

Diff

raw · ATTRIBUTION.md ATTRIBUTION.toml Cargo.lock Cargo.toml ROADMAP.md crates/ocr/Cargo.toml crates/ocr/src/lib.rs crates/print/README.md crates/print/src/imposition.rs crates/print/src/tests.rs crates/print/src/tests/optional_content.rs docs/releasing.md docs/roadmap.md packaging/windows/test-msi.ps1 parity/acrobat-features.toml

diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md--- a/ATTRIBUTION.md+++ b/ATTRIBUTION.md@@ -335,8 +335,8 @@ Fonts are fetched by `cargo xtask demo-pdf` into `target/demo-fonts/`, OCR model | `NotoColorEmoji-Regular.ttf` | Noto Color Emoji | Google Inc. | OFL-1.1 | https://github.com/google/fonts/tree/9710da1eacb3be272583c3224dcb70f9da6eadbb/ofl/notocoloremoji | Showcase PDF (cargo xtask demo-pdf) | | `Inter[opsz,wght].ttf` | Inter (variable) | The Inter Project Authors (Rasmus Andersson) | OFL-1.1 | https://github.com/google/fonts/tree/9710da1eacb3be272583c3224dcb70f9da6eadbb/ofl/inter | Showcase PDF (cargo xtask demo-pdf) | | `Inter-Italic[opsz,wght].ttf` | Inter Italic (variable) | The Inter Project Authors (Rasmus Andersson) | OFL-1.1 | https://github.com/google/fonts/tree/9710da1eacb3be272583c3224dcb70f9da6eadbb/ofl/inter | Showcase PDF (cargo xtask demo-pdf) |-| `text-detection.rten` | Ocrs text detection model | Robert Knight (ocrs-models; trained on HierText, CC-BY-SA-4.0) | CC-BY-SA-4.0 | https://github.com/robertknight/ocrs-models (the models ocrs downloads; model card: https://huggingface.co/robertknight/ocrs, cc-by-sa-4.0) | Scan & OCR: finds words on page images (cargo xtask models) |-| `text-recognition.rten` | Ocrs text recognition model | Robert Knight (ocrs-models; trained on HierText, CC-BY-SA-4.0) | CC-BY-SA-4.0 | https://github.com/robertknight/ocrs-models (the models ocrs downloads; model card: https://huggingface.co/robertknight/ocrs, cc-by-sa-4.0) | Scan & OCR: reads the words it finds (cargo xtask models) |+| `text-detection.onnx` | Ocrs text detection model | Robert Knight (ocrs-models; trained on HierText, CC-BY-SA-4.0) | CC-BY-SA-4.0 | https://github.com/robertknight/ocrs/blob/0c826441362a701c55560fefc17bf356b6d1037e/ocrs/examples/download-models.sh (author-published ONNX models; model card: https://huggingface.co/robertknight/ocrs/blob/df0edd170279ab971b53e094c627255a87e1a503/README.md, cc-by-sa-4.0) | Scan & OCR: finds words on page images (cargo xtask models) |+| `text-recognition.onnx` | Ocrs text recognition model | Robert Knight (ocrs-models; trained on HierText, CC-BY-SA-4.0) | CC-BY-SA-4.0 | https://github.com/robertknight/ocrs/blob/0c826441362a701c55560fefc17bf356b6d1037e/ocrs/examples/download-models.sh (author-published ONNX models; model card: https://huggingface.co/robertknight/ocrs/blob/df0edd170279ab971b53e094c627255a87e1a503/README.md, cc-by-sa-4.0) | Scan & OCR: reads the words it finds (cargo xtask models) |  ## Optional build inputs (1) diff --git a/ATTRIBUTION.toml b/ATTRIBUTION.toml--- a/ATTRIBUTION.toml+++ b/ATTRIBUTION.toml@@ -3356,30 +3356,30 @@ usage = "1x + 2x HiDPI 16-colour palette TIFF copied into the macOS DMG by packa sha256 = "f46881724a6621f3686a612a79dbdce4f7dbe9e2025610e44c9a094341334c2c"  [[fetched]]-file = "text-detection.rten"-url = "https://ocrs-models.s3-accelerate.amazonaws.com/text-detection.rten"+file = "text-detection.onnx"+url = "https://ocrs-models.s3-accelerate.amazonaws.com/text-detection.onnx" title = "Ocrs text detection model" author = "Robert Knight (ocrs-models; trained on HierText, CC-BY-SA-4.0)"-source = "https://github.com/robertknight/ocrs-models (the models ocrs downloads; model card: https://huggingface.co/robertknight/ocrs, cc-by-sa-4.0)"+source = "https://github.com/robertknight/ocrs/blob/0c826441362a701c55560fefc17bf356b6d1037e/ocrs/examples/download-models.sh (author-published ONNX models; model card: https://huggingface.co/robertknight/ocrs/blob/df0edd170279ab971b53e094c627255a87e1a503/README.md, cc-by-sa-4.0)" licence = "CC-BY-SA-4.0" licence_url = "https://creativecommons.org/licenses/by-sa/4.0/legalcode.txt" licence_sha256 = "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5" kind = "model" usage = "Scan & OCR: finds words on page images (cargo xtask models)"-sha256 = "f15cfb56bd02c4bf478a20343986504a1f01e1665c2b3a0ad66340f054b1b5ca"+sha256 = "a917b23dbd9524b465df7e922641b3ff2981623df4ded5a0234004ef2fee7cfe"  [[fetched]]-file = "text-recognition.rten"-url = "https://ocrs-models.s3-accelerate.amazonaws.com/text-recognition.rten"+file = "text-recognition.onnx"+url = "https://ocrs-models.s3-accelerate.amazonaws.com/text-recognition.onnx" title = "Ocrs text recognition model" author = "Robert Knight (ocrs-models; trained on HierText, CC-BY-SA-4.0)"-source = "https://github.com/robertknight/ocrs-models (the models ocrs downloads; model card: https://huggingface.co/robertknight/ocrs, cc-by-sa-4.0)"+source = "https://github.com/robertknight/ocrs/blob/0c826441362a701c55560fefc17bf356b6d1037e/ocrs/examples/download-models.sh (author-published ONNX models; model card: https://huggingface.co/robertknight/ocrs/blob/df0edd170279ab971b53e094c627255a87e1a503/README.md, cc-by-sa-4.0)" licence = "CC-BY-SA-4.0" licence_url = "https://creativecommons.org/licenses/by-sa/4.0/legalcode.txt" licence_sha256 = "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5" kind = "model" usage = "Scan & OCR: reads the words it finds (cargo xtask models)"-sha256 = "e484866d4cce403175bd8d00b128feb08ab42e208de30e42cd9889d8f1735a6e"+sha256 = "86c145c2edb96c8caed5b1ebb8f44d706408922211451c309c625157dd6061c5"  [[build_input]] name = "craft-fonts"diff --git a/Cargo.lock b/Cargo.lock--- a/Cargo.lock+++ b/Cargo.lock@@ -1174,7 +1174,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=82a24b006eefa036b43c09 [[package]] name = "craft-keymap" version = "0.1.0"-source = "git+https://github.com/storytold/craft-libs?rev=edc41f68fa24c46651c3b5117d10f0ead75ec9cb#edc41f68fa24c46651c3b5117d10f0ead75ec9cb"+source = "git+https://github.com/storytold/craft-libs?rev=acab34c0d8d84363ea3d05885f1a15601c233a19#acab34c0d8d84363ea3d05885f1a15601c233a19" dependencies = [  "egui",  "serde",@@ -1184,7 +1184,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0"-source = "git+https://github.com/storytold/craft-libs?rev=edc41f68fa24c46651c3b5117d10f0ead75ec9cb#edc41f68fa24c46651c3b5117d10f0ead75ec9cb"+source = "git+https://github.com/storytold/craft-libs?rev=acab34c0d8d84363ea3d05885f1a15601c233a19#acab34c0d8d84363ea3d05885f1a15601c233a19" dependencies = [  "craft-keymap",  "craft-quit",@@ -1210,7 +1210,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0"-source = "git+https://github.com/storytold/craft-libs?rev=edc41f68fa24c46651c3b5117d10f0ead75ec9cb#edc41f68fa24c46651c3b5117d10f0ead75ec9cb"+source = "git+https://github.com/storytold/craft-libs?rev=acab34c0d8d84363ea3d05885f1a15601c233a19#acab34c0d8d84363ea3d05885f1a15601c233a19" dependencies = [  "dispatch2",  "egui",@@ -1221,7 +1221,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0"-source = "git+https://github.com/storytold/craft-libs?rev=edc41f68fa24c46651c3b5117d10f0ead75ec9cb#edc41f68fa24c46651c3b5117d10f0ead75ec9cb"+source = "git+https://github.com/storytold/craft-libs?rev=acab34c0d8d84363ea3d05885f1a15601c233a19#acab34c0d8d84363ea3d05885f1a15601c233a19" dependencies = [  "egui",  "log",@@ -4340,6 +4340,7 @@ dependencies = [  "ocrs",  "pdfcraft-fonts",  "rten",+ "tempfile",  "thiserror 2.0.21", ] @@ -5473,6 +5474,7 @@ dependencies = [  "rten-base",  "rten-gemm",  "rten-model-file",+ "rten-onnx",  "rten-parallel",  "rten-shape-inference",  "rten-simd",@@ -5522,6 +5524,12 @@ dependencies = [  "rten-base", ] +[[package]]+name = "rten-onnx"+version = "0.26.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96944374568990b8d1bbc5bae5957585866f9dd8256130460405730948bfd42e"+ [[package]] name = "rten-parallel" version = "0.26.0"diff --git a/Cargo.toml b/Cargo.toml--- a/Cargo.toml+++ b/Cargo.toml@@ -13,12 +13,12 @@ repository = "https://github.com/storytold/pdfcraft"  [workspace.dependencies] # Shared frontend components; engines remain independent of egui.-craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "edc41f68fa24c46651c3b5117d10f0ead75ec9cb", features = ["serde"] }+craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "acab34c0d8d84363ea3d05885f1a15601c233a19", features = ["serde"] } # Quit the macOS way (#1136): ⌘Q asks about unsaved changes, and closing quits through `terminate:`.-craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "edc41f68fa24c46651c3b5117d10f0ead75ec9cb" }+craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "acab34c0d8d84363ea3d05885f1a15601c233a19" } # One menu definition for the native macOS menu bar and the in-window bar elsewhere.-craft-menu = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "edc41f68fa24c46651c3b5117d10f0ead75ec9cb" }-craft-keymap = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "edc41f68fa24c46651c3b5117d10f0ead75ec9cb", default-features = false }+craft-menu = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "acab34c0d8d84363ea3d05885f1a15601c233a19" }+craft-keymap = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "acab34c0d8d84363ea3d05885f1a15601c233a19", default-features = false } # Shared system spooler; document composition remains in pdfcraft-print. craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "42e30cd5b3f4b114270dd053fccbc33bedc47f68" } # Whether a path stored in a document may be opened (GoToR link targets).diff --git a/ROADMAP.md b/ROADMAP.md--- a/ROADMAP.md+++ b/ROADMAP.md@@ -2,6 +2,8 @@  **Stage: alpha** · next: beta, ~25% (ready for real work 50% → 75%) and ~400–700 h away +> **Last reviewed:** 2026-10-27 | **Last updated:** 2026-10-27 | **Change:** minor (M10: vector printing preserves annotation optional-content membership; estimates unchanged)+> **Last reviewed:** 2026-10-27 | **Last updated:** 2026-10-27 | **Change:** minor (M10: OCR model downloads use verified ONNX pairs with legacy discovery fallback; estimates unchanged) > **Last reviewed:** 2026-10-25 | **Last updated:** 2026-10-25 | **Change:** minor (M14 localization current state: Arabic logical catalog, explicit RTL label direction and mirrored stock chrome; native/browser RTL workflows unqualified. Native release Hans face via LXGW WenKai Lite; estimates unchanged) > **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M7, #2636 partial: pasting added text boxes and images in the engine and through `content_copy`; estimates unchanged) > **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M11: image optimization accounts for page-local UserUnit; estimates unchanged)@@ -199,6 +201,10 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md  ## Progress log +- **2026-10-27 (M10, #5005):** Vector printing retains each annotation's optional-content membership when drawing its appearance.+  Shared appearances and existing layer state remain independent; estimates unchanged.++- **2026-10-27 (M10, OCR models):** Model staging downloads and verifies the ONNX pair after the upstream RTEN URL brownout; runtime discovery prefers complete ONNX pairs per directory, retains complete RTEN fallback and preserves directory precedence. - **2026-10-24 (M10, #4158 partial):** Word, HTML, RTF and PowerPoint export keep a block that continues another on its line (an italic case name, a link, a superscript) as a run in its own style inside that paragraph, with the source's word space, instead of a paragraph of its own. Style changes that wrap onto the next line still split paragraphs (the reading blocks keep style boundaries). Estimates unchanged. - **2026-10-24 (M3, window move on Wayland, #3970 follow-up):** After a move or resize by PdfCraft's own title bar or edges, the button release given back to egui goes before the pointer leaving the window, so hover no longer sticks at the old place until the pointer moves. Found by CodeRabbit in review of #3970; a unit test covers it. Estimates unchanged. - **2026-10-24 (M14, #4253):** The annotation quick bar remembers Keep tool selected across restarts, including unpinning. Old and malformed settings keep safe defaults; the opt-in UI control channel reads and changes the same preference. Estimates unchanged.@@ -676,12 +682,17 @@ Newest first: the date, what moved, and the new overall estimate.  ## Revision history +**2026-10-27 · minor:** M10 #5005: vector printing preserves annotation optional-content membership.+Source resources and shared appearances remain unchanged.+Estimates unchanged.+ **2026-10-25 · minor:** M14 localization current state: Arabic catalogs stay logical, Arabic/Kurdish labels take an explicit RTL direction, and stock chrome mirrors; native/browser RTL input, IME and complex workflows remain unqualified. Native Simplified Chinese uses LXGW WenKai Lite; the web build has no Hans face. Estimates unchanged.  **2026-10-15 · minor:** M14/#2383 candidate: GPU device requests clamp unsupported limits while retaining the adapter texture extent. Synthetic V3D/downlevel regressions and Windows GPU-required tests pass; Raspberry Pi hardware remains unverified. Estimates unchanged.  | Date | Change | Summary | |---|---|---|+| 2026-10-27 | minor | M10: OCR stages SHA-256-verified ONNX models after the upstream RTEN URL brownout; discovery prefers a complete ONNX pair per directory, falls back to a complete RTEN pair, and never mixes formats or directories; language/web limits and estimates unchanged. | | 2026-10-23 | minor | M8, #3205 follow-up: phone-pattern redaction includes the +39 country code on labelled Italian geographic numbers with a slash; dates, protocol identifiers and whole-run guards remain. Estimates unchanged. | | 2026-10-23 | minor | M11: image downsampling measures physical resolution after page-local UserUnit scaling, including shared nested forms; synthetic measurement and optimization regressions. Estimates unchanged. | | 2026-10-23 | minor | M10: Word table cells use the grid columns they span, including cells after a merged cell; synthetic export regression and CLI reproduction. Estimates unchanged. |diff --git a/crates/ocr/Cargo.toml b/crates/ocr/Cargo.toml--- a/crates/ocr/Cargo.toml+++ b/crates/ocr/Cargo.toml@@ -13,5 +13,8 @@ workspace = true [dependencies] pdfcraft-fonts = { workspace = true } ocrs = { version = "0.13.1", default-features = false, features = ["rten"] }-rten = { version = "0.26.0", default-features = false, features = ["rten_format"] }+rten = { version = "0.26.0", default-features = false, features = ["onnx_format", "rten_format"] } thiserror.workspace = true++[dev-dependencies]+tempfile = "3.27"diff --git a/crates/ocr/src/lib.rs b/crates/ocr/src/lib.rs--- a/crates/ocr/src/lib.rs+++ b/crates/ocr/src/lib.rs@@ -15,8 +15,8 @@ use std::path::{Path, PathBuf}; pub use pdfcraft_fonts::helvetica_width;  /// The model files, as named in ATTRIBUTION.toml.-pub const DETECTION_MODEL: &str = "text-detection.rten";-pub const RECOGNITION_MODEL: &str = "text-recognition.rten";+pub const DETECTION_MODEL: &str = "text-detection.onnx";+pub const RECOGNITION_MODEL: &str = "text-recognition.onnx";  /// The recognition model's alphabet, as it was trained (ocrs-models' `DEFAULT_ALPHABET`): its /// output classes follow this order. The ocrs crate's own copy has an `E` where the training had@@ -48,10 +48,13 @@ pub struct Models { }  impl Models {-    /// The models in `dir`, if both files are there.+    /// A complete model pair in `dir`, preferring current ONNX files over legacy RTEN files.+    /// An incomplete update never mixes formats or hides an intact legacy pair.     pub fn in_dir(dir: &Path) -> Option<Models> {-        let m = Models { detection: dir.join(DETECTION_MODEL), recognition: dir.join(RECOGNITION_MODEL) };-        (m.detection.is_file() && m.recognition.is_file()).then_some(m)+        [(DETECTION_MODEL, RECOGNITION_MODEL), ("text-detection.rten", "text-recognition.rten")].into_iter().find_map(|(detection, recognition)| {+            let m = Models { detection: dir.join(detection), recognition: dir.join(recognition) };+            (m.detection.is_file() && m.recognition.is_file()).then_some(m)+        })     }      /// Look for the models: `$PDFCRAFT_MODELS`, then where the release packages install them@@ -321,6 +324,63 @@ mod tests {         assert_eq!(w.up, [-10.0, 0.0]);     } +    /// The current ONNX pair wins when an installation also retains both legacy models.+    #[test]+    fn model_discovery_prefers_the_complete_onnx_pair() {+        let dir = tempfile::tempdir().unwrap();+        for file in ["text-detection.onnx", "text-recognition.onnx"] {+            std::fs::write(dir.path().join(file), b"model").unwrap();+        }+        let expected = Some(Models { detection: dir.path().join("text-detection.onnx"), recognition: dir.path().join("text-recognition.onnx") });+        assert_eq!(Models::in_dir(dir.path()), expected, "a complete ONNX pair is sufficient");+        for file in ["text-detection.rten", "text-recognition.rten"] {+            std::fs::write(dir.path().join(file), b"model").unwrap();+        }+        assert_eq!(Models::in_dir(dir.path()), expected, "the complete ONNX pair takes precedence over legacy models");+    }++    /// An interrupted ONNX update still permits an intact legacy pair in the same directory.+    #[test]+    fn model_discovery_falls_back_to_legacy_when_the_onnx_pair_is_incomplete() {+        for current in ["text-detection.onnx", "text-recognition.onnx"] {+            let dir = tempfile::tempdir().unwrap();+            for file in [current, "text-detection.rten", "text-recognition.rten"] {+                std::fs::write(dir.path().join(file), b"model").unwrap();+            }+            assert_eq!(+                Models::in_dir(dir.path()),+                Some(Models { detection: dir.path().join("text-detection.rten"), recognition: dir.path().join("text-recognition.rten") }),+                "{current} alone must not hide a complete legacy pair"+            );+        }+    }++    /// Detection and recognition must come from one complete format pair, never a mixed update.+    #[test]+    fn model_discovery_refuses_mixed_format_pairs() {+        for pair in [["text-detection.onnx", "text-recognition.rten"], ["text-detection.rten", "text-recognition.onnx"]] {+            let dir = tempfile::tempdir().unwrap();+            for file in pair {+                std::fs::write(dir.path().join(file), b"model").unwrap();+            }+            assert_eq!(Models::in_dir(dir.path()), None, "{pair:?} is not a complete model pair");+        }+    }++    /// Existing source builds and PDFCRAFT_MODELS overrides retain their complete RTEN pair.+    #[test]+    fn model_discovery_keeps_legacy_only_installations() {+        let dir = tempfile::tempdir().unwrap();+        assert_eq!(Models::in_dir(dir.path()), None);+        std::fs::write(dir.path().join("text-detection.rten"), b"model").unwrap();+        assert_eq!(Models::in_dir(dir.path()), None, "one legacy model is incomplete");+        std::fs::write(dir.path().join("text-recognition.rten"), b"model").unwrap();+        assert_eq!(+            Models::in_dir(dir.path()),+            Some(Models { detection: dir.path().join("text-detection.rten"), recognition: dir.path().join("text-recognition.rten") })+        );+    }+     /// #103: every release package's layout puts the models where the installed app looks.     /// Mirrors packaging/{windows/package.ps1,macos/package.sh,linux/package.sh,freebsd/package.sh}.     #[test]diff --git a/crates/print/README.md b/crates/print/README.md--- a/crates/print/README.md+++ b/crates/print/README.md@@ -36,6 +36,11 @@ Each source page becomes a Form XObject (its content wrapped in q/Q, plus the pr annotations); sheets place them with a clip. The result is a fresh, unencrypted, garbage-collected file (callers check the print permission). Annotation appearances receive unused XObject names, preserving existing page resources even when they use the same naming prefix.+Vector printing also carries each annotation's optional-content membership onto its own appearance invocation.+Hidden groups, membership policies, visibility expressions and existing layer overrides therefore remain effective in the generated PDF, including when appearances are shared.+Malformed top-level membership or required resource containers produce a print error instead of an unguarded appearance.+Nested policy data is preserved without a new evaluator; readers remain responsible for optional-content semantics.+The separate on-screen and Print as image annotation-visibility gap is tracked in #3572 / #3624.  The GUI Print dialog remembers its last selected paper size across application sessions, including when Print is cancelled. The preference stores a canonical name such as `A4`;@@ -62,8 +67,7 @@ In a browser there is no spooler: the app (`pdfcraft-ui-egui`'s `web_print`) dra PDF's sheets with PdfCraft's renderer and prints them through the browser's print dialog, which sets copies, two-sided printing and colour. This crate stays free of web APIs. -Not yet: print as image, poster labels, PostScript output, colour conversion for-grayscale.+Not yet: poster labels, PostScript output and vector colour conversion for grayscale.  ## Architectural sheets and scale diff --git a/crates/print/src/imposition.rs b/crates/print/src/imposition.rs--- a/crates/print/src/imposition.rs+++ b/crates/print/src/imposition.rs@@ -145,6 +145,56 @@ pub(crate) fn appearance_matrix(doc: &Document, form: &Dict, rect: [f64; 4]) ->     Some(a) } +/// Resolve optional-content resources without turning a loading failure or reference cycle+/// into an absent entry. Keep the terminal object's identity for catalog OCG state.+fn optional_object(doc: &Document, value: &Object) -> Result<(Option<ObjRef>, std::sync::Arc<Object>), PrintError> {+    let mut object = std::sync::Arc::new(value.clone());+    let mut reference = None;+    let mut seen = std::collections::HashSet::new();+    while let Object::Ref(r) = &*object {+        if seen.len() >= 64 || !seen.insert(*r) {+            return Err(PrintError::Invalid("an optional-content resource has a cyclic reference or more than 64 references".into()));+        }+        reference = Some(*r);+        object = doc.try_get(r.num)?;+    }+    Ok((reference, object))+}++/// Preserve the complete membership rather than evaluating visibility here. The reader owns+/// policy/VE evaluation; the annotation and its appearance can have independent memberships.+fn annotation_membership(doc: &mut Document, annotation: &Dict) -> Result<Option<ObjRef>, PrintError> {+    let Some(value) = annotation.get(b"OC") else { return Ok(None) };+    let (reference, object) = optional_object(doc, value)?;+    let dict = match &*object {+        Object::Null => return Ok(None), // Null and undefined references are absent PDF dictionary entries.+        Object::Dict(dict) => dict,+        _ => return Err(PrintError::Invalid("an annotation's optional-content entry is not an OCG or OCMD dictionary".into())),+    };+    let kind = dict.get(b"Type").map(|value| optional_object(doc, value)).transpose()?;+    match kind.as_ref().and_then(|(_, object)| object.as_name()) {+        Some(b"OCG") => reference.map(Some).ok_or_else(|| PrintError::Invalid("an annotation's optional-content group must be indirect".into())),+        Some(b"OCMD") => {+            // Named Properties are indirect for interoperable OCG identity and for the renderer's+            // resource path. An OCMD has no group identity; promoting its intact dict is harmless.+            Ok(Some(reference.unwrap_or_else(|| doc.add(Object::Dict(dict.clone())))))+        }+        _ => Err(PrintError::Invalid("an annotation's optional-content dictionary must have Type OCG or OCMD".into())),+    }+}++/// Clone existing marked-content properties, including unrelated entries. Never replace an+/// unreadable map with an empty one: doing so can expose the page's own optional content.+fn optional_properties(doc: &Document, resources: &Dict) -> Result<Dict, PrintError> {+    let Some(value) = resources.get(b"Properties") else { return Ok(Dict::new()) };+    let (_, object) = optional_object(doc, value)?;+    match &*object {+        Object::Null => Ok(Dict::new()),+        Object::Dict(dict) => Ok(dict.clone()),+        _ => Err(PrintError::Invalid("cannot preserve annotation layers: page Properties is not a dictionary".into())),+    }+}+ /// A Form XObject holding page `index` as it prints (user space; BBox = crop box). /// `pages` are the document's pages, listed once by the caller: listing them for each page /// printed would make printing quadratic in the page count.@@ -157,7 +207,8 @@ pub(crate) fn page_form( ) -> Result<ObjRef, PrintError> {     let page = pages.get(index).ok_or_else(|| PrintError::Invalid(format!("there is no page {}", index.saturating_add(1))))?;     let crop = page.crop(doc);-    let mut res = page.dict.get(b"Resources").and_then(|r| doc.resolve(r).as_dict().cloned()).unwrap_or_default();+    let resources = page.dict.get(b"Resources").map(|value| optional_object(doc, value)).transpose();+    let mut res = resources.as_ref().ok().and_then(|value| value.as_ref()).and_then(|(_, object)| object.as_dict()).cloned().unwrap_or_default();     let mut body = if content == Content::FormFieldsOnly {         Vec::new()     } else {@@ -173,6 +224,8 @@ pub(crate) fn page_form(     }     let annots = page.dict.get(b"Annots").and_then(|a| doc.resolve(a).as_array().cloned()).unwrap_or_default();     let mut xobjects = res.get(b"XObject").and_then(|x| doc.resolve(x).as_dict().cloned()).unwrap_or_default();+    let mut properties = None;+    let mut property_index = 0usize;     let mut k = 0usize;     for a in annots {         let Some(d) = doc.resolve(&a).as_dict().cloned() else { continue };@@ -188,6 +241,31 @@ pub(crate) fn page_form(         let Some(ap) = appearance(doc, &d) else { continue };         let form = doc.get(ap).as_dict().cloned().unwrap_or_default();         let Some(m) = appearance_matrix(doc, &form, rect) else { continue };+        let membership = annotation_membership(doc, &d)?;+        let property = if let Some(membership) = membership {+            if properties.is_none() {+                match &resources {+                    Err(error) => return Err(PrintError::Invalid(format!("cannot preserve annotation layers: {error}"))),+                    Ok(Some((_, object))) if !matches!(&**object, Object::Null | Object::Dict(_)) => {+                        return Err(PrintError::Invalid("cannot preserve annotation layers: page Resources is not a dictionary".into()));+                    }+                    _ => {}+                }+                properties = Some(optional_properties(doc, &res)?);+            }+            let properties = properties.get_or_insert_with(Dict::new);+            let name = loop {+                let name = format!("PCPrOC{property_index}");+                property_index = property_index.checked_add(1).ok_or_else(|| PrintError::Invalid("too many annotation layer resources".into()))?;+                if !properties.contains(name.as_bytes()) {+                    break name;+                }+            };+            properties.set(name.as_bytes().to_vec(), Object::Ref(membership));+            Some(name)+        } else {+            None+        };         let ap = if !form.contains(b"Subtype")             && let Object::Stream(stream) = &*doc.get(ap)         {@@ -215,12 +293,21 @@ pub(crate) fn page_form(             }         };         let [a0, b0, c0, d0, e0, f0] = m.0;+        if let Some(name) = &property {+            body.extend(format!("/OC /{name} BDC\n").bytes());+        }         body.extend(format!("q {} {} {} {} {} {} cm /{name} Do Q\n", n(a0), n(b0), n(c0), n(d0), n(e0), n(f0)).bytes());+        if property.is_some() {+            body.extend_from_slice(b"EMC\n");+        }         xobjects.set(name.into_bytes(), Object::Ref(ap));     }     if !xobjects.is_empty() {         res.set(b"XObject".to_vec(), Object::Dict(xobjects));     }+    if let Some(properties) = properties {+        res.set(b"Properties".to_vec(), Object::Dict(properties));+    }     let mut d = Dict::new();     d.set(b"Type".to_vec(), Object::name("XObject"));     d.set(b"Subtype".to_vec(), Object::name("Form"));diff --git a/crates/print/src/tests.rs b/crates/print/src/tests.rs--- a/crates/print/src/tests.rs+++ b/crates/print/src/tests.rs@@ -955,6 +955,7 @@ fn driver_options_take_the_ppds_own_names_in_the_ui_language() { }  mod appearances;+mod optional_content;  #[test] fn repeated_content_references_share_one_decode_budget() {diff --git a/crates/print/src/tests/optional_content.rs b/crates/print/src/tests/optional_content.rsnew file mode 100644--- /dev/null+++ b/crates/print/src/tests/optional_content.rs@@ -0,0 +1,500 @@+use super::*;+use pdfcraft_render::{PageRenderer, RenderConfig, RenderRequest, RenderedPage, RequestKind};++fn numbers(values: &[f64]) -> Object {+    Object::Array(values.iter().copied().map(Object::Real).collect())+}++fn layer_fixture(off: bool) -> (Document, ObjRef, ObjRef, ObjRef) {+    let mut doc = fixture(1);+    let page = pdfcraft_model::pages(&doc)[0].obj;+    let group = doc.add(Object::Dict(Dict::from_iter([+        (b"Type".to_vec(), Object::name("OCG")),+        (b"Name".to_vec(), Object::String(pdfcraft_cos::PdfString::text("Annotation Layer"))),+    ])));+    let properties = Dict::from_iter([+        (b"OCGs".to_vec(), Object::Array(vec![Object::Ref(group)])),+        (+            b"D".to_vec(),+            Object::Dict(Dict::from_iter([+                (b"BaseState".to_vec(), Object::name("ON")),+                (b"OFF".to_vec(), Object::Array(if off { vec![Object::Ref(group)] } else { vec![] })),+            ])),+        ),+    ]);+    doc.update_dict(doc.root().unwrap(), |d| d.set(b"OCProperties".to_vec(), Object::Dict(properties))).unwrap();+    let form = Dict::from_iter([+        (b"Subtype".to_vec(), Object::name("Form")),+        (b"BBox".to_vec(), numbers(&[0.0, 0.0, 20.0, 10.0])),+        (b"Resources".to_vec(), Object::Dict(Dict::new())),+    ]);+    let appearance = doc.add(Object::Stream(Stream::flate(form, b"0 1 0 rg 0 0 20 10 re f")));+    let annotation = doc.add(Object::Dict(Dict::from_iter([+        (b"Subtype".to_vec(), Object::name("Square")),+        (b"F".to_vec(), Object::Int(4)),+        (b"Rect".to_vec(), numbers(&[10.0, 20.0, 50.0, 40.0])),+        (b"OC".to_vec(), Object::Ref(group)),+        (b"AP".to_vec(), Object::Dict(Dict::from_iter([(b"N".to_vec(), Object::Ref(appearance))]))),+    ])));+    let contents = doc.add(Object::Stream(Stream::flate(Dict::new(), b"0 0 1 rg 0 0 8 8 re f")));+    doc.update_dict(page, |d| {+        d.set(b"MediaBox".to_vec(), numbers(&[0.0, 0.0, 100.0, 100.0]));+        d.set(b"Resources".to_vec(), Object::Dict(Dict::new()));+        d.set(b"Contents".to_vec(), Object::Ref(contents));+        d.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(annotation)]));+    })+    .unwrap();+    (doc, group, annotation, appearance)+}++fn render(bytes: Vec<u8>) -> RenderedPage {+    let page = PageRenderer::new(Arc::new(bytes), RenderConfig::default()).render(RenderRequest {+        page: 0,+        kind: RequestKind::Pixels,+        tile: None,+        scale: 1.0,+        tag: 0,+        preview: false,+    });+    assert_eq!(page.error, None);+    assert!(page.warnings.is_empty(), "{:?}", page.warnings);+    assert_eq!((page.width, page.height), (100, 100));+    page+}++fn print(doc: &Document) -> Result<Vec<u8>, PrintError> {+    impose(doc, &Settings { pages: vec![0], paper: (100.0, 100.0), layout: Layout::Size(SizeMode::Actual), ..Settings::default() })+}++#[test]+fn vector_print_preserves_annotation_layer_membership() {+    for off in [false, true] {+        let (doc, _, _, _) = layer_fixture(off);+        let before = write_full(&doc, &SaveOptions::default()).unwrap();+        let printed = print(&doc).unwrap();+        let reopened = Document::open(Arc::new(printed.clone())).unwrap();+        assert_eq!(pdfcraft_model::pages(&reopened).len(), 1);+        let page = render(printed);+        let pixel = |x: usize, y: usize| &page.rgba[(y * 100 + x) * 4..(y * 100 + x + 1) * 4];+        assert_eq!(pixel(30, 70), if off { [255, 255, 255, 255] } else { [0, 255, 0, 255] }, "layer off={off}");+        assert_eq!(pixel(4, 96), [0, 0, 255, 255], "ordinary page artwork");+        assert_eq!(write_full(&doc, &SaveOptions::default()).unwrap(), before);+    }+}++fn saved(doc: &Document) -> Vec<u8> {+    write_full(doc, &SaveOptions::default()).unwrap()+}++fn pixel(page: &RenderedPage, x: usize, y: usize) -> &[u8] {+    let offset = (y * page.width as usize + x) * 4;+    &page.rgba[offset..offset + 4]+}++fn assert_appearance(page: &RenderedPage, visible: bool) {+    assert_eq!(pixel(page, 30, 70), if visible { [0, 255, 0, 255] } else { [255, 255, 255, 255] });+    assert_eq!(pixel(page, 4, 96), [0, 0, 255, 255], "ordinary page artwork");+}++fn add_group(doc: &mut Document, name: &str, off: bool) -> ObjRef {+    let group = doc.add(Object::Dict(Dict::from_iter([+        (b"Type".to_vec(), Object::name("OCG")),+        (b"Name".to_vec(), Object::String(pdfcraft_cos::PdfString::text(name))),+    ])));+    let root = doc.root().unwrap();+    let mut properties = doc.resolve(doc.get(root).as_dict().unwrap().get(b"OCProperties").unwrap()).as_dict().unwrap().clone();+    let mut groups = properties.get(b"OCGs").unwrap().as_array().unwrap().clone();+    groups.push(Object::Ref(group));+    properties.set(b"OCGs".to_vec(), Object::Array(groups));+    if off {+        let mut config = properties.get(b"D").unwrap().as_dict().unwrap().clone();+        let mut hidden = config.get(b"OFF").unwrap().as_array().unwrap().clone();+        hidden.push(Object::Ref(group));+        config.set(b"OFF".to_vec(), Object::Array(hidden));+        properties.set(b"D".to_vec(), Object::Dict(config));+    }+    doc.update_dict(root, |d| d.set(b"OCProperties".to_vec(), Object::Dict(properties))).unwrap();+    group+}++fn membership(groups: Vec<Object>, policy: Option<&str>, expression: Option<Vec<Object>>) -> Dict {+    let mut dict = Dict::from_iter([+        (b"Type".to_vec(), Object::name("OCMD")),+        (b"OCGs".to_vec(), Object::Array(groups)),+        (b"PrivatePolicy".to_vec(), Object::Array(vec![Object::Int(19), Object::name("KeepMe")])),+    ]);+    if let Some(policy) = policy {+        dict.set(b"P".to_vec(), Object::name(policy));+    }+    if let Some(expression) = expression {+        dict.set(b"VE".to_vec(), Object::Array(expression));+    }+    dict+}++fn printed_form(doc: &Document) -> Dict {+    let page = pdfcraft_model::pages(doc)[0].dict.clone();+    let resources = doc.resolve(page.get(b"Resources").unwrap());+    let xobjects = doc.resolve(resources.as_dict().unwrap().get(b"XObject").unwrap());+    doc.resolve(xobjects.as_dict().unwrap().get(b"P0").unwrap()).as_dict().unwrap().clone()+}++fn form_properties(doc: &Document) -> Dict {+    let form = printed_form(doc);+    let resources = doc.resolve(form.get(b"Resources").unwrap());+    doc.resolve(resources.as_dict().unwrap().get(b"Properties").unwrap()).as_dict().unwrap().clone()+}++#[test]+fn vector_print_preserves_ocmd_policies_and_visibility_expressions() {+    for indirect in [false, true] {+        for group_shape in 0..3 {+            let single_group = group_shape != 0;+            for (policy, visible) in [("AllOn", false), ("AnyOn", !single_group), ("AnyOff", true), ("AllOff", single_group)] {+                let (mut doc, off, annotation, appearance) = layer_fixture(true);+                let on = add_group(&mut doc, "Visible", false);+                let groups = if single_group { vec![Object::Ref(off)] } else { vec![Object::Ref(off), Object::Ref(on)] };+                let mut dict = membership(groups, Some(policy), None);+                if group_shape == 2 {+                    dict.set(b"OCGs".to_vec(), Object::Ref(off));+                }+                let private = dict.get(b"PrivatePolicy").unwrap().clone();+                let oc = if indirect { Object::Ref(doc.add(Object::Dict(dict))) } else { Object::Dict(dict) };+                doc.update_dict(annotation, |d| d.set(b"OC".to_vec(), oc)).unwrap();+                let before = saved(&doc);+                let original_appearance = doc.get(appearance);+                let printed = print(&doc).unwrap();+                assert_appearance(&render(printed.clone()), visible);+                let reopened = Document::open(Arc::new(printed)).unwrap();+                let props = form_properties(&reopened);+                let membership = props.get(b"PCPrOC0").unwrap();+                assert!(membership.as_ref().is_some(), "direct OCMD must be promoted for named-resource rendering");+                assert_eq!(reopened.resolve(membership).as_dict().unwrap().get(b"PrivatePolicy"), Some(&private));+                assert_appearance(&render(print(&reopened).unwrap()), visible);+                assert_eq!(doc.get(appearance), original_appearance);+                assert_eq!(saved(&doc), before, "policy={policy}, indirect={indirect}, single={single_group}");+            }+        }+        for case in 0..6 {+            let (mut doc, off, annotation, _) = layer_fixture(true);+            let on = add_group(&mut doc, "Visible", false);+            let mut dict = membership(vec![Object::Ref(off), Object::Ref(on)], None, None);+            let visible = match case {+                0 => true, // Missing P defaults to AnyOn.+                1 => {+                    dict.set(b"P".to_vec(), Object::name("AllOn"));+                    dict.set(b"VE".to_vec(), Object::Array(vec![Object::name("Not"), Object::Ref(off)]));+                    true // VE overrides the false AllOn policy.+                }+                2 => {+                    dict.set(b"P".to_vec(), Object::name("AnyOn"));+                    dict.set(b"VE".to_vec(), Object::Array(vec![Object::name("Not"), Object::Ref(on)]));+                    false // VE also overrides a true policy.+                }+                3 => {+                    dict.remove(b"OCGs");+                    true // Missing OCGs is a valid no-op.+                }+                4 => {+                    dict.set(b"OCGs".to_vec(), Object::Array(vec![]));+                    true+                }+                _ => {+                    dict.remove(b"OCGs");+                    dict.set(b"VE".to_vec(), Object::Array(vec![Object::name("Not"), Object::Ref(on)]));+                    false // VE-only membership is valid.+                }+            };+            let oc = if indirect { Object::Ref(doc.add(Object::Dict(dict))) } else { Object::Dict(dict) };+            doc.update_dict(annotation, |d| d.set(b"OC".to_vec(), oc)).unwrap();+            let before = saved(&doc);+            assert_appearance(&render(print(&doc).unwrap()), visible);+            assert_eq!(saved(&doc), before, "OCMD case={case}, indirect={indirect}");+        }+    }+}++#[test]+fn annotation_and_appearance_layers_are_independent_and_shared_appearances_stay_shared() {+    for annotation_off in [false, true] {+        for appearance_off in [false, true] {+            let (mut doc, _, annotation, appearance) = layer_fixture(annotation_off);+            let appearance_group = add_group(&mut doc, "Appearance", appearance_off);+            doc.update_dict(appearance, |d| d.set(b"OC".to_vec(), Object::Ref(appearance_group))).unwrap();+            let before = saved(&doc);+            let first = print(&doc).unwrap();+            assert_appearance(&render(first.clone()), !annotation_off && !appearance_off);+            let reopened = Document::open(Arc::new(first)).unwrap();+            assert_appearance(&render(print(&reopened).unwrap()), !annotation_off && !appearance_off);+            assert_eq!(saved(&doc), before);+            assert_eq!(doc.get(annotation).as_dict().unwrap().get(b"AP").unwrap().as_dict().unwrap().reference(b"N"), Some(appearance));+        }+    }+    let (mut doc, _, annotation, appearance) = layer_fixture(true);+    let visible = add_group(&mut doc, "Visible", false);+    let mut other = doc.get(annotation).as_dict().unwrap().clone();+    other.set(b"OC".to_vec(), Object::Ref(visible));+    other.set(b"Rect".to_vec(), numbers(&[10.0, 50.0, 50.0, 70.0]));+    let other = doc.add(Object::Dict(other));+    let page = pdfcraft_model::pages(&doc)[0].obj;+    doc.update_dict(page, |d| d.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(annotation), Object::Ref(other)]))).unwrap();+    let before = saved(&doc);+    let original = doc.get(appearance);+    let first = print(&doc).unwrap();+    let reopened = Document::open(Arc::new(first.clone())).unwrap();+    for bytes in [first, print(&reopened).unwrap()] {+        let image = render(bytes);+        assert_appearance(&image, false);+        assert_eq!(pixel(&image, 30, 40), [0, 255, 0, 255], "the other annotation uses the same appearance in a visible layer");+    }+    let form = printed_form(&reopened);+    let resources = reopened.resolve(form.get(b"Resources").unwrap());+    let objects = reopened.resolve(resources.as_dict().unwrap().get(b"XObject").unwrap());+    let objects = objects.as_dict().unwrap();+    assert_eq!(objects.get(b"PCPrA0"), objects.get(b"PCPrA1"), "membership belongs to each invocation, not an appearance copy");+    assert_eq!(doc.get(appearance), original);+    assert_eq!(saved(&doc), before);+}++#[test]+fn annotation_layers_keep_colliding_inherited_and_shared_page_properties() {+    for indirect_resources in [false, true] {+        for indirect_properties in [false, true] {+            for inherited in [false, true] {+                let (mut doc, hidden, annotation, appearance) = layer_fixture(true);+                let visible = add_group(&mut doc, "Visible", false);+                let unrelated = Object::Dict(Dict::from_iter([(b"PrivateKey".to_vec(), Object::name("KeepMe"))]));+                let properties = Dict::from_iter([+                    (b"PCPrOC0".to_vec(), Object::Ref(hidden)),+                    (b"PCPrOC1".to_vec(), Object::Ref(visible)),+                    (b"PCPrOC3".to_vec(), Object::Null),+                    (b"Unrelated".to_vec(), unrelated.clone()),+                ]);+                let properties = if indirect_properties { Object::Ref(doc.add(Object::Dict(properties))) } else { Object::Dict(properties) };+                let resources = Dict::from_iter([(b"Properties".to_vec(), properties)]);+                let resources = if indirect_resources { Object::Ref(doc.add(Object::Dict(resources))) } else { Object::Dict(resources) };+                // The appearance shares the page's resource owner, so in-place extension would change both.+                doc.update_dict(appearance, |d| d.set(b"Resources".to_vec(), resources.clone())).unwrap();+                let mut other = doc.get(annotation).as_dict().unwrap().clone();+                other.set(b"OC".to_vec(), Object::Ref(visible));+                other.set(b"Rect".to_vec(), numbers(&[10.0, 50.0, 50.0, 70.0]));+                let other = doc.add(Object::Dict(other));+                let contents = doc.add(Object::Stream(Stream::flate(+                    Dict::new(),+                    b"0 0 1 rg 0 0 8 8 re f\n/OC /PCPrOC0 BDC 1 0 0 rg 60 60 10 10 re f EMC\n/OC /PCPrOC1 BDC 0 0 1 rg 70 60 10 10 re f EMC\n/Span /Unrelated BDC 1 0 1 rg 80 60 10 10 re f EMC",+                )));+                let page = pdfcraft_model::pages(&doc)[0].obj;+                doc.update_dict(page, |d| {+                    d.set(b"Contents".to_vec(), Object::Ref(contents));+                    d.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(annotation), Object::Ref(other)]));+                })+                .unwrap();+                if inherited {+                    let parent = doc.get(page).as_dict().unwrap().reference(b"Parent").unwrap();+                    doc.update_dict(parent, |d| d.set(b"Resources".to_vec(), resources)).unwrap();+                    doc.update_dict(page, |d| {+                        d.remove(b"Resources");+                    })+                    .unwrap();+                } else {+                    doc.update_dict(page, |d| d.set(b"Resources".to_vec(), resources)).unwrap();+                }+                let before = saved(&doc);+                let original_appearance = doc.get(appearance);+                let first = print(&doc).unwrap();+                let reopened = Document::open(Arc::new(first.clone())).unwrap();+                let properties = form_properties(&reopened);+                assert_eq!(properties.get(b"PCPrOC3"), Some(&Object::Null));+                assert_eq!(properties.get(b"Unrelated"), Some(&unrelated));+                assert_eq!(properties.get(b"PCPrOC2"), properties.get(b"PCPrOC0"));+                assert_eq!(properties.get(b"PCPrOC4"), properties.get(b"PCPrOC1"));+                for bytes in [first, print(&reopened).unwrap()] {+                    let image = render(bytes);+                    assert_appearance(&image, false);+                    assert_eq!(pixel(&image, 30, 40), [0, 255, 0, 255]);+                    assert_eq!(pixel(&image, 65, 35), [255, 255, 255, 255], "existing hidden page content");+                    assert_eq!(pixel(&image, 75, 35), [0, 0, 255, 255], "existing visible page content");+                    assert_eq!(pixel(&image, 85, 35), [255, 0, 255, 255], "unrelated marked-content property");+                }+                assert_eq!(doc.get(appearance), original_appearance);+                assert_eq!(saved(&doc), before, "resources={indirect_resources}, properties={indirect_properties}, inherited={inherited}");+            }+        }+    }+}++fn reference_chain(doc: &mut Document, mut value: Object, references: usize) -> Object {+    for _ in 0..references {+        value = Object::Ref(doc.add(value));+    }+    value+}++fn cycle(doc: &mut Document, two_nodes: bool) -> Object {+    let first = doc.add(Object::Null);+    let second = if two_nodes { doc.add(Object::Ref(first)) } else { first };+    doc.set(first, Object::Ref(second));+    Object::Ref(first)+}++#[test]+fn absent_annotation_membership_and_null_resource_maps_remain_valid() {+    for case in 0..6 {+        let (mut doc, _, annotation, _) = layer_fixture(true);+        match case {+            0 => {+                doc.update_dict(annotation, |d| {+                    d.remove(b"OC");+                })+                .unwrap();+            }+            1 => doc.update_dict(annotation, |d| d.set(b"OC".to_vec(), Object::Null)).unwrap(),+            2 => doc.update_dict(annotation, |d| d.set(b"OC".to_vec(), Object::Ref(ObjRef::new(900_000, 0)))).unwrap(),+            _ => {+                let page = pdfcraft_model::pages(&doc)[0].obj;+                let resources = match case {+                    3 => Object::Null,+                    4 => Object::Dict(Dict::from_iter([(b"Properties".to_vec(), Object::Null)])),+                    _ => Object::Dict(Dict::from_iter([(b"Properties".to_vec(), Object::Ref(ObjRef::new(900_000, 0)))])),+                };+                doc.update_dict(page, |d| d.set(b"Resources".to_vec(), resources)).unwrap();+            }+        }+        let before = saved(&doc);+        assert_appearance(&render(print(&doc).unwrap()), case < 3);+        assert_eq!(saved(&doc), before, "null/absent case={case}");+    }+}++#[test]+fn invalid_annotation_membership_is_refused_without_mutation() {+    for case in 0..9 {+        let (mut doc, _, annotation, _) = layer_fixture(false);+        let value = match case {+            0 => Object::Int(7),+            1 => Object::name("Layer"),+            2 => Object::Array(vec![]),+            3 => Object::Dict(Dict::new()),+            4 => Object::Dict(Dict::from_iter([(b"Type".to_vec(), Object::name("Page"))])),+            5 => Object::Dict(Dict::from_iter([(b"Type".to_vec(), Object::name("OCG"))])),+            6 => Object::Ref(doc.add(Object::Stream(Stream::flate(membership(vec![], None, None), b"")))),+            7 => cycle(&mut doc, false),+            _ => cycle(&mut doc, true),+        };+        doc.update_dict(annotation, |d| d.set(b"OC".to_vec(), value)).unwrap();+        let before = saved(&doc);+        assert!(matches!(print(&doc), Err(PrintError::Invalid(_))), "invalid membership case={case}");+        assert_eq!(saved(&doc), before, "invalid membership case={case}");+    }+}++#[test]+fn optional_content_reference_resolution_is_bounded_and_keeps_terminal_group_identity() {+    for references in [64, 65] {+        for target in ["membership", "type", "properties", "resources"] {+            let (mut doc, group, annotation, _) = layer_fixture(true);+            match target {+                "membership" => {+                    // The final OCG is already indirect and counts as one hop.+                    let value = reference_chain(&mut doc, Object::Ref(group), references - 1);+                    doc.update_dict(annotation, |d| d.set(b"OC".to_vec(), value)).unwrap();+                }+                "type" => {+                    let value = reference_chain(&mut doc, Object::name("OCG"), references);+                    doc.update_dict(group, |d| d.set(b"Type".to_vec(), value)).unwrap();+                }+                _ => {+                    let value = reference_chain(&mut doc, Object::Dict(Dict::new()), references);+                    let resources = if target == "properties" { Object::Dict(Dict::from_iter([(b"Properties".to_vec(), value)])) } else { value };+                    let page = pdfcraft_model::pages(&doc)[0].obj;+                    doc.update_dict(page, |d| d.set(b"Resources".to_vec(), resources)).unwrap();+                }+            }+            let before = saved(&doc);+            let result = print(&doc);+            if references == 64 {+                let bytes = result.unwrap();+                // Check Type aliases structurally: rendering them would also test the+                // renderer's separate reference-resolution behavior.+                if target == "type" {+                    let reopened = Document::open(Arc::new(bytes)).unwrap();+                    let root = reopened.get(reopened.root().unwrap());+                    let catalog = reopened.resolve(root.as_dict().unwrap().get(b"OCProperties").unwrap());+                    let groups = catalog.as_dict().unwrap().get(b"OCGs").unwrap().as_array().unwrap();+                    assert_eq!(form_properties(&reopened).get(b"PCPrOC0"), groups.first());+                } else {+                    assert_appearance(&render(bytes), false);+                }+            } else {+                assert!(matches!(result, Err(PrintError::Invalid(_))), "target={target}");+            }+            assert_eq!(saved(&doc), before, "target={target}, references={references}");+        }+    }+}++#[test]+fn malformed_page_resource_maps_cannot_remove_optional_content_guards() {+    for target in ["Resources", "Properties"] {+        for case in 0..4 {+            let (mut doc, _, _, _) = layer_fixture(true);+            let value = match case {+                0 => Object::Int(7),+                1 => Object::Ref(doc.add(Object::Stream(Stream::flate(Dict::new(), b"")))),+                2 => cycle(&mut doc, false),+                _ => cycle(&mut doc, true),+            };+            let resources = if target == "Properties" { Object::Dict(Dict::from_iter([(b"Properties".to_vec(), value)])) } else { value };+            let page = pdfcraft_model::pages(&doc)[0].obj;+            doc.update_dict(page, |d| d.set(b"Resources".to_vec(), resources)).unwrap();+            let before = saved(&doc);+            assert!(matches!(print(&doc), Err(PrintError::Invalid(_))), "target={target}, case={case}");+            assert_eq!(saved(&doc), before, "target={target}, case={case}");+        }+    }+}++#[test]+fn malformed_membership_on_annotations_that_do_not_draw_does_not_block_printing() {+    for case in 0..6 {+        let (mut doc, _, annotation, _) = layer_fixture(false);+        doc.update_dict(annotation, |d| {+            d.set(b"OC".to_vec(), Object::Int(7));+            match case {+                0 => d.set(b"F".to_vec(), Object::Int(0)),+                1 => d.set(b"F".to_vec(), Object::Int(6)),+                2 => d.set(b"Subtype".to_vec(), Object::name("Link")),+                3 => {+                    d.remove(b"AP");+                }+                4 => d.set(b"Rect".to_vec(), Object::Array(vec![])),+                _ => {}+            }+        })+        .unwrap();+        // Resource validation is also lazy: these maps are irrelevant when no guarded+        // annotation invocation will be appended.+        let page = pdfcraft_model::pages(&doc)[0].obj;+        let resources =+            if case % 2 == 0 { Object::Dict(Dict::from_iter([(b"Properties".to_vec(), Object::Int(7))])) } else { cycle(&mut doc, false) };+        doc.update_dict(page, |d| d.set(b"Resources".to_vec(), resources)).unwrap();+        let before = saved(&doc);+        let bytes = if case == 5 {+            impose(+                &doc,+                &Settings {+                    pages: vec![0],+                    paper: (100.0, 100.0),+                    layout: Layout::Size(SizeMode::Actual),+                    content: Content::Document,+                    ..Settings::default()+                },+            )+            .unwrap()+        } else {+            print(&doc).unwrap()+        };+        assert_appearance(&render(bytes), false);+        assert_eq!(saved(&doc), before, "excluded annotation case={case}");+    }+}diff --git a/docs/releasing.md b/docs/releasing.md--- a/docs/releasing.md+++ b/docs/releasing.md@@ -69,13 +69,20 @@ pinned in `release.yml` and builds with `CRAFT_FONTS_DIR` and `CRAFT_FONTS_REQUI embed its Japanese fonts and fail rather than ship without them (`AGENTS.md` §1.4). Bump the pin deliberately. -**OCR models:** every desktop package ships the Scan & OCR models (#103). The packaging scripts call-`stage_models` (`packaging/env.sh`; `package.ps1` on Windows), which runs `cargo xtask models` to-fetch every `kind = "model"` file in `ATTRIBUTION.toml` (verified by SHA-256) with its licence text-and an `ATTRIBUTION.txt`, straight into the package, so packaging needs the network. They go where-`pdfcraft_ocr::Models::dirs_beside_exe` looks: `models\` beside `pdfcraft.exe` (MSI, portable zip),-`PdfCraft.app/Contents/Resources/models` (macOS), and `share/pdfcraft/models` beside `bin/`-(deb, rpm, tar.gz, AppImage, Flatpak, FreeBSD). The web build doesn't include them yet.+**OCR models:** desktop packaging stages the Scan & OCR models (#103).+The packaging scripts call `stage_models` (`packaging/env.sh`; `package.ps1` on Windows), which runs `cargo xtask models` to fetch every `kind = "model"` file in `ATTRIBUTION.toml` and verify its SHA-256.+The current detection and recognition files are `text-detection.onnx` and `text-recognition.onnx`.+Each model ships with its licence text and the directory's `ATTRIBUTION.txt`, so packaging needs the network.+Upstream announced the legacy RTEN download URLs' brownout in [ocrs #282](https://github.com/robertknight/ocrs/issues/282) on 2026-10-27 and directs consumers to the ONNX models.++Runtime discovery prefers a complete ONNX detection/recognition pair within each directory, then a complete legacy `text-detection.rten` / `text-recognition.rten` pair.+An incomplete ONNX update can therefore use an intact RTEN pair in the same directory.+Discovery never combines model formats or files from different directories.+Directory precedence stays the same: `$PDFCRAFT_MODELS`, the release-package locations beside the executable, then the source tree's `assets/models/`.+The first directory with a complete supported pair wins, even if an earlier legacy pair precedes a later ONNX pair.++The release-package locations are `models\` beside `pdfcraft.exe` (MSI, portable zip), `PdfCraft.app/Contents/Resources/models` (macOS), and `share/pdfcraft/models` beside `bin/` (deb, rpm, tar.gz, AppImage, Flatpak, FreeBSD).+The web build does not include these models, and OCR remains limited to the Latin alphabet without accents.  ### macOS diff --git a/docs/roadmap.md b/docs/roadmap.md--- a/docs/roadmap.md+++ b/docs/roadmap.md@@ -1,5 +1,7 @@ # PdfCraft roadmap: milestones and what's next +> **Last reviewed:** 2026-10-27 | **Last updated:** 2026-10-27 | **Change:** minor (M10: vector printing preserves annotation optional-content membership; estimates unchanged)+> **Last reviewed:** 2026-10-27 | **Last updated:** 2026-10-27 | **Change:** minor (M10: OCR model downloads use verified ONNX pairs with legacy discovery fallback; estimates unchanged) > **Last reviewed:** 2026-10-25 | **Last updated:** 2026-10-25 | **Change:** minor (M14 localization current state: Arabic logical catalog, explicit RTL label direction and mirrored stock chrome; native/browser RTL workflows unqualified. Native release Hans face via LXGW WenKai Lite; estimates unchanged) > **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M7, #2636 partial: pasting added text boxes and images in the engine and through `content_copy`; estimates unchanged) > **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M11: image optimization accounts for page-local UserUnit; estimates unchanged)@@ -193,7 +195,7 @@ total matches the parity estimate. | M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Missing: editing existing text and images in place (the longest pole), image/PDF watermarks | | M8 | Security + redaction | 100–180 | 68% | 15–30 | Done: opening protected documents, permissions, Protect Using Password, Remove security; redaction (mark text/areas/pages, Search & Redact with patterns, apply removing glyphs, image pixels, vectors, XObject content, annotations and fields, verification, full rewrite on save); Remove hidden information and Sanitize.<br>Done since: redaction codes (U.S. FOIA and Privacy Act sets as overlay text, in Redaction properties and `redact_mark`). Redaction cleans indirect and form structure references, preserving surviving form tags. Redaction retires inherited resource dictionaries, so a parent `/Pages` can't keep a removed XObject reachable; unredacted pages are left untouched. Image redaction removes alternate images and unsupported masks only on affected images. Changed marked-content spans lose replacement descriptions; untouched spans keep theirs. Hidden-text cleanup retires unused named descriptions across inherited/shared page and form resources (64 focused tests and scoped Rust 1.96 Clippy/wasm checks pass; publication CI pending). The redaction audit counts a filled cover that hides half of any one word of a long line (#2662), applied or not. Phone-pattern redaction also matches labelled Italian geographic numbers with `+39` and a slash after the area code (#3205 follow-up); unlabelled international slash numbers remain unsupported. Missing: certificate security, custom redaction code sets and pattern locales, DCT re-encoding | | M9 | Signatures (PAdES, validation) | 160–280 | 60% | 40–70 | Done: new `sign` crate (DER, X.509, CMS, PKCS #12 on RustCrypto; aws-lc-rs for RSA private keys); PAdES B-B signing (visible, invisible, existing fields, certification with DocMDP); validation with trust store and changes-after-signing classification; self-signed digital IDs; Signatures panel, message bar, sign dialogs; agent tools. Checked with pdfsig and OpenSSL.<br>Done since: macOS Keychain and Windows Current User Personal store signing (software-backed CNG keys), certificate viewer, signed documents protected from rewrites, page validation overlays separate from original signature artwork (baked Not Verified captions remain; #79 open), snapshot tabs that reuse instead of multiplying. Missing: timestamps (B-T), LTV (DSS, OCSP, CRL), FieldMDP, smart cards, PKCS #11 |-| M10 | OCR, create, export, print | 200–350 | 33% | 120–215 | Done: create from blank/text/PNG/JPEG/TIFF (multi-page)/GIF/BMP; export PNG/JPEG/TIFF and text; Print (Acrobat's sizing, n-up, booklet, poster, comments & forms, preview, the CUPS and Windows spoolers, print-ready PDF).<br>Done since: embedded/72/custom DPI choices for image imports; export all images; OCR (searchable image for pages, ranges and multiple files); single-sided cut-and-stack imposition with cut marks, through Print and doc_print; architectural/ANSI/large ISO sheet presets, Match page at 100% and PDF-scale preview (#599 follow-up); Create PDF from multiple files (PDFs, images and text, edited as pages in the grid); OCR can also read pictures on pages that have text, without adding that text twice (#1028). Done since: Word invoice export uses borderless inferred tables, floating positioned text/artwork only where text overlaps an image or is rotated, and per-page sizes, covered by synthetic invoice automation regressions (#773); printing on the web through the browser's print dialog, sheets drawn by PdfCraft (gap 4). Lossless image export applies per-component Decode, including Indexed mapping (#1201 partial). Existing 16-bit precision and color-management limits remain. #3532 partial: vector printing retains existing appearances with absent Subtype through a print-owned Form copy; source artwork stays unchanged. #3120: Office export reads form XObjects 50 levels deep, as the renderer does, and up to 50 000 a page; pages past that are listed in `truncated_pages`. Word table cells use the grid columns they span, including cells after a merged cell. Done since: text in a table slot covered by another cell's span remains as paragraph text in Word, HTML, RTF and PowerPoint. Missing: OCR languages beyond Latin, editable-text OCR output, full Office layout fidelity/import. Done since: dotted-leader contents entries stay in separate complete paragraphs (#1757) #2156 candidate: last selected print paper persists across sessions; other print preferences unchanged. Image export applies soft-mask Decode opacity intervals before resizing, including indirect entries and inverted ranges. Vector printing gives annotation appearances unoccupied XObject names so existing page artwork survives. |+| M10 | OCR, create, export, print | 200–350 | 33% | 120–215 | Done: create from blank/text/PNG/JPEG/TIFF (multi-page)/GIF/BMP; export PNG/JPEG/TIFF and text; Print (Acrobat's sizing, n-up, booklet, poster, comments & forms, preview, the CUPS and Windows spoolers, print-ready PDF).<br>Done since: embedded/72/custom DPI choices for image imports; export all images; OCR (searchable image for pages, ranges and multiple files); single-sided cut-and-stack imposition with cut marks, through Print and doc_print; architectural/ANSI/large ISO sheet presets, Match page at 100% and PDF-scale preview (#599 follow-up); Create PDF from multiple files (PDFs, images and text, edited as pages in the grid); OCR can also read pictures on pages that have text, without adding that text twice (#1028). Model staging fetches SHA-256-verified ONNX detection/recognition files after the upstream RTEN URL brownout; runtime discovery prefers complete ONNX pairs per directory, then complete legacy RTEN pairs, without mixing formats or changing directory precedence. Done since: Word invoice export uses borderless inferred tables, floating positioned text/artwork only where text overlaps an image or is rotated, and per-page sizes, covered by synthetic invoice automation regressions (#773); printing on the web through the browser's print dialog, sheets drawn by PdfCraft (gap 4). Lossless image export applies per-component Decode, including Indexed mapping (#1201 partial). Existing 16-bit precision and color-management limits remain. #3532 partial: vector printing retains existing appearances with absent Subtype through a print-owned Form copy; source artwork stays unchanged. #3120: Office export reads form XObjects 50 levels deep, as the renderer does, and up to 50 000 a page; pages past that are listed in `truncated_pages`. Word table cells use the grid columns they span, including cells after a merged cell. Done since: text in a table slot covered by another cell's span remains as paragraph text in Word, HTML, RTF and PowerPoint. Missing: OCR languages beyond Latin, editable-text OCR output, full Office layout fidelity/import. Done since: dotted-leader contents entries stay in separate complete paragraphs (#1757) #2156 candidate: last selected print paper persists across sessions; other print preferences unchanged. Image export applies soft-mask Decode opacity intervals before resizing, including indirect entries and inverted ranges. Vector printing gives annotation appearances unoccupied XObject names so existing page artwork survives. Vector printing preserves each annotation's OCG/OCMD membership and shared-appearance independence (#5005). | | M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Target-version compatibility is partial: newer content is not detected or converted. Content stream boundaries preserve comments, split operands and graphics state when image fragments merge. Image downsampling includes page-local `/UserUnit` scaling when measuring physical resolution. Done since: reject invalid image and soft-mask dimensions with checked sizing (#2178). Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA | | M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds. Character encoding accepts Identity-H/V with Adobe CJK collections and predefined CJK CMaps independently (#3673); per-glyph validation and embedded-font extraction remain separate.<br>Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded, text-only auto-tag proposal tool for one page. Marking a figure decorative rewrites only that stream (#1324). An XFA radio item whose value contains a space is written back unchanged (#1319). Done since: #2569: Growable multiline XFA text reflows after edits, with undo/redo, save/reopen and print coverage; oversized fields still become read-only page text. Structured-data synchronization warnings retain accepted whitespace without relayout from stale data. Done since: #2572: Every repeated page-master button resolves its own field to the shared XFA click script, including print buttons. Done since: #2570: Dynamic XFA rich-text fields carry exData/maxLength into AcroForm MaxLen for reported and enforced Unicode character limits, retained after save/reopen. Done since: #2589: Active XFA skips PDF-container fallback scripts while retaining requested messages and saved scripts; ordinary/static/unlaid-out documents and explicit console/field calls keep their existing behavior. Missing: writing proposed tags and parent tree, field autotag, visual Tags/Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA<br>Reading colours: pending page backgrounds follow the configured colour (#2059). | | M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers<br>Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. CLI robustness scans visit each directory once through overlapping roots and symlink aliases. |@@ -242,6 +244,10 @@ M2 (renderer), M7 (content editing), M10 (OCR and Office), M11 (Preflight and st  ## Revision history +**2026-10-27 · minor:** M10 #5005: vector printing preserves annotation optional-content membership.+Source resources and shared appearances remain unchanged.+Estimates unchanged.+ **2026-10-25 · minor:** M14 localization current state: Arabic catalogs stay logical, Arabic/Kurdish labels take an explicit RTL direction, and stock chrome mirrors; native/browser RTL input, IME and complex workflows remain unqualified. Native Simplified Chinese uses LXGW WenKai Lite; the web build has no Hans face. Estimates unchanged.  **2026-10-23 · minor:** M11: image downsampling uses physical resolution after page-local `/UserUnit` scaling, including shared nested forms.@@ -254,6 +260,7 @@ Estimates unchanged.  | Date | Change | Summary | |---|---|---|+| 2026-10-27 | minor | M10: OCR stages SHA-256-verified ONNX models after the upstream RTEN URL brownout; discovery prefers a complete ONNX pair per directory, falls back to a complete RTEN pair, and never mixes formats or directories; language/web limits and estimates unchanged. | | 2026-10-24 | minor | M3, #3970 follow-up: the button release given back after a window move or resize goes before the pointer leaving, so hover doesn't stick. Estimates unchanged. | | 2026-10-23 | minor | M8, #3205 follow-up: phone-pattern redaction includes the +39 country code on labelled Italian geographic numbers with a slash; dates, protocol identifiers and whole-run guards remain. Estimates unchanged. | | 2026-10-23 | minor | M10: Word table cells use the grid columns they span, including cells after a merged cell; synthetic export regression and CLI reproduction. Estimates unchanged. |diff --git a/packaging/windows/test-msi.ps1 b/packaging/windows/test-msi.ps1--- a/packaging/windows/test-msi.ps1+++ b/packaging/windows/test-msi.ps1@@ -288,13 +288,16 @@ $modelsDir = Read-Row 'SELECT `Directory_Parent`, `DefaultDir` FROM `Directory` Assert-Equal $modelsDir[0] 'INSTALLFOLDER' 'OCR models folder parent' # DefaultDir is `models`, or `SHORT|models` with a generated 8.3 name. if ($modelsDir[1] -notmatch '(^|\|)models$') { throw "OCR models folder name: '$($modelsDir[1])'" }-$modelFiles = 0+$modelFiles = @() $view = $Database.OpenView('SELECT `File`.`FileName` FROM `File`, `Component` WHERE `File`.`Component_` = `Component`.`Component` AND `Component`.`Directory_` = ''ModelsFolder''') try {   [void] $view.Execute()-  while ($record = $view.Fetch()) { if ($record.StringData(1) -match '\.rten$') { $modelFiles++ } }+  # FileName can contain a generated 8.3 name before the long name: SHORT|long.+  while ($record = $view.Fetch()) { $modelFiles += ($record.StringData(1) -split '\|')[-1] } } finally { [void] $view.Close() }-if ($modelFiles -lt 2) { throw "expected the OCR models (*.rten) in models\, found $modelFiles" }+foreach ($model in @('text-detection.onnx', 'text-recognition.onnx')) {+  Assert-Equal (@($modelFiles | Where-Object { $_ -ceq $model }).Count) 1 "OCR model $model in models\"+} $rm = Read-Row 'SELECT `Dialog` FROM `Dialog` WHERE `Dialog` = ''MsiRMFilesInUse''' 1 Assert-Equal $rm[0] 'MsiRMFilesInUse' 'Files-in-use dialog' [void] [Runtime.InteropServices.Marshal]::FinalReleaseComObject($Database)diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@ -6544,8 +6544,8 @@ milestone = "M10" status = "shipped" commands = ["ocr.recognize"] tools = ["ocr_recognize", "ocr_status"]-evidence = ["crates/engine/src/tests.rs::recognize_text_makes_a_scanned_page_searchable", "crates/automation/tests/it/automation.rs::ocr_tools_make_a_scan_searchable", "crates/ui-egui/tests/it/ocr.rs::recognize_text_dialog_adds_searchable_text"]-notes = "ocrs engine (MIT/Apache) with CC-BY-SA models fetched by `cargo xtask models`; the desktop release packages ship them (#103; packaging/env.sh stage_models), the web build does not yet; runs on a worker thread with progress; one undoable step; pages with text are skipped unless asked (ocr.skip-renderable-text)."+evidence = ["crates/ocr/src/lib.rs::model_discovery_prefers_the_complete_onnx_pair", "crates/ocr/src/lib.rs::model_discovery_falls_back_to_legacy_when_the_onnx_pair_is_incomplete", "crates/ocr/src/lib.rs::model_discovery_refuses_mixed_format_pairs", "crates/ocr/src/lib.rs::model_discovery_keeps_legacy_only_installations", "crates/engine/src/tests.rs::recognize_text_makes_a_scanned_page_searchable", "crates/automation/tests/it/automation.rs::ocr_tools_make_a_scan_searchable", "crates/ui-egui/tests/it/ocr.rs::recognize_text_dialog_adds_searchable_text"]+notes = "ocrs engine (MIT/Apache) with CC-BY-SA ONNX models fetched and SHA-256 checked by `cargo xtask models`; within each search directory, a complete ONNX pair takes precedence over a complete legacy RTEN pair, incomplete and mixed-format pairs are not combined, and directory precedence is unchanged; the desktop release packages ship them (#103; packaging/env.sh stage_models), the web build does not yet; runs on a worker thread with progress; one undoable step; pages with text are skipped unless asked (ocr.skip-renderable-text)."  [[feature]] id = "ocr.recognize-range"@@ -8156,8 +8156,8 @@ milestone = "M10" status = "shipped" commands = ["print.dialog"] tools = ["doc_print"]-evidence = ["crates/print/src/tests.rs::imposed_pdf_has_the_sheets_and_honours_comments_and_forms", "crates/print/src/tests/appearances.rs::annotation_appearances_do_not_replace_page_xobjects"]-notes = "Print flag honoured; appearance resource names preserve existing page XObjects and distinct annotations, including inherited resources"+evidence = ["crates/print/src/tests.rs::imposed_pdf_has_the_sheets_and_honours_comments_and_forms", "crates/print/src/tests/appearances.rs::annotation_appearances_do_not_replace_page_xobjects", "crates/print/src/tests/optional_content.rs::vector_print_preserves_annotation_layer_membership"]+notes = "Print flags honoured; existing page XObjects and annotation appearances retain their resources. Vector output preserves per-annotation OCG/OCMD membership without changing shared appearances, including existing layer overrides. Nested policy data remains reader-evaluated; missing appearances and the separate raster annotation-visibility gap remain."  [[feature]] id = "print.print-with-comment-summary"