collective

Browse / github.com/storytold/pdfcraft / patch

M10: preserve TIFF ICC profiles on image import

M10: preserve TIFF ICC profiles on image import ## What this changes Addresses TIFF ICC retention in section 10 of #1201. That broader color-semantics audit remains open. Creating a PDF from a TIFF discarded its embedded color profile, so a linear-profile mid-gray sample rendered at 128 instead of the correctly color-managed 188. Create PDF and Add image now retain compatible Gray, RGB and CMYK profiles from each supported TIFF directory as `/ICCBased`, using the existing shared profile writer. Byte-identical profiles in one Create operation share one PDF object. Profiled RGBA remains RGB even when all channel values are equal, and its op

Status
open
Score
0.00
Adopters
0 other operators
Author
KyleKassen (imported from pull request #5032, open)
Base
e9fc890a862ea2d8c895ea32ddecda98580483cd
Size
+458 −50 in 17 files
Review
pending
Shared
2026-10-28
Id
6a6418ad88af3084dec0d0a1

How it went

No other operator has reported using it yet.

Diff

raw · ATTRIBUTION.md ATTRIBUTION.toml Cargo.lock Cargo.toml ROADMAP.md crates/automation/README.md crates/automation/tests/it/automation.rs crates/create/README.md crates/create/src/lib.rs crates/create/src/tests.rs crates/create/src/tests/tiff_icc.rs crates/ocr/Cargo.toml crates/ocr/src/lib.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, #1201 partial: TIFF imports retain compatible per-directory ICC profiles; 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,12 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md  ## Progress log +- **2026-10-27 (M10, #1201 partial):** Create PDF and Add image retain compatible per-directory TIFF ICC profiles through save/reopen.+  Profiled neutral RGBA stays RGB, with separate opacity; profile bytes are bounded and count toward the retained TIFF-page budget.+  Impossible profile counts are rejected against the source length before allocation or profile I/O.+  Existing 16-bit precision, associated-alpha handling and unsupported TIFF-format limits remain.++- **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.@@ -682,6 +690,7 @@ Newest first: the date, what moved, and the new overall estimate.  | 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/automation/README.md b/crates/automation/README.md--- a/crates/automation/README.md+++ b/crates/automation/README.md@@ -229,3 +229,8 @@ behavior. Back/Forward returns to page tops, does not restore zoom, does not switch documents, and is not saved across restarts. Standalone engine/MCP sessions have no viewport, so they do not have a separate navigation-history tool; use the opt-in UI control channel to navigate the displayed document.++TIFF images created with `doc_create` or inserted with `page_add_image` retain compatible per-directory ICC profiles through save/reopen.+Profiled RGB samples stay RGB even when neutral, and transparency remains a separate grayscale soft mask.+Optional TIFF profiles over 16 MiB or with unreadable, malformed or mismatched metadata fall back to the device color space.+The source image is unchanged; existing 16-bit precision and unsupported TIFF-format limits remain.diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs--- a/crates/automation/tests/it/automation.rs+++ b/crates/automation/tests/it/automation.rs@@ -2719,6 +2719,68 @@ fn exporting_images_and_text_through_tools() {     assert!(a.call("doc_export_text", &json!({ "doc": doc, "path": "/etc/x.txt" })).is_err(), "confined to the root"); } +#[test]+fn tiff_icc_survives_create_add_save_reopen_without_changing_source() {+    use pdfcraft_cos::{Document, Object};+    // Contributor-original 4x2 RGB TIFF and synthetic ICC header, generated entirely here.+    let mut profile = vec![0u8; 300];+    profile[..4].copy_from_slice(&300u32.to_be_bytes());+    profile[12..16].copy_from_slice(b"prtr");+    profile[16..20].copy_from_slice(b"RGB ");+    profile[36..40].copy_from_slice(b"acsp");+    let tags = [+        (256u16, 4u16, 1u32, 4u32),+        (257, 4, 1, 2),+        (258, 3, 3, 134),+        (259, 3, 1, 1),+        (262, 3, 1, 2),+        (273, 4, 1, 440),+        (277, 3, 1, 3),+        (278, 4, 1, 2),+        (279, 4, 1, 24),+        (34675, 7, 300, 140),+    ];+    let mut bytes = b"II*\0".to_vec();+    bytes.extend_from_slice(&8u32.to_le_bytes());+    bytes.extend_from_slice(&10u16.to_le_bytes());+    for (tag, kind, count, value) in tags {+        bytes.extend_from_slice(&tag.to_le_bytes());+        bytes.extend_from_slice(&kind.to_le_bytes());+        bytes.extend_from_slice(&count.to_le_bytes());+        bytes.extend_from_slice(&value.to_le_bytes());+    }+    bytes.extend_from_slice(&0u32.to_le_bytes());+    bytes.extend_from_slice(&[8, 0, 8, 0, 8, 0]);+    bytes.extend_from_slice(&profile);+    bytes.extend_from_slice(&[90, 80, 70].repeat(8));+    let dir = workdir("tiff-icc");+    std::fs::write(dir.join("scan.tiff"), &bytes).unwrap();+    let mut a = auto(&dir);+    let created = ok(&mut a, "doc_create", json!({"from":"images","paths":["scan.tiff"]}))["doc"].as_u64().unwrap();+    let added = ok(&mut a, "doc_create", json!({"from":"blank","width":64,"height":32}))["doc"].as_u64().unwrap();+    ok(&mut a, "page_add_image", json!({"doc":added,"page":1,"path":"scan.tiff","rect":[0,0,4,2]}));+    for (doc, path) in [(created, "created.pdf"), (added, "added.pdf")] {+        ok(&mut a, "doc_save", json!({"doc":doc,"path":path}));+        ok(&mut a, "doc_close", json!({"doc":doc}));+        let reopened = ok(&mut a, "doc_open", json!({"path":path}))["doc"].as_u64().unwrap();+        assert!(a.call("page_render", &json!({"doc":reopened,"page":1,"dpi":72})).is_ok());+        let saved = Document::open(std::sync::Arc::new(std::fs::read(dir.join(path)).unwrap())).unwrap();+        let page = pdfcraft_model::pages(&saved).remove(0);+        let res = saved.resolve(page.dict.get(b"Resources").unwrap());+        let objects = saved.resolve(res.as_dict().unwrap().get(b"XObject").unwrap());+        let image = saved.resolve(objects.as_dict().unwrap().iter().next().unwrap().1);+        let Object::Stream(image) = &*image else { panic!("image XObject") };+        let color = image.dict.get(b"ColorSpace").unwrap().as_array().expect("TIFF stays ICC-tagged");+        assert_eq!(color[0].as_name(), Some(&b"ICCBased"[..]));+        let icc = saved.resolve(&color[1]);+        let Object::Stream(icc) = &*icc else { panic!("ICC stream") };+        assert_eq!(icc.dict.int(b"N"), Some(3));+        assert_eq!(icc.decoded().unwrap(), profile);+        assert_eq!(image.decoded().unwrap(), [90, 80, 70].repeat(8));+    }+    assert_eq!(std::fs::read(dir.join("scan.tiff")).unwrap(), bytes);+}+ #[test] fn accessibility_character_encoding_accepts_identity_cjk_through_tools() {     use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, SaveOptions, Stream, write_full};diff --git a/crates/create/README.md b/crates/create/README.md--- a/crates/create/README.md+++ b/crates/create/README.md@@ -7,11 +7,15 @@ Layer L4. Create a PDF (Acrobat's Create a PDF tool), execution plan M10.2:   (PNG `pHYs`, JPEG JFIF density; 72 dpi when absent). JPEG data is embedded as is   (`/DCTDecode`, grey, RGB or Adobe-inverted CMYK); PNG is decoded and stored with Flate,   with transparency as a soft mask. An ICC profile in the file (JPEG `APP2 ICC_PROFILE`, PNG-  `iCCP`) that matches the image's colour space is kept as an `/ICCBased` colour space with+  `iCCP`, TIFF per-directory tag 34675) that matches the image's colour space is kept as an `/ICCBased` colour space with   the device space as `/Alternate`; images with the same profile share one profile object.   JPEG metadata scanning skips marker fill bytes and reads application segments after the   frame header, stopping at the first scan or end marker. Broken or mismatched ICC profiles-  still fall back to the device colour space;+  still fall back to the device colour space.+  TIFF profiles are read directly as bounded bytes (at most 16 MiB each) and count toward the retained TIFF-page budget.+  Declared profiles larger than the source file are rejected before allocation or profile I/O.+  Profiled RGBA keeps RGB samples even when the channel values are equal; opacity stays in an untagged grayscale soft mask.+  Missing, unreadable, over-limit or incompatible TIFF profiles keep the device colour space; - `from_images_with_resolution(images, ImageResolution::Dpi(dpi))`: override the page   resolution (1–1200 dpi), without resampling or recompressing image pixels. Use 72 dpi   for one point per pixel, or `ImageResolution::Embedded` for the same behavior as@@ -31,3 +35,5 @@ Soft-mask Decode intervals map samples to opacity before the mask is resized, in The existing 16-bit path still uses each sample's high byte. JPEG image Decode handling remains limited. ICC transforms and calibrated color conversion remain outside this export path.++TIFF ICC retention does not change high-byte-only 16-bit conversion, associated-alpha handling, or the decoder's existing refusal of two-sample grayscale-alpha TIFFs.diff --git a/crates/create/src/lib.rs b/crates/create/src/lib.rs--- a/crates/create/src/lib.rs+++ b/crates/create/src/lib.rs@@ -366,8 +366,13 @@ fn png_image(name: &str, bytes: &[u8]) -> Result<Embedded, CreateError> {  /// 8-bit RGBA pixels → an image (gray when every pixel is, with a soft mask when any pixel is /// not opaque).-fn rgba_image(rgba: &[u8], (w, h): (u32, u32), dpi: (f64, f64)) -> Embedded {-    let gray = rgba.as_chunks::<4>().0.iter().all(|p| p[0] == p[1] && p[1] == p[2]);+fn rgba_image(rgba: &[u8], px: (u32, u32), dpi: (f64, f64)) -> Embedded {+    rgba_image_in_space(rgba, px, dpi, false)+}++/// An RGB profile describes RGB samples even when all three channels happen to be equal.+fn rgba_image_in_space(rgba: &[u8], (w, h): (u32, u32), dpi: (f64, f64), preserve_rgb: bool) -> Embedded {+    let gray = !preserve_rgb && rgba.as_chunks::<4>().0.iter().all(|p| p[0] == p[1] && p[1] == p[2]);     let opaque = rgba.as_chunks::<4>().0.iter().all(|p| p[3] == 255);     let colour: Vec<u8> = if gray {         rgba.as_chunks::<4>().0.iter().map(|p| p[0]).collect()@@ -418,6 +423,28 @@ const MAX_DECODED_BYTES: usize = 2 << 30; /// whole address space on 32-bit targets (wasm32), where 4 GiB doesn't fit in `usize`. const MAX_DECODED_TOTAL: usize = MAX_DECODED_BYTES.saturating_mul(2); +/// Bound optional TIFF color metadata separately from the much larger pixel budget.+const MAX_TIFF_ICC_BYTES: usize = 16 << 20;++/// Read the current directory's profile without materializing one TIFF `Value` per byte.+fn tiff_icc(dec: &mut tiff::decoder::Decoder<std::io::Cursor<&[u8]>>, components: usize) -> Option<Vec<u8>> {+    use tiff::tags::{Tag, Type};+    let file_len = dec.inner().get_ref().len();+    let mut ifd = dec.image_ifd();+    let entry = ifd.find_entry(Tag::IccProfile)?;+    let len = usize::try_from(entry.count()).ok()?;+    if !matches!(entry.field_type(), Type::BYTE | Type::UNDEFINED) || !(128..=MAX_TIFF_ICC_BYTES.min(file_len)).contains(&len) {+        return None;+    }+    let mut profile = Vec::new();+    profile.try_reserve_exact(len).ok()?;+    profile.resize(len, 0);+    if ifd.find_tag_bytes(Tag::IccProfile, &mut profile, 0).ok()?? != len {+        return None;+    }+    icc_for(profile, components)+}+ /// The first `wanted` pages of a TIFF (multi-page scans become multi-page PDFs). fn tiff_pages(name: &str, bytes: &[u8], wanted: usize) -> Result<Vec<Embedded>, CreateError> {     tiff_pages_within(name, bytes, wanted, MAX_DECODED_TOTAL)@@ -452,13 +479,20 @@ fn tiff_pages_within(name: &str, bytes: &[u8], wanted: usize, budget: usize) ->             if v.is_finite() && v >= 1.0 { v } else { 72.0 }         };         let dpi = (res(Tag::XResolution, &mut dec), res(Tag::YResolution, &mut dec));+        let components = match ct {+            C::Gray(_) | C::GrayA(_) => 1,+            C::RGB(_) | C::RGBA(_) => 3,+            C::CMYK(_) => 4,+            _ => 0,+        };+        let icc = tiff_icc(&mut dec, components);         let data = match dec.read_image().map_err(|e| bad(e.to_string()))? {             DecodingResult::U8(v) => v,             // 16-bit samples: keep the high byte.             DecodingResult::U16(v) => v.iter().map(|x| (x >> 8) as u8).collect(),             _ => return Err(bad("this TIFF sample format isn't supported".into())),         };-        let page = match ct {+        let mut page = match ct {             C::Gray(1) => {                 // Bilevel scans stay 1 bit per pixel (0 = black after the decoder's inversion).                 let mut d = Dict::new();@@ -484,14 +518,18 @@ fn tiff_pages_within(name: &str, bytes: &[u8], wanted: usize, budget: usize) ->                 d.set(b"BitsPerComponent".to_vec(), Object::Int(8));                 Embedded { dict: d, data, filtered: false, smask: None, icc: None, px: (w, h), dpi }             }-            C::RGBA(8 | 16) => rgba_image(&data, (w, h), dpi),+            C::RGBA(8 | 16) => rgba_image_in_space(&data, (w, h), dpi, icc.is_some()),             C::GrayA(8 | 16) => {                 let rgba: Vec<u8> = data.as_chunks::<2>().0.iter().flat_map(|p| [p[0], p[0], p[0], p[1]]).collect();                 rgba_image(&rgba, (w, h), dpi)             }             other => return Err(bad(format!("{other:?} TIFF images aren't supported yet"))),         };-        kept = kept.saturating_add(page.data.len()).saturating_add(page.smask.as_ref().map_or(0, |(_, alpha)| alpha.len()));+        page.icc = icc;+        kept = kept+            .saturating_add(page.data.len())+            .saturating_add(page.smask.as_ref().map_or(0, |(_, alpha)| alpha.len()))+            .saturating_add(page.icc.as_ref().map_or(0, Vec::capacity));         if kept > budget {             return Err(bad(format!("the TIFF's pages take more than {} MiB together", budget >> 20)));         }diff --git a/crates/create/src/tests.rs b/crates/create/src/tests.rs--- a/crates/create/src/tests.rs+++ b/crates/create/src/tests.rs@@ -4,6 +4,8 @@ use pdfcraft_cos::{SaveOptions, write_full};  use super::*; +mod tiff_icc;+ fn reopen(doc: &Document) -> Document {     let bytes = write_full(doc, &SaveOptions::default()).unwrap();     hayro_syntax::Pdf::new(bytes.clone()).expect("parses");diff --git a/crates/create/src/tests/tiff_icc.rs b/crates/create/src/tests/tiff_icc.rsnew file mode 100644--- /dev/null+++ b/crates/create/src/tests/tiff_icc.rs@@ -0,0 +1,202 @@+use super::*;++/// Contributor-original uncompressed TIFF, with an optional UNDEFINED ICC field.+fn tagged_tiff(photo: u16, channels: u16, bits: u16, pixels: &[u8], profile: Option<&[u8]>) -> Vec<u8> {+    let width = pixels.len() * 8 / usize::from(channels) / usize::from(bits);+    let short = |value: u16| value.to_le_bytes().to_vec();+    let long = |value: u32| value.to_le_bytes().to_vec();+    let mut tags = vec![+        (256u16, 4u16, 1u32, long(width as u32)),+        (257, 4, 1, long(1)),+        (258, 3, u32::from(channels), short(bits).repeat(usize::from(channels))),+        (259, 3, 1, short(1)),+        (262, 3, 1, short(photo)),+        (273, 4, 1, long(0)),+        (277, 3, 1, short(channels)),+        (278, 4, 1, long(1)),+        (279, 4, 1, long(pixels.len() as u32)),+    ];+    if (photo == 1 && channels == 2) || (photo == 2 && channels == 4) {+        tags.push((338, 3, 1, short(2))); // unassociated alpha+    }+    if let Some(profile) = profile {+        tags.push((34675, 7, profile.len() as u32, profile.to_vec()));+    }+    tags.sort_by_key(|tag| tag.0);+    let extra_start = 8 + 2 + tags.len() * 12 + 4;+    let mut extra = Vec::new();+    let mut out = b"II*\0".to_vec();+    out.extend_from_slice(&8u32.to_le_bytes());+    out.extend_from_slice(&(tags.len() as u16).to_le_bytes());+    let strip_entry = out.len() + tags.iter().position(|tag| tag.0 == 273).unwrap() * 12 + 8;+    for (tag, kind, count, mut data) in tags {+        out.extend_from_slice(&tag.to_le_bytes());+        out.extend_from_slice(&kind.to_le_bytes());+        out.extend_from_slice(&count.to_le_bytes());+        if data.len() <= 4 {+            data.resize(4, 0);+            out.extend_from_slice(&data);+        } else {+            out.extend_from_slice(&((extra_start + extra.len()) as u32).to_le_bytes());+            extra.extend_from_slice(&data);+            if extra.len() % 2 != 0 {+                extra.push(0);+            }+        }+    }+    out.extend_from_slice(&0u32.to_le_bytes());+    out.extend_from_slice(&extra);+    let offset = out.len() as u32;+    out[strip_entry..strip_entry + 4].copy_from_slice(&offset.to_le_bytes());+    out.extend_from_slice(pixels);+    out+}++#[test]+fn tiff_icc_keeps_supported_color_samples_and_profiles() {+    for (photo, channels, space, device) in [(1, 1, b"GRAY", "DeviceGray"), (2, 3, b"RGB ", "DeviceRGB"), (5, 4, b"CMYK", "DeviceCMYK")] {+        let profile = icc_profile(space);+        for bits in [8, 16] {+            let samples = if bits == 8 { vec![90u8; channels as usize] } else { [7, 90].repeat(channels as usize) };+            let bytes = tagged_tiff(photo, channels, bits, &samples, Some(&profile));+            let doc = reopen(&from_images(&[("color.tiff".into(), bytes.clone())]).unwrap());+            let (n, alternate, actual, _) = icc_of(&doc, &image_of(&doc, 0)).expect("TIFF profile survives save/reopen");+            assert_eq!((n, alternate, actual), (i64::from(channels), device.as_bytes().to_vec(), profile.clone()));+            let image = embed("color.tiff", &bytes, 1).unwrap().remove(0);+            assert_eq!(image.data, vec![90; channels as usize]);+            let mut doc = Document::new_empty();+            let (r, _) = image_xobject(&mut doc, "color.tiff", &bytes).unwrap();+            let Object::Stream(s) = &*doc.get(r) else { panic!() };+            assert_eq!(icc_of(&doc, &s.dict).unwrap().2, profile);+        }+    }+    let profile = icc_profile(b"GRAY");+    let bytes = tagged_tiff(1, 1, 1, &[0b1010_0110], Some(&profile));+    let image = embed("scan.tiff", &bytes, 1).unwrap().remove(0);+    assert_eq!(image.data, [0b1010_0110]);+    assert_eq!(image.icc, Some(profile.clone()));+    let doc = reopen(&from_images(&[("scan.tiff".into(), bytes)]).unwrap());+    assert_eq!(icc_of(&doc, &image_of(&doc, 0)).map(|(n, _, p, _)| (n, p)), Some((1, profile)));++    // BigTIFF uses the same bounded raw profile read, including profiles above 1 MiB.+    let mut profile = icc_profile(b"RGB ");+    profile.resize((1 << 20) + 1, 0);+    let profile_len = profile.len() as u32;+    profile[..4].copy_from_slice(&profile_len.to_be_bytes());+    let mut out = std::io::Cursor::new(Vec::new());+    {+        let mut encoder = tiff::encoder::TiffEncoder::new_big(&mut out).unwrap();+        let mut page = encoder.new_image::<tiff::encoder::colortype::RGB8>(1, 1).unwrap();+        page.encoder().write_tag(tiff::tags::Tag::IccProfile, profile.as_slice()).unwrap();+        page.write_data(&[90, 80, 70]).unwrap();+    }+    let bytes = out.into_inner();+    assert!(bytes.starts_with(b"II+\0"));+    assert_eq!(embed("big.tiff", &bytes, 1).unwrap().remove(0).icc, Some(profile));+}++#[test]+fn tiff_icc_alpha_keeps_the_profile_component_space() {+    for (photo, channels, space, color) in [(2, 4, b"RGB ", vec![90, 90, 90]), (2, 4, b"RGB ", vec![90, 80, 70])] {+        let profile = icc_profile(space);+        for bits in [8, 16] {+            let mut samples = color.clone();+            samples.push(128);+            if bits == 16 {+                samples = samples.into_iter().flat_map(|v| [0, v]).collect();+            }+            let bytes = tagged_tiff(photo, channels, bits, &samples, Some(&profile));+            let image = embed("alpha.tiff", &bytes, 1).unwrap().remove(0);+            assert_eq!(image.icc, Some(profile.clone()));+            assert_eq!(image.data, color, "profiled RGB remains RGB even with neutral channel values");+            let (mask, alpha) = image.smask.unwrap();+            assert_eq!(mask.name(b"ColorSpace"), Some(&b"DeviceGray"[..]));+            assert_eq!(alpha, [128]);+            assert!(!mask.contains(b"ICCBased"));+            let doc = reopen(&from_images(&[("alpha.tiff".into(), bytes)]).unwrap());+            let dict = image_of(&doc, 0);+            assert_eq!(icc_of(&doc, &dict).map(|(n, _, p, _)| (n, p)), Some((i64::from(channels - 1), profile.clone())));+            let mask = doc.resolve(dict.get(b"SMask").unwrap());+            let Object::Stream(mask) = &*mask else { panic!() };+            assert_eq!(mask.dict.name(b"ColorSpace"), Some(&b"DeviceGray"[..]));+            assert_eq!(mask.decoded().unwrap(), [128]);+        }+    }+}++#[test]+fn tiff_icc_is_per_directory_and_shares_identical_profiles() {+    let profile = icc_profile(b"RGB ");+    let mut different = profile.clone();+    different[128] ^= 1;+    let mut out = std::io::Cursor::new(Vec::new());+    {+        let mut encoder = tiff::encoder::TiffEncoder::new(&mut out).unwrap();+        for profile in [Some(&profile), Some(&different), None, Some(&profile)] {+            let mut page = encoder.new_image::<tiff::encoder::colortype::RGB8>(1, 1).unwrap();+            if let Some(profile) = profile {+                page.encoder().write_tag(tiff::tags::Tag::IccProfile, profile.as_slice()).unwrap();+            }+            page.write_data(&[90, 80, 70]).unwrap();+        }+    }+    let bytes = out.into_inner();+    let doc = reopen(&from_images(&[("pages.tiff".into(), bytes)]).unwrap());+    let first = icc_of(&doc, &image_of(&doc, 0)).unwrap();+    assert_eq!(first.2, profile);+    assert_eq!(icc_of(&doc, &image_of(&doc, 1)).unwrap().2, different);+    assert_eq!(image_of(&doc, 2).name(b"ColorSpace"), Some(&b"DeviceRGB"[..]));+    assert_eq!(first.3, icc_of(&doc, &image_of(&doc, 3)).unwrap().3);+}++#[test]+fn tiff_icc_counts_toward_the_retained_budget() {+    let profile = icc_profile(b"RGB ");+    let bytes = tagged_tiff(2, 3, 8, &[90, 80, 70], Some(&profile));+    assert!(tiff_pages_within("budget.tiff", &bytes, 1, profile.len() + 2).is_err());+    assert!(tiff_pages_within("budget.tiff", &bytes, 1, profile.len() + 3).is_ok());+}++#[test]+fn tiff_icc_impossible_count_returns_before_reading_profile_bytes() {+    let profile = icc_profile(b"RGB ");+    let mut bytes = tagged_tiff(2, 3, 8, &[90, 80, 70], Some(&profile));+    let impossible_count = bytes.len() as u32 + 1;+    assert!(impossible_count < MAX_TIFF_ICC_BYTES as u32);+    bytes[122..126].copy_from_slice(&impossible_count.to_le_bytes());+    let mut decoder = tiff::decoder::Decoder::new(std::io::Cursor::new(bytes.as_slice())).unwrap();+    // Start away from the profile: even a failed exact read may otherwise leave the cursor there.+    decoder.inner().set_position(0);+    let before = decoder.inner().position();+    assert!(tiff_icc(&mut decoder, 3).is_none());+    assert_eq!(decoder.inner().position(), before, "an impossible count must return before attempting profile I/O");+}++#[test]+fn tiff_icc_missing_malformed_and_mismatched_profiles_keep_device_color() {+    let mut broken = icc_profile(b"RGB ");+    broken[36] = 0;+    for profile in [None, Some(Vec::new()), Some(vec![0; 127]), Some(broken), Some(icc_profile(b"GRAY"))] {+        let bytes = tagged_tiff(2, 3, 8, &[90, 80, 70], profile.as_deref());+        let image = embed("fallback.tiff", &bytes, 1).unwrap().remove(0);+        assert!(image.icc.is_none());+        assert_eq!(image.dict.name(b"ColorSpace"), Some(&b"DeviceRGB"[..]));+        assert_eq!(image.data, [90, 80, 70]);+        let doc = reopen(&from_images(&[("fallback.tiff".into(), bytes)]).unwrap());+        assert_eq!(image_of(&doc, 0).name(b"ColorSpace"), Some(&b"DeviceRGB"[..]));+    }+    let profile = icc_profile(b"RGB ");+    let mut oversized = tagged_tiff(2, 3, 8, &[90, 80, 70], Some(&profile));+    // The last entry's count claims more than the app's metadata ceiling, without a large fixture.+    oversized[122..126].copy_from_slice(&((MAX_TIFF_ICC_BYTES + 1) as u32).to_le_bytes());+    let image = embed("oversized.tiff", &oversized, 1).unwrap().remove(0);+    assert!(image.icc.is_none());+    assert_eq!(image.data, [90, 80, 70]);+    for (offset, data) in [(120, 3u16.to_le_bytes().to_vec()), (126, ((oversized.len() - 10) as u32).to_le_bytes().to_vec())] {+        let mut malformed = tagged_tiff(2, 3, 8, &[90, 80, 70], Some(&profile));+        malformed[offset..offset + data.len()].copy_from_slice(&data);+        let image = embed("malformed.tiff", &malformed, 1).unwrap().remove(0);+        assert!(image.icc.is_none(), "non-byte or truncated profile is ignored");+        assert_eq!(image.data, [90, 80, 70]);+    }+}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/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, #1201 partial: TIFF imports retain compatible per-directory ICC profiles; 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. TIFF imports retain compatible per-directory ICC profiles through create/add/save/reopen, including neutral RGBA; bounded profile bytes count toward the retained-page budget (#1201 section 10 partial). | | 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. |@@ -254,6 +256,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@@ -2082,8 +2082,8 @@ milestone = "M7" status = "shipped" commands = ["edit.image"] tools = ["page_add_image"]-evidence = ["crates/ui-egui/tests/it/content.rs::typing_moving_styling_and_deleting_added_content", "crates/ui-egui/tests/it/content.rs::a_picture_on_the_clipboard_is_pasted_onto_the_page", "crates/automation/tests/it/automation.rs::adding_content_through_tools", "crates/edit/src/tests.rs::added_text_and_images_are_page_content_that_stays_editable", "crates/engine/src/tests.rs::added_text_and_images_render_and_stay_editable"]-notes = "PNG, JPEG, TIFF, GIF, BMP; centred at natural size or in a rect. ⌘V / Ctrl+V pastes a picture from the system clipboard onto the current page the same way (desktop only)"+evidence = ["crates/ui-egui/tests/it/content.rs::typing_moving_styling_and_deleting_added_content", "crates/ui-egui/tests/it/content.rs::a_picture_on_the_clipboard_is_pasted_onto_the_page", "crates/automation/tests/it/automation.rs::adding_content_through_tools", "crates/edit/src/tests.rs::added_text_and_images_are_page_content_that_stays_editable", "crates/engine/src/tests.rs::added_text_and_images_render_and_stay_editable", "crates/automation/tests/it/automation.rs::tiff_icc_survives_create_add_save_reopen_without_changing_source"]+notes = "PNG, JPEG, TIFF, GIF, BMP; centred at natural size or in a rect. ⌘V / Ctrl+V pastes a picture from the system clipboard onto the current page the same way (desktop only). TIFF imports keep compatible ICC profiles through save/reopen without changing the source image."  [[feature]] id = "edit.cut-copy-paste-objects"@@ -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"@@ -6872,8 +6872,8 @@ milestone = "M10" status = "shipped" commands = ["create.images"] tools = ["doc_create"]-evidence = ["crates/create/src/tests.rs::jpeg_2000_images_are_embedded_as_is", "crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::embedded_icc_profiles_tag_the_image_colour_space"]-notes = "PNG, JPEG, TIFF (multi-page), GIF (first frame), BMP, and JPEG 2000 (JP2 or codestream, embedded as JPXDecode with its capture resolution). JPEG and PNG ICC profiles are kept as /ICCBased; TIFF profiles are not read yet"+evidence = ["crates/create/src/tests.rs::jpeg_2000_images_are_embedded_as_is", "crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::embedded_icc_profiles_tag_the_image_colour_space", "crates/create/src/tests/tiff_icc.rs::tiff_icc_keeps_supported_color_samples_and_profiles", "crates/create/src/tests/tiff_icc.rs::tiff_icc_alpha_keeps_the_profile_component_space", "crates/automation/tests/it/automation.rs::tiff_icc_survives_create_add_save_reopen_without_changing_source"]+notes = "PNG, JPEG, TIFF (multi-page), GIF (first frame), BMP, and JPEG 2000 (JP2 or codestream, embedded as JPXDecode with its capture resolution). JPEG, PNG and supported TIFF Gray/RGB/CMYK ICC profiles are kept as /ICCBased. TIFF profiles are per directory, bounded to 16 MiB and included in the retained-page budget; malformed, unreadable, over-limit or incompatible metadata keeps device color. Neutral profiled RGBA remains RGB with separate opacity. Existing high-byte-only 16-bit conversion, associated-alpha handling and grayscale-alpha decoder limits remain"  [[feature]] id = "create.from-multipage-tiff"@@ -6884,8 +6884,8 @@ milestone = "M10" status = "shipped" commands = ["create.images", "create.file"] tools = ["doc_create"]-evidence = ["crates/create/src/tests.rs::bmp_gif_and_multi_page_tiff_images", "crates/create/src/tests.rs::bigtiff_images_become_pages"]-notes = "every page; 1-bit scans stay 1-bit; resolution from the TIFF; classic TIFF and BigTIFF"+evidence = ["crates/create/src/tests.rs::bmp_gif_and_multi_page_tiff_images", "crates/create/src/tests.rs::bigtiff_images_become_pages", "crates/create/src/tests/tiff_icc.rs::tiff_icc_is_per_directory_and_shares_identical_profiles", "crates/create/src/tests/tiff_icc.rs::tiff_icc_counts_toward_the_retained_budget"]+notes = "every page; 1-bit scans stay 1-bit; resolution from the TIFF; classic TIFF and BigTIFF. Each directory keeps a compatible Gray/RGB/CMYK ICC profile, with byte-identical profiles shared; profile buffers count toward the retained-page budget."  [[feature]] id = "create.from-text"