Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

AF.1: import bounded Affinity previews with fidelity warnings

callmeBalloch1bb37eda053f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 704f78d0c..490447842 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -181,6 +181,8 @@ jobs:
- { crate: codecs, name: decode_tiff }
- { crate: codecs, name: decode_exr }
- { crate: codecs, name: decode_heif }
+ - { crate: affinity, name: preview }
+ - { crate: affinity, name: import_preview, args: "--features io" }
- { crate: format, name: load }
steps:
- uses: actions/checkout@v4
@@ -192,7 +194,7 @@ jobs:
run: cargo install cargo-fuzz --locked
- name: Fuzz
working-directory: crates/${{ matrix.target.crate }}
- run: cargo fuzz run ${{ matrix.target.name }} -- -max_total_time=${{ inputs.fuzz_seconds }}
+ run: cargo fuzz run ${{ matrix.target.name }} ${{ matrix.target.args }} -- -max_total_time=${{ inputs.fuzz_seconds }}
- name: Upload crash artifacts
if: failure()
uses: actions/upload-artifact@v4
diff --git a/Cargo.lock b/Cargo.lock
index b4c13406c..9d222415c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3490,6 +3490,14 @@ dependencies = [
"x11rb",
]
+[[package]]
+name = "photocraft-affinity"
+version = "0.4.1"
+dependencies = [
+ "crc32fast",
+ "proptest",
+]
+
[[package]]
name = "photocraft-algo"
version = "0.4.1"
@@ -3683,6 +3691,9 @@ name = "photocraft-io"
version = "0.4.1"
dependencies = [
"blake3",
+ "crc32fast",
+ "flate2",
+ "photocraft-affinity",
"photocraft-algo",
"photocraft-cms",
"photocraft-codecs",
diff --git a/Cargo.toml b/Cargo.toml
index bec146191..9e5648d94 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -20,6 +20,7 @@ photocraft-ops = { path = "crates/ops" }
photocraft-psd = { path = "crates/psd" }
photocraft-codecs = { path = "crates/codecs" }
photocraft-raw = { path = "crates/raw" }
+photocraft-affinity = { path = "crates/affinity" }
photocraft-compose = { path = "crates/compose" }
photocraft-gpu = { path = "crates/gpu" }
photocraft-paint = { path = "crates/paint" }
diff --git a/README.md b/README.md
index 34f898454..c9ff2590a 100644
--- a/README.md
+++ b/README.md
@@ -199,7 +199,7 @@ Every screenshot here is the real app at work on public-domain art, rendered off
</td>
<td width="33%" valign="top">
<h4>🗂️ Formats</h4>
- PSD and PSB, layered TIFF (Photoshop's layer data in the TIFF, read and written in either byte order), plus flat PNG, JPEG, TIFF, WebP (lossy and lossless), GIF, BMP, TGA, ICO, QOI, PNM, OpenEXR, Radiance HDR and AVIF, with symmetric read and write at 8, 16 and 32 bits, HEIC photos from iPhone and Mac (read; in official builds, an optional <code>--features heif</code> build feature), and the native <code>.pcraft</code> format.
+ PSD and PSB, layered TIFF (Photoshop's layer data in the TIFF, read and written in either byte order), plus flat PNG, JPEG, TIFF, WebP (lossy and lossless), GIF, BMP, TGA, ICO, QOI, PNM, OpenEXR, Radiance HDR and AVIF, with symmetric read and write at 8, 16 and 32 bits, HEIC photos from iPhone and Mac (read; in official builds, an optional <code>--features heif</code> build feature), and the native <code>.pcraft</code> format. Some current Affinity <code>.af</code> files open as their embedded PNG preview, with a warning: native layers and full-resolution artwork are not imported, previewless and legacy files are unsupported, and Affinity export is unavailable.
</td>
<td width="33%" valign="top">
<h4>🪄 The everyday essentials</h4>
diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs
index 65e1a98b8..9fb616a4a 100644
--- a/apps/photocraft-cli/src/lib.rs
+++ b/apps/photocraft-cli/src/lib.rs
@@ -288,7 +288,7 @@ fn same_dir(a: &Path, b: &Path) -> bool {
}
fn is_input(p: &Path) -> bool {
- let known = |e: &str| matches!(e, "pcraft" | "psd" | "psb") || photocraft_codecs::from_extension(e).is_some_and(|f| photocraft_codecs::caps(f).read);
+ let known = |e: &str| matches!(e, "pcraft" | "psd" | "psb" | "af") || photocraft_codecs::from_extension(e).is_some_and(|f| photocraft_codecs::caps(f).read);
p.is_file() && p.extension().is_some_and(|e| known(&e.to_string_lossy().to_ascii_lowercase()))
}
diff --git a/apps/photocraft-web/src/web.rs b/apps/photocraft-web/src/web.rs
index 95e31faac..a71902346 100644
--- a/apps/photocraft-web/src/web.rs
+++ b/apps/photocraft-web/src/web.rs
@@ -11,11 +11,11 @@ use wasm_bindgen::JsCast as _;
type Inbox = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
-/// Everything File › Open reads: PhotoCraft and Photoshop documents, flat images, and Photoshop
+/// Everything File › Open reads: PhotoCraft, Photoshop and Affinity preview documents, flat images, and Photoshop
/// brushes (.abr) and gradients (.grd), which go to the preset libraries.
const OPEN_EXTS: &[&str] = &[
"pcraft", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam",
- "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd",
+ "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "af",
];
const CANVAS_ID: &str = "photocraft_canvas";
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs
index e7faf24f2..95626922e 100644
--- a/apps/photocraft/src/services.rs
+++ b/apps/photocraft/src/services.rs
@@ -11,11 +11,11 @@ use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
-/// Everything File › Open reads: PhotoCraft and Photoshop documents, flat images, and Photoshop
+/// Everything File › Open reads: PhotoCraft, Photoshop and Affinity preview documents, flat images, and Photoshop
/// brushes (.abr) and gradients (.grd), which go to the preset libraries.
const OPEN_EXTS: &[&str] = &[
"pcraft", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam",
- "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd",
+ "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "af",
];
/// File › Save As formats: (filter name, extensions). The filter matching the suggested name's
diff --git a/book/src/SUMMARY.md b/book/src/SUMMARY.md
index d3ef25c8c..e819bfbdc 100644
--- a/book/src/SUMMARY.md
+++ b/book/src/SUMMARY.md
@@ -21,6 +21,7 @@
- [Overview](formats/overview.md)
- [PSD and PSB](formats/psd-psb.md)
- [Raster formats](formats/raster-formats.md)
+- [Affinity previews](formats/affinity.md)
- [The `.pcraft` format](formats/pcraft.md)
# Automation
diff --git a/book/src/architecture/crates.md b/book/src/architecture/crates.md
index c423cf2eb..34df8b601 100644
--- a/book/src/architecture/crates.md
+++ b/book/src/architecture/crates.md
@@ -5,7 +5,7 @@ The layer numbers below describe allowed dependency direction, not runtime privi
| Layer | Crates | Responsibility |
|---|---|---|
| L0 | `geom`, `cms`, `color`, `raster` | Geometry, ICC processing, color/blend math, pixel formats, and copy-on-write tiles |
-| L0 standalone | `psd`, `codecs` | PSD/PSB and flat raster format parsing/encoding |
+| L0 standalone | `psd`, `codecs`, `affinity` | PSD/PSB and flat raster format parsing/encoding; bounded Affinity preview extraction |
| L1 | `doc` | Pure-data documents, layers, masks, effects, adjustments, text, vectors, and smart objects |
| L2 | `ops`, `paint`, `algo`, `text`, `vector` | History operations, painting, imaging algorithms, type, paths, and shapes |
| L3 | `compose`, `gpu`, `format` | CPU composition, wgpu composition, and `.pcraft` persistence |
diff --git a/book/src/formats/affinity.md b/book/src/formats/affinity.md
new file mode 100644
index 000000000..70e32c0bf
--- /dev/null
+++ b/book/src/formats/affinity.md
@@ -0,0 +1,28 @@
+# Affinity previews
+
+PhotoCraft can open the **embedded PNG preview** in some current Affinity `.af` files. The
+document contains one editable raster layer named “Affinity preview”, at the preview's actual
+dimensions. The preview may be smaller than the source document. Native layers, text, vectors,
+masks, effects, pages and document colour settings are not imported; the warning on open
+explains this limitation.
+
+This is preview import, not editable Affinity document support. Files without an indexed PNG
+preview fail with an actionable error. Legacy `.afphoto`, `.afdesign` and `.afpub` containers
+are recognized, but their thumbnail layouts are unverified and rejected. Export PSD or PNG
+from Affinity for full-resolution artwork.
+
+An opened preview starts without a save path, including when the source was renamed to another
+extension. Save asks for a new copy. Writing `.af`, `.afphoto`, `.afdesign` or `.afpub` is
+unsupported. Saving `.pcraft`, PSD or PNG saves the imported preview, not the native content.
+Place, smart-object content decoding and auxiliary imports that cannot display the warning
+reject the preview; export PSD or PNG in Affinity before using those paths.
+
+The standalone `photocraft-affinity` crate inspects the container and reads only the declared
+version-12 thumbnail offset. It never scans for PNGs or decompresses the object graph. The PNG
+decoder validates the compressed preview with limits of 4096 pixels per dimension and 128 MiB
+of decoded allocation; encoded PNGs are limited to 16 MiB.
+Every PNG chunk CRC is checked. Compressed PNG metadata and animated PNG previews are rejected
+before decoding; these have not been observed in the native oracle files.
+
+See [the crate's format notes](https://github.com/storytold/photocraft/blob/main/crates/affinity/README.md)
+for observed layouts, provenance, tests and the remaining native-import work.
diff --git a/book/src/formats/overview.md b/book/src/formats/overview.md
index 7c36352a5..41937cefc 100644
--- a/book/src/formats/overview.md
+++ b/book/src/formats/overview.md
@@ -1,13 +1,14 @@
# Format overview
-External bytes enter PhotoCraft through three main paths:
+External bytes enter PhotoCraft through four main paths:
- `photocraft-psd` parses and writes PSD and PSB structures.
- `photocraft-codecs` decodes and encodes flat raster formats.
- `photocraft-format` loads and saves the native `.pcraft` bundle.
+- `photocraft-affinity` inspects Affinity containers and extracts an indexed PNG preview in some current `.af` files; it does not decode native layers.
`photocraft-io` maps PSD and flat images into the document model and exports documents back to those formats. It is the integration layer; parsing limits remain the responsibility of the underlying format crates.
Formats are a primary security boundary. File extension is not a trust signal, metadata can be attacker-controlled, and small compressed inputs can declare very large decoded outputs. Callers should use the bounded default APIs and preserve errors rather than retrying with unlimited limits.
-See [PSD and PSB](psd-psb.md), [Raster formats](raster-formats.md), and [The `.pcraft` format](pcraft.md). Cross-format hardening guidance is in [Parser hardening](../security/parser-hardening.md).
+See [PSD and PSB](psd-psb.md), [Raster formats](raster-formats.md), [Affinity previews](affinity.md), and [The `.pcraft` format](pcraft.md). Cross-format hardening guidance is in [Parser hardening](../security/parser-hardening.md).
diff --git a/crates/affinity/Cargo.toml b/crates/affinity/Cargo.toml
new file mode 100644
index 000000000..7a4df2cba
--- /dev/null
+++ b/crates/affinity/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "photocraft-affinity"
+description = "Bounded Affinity container inspection and embedded PNG preview extraction"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[lints]
+workspace = true
+
+[dependencies]
+crc32fast = "1.5"
+
+[dev-dependencies]
+proptest = { workspace = true }
diff --git a/crates/affinity/README.md b/crates/affinity/README.md
new file mode 100644
index 000000000..e53b001e6
--- /dev/null
+++ b/crates/affinity/README.md
@@ -0,0 +1,86 @@
+# photocraft-affinity
+
+Standalone Rust inspection of Affinity containers and extraction of an indexed
+PNG preview. It does **not** decode the native document graph or write Affinity files. The
+`photocraft-io` adapter opens the preview as one raster layer and reports the fidelity limitation.
+
+`inspect(bytes)` recognizes document-class containers with versions 7–12. `preview(bytes)`
+accepts only the version-12 thumbnail record observed in newly generated Affinity 3.3.0.4850
+documents. Versions 7–11, files without an indexed thumbnail, other encodings, and unknown
+record layouts return an actionable error. Not every current `.af` file contains a preview.
+Recognizing a filename extension or the container magic does not establish editable support.
+
+The preview must be decoded by a bounded PNG decoder: this crate checks the PNG signature,
+IHDR dimensions, every chunk CRC, chunk boundaries and exact IEND termination; it does not validate
+compressed pixels or the native colour settings. Limits are 16 MiB of encoded PNG and 4096
+pixels in either dimension. The I/O adapter additionally limits decoded allocation to 128 MiB.
+Offsets and lengths are checked before indexing. No compressed object graph is decompressed.
+The only runtime dependency is the already-used, permissively licensed `crc32fast` checksum crate.
+Compressed PNG text/profile chunks (`zTXt`, `iTXt`, `iCCP`) and APNG records are unsupported
+and rejected before decoding. The observed native previews contain only IHDR, pHYs, IDAT and
+IEND; relaxing this policy needs a total metadata allocation bound and native-file oracles.
+IHDR must be first and unique, IDAT chunks must be present and contiguous, and an optional
+PLTE must be unique and precede IDAT. Unknown critical chunks are rejected. This protects
+against trailing format errors that the image decoder may otherwise treat as partial output.
+
+## Observed record layout
+
+All container integers below are little-endian. The header's offset 24 points to the record;
+signature scanning is deliberately unsupported because a resource or obsolete revision may
+contain another PNG.
+
+| Record offset | Size | Observed value |
+|---|---:|---|
+| 0 | 8 | `ffffffff` followed by `Thmb` |
+| 8 | 4 | Record version 1 |
+| 12 | 4 | PNG byte length + 13 |
+| 16 | 4 | PNG start offset 29 |
+| 20 | 4 | Zero |
+| 24 | 4 | PNG byte length |
+| 28 | 1 | PNG encoding 1 |
+| 29 | declared length | Exactly one PNG |
+
+This is a narrow, observed layout rather than a vendor specification. Expanding it needs
+independent, synthetic native-file oracles and deliberate version dispatch.
+
+## Provenance and verification
+
+The public MIT-licensed [afread reader at `04b6723`](https://github.com/VMDevCpp/afread/tree/04b672334a43e3e37ded6b5ffc57af231d589774) (Vladimir Mamonov, 2020–2021) was consulted for
+the legacy header layout, `Prsn` document class and versions 7–11. This crate's Rust code was
+written independently; it does not incorporate C++, GPL/AGPL readers or proprietary source.
+The version-12 thumbnail layout was observed through files authored from scratch with the
+public Affinity scripting SDK. No proprietary application bundle or private user files were read.
+
+Unit tests use generated record envelopes, every truncation, bad offsets, dimensions and
+mutations. Integration tests exercise the bounded PNG decoder, alpha, copy export and save
+protection, including 8-bit RGBA and 16-bit Gray/alpha previews. Warningless auxiliary imports
+(Place, smart-object decoding, stack/batch, displacement maps, variables, notes and video)
+reject an Affinity derivative preview so it cannot be silently treated as native content.
+A local ignored `native_affinity_oracle` in `crates/io/tests/affinity.rs` compares
+generated Affinity files against their PNG exports. Binary oracles belong in the shared
+[photocraft-corpus](https://github.com/storytold/photocraft-corpus), with committed generators,
+scrubbed personal metadata and a pinned hash manifest; they are never committed here.
+
+```sh
+cargo test -p photocraft-affinity
+cargo test -p photocraft-io --test affinity
+AFFINITY_ORACLE_DIR=/path/to/generated/files cargo test -p photocraft-io --test affinity native_affinity_oracle -- --ignored
+cd crates/affinity/fuzz
+cargo +nightly fuzz run preview -- -max_total_time=60 -max_len=20000 -timeout=5
+cargo +nightly fuzz run import_preview --features io -- -max_total_time=60 -max_len=20000 -timeout=5
+```
+
+Native editable import remains a separate project:
+
+- Validate the allocation table and revision chain and choose the current `doc.dat`, including
+ incremental saves, deletions, object checksums and resource bounds.
+- Decode zstd/deflate and predictors with independent output, ratio and work limits.
+- Build a typed tagged intermediate model, resolving object references with cycle, count and
+ depth limits before mapping data into the document model.
+- Preserve RGB/Gray/CMYK/Lab, 8/16/32f depth and ICC profiles; map raster tiles, layer order,
+ groups, transforms, masks and blends; issue explicit warnings for unsupported effects,
+ text, vectors, pages and other records rather than silently flattening or dropping them.
+- Verify native-file oracles across application/platform versions and malformed inputs.
+ Native writing and round trips need a later design for carrying unknown records safely.
+
+Preview import must never be presented as completing those tasks or preserving the original artwork.
diff --git a/crates/affinity/fuzz/.gitignore b/crates/affinity/fuzz/.gitignore
new file mode 100644
index 000000000..ab0eaa1a4
--- /dev/null
+++ b/crates/affinity/fuzz/.gitignore
@@ -0,0 +1,5 @@
+target/
+corpus/
+artifacts/
+coverage/
+Cargo.lock
diff --git a/crates/affinity/fuzz/Cargo.toml b/crates/affinity/fuzz/Cargo.toml
new file mode 100644
index 000000000..288d89e12
--- /dev/null
+++ b/crates/affinity/fuzz/Cargo.toml
@@ -0,0 +1,34 @@
+[package]
+name = "photocraft-affinity-fuzz"
+version = "0.0.0"
+publish = false
+edition = "2024"
+license = "MIT OR Apache-2.0"
+
+[package.metadata]
+cargo-fuzz = true
+
+[workspace]
+
+[features]
+io = ["dep:photocraft-io"]
+
+[dependencies]
+libfuzzer-sys = "0.4"
+photocraft-affinity = { path = ".." }
+photocraft-io = { path = "../../io", optional = true }
+
+[[bin]]
+name = "preview"
+path = "fuzz_targets/preview.rs"
+test = false
+doc = false
+bench = false
+
+[[bin]]
+name = "import_preview"
+path = "fuzz_targets/import_preview.rs"
+required-features = ["io"]
+test = false
+doc = false
+bench = false
diff --git a/crates/affinity/fuzz/fuzz_targets/import_preview.rs b/crates/affinity/fuzz/fuzz_targets/import_preview.rs
new file mode 100644
index 000000000..13e4bd79b
--- /dev/null
+++ b/crates/affinity/fuzz/fuzz_targets/import_preview.rs
@@ -0,0 +1,10 @@
+#![no_main]
+
+use libfuzzer_sys::fuzz_target;
+
+fuzz_target!(|data: &[u8]| {
+ // Exercise the bounded preview PNG decoder and document mapping, not unrelated formats.
+ if photocraft_affinity::is_affinity(data) {
+ let _ = photocraft_io::import("fuzz.af", data);
+ }
+});
diff --git a/crates/affinity/fuzz/fuzz_targets/preview.rs b/crates/affinity/fuzz/fuzz_targets/preview.rs
new file mode 100644
index 000000000..60ab2dfd3
--- /dev/null
+++ b/crates/affinity/fuzz/fuzz_targets/preview.rs
@@ -0,0 +1,8 @@
+#![no_main]
+
+use libfuzzer_sys::fuzz_target;
+
+fuzz_target!(|data: &[u8]| {
+ let _ = photocraft_affinity::inspect(data);
+ let _ = photocraft_affinity::preview(data);
+});
diff --git a/crates/affinity/src/lib.rs b/crates/affinity/src/lib.rs
new file mode 100644
index 000000000..95f6e87ee
--- /dev/null
+++ b/crates/affinity/src/lib.rs
@@ -0,0 +1,394 @@
+//! Affinity container inspection, without interpreting the compressed document graph.
+//!
+//! The header layout was researched with MIT-licensed afread (see README). The version-12
+//! thumbnail record was observed in synthetic documents saved by Affinity 3.3. Do not scan for
+//! PNG signatures: an unrelated resource or an obsolete revision is not a document preview.
+#![forbid(unsafe_code)]
+#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
+
+use std::fmt;
+
+pub const MAGIC: &[u8; 4] = b"\x00\xffKA";
+pub const MAX_PREVIEW_BYTES: usize = 16 << 20;
+pub const MAX_PREVIEW_DIMENSION: u32 = 4096;
+
+/// Container failure. The compressed graph is deliberately never decompressed here.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Error {
+ Malformed(&'static str),
+ Unsupported(&'static str),
+ Limit(&'static str),
+}
+
+impl fmt::Display for Error {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let (kind, reason) = match self {
+ Self::Malformed(s) => ("damaged Affinity file", s),
+ Self::Unsupported(s) => ("unsupported Affinity file", s),
+ Self::Limit(s) => ("Affinity preview limit exceeded", s),
+ };
+ write!(f, "{kind}: {reason}; export PNG, PSD or SVG from Affinity for full-resolution artwork")
+ }
+}
+
+impl std::error::Error for Error {}
+
+/// Header identity; offsets remain private so callers cannot bypass validation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Header {
+ pub version: u16,
+ thumbnail_offset: u64,
+}
+
+/// Borrowed embedded thumbnail, at its own dimensions, never the native document dimensions.
+#[derive(Debug)]
+pub struct Preview<'a> {
+ pub png: &'a [u8],
+ pub width: u32,
+ pub height: u32,
+}
+
+pub fn is_affinity(bytes: &[u8]) -> bool {
+ bytes.starts_with(MAGIC)
+}
+
+fn bytes_at(bytes: &[u8], offset: usize, length: usize) -> Result<&[u8], Error> {
+ let end = offset.checked_add(length).ok_or(Error::Malformed("offset overflow"))?;
+ bytes.get(offset..end).ok_or(Error::Malformed("truncated record"))
+}
+
+fn le16(bytes: &[u8], offset: usize) -> Result<u16, Error> {
+ let b = bytes_at(bytes, offset, 2)?;
+ Ok(u16::from_le_bytes(b.try_into().map_err(|_| Error::Malformed("integer"))?))
+}
+
+fn le32(bytes: &[u8], offset: usize) -> Result<u32, Error> {
+ let b = bytes_at(bytes, offset, 4)?;
+ Ok(u32::from_le_bytes(b.try_into().map_err(|_| Error::Malformed("integer"))?))
+}
+
+fn le64(bytes: &[u8], offset: usize) -> Result<u64, Error> {
+ let b = bytes_at(bytes, offset, 8)?;
+ Ok(u64::from_le_bytes(b.try_into().map_err(|_| Error::Malformed("integer"))?))
+}
+
+fn be32(bytes: &[u8], offset: usize) -> Result<u32, Error> {
+ let b = bytes_at(bytes, offset, 4)?;
+ Ok(u32::from_be_bytes(b.try_into().map_err(|_| Error::Malformed("PNG integer"))?))
+}
+
+/// Recognize documents, rejecting add-ons with the same magic and unknown container versions.
+pub fn inspect(bytes: &[u8]) -> Result<Header, Error> {
+ if !is_affinity(bytes) {
+ return Err(Error::Malformed("missing container signature"));
+ }
+ let version = le16(bytes, 4)?;
+ if !(7..=12).contains(&version) {
+ return Err(Error::Unsupported("unverified container version"));
+ }
+ if le16(bytes, 6)? != 0 {
+ return Err(Error::Unsupported("container flags"));
+ }
+ // afread's Prsn document class, stored little-endian. Brushes, macros and palettes
+ // share the magic but must not be opened as documents.
+ if bytes_at(bytes, 8, 4)? != b"nsrP" {
+ return Err(Error::Unsupported("this container is not an Affinity document"));
+ }
+ if bytes_at(bytes, 12, 4)? != b"#Inf" {
+ return Err(Error::Malformed("missing information header"));
+ }
+ bytes_at(bytes, 0, if version == 7 { 64 } else { 72 })?;
+ if version > 7 && bytes_at(bytes, 64, 4)? != b"Prot" {
+ return Err(Error::Malformed("missing protocol header"));
+ }
+ Ok(Header { version, thumbnail_offset: le64(bytes, 24)? })
+}
+
+/// Read only the indexed version-12 `Thmb` record and validate every PNG chunk CRC.
+/// Compressed pixels must still be validated by the consuming image decoder, with allocation limits.
+pub fn preview(bytes: &[u8]) -> Result<Preview<'_>, Error> {
+ let h = inspect(bytes)?;
+ if h.version != 12 {
+ return Err(Error::Unsupported("legacy preview records have not been verified"));
+ }
+ if h.thumbnail_offset == 0 {
+ return Err(Error::Unsupported("no embedded preview; native layer decoding is not implemented"));
+ }
+ let offset = usize::try_from(h.thumbnail_offset).map_err(|_| Error::Malformed("thumbnail offset overflow"))?;
+ if offset < 72 {
+ return Err(Error::Malformed("thumbnail overlaps the file header"));
+ }
+ let record = bytes.get(offset..).ok_or(Error::Malformed("thumbnail offset outside file"))?;
+ if bytes_at(record, 0, 8)? != b"\xff\xff\xff\xffThmb" {
+ return Err(Error::Malformed("missing indexed thumbnail"));
+ }
+ if le32(record, 8)? != 1 || bytes_at(record, 28, 1)? != [1] {
+ return Err(Error::Unsupported("thumbnail record version or encoding"));
+ }
+ let size = usize::try_from(le32(record, 24)?).map_err(|_| Error::Limit("encoded size"))?;
+ if size > MAX_PREVIEW_BYTES {
+ return Err(Error::Limit("encoded preview exceeds 16 MiB"));
+ }
+ if le32(record, 16)? != 29 || le32(record, 20)? != 0 || u64::from(le32(record, 12)?) != size as u64 + 13 {
+ return Err(Error::Malformed("inconsistent thumbnail record lengths"));
+ }
+ let png = bytes_at(record, 29, size)?;
+ if bytes_at(png, 0, 8)? != b"\x89PNG\r\n\x1a\n" || be32(png, 8)? != 13 || bytes_at(png, 12, 4)? != b"IHDR" {
+ return Err(Error::Malformed("thumbnail is not a PNG"));
+ }
+ let width = be32(png, 16)?;
+ let height = be32(png, 20)?;
+ if width == 0 || height == 0 || width > MAX_PREVIEW_DIMENSION || height > MAX_PREVIEW_DIMENSION {
+ return Err(Error::Limit("preview dimensions must be 1..4096"));
+ }
+ // Bound work by bytes, not a file-supplied chunk count, and require exactly one complete PNG.
+ let mut pos = 8usize;
+ let mut seen_ihdr = false;
+ let mut seen_plte = false;
+ let mut seen_idat = false;
+ let mut idat_ended = false;
+ loop {
+ let length = usize::try_from(be32(png, pos)?).map_err(|_| Error::Limit("PNG chunk length"))?;
+ let chunk_size = length.checked_add(12).ok_or(Error::Malformed("PNG chunk overflow"))?;
+ let chunk = bytes_at(png, pos, chunk_size)?;
+ let crc_offset = chunk_size.checked_sub(4).ok_or(Error::Malformed("PNG CRC offset"))?;
+ let protected = chunk.get(4..crc_offset).ok_or(Error::Malformed("PNG CRC span"))?;
+ if crc32fast::hash(protected) != be32(chunk, crc_offset)? {
+ return Err(Error::Malformed("PNG chunk CRC mismatch"));
+ }
+ let kind = bytes_at(chunk, 4, 4)?;
+ if !kind.iter().all(u8::is_ascii_alphabetic) {
+ return Err(Error::Malformed("invalid PNG chunk name"));
+ }
+ // Native oracles have no compressed metadata or animation. Reject before any decoder
+ // can inflate many individually capped text/profile chunks or silently pick a frame.
+ if matches!(kind, b"zTXt" | b"iTXt" | b"iCCP") {
+ return Err(Error::Unsupported("compressed PNG metadata in preview"));
+ }
+ if matches!(kind, b"acTL" | b"fcTL" | b"fdAT") {
+ return Err(Error::Unsupported("animated PNG preview"));
+ }
+ match kind {
+ b"IHDR" => {
+ if seen_ihdr || pos != 8 {
+ return Err(Error::Malformed("PNG IHDR must be first and unique"));
+ }
+ seen_ihdr = true;
+ }
+ b"PLTE" => {
+ if seen_plte || seen_idat {
+ return Err(Error::Malformed("PNG PLTE must be unique and precede IDAT"));
+ }
+ seen_plte = true;
+ }
+ b"IDAT" => {
+ if idat_ended {
+ return Err(Error::Malformed("PNG IDAT chunks must be contiguous"));
+ }
+ seen_idat = true;
+ }
+ b"IEND" => {
+ if !seen_idat {
+ return Err(Error::Malformed("PNG has no image data"));
+ }
+ }
+ _ => {
+ if kind.first().is_some_and(|b| b.is_ascii_uppercase()) {
+ return Err(Error::Unsupported("unknown critical PNG chunk"));
+ }
+ }
+ }
+ if seen_idat && kind != b"IDAT" {
+ idat_ended = true;
+ }
+ pos = pos.checked_add(chunk_size).ok_or(Error::Malformed("PNG offset overflow"))?;
+ if kind == b"IEND" {
+ if length != 0 || pos != png.len() {
+ return Err(Error::Malformed("PNG end or trailing data"));
+ }
+ break;
+ }
+ }
+ Ok(Preview { png, width, height })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use proptest::prelude::*;
+
+ fn fixture() -> Vec<u8> {
+ let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
+ png.extend(13u32.to_be_bytes());
+ png.extend(b"IHDR");
+ png.extend(2u32.to_be_bytes());
+ png.extend(1u32.to_be_bytes());
+ png.extend([8, 6, 0, 0, 0]);
+ let ihdr_crc = crc32fast::hash(&png[12..]);
+ png.extend(ihdr_crc.to_be_bytes());
+ png.extend([0; 4]);
+ png.extend(b"IDAT");
+ png.extend(crc32fast::hash(b"IDAT").to_be_bytes());
+ png.extend([0; 4]);
+ png.extend(b"IEND");
+ png.extend(crc32fast::hash(b"IEND").to_be_bytes());
+ // Valid CRCs, but no compressed pixels: consuming decoders still validate those.
+ file(&png)
+ }
+
+ fn file(png: &[u8]) -> Vec<u8> {
+ let mut b = vec![0; 72];
+ b[..4].copy_from_slice(MAGIC);
+ b[4..6].copy_from_slice(&12u16.to_le_bytes());
+ b[8..12].copy_from_slice(b"nsrP");
+ b[12..16].copy_from_slice(b"#Inf");
+ b[24..32].copy_from_slice(&72u64.to_le_bytes());
+ b[64..68].copy_from_slice(b"Prot");
+ b.extend(b"\xff\xff\xff\xffThmb");
+ b.extend(1u32.to_le_bytes());
+ b.extend((png.len() as u32 + 13).to_le_bytes());
+ b.extend(29u32.to_le_bytes());
+ b.extend(0u32.to_le_bytes());
+ b.extend((png.len() as u32).to_le_bytes());
+ b.push(1);
+ b.extend(png);
+ b
+ }
+
+ fn chunk(kind: &[u8; 4], data: &[u8]) -> Vec<u8> {
+ let mut tagged = kind.to_vec();
+ tagged.extend(data);
+ let mut result = (data.len() as u32).to_be_bytes().to_vec();
+ result.extend(&tagged);
+ result.extend(crc32fast::hash(&tagged).to_be_bytes());
+ result
+ }
+
+ #[test]
+ fn indexed_preview_and_header() {
+ let b = fixture();
+ assert_eq!(inspect(&b).unwrap().version, 12);
+ let p = preview(&b).unwrap();
+ assert_eq!((p.width, p.height), (2, 1));
+ assert_eq!(p.png, &b[101..]);
+ }
+
+ #[test]
+ fn every_truncation_is_rejected() {
+ let b = fixture();
+ for end in 0..b.len() {
+ assert!(preview(&b[..end]).is_err(), "{end}");
+ }
+ }
+
+ #[test]
+ fn rejects_assets_versions_offsets_lengths_and_bombs() {
+ let b = fixture();
+ for (offset, value) in [
+ (4, 13u64.to_le_bytes().to_vec()),
+ (8, b"urBR".to_vec()),
+ (24, u64::MAX.to_le_bytes().to_vec()),
+ (24, 1u64.to_le_bytes().to_vec()),
+ (24, 0u64.to_le_bytes().to_vec()),
+ (84, u32::MAX.to_le_bytes().to_vec()),
+ (88, 30u32.to_le_bytes().to_vec()),
+ (96, u32::MAX.to_le_bytes().to_vec()),
+ (117, 5000u32.to_be_bytes().to_vec()),
+ ] {
+ let mut broken = b.clone();
+ broken[offset..offset + value.len()].copy_from_slice(&value);
+ assert!(preview(&broken).is_err(), "offset {offset}");
+ }
+ for version in 7..12 {
+ let mut legacy = b.clone();
+ legacy[4..6].copy_from_slice(&(version as u16).to_le_bytes());
+ assert!(inspect(&legacy).is_ok());
+ assert!(matches!(preview(&legacy), Err(Error::Unsupported(_))));
+ }
+ }
+
+ #[test]
+ fn an_unindexed_png_or_resource_is_never_used() {
+ let mut b = fixture();
+ b[24..32].copy_from_slice(&0u64.to_le_bytes());
+ assert!(preview(&b).is_err());
+ b[24..32].copy_from_slice(&72u64.to_le_bytes());
+ b[76..80].copy_from_slice(b"Meta");
+ assert!(preview(&b).is_err());
+ }
+
+ #[test]
+ fn every_chunk_crc_including_iend_and_ancillary_is_checked() {
+ let mut bad_iend = fixture();
+ *bad_iend.last_mut().unwrap() ^= 1;
+ assert_eq!(preview(&bad_iend).unwrap_err(), Error::Malformed("PNG chunk CRC mismatch"));
+
+ let b = fixture();
+ let mut png = preview(&b).unwrap().png.to_vec();
+ let tagged = b"tEXtnote\0preview";
+ let mut chunk = ((tagged.len() - 4) as u32).to_be_bytes().to_vec();
+ chunk.extend(tagged);
+ chunk.extend(crc32fast::hash(tagged).to_be_bytes());
+ let end = png.len() - 12;
+ png.splice(end..end, chunk.clone());
+ assert!(preview(&file(&png)).is_ok());
+ png[end + chunk.len() - 1] ^= 1;
+ assert_eq!(preview(&file(&png)).unwrap_err(), Error::Malformed("PNG chunk CRC mismatch"));
+ }
+
+ #[test]
+ fn compressed_metadata_and_animation_are_rejected_before_pixel_decoding() {
+ let b = fixture();
+ for kind in [b"zTXt", b"iTXt", b"iCCP", b"acTL", b"fcTL", b"fdAT"] {
+ let mut png = preview(&b).unwrap().png.to_vec();
+ // The chunk claims compressed metadata without making the parser inflate it.
+ let mut tagged = kind.to_vec();
+ tagged.extend(b"preview\0\0\x78\x9c");
+ let mut chunk = ((tagged.len() - 4) as u32).to_be_bytes().to_vec();
+ chunk.extend(&tagged);
+ chunk.extend(crc32fast::hash(&tagged).to_be_bytes());
+ let end = png.len() - 12;
+ png.splice(end..end, chunk);
+ assert!(matches!(preview(&file(&png)), Err(Error::Unsupported(_))), "{kind:?}");
+ }
+ }
+
+ #[test]
+ fn critical_chunk_order_is_checked_even_after_image_data() {
+ let b = fixture();
+ let original = preview(&b).unwrap().png.to_vec();
+ for trailing in [chunk(b"IHDR", &original[16..29]), chunk(b"PLTE", &[0, 0, 0]), chunk(b"ABCD", &[])] {
+ let mut png = original.clone();
+ let end = png.len() - 12;
+ png.splice(end..end, trailing);
+ assert!(preview(&file(&png)).is_err());
+ }
+ let mut no_image = original.clone();
+ no_image.drain(33..45);
+ assert!(preview(&file(&no_image)).is_err());
+ let mut duplicate_palette = original.clone();
+ duplicate_palette.splice(33..33, chunk(b"PLTE", &[0, 0, 0]).repeat(2));
+ assert!(preview(&file(&duplicate_palette)).is_err());
+ let mut split_image = original;
+ let end = split_image.len() - 12;
+ let mut interrupted = chunk(b"tEXt", b"note\0preview");
+ interrupted.extend(chunk(b"IDAT", &[]));
+ split_image.splice(end..end, interrupted);
+ assert!(preview(&file(&split_image)).is_err());
+ }
+
+ proptest! {
+ #![proptest_config(ProptestConfig::with_cases(256))]
+ #[test]
+ fn arbitrary_input_never_panics(b in prop::collection::vec(any::<u8>(), 0..2048)) {
+ let _ = inspect(&b);
+ let _ = preview(&b);
+ }
+ #[test]
+ fn mutations_never_panic(edits in prop::collection::vec((0usize..200, any::<u8>()), 0..32)) {
+ let mut b = fixture();
+ for (i, value) in edits { if let Some(v) = b.get_mut(i) { *v = value; } }
+ let _ = preview(&b);
+ }
+ }
+}
diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs
index 09513c231..004b806ec 100644
--- a/crates/automation/src/files.rs
+++ b/crates/automation/src/files.rs
@@ -13,22 +13,23 @@ use crate::AutomationError;
pub struct Opened {
pub document: Document,
pub warnings: Vec<String>,
+ pub source_read_only: bool,
}
/// Decode a document that was read through a filesystem capability.
pub fn open_bytes(name: &str, bytes: &[u8]) -> Result<Opened, AutomationError> {
if Path::new(name).extension().is_some_and(|extension| extension.eq_ignore_ascii_case(photocraft_format::EXTENSION)) {
- return Ok(Opened { document: photocraft_format::load_from_bytes(bytes)?, warnings: Vec::new() });
+ return Ok(Opened { document: photocraft_format::load_from_bytes(bytes)?, warnings: Vec::new(), source_read_only: false });
}
let r = photocraft_io::import(name, bytes)?;
- Ok(Opened { document: r.document, warnings: r.warnings })
+ Ok(Opened { document: r.document, warnings: r.warnings, source_read_only: r.source_read_only })
}
/// Open a document from disk. Directory bundles and `.pcraft` ZIPs load
/// natively; everything else goes through `photocraft-io` (PSD, PNG, …).
pub fn open(path: &Path) -> Result<Opened, AutomationError> {
if path.is_dir() {
- return Ok(Opened { document: photocraft_format::load_path(path)?, warnings: Vec::new() });
+ return Ok(Opened { document: photocraft_format::load_path(path)?, warnings: Vec::new(), source_read_only: false });
}
let bytes = photocraft_format::read_file(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs
index e3bd8c74b..79d84248f 100644
--- a/crates/automation/src/headless.rs
+++ b/crates/automation/src/headless.rs
@@ -91,7 +91,10 @@ impl Headless {
}
None => Some(requested.to_string()),
};
- let index = self.session.add_document(o.document, path);
+ let index = self.session.add_document(o.document, path.filter(|_| !o.source_read_only));
+ if let Some(st) = self.session.active_mut() {
+ st.source_read_only = o.source_read_only;
+ }
let d = &self.session.documents()[index];
Ok(json!({
"index": index,
diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rs
index cf745dc75..40fb341fd 100644
--- a/crates/automation/tests/mcp.rs
+++ b/crates/automation/tests/mcp.rs
@@ -316,6 +316,49 @@ fn write_image(dir: &std::path::Path, name: &str, format: photocraft_codecs::For
bytes
}
+#[tokio::test(flavor = "multi_thread")]
+async fn affinity_preview_warns_and_requires_a_new_save_path() {
+ let dir = tmp("affinity-preview");
+ let png = write_image(&dir, "preview.png", photocraft_codecs::Format::Png);
+ // Synthetic v12 envelope; the native document graph is intentionally absent.
+ let mut bytes = vec![0; 72];
+ bytes[..4].copy_from_slice(b"\x00\xffKA");
+ bytes[4..6].copy_from_slice(&12u16.to_le_bytes());
+ bytes[8..12].copy_from_slice(b"nsrP");
+ bytes[12..16].copy_from_slice(b"#Inf");
+ bytes[24..32].copy_from_slice(&72u64.to_le_bytes());
+ bytes[64..68].copy_from_slice(b"Prot");
+ bytes.extend(b"\xff\xff\xff\xffThmb");
+ bytes.extend(1u32.to_le_bytes());
+ bytes.extend((png.len() as u32 + 13).to_le_bytes());
+ bytes.extend(29u32.to_le_bytes());
+ bytes.extend(0u32.to_le_bytes());
+ bytes.extend((png.len() as u32).to_le_bytes());
+ bytes.push(1);
+ bytes.extend(png);
+ std::fs::write(dir.join("source.af"), &bytes).unwrap();
+ // A renamed layered extension must not bypass source protection.
+ std::fs::write(dir.join("renamed.psd"), &bytes).unwrap();
+ let client = connect(headless_in(&dir)).await;
+ for name in ["source.af", "renamed.psd"] {
+ let opened = json_of(&call(&client, "doc_open", json!({"path": name})).await);
+ assert!(opened["warnings"].to_string().contains("Native layers"));
+ assert_eq!(opened["width"], 16);
+ let refused = call(&client, "doc_save", json!({})).await;
+ assert_eq!(refused.is_error, Some(true), "{}", text(&refused));
+ assert!(text(&refused).contains("pass `path`"), "{}", text(&refused));
+ let native = call(&client, "doc_save", json!({"path": "source.af"})).await;
+ assert_eq!(native.is_error, Some(true));
+ assert!(text(&native).contains("Affinity export"));
+ assert_eq!(std::fs::read(dir.join(name)).unwrap(), bytes);
+ }
+ json_of(&call(&client, "doc_save", json!({"path": "copy.pcraft"})).await);
+ assert_eq!(json_of(&call(&client, "doc_save", json!({})).await)["path"], "copy.pcraft");
+ assert_eq!(std::fs::read(dir.join("source.af")).unwrap(), bytes);
+ client.cancel().await.unwrap();
+ cleanup(&dir);
+}
+
/// A save without `path` writes back only to a layered file in its own format (#416).
#[tokio::test(flavor = "multi_thread")]
async fn save_without_path_never_flattens_over_the_opened_file() {
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index 4b4d6269e..05b0db1ca 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -117,7 +117,7 @@ pub(crate) fn list_images(dir: &str) -> Result<Vec<String>> {
/// Extensions the batch commands pick up from a folder.
const OPENABLE: &[&str] = &[
"psd", "psb", "pcraft", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "exr", "hdr", "qoi", "ico", "pnm", "ppm", "pgm", "heic", "heif",
- "hif", "dng", "cr2", "nef", "nrw", "arw", "pef",
+ "hif", "dng", "cr2", "nef", "nrw", "arw", "pef", "af",
];
pub(crate) fn file_name(path: &str) -> String {
@@ -178,7 +178,15 @@ pub(crate) fn sanitize(name: &str) -> String {
}
pub(crate) fn import(name: &str, bytes: &[u8]) -> Result<Document> {
- photocraft_io::import(name, bytes).map(|r| r.document).map_err(|e| EngineError::Other(format!("{name}: {e}")))
+ let r = photocraft_io::import(name, bytes).map_err(|e| EngineError::Other(format!("{name}: {e}")))?;
+ // Auxiliary imports return only a document and cannot surface the preview's fidelity warning.
+ // Open has its own warning-preserving path; never silently place or process a thumbnail.
+ if r.source_read_only {
+ return Err(EngineError::Other(format!(
+ "{name}: only an Affinity preview is available; open it with File › Open to see the warning, or export PSD or PNG from Affinity before using it here"
+ )));
+ }
+ Ok(r.document)
}
/// What a headless save writes beyond the format: JPEG quality and TIFF layers.
@@ -341,7 +349,10 @@ pub fn open_bytes_as(s: &mut Session, name: &str, bytes: &[u8], as_ext: Option<&
}
};
// Color Settings policies (preserve / convert / discard the embedded profile).
- let (i, color) = s.open_document(doc, path);
+ let (i, color) = s.open_document(doc, path.filter(|_| !r.source_read_only));
+ if let Some(st) = s.active_mut() {
+ st.source_read_only = r.source_read_only;
+ }
// Import notes (e.g. how a camera raw was developed, or that only its preview opened).
Ok(json!({"document": i, "color": color, "warnings": r.warnings}))
}
diff --git a/crates/engine/src/filters_ext.rs b/crates/engine/src/filters_ext.rs
index 1f25aff52..8c93a4096 100644
--- a/crates/engine/src/filters_ext.rs
+++ b/crates/engine/src/filters_ext.rs
@@ -427,8 +427,8 @@ pub(crate) fn resolve(s: &Session, fp: &mut FilterParams, p: &Value) -> Result<(
let layer = p.get("mapLayer").and_then(Value::as_u64);
let img = if let Some(path) = p.get("mapPath").and_then(Value::as_str).filter(|p| !p.is_empty()) {
let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("cannot read displacement map `{path}`: {e}")))?;
- let imported = photocraft_io::import(path, &bytes).map_err(|e| EngineError::Other(format!("cannot open displacement map `{path}`: {e}")))?;
- map_from_document(&imported.document, layer)
+ let imported = crate::file_cmds::import(path, &bytes).map_err(|e| EngineError::Other(format!("cannot open displacement map `{path}`: {e}")))?;
+ map_from_document(&imported, layer)
} else if let Some(d) = p.get("mapDocument") {
let docs = s.documents();
let found = match d {
diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs
index 0bbacbecf..f473f3ad9 100644
--- a/crates/engine/src/jobs.rs
+++ b/crates/engine/src/jobs.rs
@@ -427,6 +427,9 @@ impl Session {
},
move |s, r: photocraft_io::ImportResult| {
let (index, color) = s.open_document(r.document, None);
+ if let Some(st) = s.active_mut() {
+ st.source_read_only = r.source_read_only;
+ }
Ok(json!({"document": index, "name": name_a, "warnings": r.warnings, "color": color}))
},
)
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 48aad0515..624536dfc 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -155,6 +155,8 @@ pub struct DocState {
/// Anchor of ⇧-click range selection (the last plainly or ⌘-clicked layer).
pub layer_anchor: Option<LayerId>,
pub path: Option<String>,
+ /// An Affinity preview must not acquire the native source as its Save path.
+ pub source_read_only: bool,
/// Increments on every change; UIs re-render when it moves.
pub revision: u64,
pub saved_revision: u64,
@@ -191,6 +193,7 @@ impl DocState {
selected_layers: active_layer.into_iter().collect(),
layer_anchor: active_layer,
path,
+ source_read_only: false,
revision: 1,
saved_revision: 1,
last_damage: None,
diff --git a/crates/engine/src/notes_cmds.rs b/crates/engine/src/notes_cmds.rs
index aac8efe33..54bbd60b7 100644
--- a/crates/engine/src/notes_cmds.rs
+++ b/crates/engine/src/notes_cmds.rs
@@ -165,7 +165,7 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
/// File › Import › Notes… from file bytes (what a file picker returns).
pub fn import_notes_from(s: &mut Session, name: &str, bytes: &[u8]) -> Result<Value> {
- let src = photocraft_io::import(name, bytes).map_err(|e| EngineError::Other(format!("{name}: {e}")))?.document;
+ let src = crate::file_cmds::import(name, bytes)?;
if src.notes.is_empty() {
return Err(EngineError::Other(format!("{name} has no notes")));
}
diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rs
index 2578e7f09..2e5647fdd 100644
--- a/crates/engine/src/smart_cmds.rs
+++ b/crates/engine/src/smart_cmds.rs
@@ -64,7 +64,7 @@ pub fn encode_source(doc: &Document) -> Result<Vec<u8>> {
/// Decodes smart-object contents (a `.pcraft` bundle, PSD/PSB, or any flat image format).
pub fn decode_source(file_name: &str, bytes: &[u8]) -> Result<Document> {
- photocraft_io::import(file_name, bytes).map(|r| r.document).map_err(|e| other(format!("can't read smart object contents \"{file_name}\": {e}")))
+ crate::file_cmds::import(file_name, bytes).map_err(|e| other(format!("can't read smart object contents \"{file_name}\": {e}")))
}
fn base_name(path: &str) -> String {
diff --git a/crates/engine/src/variables_cmds.rs b/crates/engine/src/variables_cmds.rs
index 2cf30e7dd..65e3ffee0 100644
--- a/crates/engine/src/variables_cmds.rs
+++ b/crates/engine/src/variables_cmds.rs
@@ -190,7 +190,7 @@ fn replace_pixels(doc: &mut Document, layer: LayerId, path: &str, method: PixelM
}
let fmt = doc.pixel_format();
let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("read `{path}`: {e}")))?;
- let src = photocraft_io::import(path, &bytes).map_err(|e| EngineError::Other(format!("`{path}`: {e}")))?.document;
+ let src = crate::file_cmds::import(path, &bytes)?;
let img = crate::file_cmds::flattened(&src, fmt);
let (iw, ih) = (src.size.width.max(1) as f64, src.size.height.max(1) as f64);
let (tw, th) = (target.width() as f64, target.height() as f64);
diff --git a/crates/engine/src/video_cmds.rs b/crates/engine/src/video_cmds.rs
index cefe37ca3..744f8c20d 100644
--- a/crates/engine/src/video_cmds.rs
+++ b/crates/engine/src/video_cmds.rs
@@ -183,7 +183,7 @@ fn load_frames(path: &str, fmt: photocraft_color::PixelFormat) -> Result<Vec<Sur
for f in &files {
let bytes = std::fs::read(f).map_err(|e| EngineError::Other(format!("read `{}`: {e}", f.display())))?;
let name = f.to_string_lossy();
- let doc = photocraft_io::import(&name, &bytes).map_err(|e| EngineError::Other(format!("`{}`: {e}", f.display())))?.document;
+ let doc = crate::file_cmds::import(&name, &bytes)?;
frames.push(crate::file_cmds::flattened(&doc, fmt));
}
Ok(frames)
diff --git a/crates/engine/tests/affinity.rs b/crates/engine/tests/affinity.rs
new file mode 100644
index 000000000..c4e343e34
--- /dev/null
+++ b/crates/engine/tests/affinity.rs
@@ -0,0 +1,84 @@
+//! A preview is a new document, never a save target for the Affinity source.
+#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+
+use std::sync::Arc;
+
+use photocraft_engine::Session;
+use photocraft_engine::file_cmds::open_bytes_as;
+use photocraft_engine::jobs::{OpenSource, Started};
+use serde_json::json;
+
+fn fixture() -> Vec<u8> {
+ let mut src = Session::new();
+ src.execute("file.new", json!({"width": 2, "height": 1, "background": "#dc283c"})).unwrap();
+ let png = photocraft_io::export(&src.active().unwrap().doc, "preview.png", &Default::default()).unwrap().bytes;
+ // Observed v12 preview envelope, without a native object graph.
+ let mut bytes = vec![0; 72];
+ bytes[..4].copy_from_slice(b"\x00\xffKA");
+ bytes[4..6].copy_from_slice(&12u16.to_le_bytes());
+ bytes[8..12].copy_from_slice(b"nsrP");
+ bytes[12..16].copy_from_slice(b"#Inf");
+ bytes[24..32].copy_from_slice(&72u64.to_le_bytes());
+ bytes[64..68].copy_from_slice(b"Prot");
+ bytes.extend(b"\xff\xff\xff\xffThmb");
+ bytes.extend(1u32.to_le_bytes());
+ bytes.extend((png.len() as u32 + 13).to_le_bytes());
+ bytes.extend(29u32.to_le_bytes());
+ bytes.extend(0u32.to_le_bytes());
+ bytes.extend((png.len() as u32).to_le_bytes());
+ bytes.push(1);
+ bytes.extend(png);
+ bytes
+}
+
+#[test]
+fn preview_never_saves_back_to_its_native_or_renamed_source() {
+ let dir = std::env::temp_dir().join(format!("photocraft-affinity-source-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let bytes = fixture();
+ for name in ["source.af", "renamed.psd"] {
+ let path = dir.join(name).to_string_lossy().into_owned();
+ std::fs::write(&path, &bytes).unwrap();
+ let mut s = Session::new();
+ let r = open_bytes_as(&mut s, &path, &bytes, None, Some(path.clone())).unwrap();
+ assert!(r["warnings"].to_string().contains("embedded"));
+ assert!(s.active().unwrap().path.is_none(), "{name}");
+ assert!(s.active().unwrap().source_read_only);
+ assert!(!s.is_enabled("file.revert"));
+ assert_eq!(std::fs::read(&path).unwrap(), bytes);
+ // Explicit native export is refused before any file is written.
+ let native = dir.join("refused.af");
+ assert!(s.execute("file.saveACopy", json!({"path": native})).is_err());
+ assert!(!native.exists());
+ let copy = dir.join(format!("{name}.pcraft"));
+ s.execute("file.saveACopy", json!({"path": copy})).unwrap();
+ assert!(photocraft_io::import("copy.pcraft", &std::fs::read(copy).unwrap()).is_ok());
+ assert_eq!(std::fs::read(path).unwrap(), bytes);
+ }
+ std::fs::remove_dir_all(dir).unwrap();
+}
+
+#[test]
+fn background_preview_retains_the_source_protection_and_warning() {
+ let mut s = Session::new();
+ let started = s.start_open("source.af", OpenSource::Bytes(Arc::new(fixture()))).unwrap();
+ let result = match started {
+ Started::Job(id) => s.wait_job(id).unwrap(),
+ Started::Done(v) => v,
+ };
+ assert!(result["warnings"].to_string().contains("Native layers"));
+ assert!(s.active().unwrap().source_read_only);
+ assert!(s.active().unwrap().path.is_none());
+}
+
+#[test]
+fn warningless_auxiliary_paths_cannot_silently_use_a_thumbnail() {
+ let bytes = fixture();
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
+ let layers = s.active().unwrap().doc.layers.len();
+ let error = photocraft_engine::file_cmds::place_bytes(&mut s, "source.af", bytes.clone(), None, &json!({})).unwrap_err().to_string();
+ assert!(error.contains("only an Affinity preview"), "{error}");
+ assert_eq!(s.active().unwrap().doc.layers.len(), layers);
+ assert!(photocraft_engine::smart_cmds::decode_source("source.af", &bytes).unwrap_err().to_string().contains("export PSD or PNG"));
+}
diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml
index eb8bc833c..9db74a139 100644
--- a/crates/io/Cargo.toml
+++ b/crates/io/Cargo.toml
@@ -26,6 +26,7 @@ photocraft-algo = { workspace = true }
photocraft-psd = { workspace = true }
photocraft-codecs = { workspace = true }
photocraft-raw = { workspace = true }
+photocraft-affinity = { workspace = true }
photocraft-text = { workspace = true }
photocraft-paint = { workspace = true }
photocraft-vector = { workspace = true }
@@ -35,6 +36,8 @@ serde_json = { workspace = true }
blake3 = { version = "1.8", default-features = false, features = ["pure"] }
[dev-dependencies]
+crc32fast = "1.5"
+flate2 = { workspace = true }
photocraft-psd = { workspace = true, features = ["testgen"] }
photocraft-raw = { workspace = true, features = ["testgen"] }
proptest = { workspace = true }
diff --git a/crates/io/src/affinity.rs b/crates/io/src/affinity.rs
new file mode 100644
index 000000000..24cdf4dea
--- /dev/null
+++ b/crates/io/src/affinity.rs
@@ -0,0 +1,31 @@
+//! Affinity documents currently open as their embedded preview, with an explicit warning.
+
+use crate::{ImportResult, IoError};
+
+pub use photocraft_affinity::is_affinity;
+
+/// Extensions recognized as Affinity documents (legacy containers get an actionable error).
+pub const EXTENSIONS: &[&str] = &["af", "afphoto", "afdesign", "afpub"];
+
+pub fn has_extension(name: &str) -> bool {
+ name.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).is_some_and(|(_, ext)| EXTENSIONS.iter().any(|e| ext.eq_ignore_ascii_case(e)))
+}
+
+pub(crate) fn import(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {
+ let p = photocraft_affinity::preview(bytes).map_err(|e| IoError::Unsupported(e.to_string()))?;
+ let opts = photocraft_codecs::DecodeOptions {
+ limits: photocraft_codecs::Limits { max_width: 4096, max_height: 4096, max_pixels: 4096 * 4096, max_alloc: 128 << 20 },
+ ..Default::default()
+ };
+ let img = photocraft_codecs::decode_with(p.png, &opts)?;
+ let mut r = crate::flat::image_to_document(name, &img)?;
+ if let Some(layer) = r.document.layers.first_mut() {
+ layer.name = "Affinity preview".into();
+ layer.locks = Default::default();
+ }
+ r.source_read_only = true;
+ r.warnings.insert(0, format!(
+ "Opened only Affinity's embedded {}×{} PNG preview, which may be smaller than the document. Native layers, vectors, text, masks, effects, pages and the document's colour settings are not imported. Save a new copy; the Affinity source cannot be saved back. Export PSD or PNG from Affinity for full-resolution artwork.", p.width, p.height
+ ));
+ Ok(r)
+}
diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs
index 9ccaf4080..7356a6d2e 100644
--- a/crates/io/src/flat.rs
+++ b/crates/io/src/flat.rs
@@ -102,7 +102,7 @@ pub(crate) fn image_to_document(name: &str, img: &Image) -> Result<ImportResult,
if !img.meta.text.is_empty() {
warnings.push(format!("{} text metadata entries are not kept in the document", img.meta.text.len()));
}
- Ok(ImportResult { document: doc, warnings })
+ Ok(ImportResult { document: doc, warnings, source_read_only: false })
}
/// `Some(surface)` when the document is exactly one visible, unmasked,
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 4cd40d795..69a7f085e 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -15,6 +15,8 @@
//! layer; unsupported raw variants fall back to the embedded JPEG preview.
//! * Layered TIFFs (Photoshop layer data in tags 37724 and 34377) open with their
//! layers through the PSD path and are written back the same way; see `tiff_layers`.
+//! * Some Affinity version-12 containers open as their indexed PNG preview, with
+//! an explicit fidelity warning and no source save path; see `affinity`.
//! * Every other format goes through `photocraft-codecs` as a single
//! "Background" layer (depth and Gray/RGB/CMYK model preserved).
//!
@@ -25,6 +27,7 @@
pub mod abr_map;
mod adjust_map;
+pub mod affinity;
pub mod annotations_map;
pub mod blocks;
mod channel_map;
@@ -87,6 +90,8 @@ pub struct ImportResult {
pub document: Document,
/// Human-readable notes about anything approximated or dropped.
pub warnings: Vec<String>,
+ /// An Affinity preview must not retain a Save path to its native source.
+ pub source_read_only: bool,
}
/// Result of [`export`].
@@ -139,7 +144,7 @@ pub fn is_psd(bytes: &[u8]) -> bool {
bytes.starts_with(b"8BPS")
}
-/// Imports a file. PSD/PSB and camera raws are detected by magic; everything
+/// Imports a file. PSD/PSB, Affinity containers and camera raws are detected by magic; everything
/// else is decoded with `photocraft-codecs`.
pub fn import(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {
import_with(name, bytes, &photocraft_raster::Interrupt::NONE)
@@ -158,7 +163,7 @@ pub fn import_with(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt)
fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt) -> Result<ImportResult, IoError> {
// A declared native extension must reach its loader so malformed bundles retain format errors.
if has_extension(name, photocraft_format::EXTENSION) || photocraft_format::is_pcraft(bytes) {
- return Ok(ImportResult { document: photocraft_format::load_from_bytes(bytes)?, warnings: Vec::new() });
+ return Ok(ImportResult { document: photocraft_format::load_from_bytes(bytes)?, warnings: Vec::new(), source_read_only: false });
}
if is_psd(bytes) {
let file = PsdFile::from_bytes(bytes)?;
@@ -171,7 +176,10 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt) -
ctl.progress(0.05);
let (mut document, warnings) = psd_import::psd_to_document_with(&file, ctl).ok_or(IoError::Cancelled)?;
document.name = name.to_string();
- return Ok(ImportResult { document, warnings });
+ return Ok(ImportResult { document, warnings, source_read_only: false });
+ }
+ if affinity::is_affinity(bytes) || affinity::has_extension(name) {
+ return affinity::import(name, bytes);
}
if raw::is_raw(bytes) {
return raw::import_raw(name, bytes);
@@ -191,6 +199,9 @@ fn has_extension(name: &str, expected: &str) -> bool {
/// bare extension).
pub fn export(doc: &Document, name_or_ext: &str, opts: &ExportOptions) -> Result<ExportResult, IoError> {
let ext = extension(name_or_ext);
+ if affinity::EXTENSIONS.contains(&ext.as_str()) {
+ return Err(IoError::Unsupported("Affinity export is not implemented; save a new PSD, PNG or .pcraft copy".into()));
+ }
if ext == photocraft_format::EXTENSION {
let previews = photocraft_format::SaveOptions {
thumbnail: Some(photocraft_compose::thumbnail(doc, 256)),
diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs
index 6ad712c19..1a621c21c 100644
--- a/crates/io/src/tiff_layers.rs
+++ b/crates/io/src/tiff_layers.rs
@@ -112,7 +112,7 @@ pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8]) -> Result<I
if !img.meta.text.is_empty() {
warnings.push(format!("{} text metadata entries are not kept in the document", img.meta.text.len()));
}
- Ok(ImportResult { document: doc, warnings })
+ Ok(ImportResult { document: doc, warnings, source_read_only: false })
}
/// Interleaved native-endian samples → planar big-endian planes (PSD merged-image order),
diff --git a/crates/io/tests/affinity.rs b/crates/io/tests/affinity.rs
new file mode 100644
index 000000000..2b7ac73d1
--- /dev/null
+++ b/crates/io/tests/affinity.rs
@@ -0,0 +1,212 @@
+//! Preview-only imports keep pixels and alpha, warn about native content, and never write .af.
+#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+
+use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType};
+use photocraft_io::{ExportOptions, export, import};
+use proptest::prelude::*;
+use std::io::Write as _;
+
+fn png() -> Vec<u8> {
+ let img = Image::from_raw(2, 1, ChannelLayout::Rgba, SampleType::U8, vec![220, 40, 60, 255, 0, 0, 0, 0]).unwrap();
+ photocraft_codecs::encode(&img, Format::Png, &EncodeOptions::default()).unwrap()
+}
+
+fn chunk(kind: &[u8; 4], data: &[u8]) -> Vec<u8> {
+ let mut tagged = kind.to_vec();
+ tagged.extend(data);
+ let mut result = (data.len() as u32).to_be_bytes().to_vec();
+ result.extend(&tagged);
+ result.extend(crc32fast::hash(&tagged).to_be_bytes());
+ result
+}
+
+/// A synthetic record envelope, not an Affinity document writer (there is no object graph).
+fn file(png: &[u8]) -> Vec<u8> {
+ let mut b = vec![0; 72];
+ b[..4].copy_from_slice(photocraft_affinity::MAGIC);
+ b[4..6].copy_from_slice(&12u16.to_le_bytes());
+ b[8..12].copy_from_slice(b"nsrP");
+ b[12..16].copy_from_slice(b"#Inf");
+ b[24..32].copy_from_slice(&72u64.to_le_bytes());
+ b[64..68].copy_from_slice(b"Prot");
+ b.extend(b"\xff\xff\xff\xffThmb");
+ b.extend(1u32.to_le_bytes());
+ b.extend((png.len() as u32 + 13).to_le_bytes());
+ b.extend(29u32.to_le_bytes());
+ b.extend(0u32.to_le_bytes());
+ b.extend((png.len() as u32).to_le_bytes());
+ b.push(1);
+ b.extend(png);
+ b
+}
+
+#[test]
+fn preview_is_named_and_warns_at_its_actual_size() {
+ let r = import("art.af", &file(&png())).unwrap();
+ assert_eq!((r.document.size.width, r.document.size.height), (2, 1));
+ assert_eq!(r.document.layers.len(), 1);
+ assert_eq!(r.document.layers[0].name, "Affinity preview");
+ assert!(r.source_read_only);
+ assert!(r.warnings[0].contains("2×1"));
+ assert!(r.warnings[0].contains("Native layers"));
+ let out = export(&r.document, "copy.png", &ExportOptions::default()).unwrap();
+ let img = photocraft_codecs::decode(&out.bytes).unwrap();
+ assert_eq!(img.data(), &[220, 40, 60, 255, 0, 0, 0, 0]);
+ let native = export(&r.document, "copy.pcraft", &ExportOptions::default()).unwrap();
+ let back = import("copy.pcraft", &native.bytes).unwrap();
+ assert_eq!(back.document.size, r.document.size);
+ assert!(!back.source_read_only);
+ for ext in photocraft_io::affinity::EXTENSIONS {
+ assert!(export(&r.document, ext, &ExportOptions::default()).unwrap_err().to_string().contains("Affinity export"));
+ }
+}
+
+#[test]
+fn magic_wins_over_the_name_and_renamed_legacy_files_are_rejected() {
+ assert!(import("renamed.png", &file(&png())).unwrap().source_read_only);
+ assert!(import("unknown", &file(&png())).unwrap().source_read_only);
+ assert!(import("fake.af", &png()).is_err());
+ let mut legacy = file(&png());
+ legacy[4..6].copy_from_slice(&10u16.to_le_bytes());
+ assert!(import("legacy.afphoto", &legacy).unwrap_err().to_string().contains("legacy preview"));
+ assert!(import("legacy.af", &legacy).is_err());
+}
+
+#[test]
+fn preview_decoder_preserves_16_bit_gray_and_alpha() {
+ let img = Image::from_u16(2, 1, ChannelLayout::GrayA, &[12345, 65535, 0, 0]).unwrap();
+ let encoded = photocraft_codecs::encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
+ let r = import("gray.af", &file(&encoded)).unwrap();
+ assert_eq!(r.document.depth, photocraft_color::SampleType::U16);
+ assert_eq!(r.document.mode, photocraft_color::ColorMode::Grayscale);
+ let out = export(&r.document, "copy.png", &ExportOptions::default()).unwrap();
+ let decoded = photocraft_codecs::decode(&out.bytes).unwrap();
+ assert_eq!(decoded.sample_type(), SampleType::U16);
+ assert_eq!(decoded.data(), img.data());
+}
+
+#[test]
+fn previewless_current_files_return_an_export_fallback() {
+ let mut bytes = file(&png());
+ bytes[24..32].fill(0);
+ let error = import("no-preview.af", &bytes).unwrap_err().to_string();
+ assert!(error.contains("no embedded preview"), "{error}");
+ assert!(error.contains("export PNG, PSD or SVG"), "{error}");
+}
+
+#[test]
+fn corruption_and_every_truncation_fail_without_a_document() {
+ let b = file(&png());
+ for end in 0..b.len() {
+ assert!(import("bad.af", &b[..end]).is_err(), "{end}");
+ }
+ let mut bad_crc = b.clone();
+ // IHDR's CRC; the envelope reader rejects every PNG chunk's bad CRC.
+ bad_crc[130] ^= 1;
+ assert!(import("bad.af", &bad_crc).is_err());
+}
+
+#[test]
+fn crc_failures_after_idat_cannot_be_tolerated_as_partial_pngs() {
+ let mut bad_iend = file(&png());
+ *bad_iend.last_mut().unwrap() ^= 1;
+ assert!(import("bad-iend.af", &bad_iend).unwrap_err().to_string().contains("PNG chunk CRC"));
+
+ let mut encoded = png();
+ let tagged = b"tEXtnote\0preview";
+ let mut chunk = ((tagged.len() - 4) as u32).to_be_bytes().to_vec();
+ chunk.extend(tagged);
+ chunk.extend(crc32fast::hash(tagged).to_be_bytes());
+ let end = encoded.len() - 12;
+ encoded.splice(end..end, chunk.clone());
+ assert!(import("valid-ancillary.af", &file(&encoded)).is_ok());
+ encoded[end + chunk.len() - 1] ^= 1;
+ assert!(import("bad-ancillary.af", &file(&encoded)).unwrap_err().to_string().contains("PNG chunk CRC"));
+}
+
+#[test]
+fn compressed_metadata_and_apng_fail_before_reaching_the_decoder() {
+ for kind in [b"zTXt", b"iTXt", b"iCCP", b"acTL", b"fcTL", b"fdAT"] {
+ let mut encoded = png();
+ // A tiny declared payload stands in for arbitrarily large inflated metadata. It must
+ // return the format's unsupported error, not be passed to a decompressor.
+ let mut tagged = kind.to_vec();
+ tagged.extend(b"preview\0\0\x78\x9c");
+ let mut chunk = ((tagged.len() - 4) as u32).to_be_bytes().to_vec();
+ chunk.extend(&tagged);
+ chunk.extend(crc32fast::hash(&tagged).to_be_bytes());
+ let end = encoded.len() - 12;
+ encoded.splice(end..end, chunk);
+ let error = import("unsupported.af", &file(&encoded)).unwrap_err().to_string();
+ assert!(error.contains("unsupported Affinity file"), "{kind:?}: {error}");
+ assert!(error.contains("PNG metadata") || error.contains("animated PNG"), "{error}");
+ }
+}
+
+#[test]
+fn many_valid_compressed_text_chunks_cannot_bypass_the_total_memory_budget() {
+ let mut compressor = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best());
+ for _ in 0..1024 {
+ compressor.write_all(&[b'x'; 1024]).unwrap();
+ }
+ let compressed = compressor.finish().unwrap();
+ assert!(compressed.len() < 2048);
+ let mut tagged = b"zTXtnote\0\0".to_vec();
+ tagged.extend(compressed);
+ let mut chunk = ((tagged.len() - 4) as u32).to_be_bytes().to_vec();
+ chunk.extend(&tagged);
+ chunk.extend(crc32fast::hash(&tagged).to_be_bytes());
+ let mut encoded = png();
+ let end = encoded.len() - 12;
+ // A few MiB of encoded PNG would otherwise carry 1 GiB of aggregate text.
+ encoded.splice(end..end, chunk.repeat(1024));
+ let error = import("text-bomb.af", &file(&encoded)).unwrap_err().to_string();
+ assert!(error.contains("compressed PNG metadata"), "{error}");
+}
+
+#[test]
+fn invalid_critical_chunks_after_idat_fail_before_png_finish() {
+ let original = png();
+ for trailing in [chunk(b"IHDR", &original[16..29]), chunk(b"PLTE", &[0, 0, 0]), chunk(b"ABCD", &[])] {
+ let mut encoded = original.clone();
+ let end = encoded.len() - 12;
+ encoded.splice(end..end, trailing);
+ let error = import("bad-order.af", &file(&encoded)).unwrap_err().to_string();
+ assert!(error.contains("Affinity file"), "{error}");
+ }
+ let mut encoded = original;
+ let end = encoded.len() - 12;
+ let mut interrupted = chunk(b"tEXt", b"note\0preview");
+ interrupted.extend(chunk(b"IDAT", &[]));
+ encoded.splice(end..end, interrupted);
+ assert!(import("split-idat.af", &file(&encoded)).unwrap_err().to_string().contains("IDAT chunks must be contiguous"));
+}
+
+proptest! {
+ #![proptest_config(ProptestConfig::with_cases(128))]
+ #[test]
+ fn preview_and_decoder_survive_mutations(edits in prop::collection::vec((0usize..300, any::<u8>()), 0..16)) {
+ let mut b = file(&png());
+ for (i, v) in edits { if let Some(byte) = b.get_mut(i) { *byte = v; } }
+ let _ = import("mutated.af", &b);
+ }
+}
+
+/// Optional local oracle; authored by Affinity 3.3, never committed as a binary fixture.
+#[test]
+#[ignore = "set AFFINITY_ORACLE_DIR to synthetic Affinity .af and exported PNG files"]
+fn native_affinity_oracle() {
+ let dir = std::env::var("AFFINITY_ORACLE_DIR").unwrap();
+ for (name, size) in [("synthetic-rectangle", (64, 48)), ("synthetic-large", (1024, 768))] {
+ let bytes = std::fs::read(format!("{dir}/{name}.af")).unwrap();
+ let r = import(&format!("{name}.af"), &bytes).unwrap();
+ assert_eq!((r.document.size.width, r.document.size.height), size);
+ let preview = photocraft_affinity::preview(&bytes).unwrap();
+ let source = photocraft_codecs::decode(&std::fs::read(format!("{dir}/{name}.png")).unwrap()).unwrap();
+ let decoded = photocraft_codecs::decode(preview.png).unwrap();
+ assert_eq!(decoded.data().len(), size.0 as usize * size.1 as usize * 4);
+ if name == "synthetic-rectangle" {
+ assert_eq!(decoded.data(), source.data());
+ }
+ }
+}
diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs
index 6339ac77f..8c5f81c48 100644
--- a/crates/ui-egui/src/file_open.rs
+++ b/crates/ui-egui/src/file_open.rs
@@ -45,7 +45,7 @@ pub fn display_name(path: &str) -> String {
impl PhotocraftApp {
/// Open `bytes` read from the file at `path`: the document is named after the file, keeps
- /// `path` for File › Save, and `path` goes to the top of Open Recent. Returns the import
+ /// `path` for File › Save unless it is a derivative preview, and `path` goes to the top of Open Recent. Returns the import
/// warnings (also shown to the user).
pub fn open_file(&mut self, path: &str, bytes: &[u8]) -> Result<Vec<String>, String> {
// Brushes/gradients go to the preset libraries (no document, no Open Recent entry).
@@ -63,10 +63,11 @@ impl PhotocraftApp {
}
/// Record that the active document was just opened from `path`: File › Save writes back to it
- /// (unless it's a template) and it goes to the top of Open Recent.
+ /// (unless it's a template or derivative preview) and it goes to the top of Open Recent.
pub(crate) fn opened_from(&mut self, path: &str) {
if !is_template(path)
&& let Some(st) = self.session.active_mut()
+ && !st.source_read_only
{
st.path = Some(path.to_string());
}
diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs
index 87573d104..cbe22155d 100644
--- a/crates/ui-egui/src/file_open/tests.rs
+++ b/crates/ui-egui/src/file_open/tests.rs
@@ -61,6 +61,27 @@ fn open_file_sets_name_path_and_recent() {
assert!(app.ui.notices.is_empty());
}
+#[test]
+fn affinity_preview_does_not_acquire_the_source_path_even_when_renamed() {
+ for automation in [false, true] {
+ for path in ["/pics/source.af", "/pics/renamed.psd"] {
+ let (mut app, written) = app_with(None, None);
+ // The fake importer supplies the preview; its source signature controls path policy.
+ if automation {
+ app.open_automation_bytes(&display_name(path), b"\x00\xffKA").unwrap();
+ app.opened_from(path);
+ } else {
+ app.open_file(path, b"\x00\xffKA").unwrap();
+ }
+ assert!(app.session.active().unwrap().source_read_only);
+ assert!(app.session.active().unwrap().path.is_none());
+ assert_eq!(app.ui.recent_files.first().map(String::as_str), Some(path));
+ assert_eq!(menus::invoke(&mut app, &egui::Context::default(), "file.save", json!({})).unwrap_err(), "cancelled");
+ assert!(written.borrow().is_empty());
+ }
+ }
+}
+
#[test]
fn file_open_dialog_sets_path_so_save_writes_in_place() {
// The dialog returns a full path: the document is named after the file, not the path.
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index c6edf19a4..b2901a631 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -757,6 +757,9 @@ impl PhotocraftApp {
// Edit › Color Settings policies apply on open; mismatches can ask what to do.
// No path yet: a bare name isn't a location to save back to (`open_file` sets the path).
let (_, color) = self.session.open_document(doc, None);
+ if let Some(st) = self.session.active_mut() {
+ st.source_read_only = photocraft_io::affinity::is_affinity(bytes);
+ }
self.sync_views();
self.ui.status = format!("Opened {name}");
self.ui.status_error = false;
@@ -797,6 +800,9 @@ impl PhotocraftApp {
let (doc, warnings) = import(name, bytes)?;
// The caller records the path it read from.
self.session.add_document(doc, None);
+ if let Some(st) = self.session.active_mut() {
+ st.source_read_only = photocraft_io::affinity::is_affinity(bytes);
+ }
self.sync_views();
self.ui.status = format!("Opened {name}");
self.ui.status_error = false;
diff --git a/docs/architecture.md b/docs/architecture.md
index 63a3bc599..1f4ca3260 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -99,6 +99,7 @@ photocraft/
│ ├─ adobe-assets/ photocraft-adobe-assets .abr .asl .aco/.ase .grd .pat .csh .atn .cube/.3dl, ACR .xmp presets (standalone, like psd)
│ ├─ codecs/ photocraft-codecs png/jpeg/tiff/webp/gif/bmp/avif decode/encode, heif/heic decode (feature `heif`)
│ ├─ heif/ photocraft-heif optional HEIF/HEIC decoder (heic-rs, pure Rust); used only by codecs behind its `heif` feature (standalone)
+│ ├─ affinity/ photocraft-affinity bounded container inspection and indexed PNG preview extraction (standalone; no native graph decoder)
│ ├─ raw/ photocraft-raw clean-room camera RAW decode (DNG, CR2, TIFF/EP) + develop pipeline (standalone, like psd)
│ ├─ format/ photocraft-format native document format (.pcraft bundle): manifest + content-addressed tiles
│ ├─ io/ photocraft-io import/export orchestration; doc ⇄ PSD mapping; PDF/SVG import (features)
diff --git a/docs/roadmap.md b/docs/roadmap.md
index 50b400f4f..428518020 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -28,6 +28,12 @@ readiness; treat it as an upper bound.
**Menu parity: 532 / 625 (85.1%)** on 2026-10-01, up from 224 (35.8%) the day before. See [`parity.md`](parity.md).
+2026-10-08: Affinity `.af` import has an initial, bounded **embedded-preview-only** path
+([format notes](../crates/affinity/README.md)). Some version-12 documents open at the preview's
+dimensions with an explicit warning and without a source save path. Previewless files and
+legacy containers remain unsupported; native layers, document colour settings, full-resolution
+content and Affinity writing are still missing. This does not raise editable-format parity.
+
## Honest parity assessment (2026-10-05)
This is the reference answer to "how close are we to Photoshop parity, really". Agents: read it
@@ -149,4 +155,3 @@ Each milestone has a **definition of done (DoD)** and must leave `main` green on
| **M10** | Smart features | `ml` (ort native / ort-web on the web), Select Subject/Object/Sky, Remove BG, Remove tool, content-aware fill, healing, AI denoise, RAW develop | Quality benchmarks on a public dataset; timing budgets |
| **M11** | Automation + formats | MCP server, batch, scripting, remaining formats (JP2, DICOM, DPX…), C2PA | An agent completes 10 scripted edit tasks via MCP |
| **M12** | Pro parity | CMYK/Lab UI, print, HDR display, photomerge/HDR merge, timeline, layer comps, artboards, symmetry, neural filters | `xtask parity` ≥ 90% of Photoshop menu checklist |
-
diff --git a/docs/scorecard.md b/docs/scorecard.md
index f903a5108..fa4fcec70 100644
--- a/docs/scorecard.md
+++ b/docs/scorecard.md
@@ -12,7 +12,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
| [Workspace and UI](#workspace-and-ui) | 0 | 5 | 18 | settings that do nothing: 57 of 135 (target 0) |
| [Type](#type) | 0 | 3 | 6 | |
| [Automation](#automation) | 3 | 2 | 6 | 627 of 627 menu items live (100.0%) |
-| [Reliability](#reliability) | 4 | 1 | 2 | never-crash lints on 27 of 27 crates; panic_hunt present |
+| [Reliability](#reliability) | 4 | 1 | 2 | never-crash lints on 28 of 28 crates; panic_hunt present |
| [Distribution](#distribution) | 4 | 4 | 3 | |
| [Open bugs](#open-bugs) | 12 | 4 | 16 | |
@@ -218,7 +218,7 @@ Menu wiring (`docs/parity.md`): 627 of 627 menu items live (100.0%). This counts
## Reliability
-Never-crash attribute on 27 of 27 crate roots.
+Never-crash attribute on 28 of 28 crate roots.
| Id | Target | Status | Issue | Note |
|---|---|---|---|---|
diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs
index 7a97c94f1..7d567d4ba 100644
--- a/xtask/src/layers.rs
+++ b/xtask/src/layers.rs
@@ -42,6 +42,7 @@ pub const TABLE: &[(&str, Class)] = &[
// Optional HEIF/HEIC decoder (heic-rs), used only by `codecs` behind its `heif` feature.
("heif", Class::Standalone),
("raw", Class::Standalone),
+ ("affinity", Class::Standalone),
("adobe-assets", Class::Standalone),
// Pen tablet input (the one isolated `unsafe` helper: AppKit interop on macOS).
("tablet", Class::Standalone),