diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 31b8d85666..5baf73fb12 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -206,6 +206,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
@@ -217,7 +219,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/ATTRIBUTION.md b/ATTRIBUTION.md
index 5212a046b4..fdaf7627d0 100644
--- a/ATTRIBUTION.md
+++ b/ATTRIBUTION.md
@@ -84,6 +84,7 @@ next to the files:
| `corpus/psd/` (170 files) | Small selection of the psd-tools and ag-psd test files | Kota Yamaguchi; Agamnentzar | psd-tools (above) and [ag-psd `test/`](https://github.com/Agamnentzar/ag-psd/tree/master/test) | MIT (both) |
| `corpus/heif/` (9 files, 0.1 MB) | HEIC/HEIF test files: `heic-rs/` checkerboards, RGB strips and a grid-tiled photo with EXIF and XMP (synthetic pixels encoded by macOS `sips`, each `.ref.png` Apple's decode); `pillow-heif/` the 10-bit RGBA `RGBA_10__29x100.heif` and its source `RGBA_16__29x100.png` | Thomas Braun (heic-rs); Pillow-Heif contributors | [heic-rs `tests/fixtures`](https://github.com/tbraun96/heic-rs/tree/main/tests/fixtures), [pillow-heif `tests/images`](https://github.com/bigcat88/pillow_heif/tree/master/tests/images) | MIT OR Apache-2.0 (heic-rs); BSD-3-Clause (pillow-heif) |
| `corpus/exr/` (5 files, 2.3 MB) | The deep OpenEXR test images `11`, `42`, `64`, `multivariate` and `objectid.deep.exr` | Contributors to the OpenEXR Project | [openexr `src/test/bin/test_images`](https://github.com/AcademySoftwareFoundation/openexr/tree/main/src/test/bin/test_images) | BSD-3-Clause |
+| `corpus/affinity/` (21 files, 2.4 MB) | Public Affinity documents, unmodified: `vector-art/` (9), `afdesignload/` (9), `jac21/` (2) and `asset-store-template/` (1), each with its upstream licence next to it | samuel-etver; Nick Beeuwsaert; Jeremy Cantu; DAIKI (eviltwo) | [vector-art `simple/`](https://github.com/samuel-etver/vector-art/tree/255f8add3c8f0740196e22bd59502b811b532f0b/simple), [AFDesignLoad `testDesigns/`](https://github.com/NickBeeuwsaert/AFDesignLoad/tree/a18dd50a7079fb861a28835eeefa0d015f03f4a1/testDesigns), [Jac21/Branding `Logos/JC/DesignerFiles/Affinity`](https://github.com/Jac21/Branding/tree/57ae3f45bf4637f6927c0b07de25b922c55f944f/Logos/JC/DesignerFiles/Affinity), [AssetStoreTemplate `AssetStoreTemplate/`](https://github.com/eviltwo/AssetStoreTemplate/tree/f671981ee89d15526285b3cc87b4393d3defe644/AssetStoreTemplate) | CC0-1.0 (vector-art); MIT, Copyright (c) 2015 Nick Beeuwsaert; MIT, Copyright (c) 2018 Jeremy Cantu; MIT, Copyright (c) 2024 DAIKI |
| `corpus/pngsuite/` | PngSuite | Willem van Schaik | | Public domain |
Files copied into `corpus/` by hand (tiff, exr, raw) must be MIT, BSD or CC0.
diff --git a/Cargo.lock b/Cargo.lock
index c9f9b0a879..9dd34b93c9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4009,6 +4009,16 @@ dependencies = [
"zbus",
]
+[[package]]
+name = "photocraft-affinity"
+version = "0.5.0"
+dependencies = [
+ "crc32fast",
+ "flate2",
+ "proptest",
+ "ruzstd",
+]
+
[[package]]
name = "photocraft-algo"
version = "0.5.0"
@@ -4126,6 +4136,7 @@ version = "0.5.0"
dependencies = [
"blake3",
"flate2",
+ "photocraft-affinity",
"photocraft-algo",
"photocraft-cms",
"photocraft-codecs",
@@ -4204,6 +4215,9 @@ name = "photocraft-io"
version = "0.5.0"
dependencies = [
"blake3",
+ "crc32fast",
+ "flate2",
+ "photocraft-affinity",
"photocraft-algo",
"photocraft-cms",
"photocraft-codecs",
diff --git a/Cargo.toml b/Cargo.toml
index 24b00462ac..b7adf41032 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 966258d1b6..3dd367c35f 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
🗂️ Formats
- PSD and PSB, layered TIFF (Photoshop's layer data in the TIFF, read and written in either byte order), SVG (opens as shape layers, places as a vector Smart Object), 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 --features heif build feature), and the native .pcraft format.
+ PSD and PSB, layered TIFF (Photoshop's layer data in the TIFF, read and written in either byte order), SVG (opens as shape layers, places as a vector Smart Object), 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 --features heif build feature), and the native .pcraft format. Affinity documents (.af, .afdesign, .afphoto, .afpub) open natively, read only, with artboards, layers, vectors, text, images and masks; effects, adjustments and other unsupported parts are listed in a warning, and Affinity export is unavailable.
🪄 The everyday essentials
diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs
index 43f71fb769..fcccb2b38b 100644
--- a/apps/photocraft-cli/src/lib.rs
+++ b/apps/photocraft-cli/src/lib.rs
@@ -340,7 +340,10 @@ 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" | "afdesign" | "afphoto" | "afpub")
+ || 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 90c8f64d15..df49842f6a 100644
--- a/apps/photocraft-web/src/web.rs
+++ b/apps/photocraft-web/src/web.rs
@@ -12,11 +12,12 @@ use wasm_bindgen::JsCast as _;
type Inbox = Arc)>>>;
-/// Everything File › Open reads: PhotoCraft and Photoshop documents, flat images, and Photoshop
-/// brushes (.abr), gradients (.grd) and swatches (.aco, .ase), which go to the preset libraries.
+/// Everything File › Open reads: PhotoCraft, Photoshop and Affinity documents, flat images, and
+/// Photoshop brushes (.abr), gradients (.grd) and swatches (.aco, .ase), 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", "svg", "svgz", "aco", "ase",
+ "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af",
+ "afdesign", "afphoto", "afpub",
];
const CANVAS_ID: &str = "photocraft_canvas";
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs
index 363059ad57..ab406d2866 100644
--- a/apps/photocraft/src/services.rs
+++ b/apps/photocraft/src/services.rs
@@ -13,11 +13,12 @@ use std::pin::Pin;
use std::rc::Rc;
use std::sync::Arc;
-/// Everything File › Open reads: PhotoCraft and Photoshop documents, flat images, and Photoshop
-/// brushes (.abr), gradients (.grd) and swatches (.aco, .ase), which go to the preset libraries.
+/// Everything File › Open reads: PhotoCraft, Photoshop and Affinity documents, flat images, and
+/// Photoshop brushes (.abr), gradients (.grd) and swatches (.aco, .ase), 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", "svg", "svgz", "aco", "ase",
+ "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af",
+ "afdesign", "afphoto", "afpub",
];
/// 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 a141aded96..c85cfdf1f4 100644
--- a/book/src/SUMMARY.md
+++ b/book/src/SUMMARY.md
@@ -22,6 +22,7 @@
- [PSD and PSB](formats/psd-psb.md)
- [Raster formats](formats/raster-formats.md)
- [SVG](formats/svg.md)
+- [Affinity documents](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 c423cf2eb0..34df8b601c 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 0000000000..36544c7fc5
--- /dev/null
+++ b/book/src/formats/affinity.md
@@ -0,0 +1,31 @@
+# Affinity documents
+
+PhotoCraft opens native Affinity documents: `.af` files from Affinity 3 and `.afdesign`,
+`.afphoto` and `.afpub` files from Affinity 1 and 2. Layers come in as editable PhotoCraft layers:
+
+- pages and artboards become artboards (Publisher spreads sit side by side);
+- layers and groups become groups;
+- curves and shapes (rectangles, ellipses, polygons, stars and the other geometric shapes) become
+ shape layers with their fill, gradient and stroke;
+- artistic and frame text becomes type layers, drawn with the fonts installed on your computer;
+- placed JPEG and PNG images become embedded smart objects, and pixel layers become pixel layers;
+- vector and pixel masks, opacity, visibility, locks, names and blend modes are kept.
+
+The document is 8-bit RGB at the Affinity document's resolution. What PhotoCraft can't reproduce is
+listed in a warning when the file opens, for example layer effects, adjustment layers and live
+filters, brush strokes (drawn as plain strokes), special shapes such as clouds and hearts (drawn as
+ellipses), master pages, and CMYK or Lab colour (converted to RGB without the document's profile).
+Nothing is dropped without a warning.
+
+PhotoCraft can't write Affinity files. An opened Affinity document has no save path: Save asks for
+a new file (`.pcraft`, PSD, PNG…) and never writes over the Affinity file.
+
+If the native data can't be read (a damaged file, or a layout PhotoCraft doesn't know), PhotoCraft
+opens the small PNG preview Affinity stores in the file instead, as a single pixel layer named
+“Affinity preview”, and the warning says why. That preview can't be placed or used by File ▸ Place,
+stacks, batch processing or other imports that can't show the warning. Export PSD or PNG from
+Affinity in that case.
+
+See [the crate's notes](https://github.com/storytold/photocraft/blob/main/crates/affinity/README.md)
+for the full list of what is imported, how the reader was written and validated, and its safety
+limits.
diff --git a/book/src/formats/overview.md b/book/src/formats/overview.md
index bb8108c082..0f066983cb 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` reads native Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`): layers, artboards, vectors, text, images and masks; it does not write them.
`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), [SVG](svg.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), [SVG](svg.md), [Affinity documents](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 0000000000..e686e737ef
--- /dev/null
+++ b/crates/affinity/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+name = "photocraft-affinity"
+description = "Bounded reader for native Affinity documents: archive, object stream and document model"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[lints]
+workspace = true
+
+[features]
+# Synthetic-container builders for tests and fuzz seeds; not an Affinity exporter.
+synth = []
+
+[dependencies]
+crc32fast = "1.5"
+flate2 = { workspace = true }
+ruzstd = "0.9"
+
+[dev-dependencies]
+proptest = { workspace = true }
diff --git a/crates/affinity/README.md b/crates/affinity/README.md
new file mode 100644
index 0000000000..3672eb3a93
--- /dev/null
+++ b/crates/affinity/README.md
@@ -0,0 +1,149 @@
+# photocraft-affinity
+
+An independent, bounded Rust reader for native Affinity documents: `.af` from Affinity 3 and
+`.afdesign`, `.afphoto` and `.afpub` from Affinity 1 and 2 (container versions 8 to 12). It reads
+the archive, the tagged object stream in `doc.dat` and the part of the document model listed below,
+and hands `photocraft-io` a document in pixels with every transform composed. It does not write
+Affinity files.
+
+## What is imported
+
+`photocraft-io` maps the model to an 8-bit RGB document at the Affinity document's resolution:
+
+| Affinity | PhotoCraft |
+|---|---|
+| Pages, Publisher spreads | one artboard per spread, spreads side by side 64 px apart |
+| Artboards (`ShpN` with `ABEn`), with name, solid background, any transform | artboards (nested ones as groups with a vector mask) |
+| Layers (`Scop`), groups (`Grup`), pass-through or isolated | groups (pass-through or Normal) |
+| Curves (`PCrv`): cubic subpaths, closed flags, live corners (`CnrD`) | shape layers (multi-subpath curves fill even-odd) |
+| Rectangles with corner radii (relative or absolute), ellipses, polygons (smooth too), stars, square stars, pies, triangles, trapezoids | shape layers |
+| Compound shapes (`Comp`, add and subtract) | one even-odd shape |
+| A shape or curve with children clips them | group with the outline as vector mask, the shape at its bottom |
+| Vector masks (`AdCh` curves and shapes) | vector masks |
+| Pixel masks (`MRst`, attached or as a layer in a group) | layer masks |
+| Solid fills: RGBA, HSLA, CMYK, grey, Lab (D50) | shape fill (converted to RGB) |
+| Linear, elliptical and radial gradients with Affinity's midpoint bias | gradient fills |
+| Strokes: weight, scale with object, dash pattern, alignment, caps, joins, miter limit | shape strokes |
+| Fill layers (`FRst`) | filled rectangles |
+| Artistic and frame text: characters, font family/weight/style, size, tracking, fixed leading, colour, paragraph alignment, first baseline | type layers (rendered with the fonts installed) |
+| Placed images (`ImgN`): the original JPEG/PNG embedded in the file | embedded smart objects |
+| Pixel layers (`Rstr`): RGBA 8/16-bit and CMYK 8-bit tiles, cropped to their content | pixel layers |
+| Embedded documents and symbols (`EmbN`) | the picture Affinity cached of them |
+| Opacity, visibility, lock, names, blend modes | the same (Add as Linear Dodge) |
+
+Everything else is reported in the import warnings, one line per kind with a count, never
+dropped silently: layer effects, adjustment layers and live filters, brush and pressure strokes,
+transparency gradients, fill opacity, bitmap fills, master pages, conical gradients, special shapes
+(cloud, heart, cog, callouts, arrows…, imported as their bounding ellipse), corner types other than
+round, stars with rounded points, several fills or strokes on one object (one of each is used),
+strokes behind the fill, outlined or scaled text, text fields such as page numbers, frames with
+columns or a curved outline, grey/Lab/32-bit pixels, CMYK and Lab colour (converted to RGB without
+the document's profile), facing pages and the Average, Negation, Reflect, Glow and Erase blend
+modes (as Normal).
+
+Opened Affinity documents start without a save path: Save asks for a new copy and never writes
+back over the Affinity file. When the native document can't be read at all, `photocraft-io` opens
+the embedded PNG preview instead, as one pixel layer named “Affinity preview”, with a warning
+that names the reason. That preview can't be placed or used by imports that can't show the
+warning (smart-object decoding, stacks, batch, displacement maps, variables).
+
+## Embedded preview
+
+`preview(bytes)` reads only the thumbnail record the header's offset 24 points to (the same in
+container versions 8 to 12); it never scans for PNG signatures. All integers are little-endian.
+
+| 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 |
+
+The PNG is limited to 16 MiB and 4096 pixels a side. IHDR must come first and be unique, IDAT
+chunks contiguous, an optional PLTE unique and before IDAT, every chunk CRC must match and IEND must
+end the file; compressed metadata (`zTXt`, `iTXt`, `iCCP`), APNG chunks and unknown critical chunks
+are rejected. The I/O adapter decodes it with a 128 MiB allocation limit.
+
+## Provenance and clean-room
+
+Affinity has no published file-format specification, so this reader is built only from a public
+description of the format and from public files, never from Affinity itself. This is how
+PhotoCraft already treats formats that are only partly documented: `photocraft-psd` fills the gaps
+in Adobe's specification from the MIT-licensed psd-tools and ag-psd, and `photocraft-raw` recovered
+Nikon's compression tables by black-box analysis of CC0 sample files (see their READMEs).
+
+* **No Affinity software.** Affinity was never downloaded, installed, run, scripted, screenshotted or
+ disassembled for this work, and nothing from an Affinity installation (program code, resources,
+ presets, fonts, colour profiles) was read. No file was made with Affinity for it: every sample
+ is a document its author published.
+* **A public, permissively licensed description.** The container and object-stream layout was
+ learned from [VMDevCpp/afread](https://github.com/VMDevCpp/afread) (MIT, at
+ `04b672334a43e3e37ded6b5ffc57af231d589774`, written for container versions 7–11) and re-described
+ in our own words before this Rust code was written; no code was translated. No GPL/AGPL code (such
+ as Inkscape's Affinity extension) was read.
+* **Every structure checked against public files.** afread doesn't say how its author learned the
+ format, so nothing here rests on it alone: each structure the reader relies on is confirmed by
+ the public documents. Every archive entry carries a CRC-32 that must match, and every field in
+ the object stream names its own type, so a misread layout fails loudly instead of producing
+ plausible wrong data.
+* **Meaning fitted to Affinity's own pictures.** What shapes, paints, text and pixel data mean was
+ worked out by comparing our render with the thumbnail every Affinity document embeds (Affinity's
+ render of itself), on 176 public documents saved by Affinity 1.x, 2.x and 3.0/3.1 on Windows,
+ macOS and iPad. The collection has since grown to 189 distinct documents, and the reader opens
+ all of them. Most are published under CC0, MIT, BSD, Apache-2.0 or CC BY (-SA); the others
+ (no licence stated, or GPL or non-commercial terms) were only opened locally to compare
+ pictures, never committed or redistributed. The corpus test keeps the comparison for the pinned
+ files, which are CC0, MIT or Apache-2.0 only.
+* **Nothing of Affinity's is in this repository**: no program code, assets or documents. The test
+ files are fetched at pinned commits and sha256-verified, never committed.
+* **Read-only.** Nothing is written in Affinity's format; export waits until someone can check
+ written files in Affinity itself.
+
+The same reader is shared, as an independent copy, with VectorCraft's `vectorcraft-affinity`.
+
+## Validation
+
+* Unit tests on synthetic containers built by the `synth` feature (stored, zlib and zstd entries,
+ checksums, budgets, cycles, hostile streams, every truncation) and property tests of random
+ mutations, here and in `photocraft-io`'s `tests/affinity.rs`.
+* `cargo xtask corpus --affinity` fetches 21 public CC0/MIT documents, including the four
+ Affinity 3 `.af` files of [samuel-etver/vector-art](https://github.com/samuel-etver/vector-art)
+ (CC0), at pinned commits, each checked against `xtask/affinity-corpus.sha256`. `tests/real_files.rs`
+ parses them; `photocraft-io`'s `tests/affinity_corpus.rs` imports and flattens each one and
+ compares it with the thumbnail Affinity saved in it (mean difference 0–4.6 of 255, with a
+ ceiling per file).
+* `fuzz/` has `cargo-fuzz` targets for the whole reader (`preview`), the object stream (`stream`)
+ and the I/O import (`import_preview`); CI's fuzz job runs `preview` and `import_preview`:
+
+ ```sh
+ cd crates/affinity/fuzz
+ cargo +nightly fuzz run stream -- -max_total_time=600
+ cargo +nightly fuzz run import_preview --features io -- -max_total_time=600
+ ```
+
+What has not been verified: files from Affinity builds or platforms outside the public set, files
+written by other applications, rotated or skewed images against Affinity's render, mask polarity
+against a render with and without the mask, and anything listed as a warning above. The `synth`
+builders write only what this reader accepts; Affinity has never opened their output, so they are
+test fixtures, not an exporter.
+
+## Safety limits
+
+Every size is checked before it is allocated: 256 MiB per archive entry and 1 GiB per import by
+default (`Limits`), a 64 MiB zstd window, 4096 saved revisions, array lengths no longer than the
+bytes left, 16 777 216 decoded values per document stream (fields and array elements together, counted before
+anything is allocated: a value takes about 40 bytes in memory however few it took in the file; the largest of
+those 189 public documents uses 3.3 million), 384 levels of object nesting, 128 levels of layers, 500 000 layers, four million curve
+nodes per curve, 64 megapixels per pixel layer (cropped to its content first) and 1024 gradient
+stops; `photocraft-io` adds 300 000 pixels a side per document and 64 megapixels per image on the
+canvas. Every archive entry's CRC-32 and size must match. Malformed input returns an `Error`; the
+crate has no panics outside tests.
+
+## Privacy
+
+Affinity documents can hold the folder they were saved in, user names, original image paths and
+XMP metadata. This reader never imports those fields.
diff --git a/crates/affinity/fuzz/.gitignore b/crates/affinity/fuzz/.gitignore
new file mode 100644
index 0000000000..ab0eaa1a49
--- /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 0000000000..6c61c87b1f
--- /dev/null
+++ b/crates/affinity/fuzz/Cargo.toml
@@ -0,0 +1,41 @@
+[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 = "..", features = ["synth"] }
+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
+
+[[bin]]
+name = "stream"
+path = "fuzz_targets/stream.rs"
+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 0000000000..5017719749
--- /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]| {
+ // The complete import: native document mapping, or the preview fallback.
+ 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 0000000000..31e2bf973a
--- /dev/null
+++ b/crates/affinity/fuzz/fuzz_targets/preview.rs
@@ -0,0 +1,10 @@
+#![no_main]
+
+use libfuzzer_sys::fuzz_target;
+
+// The whole native reader (archive, object stream, model) and the preview, on arbitrary bytes.
+fuzz_target!(|data: &[u8]| {
+ let _ = photocraft_affinity::container::header(data);
+ let _ = photocraft_affinity::preview(data);
+ let _ = photocraft_affinity::read(data, photocraft_affinity::Limits { max_entry: 16 << 20, max_total: 64 << 20 });
+});
diff --git a/crates/affinity/fuzz/fuzz_targets/stream.rs b/crates/affinity/fuzz/fuzz_targets/stream.rs
new file mode 100644
index 0000000000..fd6128a66a
--- /dev/null
+++ b/crates/affinity/fuzz/fuzz_targets/stream.rs
@@ -0,0 +1,11 @@
+#![no_main]
+
+use libfuzzer_sys::fuzz_target;
+
+// The doc.dat object stream and the model built from it, wrapped in a stored archive entry so
+// mutations reach the tagged grammar instead of the archive's checksum.
+fuzz_target!(|stream: &[u8]| {
+ let _ = photocraft_affinity::stream::parse(stream);
+ let file = photocraft_affinity::synth::container(&[("doc.dat", stream, photocraft_affinity::synth::Method::Stored)], None);
+ let _ = photocraft_affinity::read(&file, photocraft_affinity::Limits { max_entry: 16 << 20, max_total: 64 << 20 });
+});
diff --git a/crates/affinity/src/access.rs b/crates/affinity/src/access.rs
new file mode 100644
index 0000000000..0b60ed7dbd
--- /dev/null
+++ b/crates/affinity/src/access.rs
@@ -0,0 +1,105 @@
+//! Typed reads of [`Stream`] objects. Every accessor returns `None` when a field is missing or has
+//! another type, so the document mapping treats odd data as absent rather than failing.
+
+use crate::stream::{ObjId, Object, Stream, Tag, Value};
+
+impl Stream {
+ pub fn object(&self, id: ObjId) -> Option<&Object> {
+ self.objects.get(id)
+ }
+
+ pub fn field(&self, id: ObjId, tag: &[u8; 4]) -> Option<&Value> {
+ self.object(id)?.get(Tag::of(tag))
+ }
+
+ pub fn class(&self, id: ObjId) -> Option {
+ self.object(id).map(|o| o.class)
+ }
+
+ pub fn is(&self, id: ObjId, class: &[u8; 4]) -> bool {
+ self.class(id) == Some(Tag::of(class))
+ }
+
+ /// A child object (shared, linked or inline); `None` for null or missing.
+ pub fn obj(&self, id: ObjId, tag: &[u8; 4]) -> Option {
+ match self.field(id, tag)? {
+ Value::Obj(o) => *o,
+ _ => None,
+ }
+ }
+
+ /// An array of objects (nulls skipped).
+ pub fn objs(&self, id: ObjId, tag: &[u8; 4]) -> Vec {
+ match self.field(id, tag) {
+ Some(Value::Array(a)) => a.iter().filter_map(|v| if let Value::Obj(Some(o)) = v { Some(*o) } else { None }).collect(),
+ _ => Vec::new(),
+ }
+ }
+
+ pub fn f64(&self, id: ObjId, tag: &[u8; 4]) -> Option {
+ match self.field(id, tag)? {
+ Value::Float(f) if f.is_finite() => Some(*f),
+ _ => None,
+ }
+ }
+
+ pub fn int(&self, id: ObjId, tag: &[u8; 4]) -> Option {
+ match self.field(id, tag)? {
+ Value::Int(i) => Some(*i),
+ Value::UInt(u) => i64::try_from(*u).ok(),
+ _ => None,
+ }
+ }
+
+ pub fn bool(&self, id: ObjId, tag: &[u8; 4]) -> Option {
+ match self.field(id, tag)? {
+ Value::Bool(b) => Some(*b),
+ _ => None,
+ }
+ }
+
+ pub fn str(&self, id: ObjId, tag: &[u8; 4]) -> Option<&str> {
+ match self.field(id, tag)? {
+ Value::Str(s) => Some(s),
+ _ => None,
+ }
+ }
+
+ pub fn enumeration(&self, id: ObjId, tag: &[u8; 4]) -> Option<(u16, u16)> {
+ match self.field(id, tag)? {
+ Value::Enum { id, version } => Some((*id, *version)),
+ _ => None,
+ }
+ }
+
+ /// A fixed vector of `N` finite floats (points, rectangles, transforms).
+ pub fn floats(&self, id: ObjId, tag: &[u8; 4]) -> Option<[f64; N]> {
+ match self.field(id, tag)? {
+ Value::Floats(v) if v.len() == N && v.iter().all(|f| f.is_finite()) => {
+ let mut a = [0.0; N];
+ a.copy_from_slice(v);
+ Some(a)
+ }
+ _ => None,
+ }
+ }
+
+ pub fn bytes(&self, id: ObjId, tag: &[u8; 4]) -> Option<&[u8]> {
+ match self.field(id, tag)? {
+ Value::Bytes(b) | Value::Blob(b) => Some(b),
+ _ => None,
+ }
+ }
+
+ pub fn entry(&self, id: ObjId, tag: &[u8; 4]) -> Option<&str> {
+ match self.field(id, tag)? {
+ Value::Entry(s) => Some(s),
+ _ => None,
+ }
+ }
+
+ /// Untagged fields of a positional object, in order.
+ pub fn positional(&self, id: ObjId) -> impl Iterator {
+ self.object(id).into_iter().flat_map(|o| o.fields.iter().map(|(_, v)| v))
+ }
+}
diff --git a/crates/affinity/src/container.rs b/crates/affinity/src/container.rs
new file mode 100644
index 0000000000..0829f85816
--- /dev/null
+++ b/crates/affinity/src/container.rs
@@ -0,0 +1,371 @@
+//! The Affinity archive: header, the chain of file allocation tables (one per save) and
+//! bounded, CRC-checked extraction of named entries such as `doc.dat` and raster tiles.
+
+use std::collections::{HashMap, HashSet};
+use std::io::Read;
+
+use crate::Error;
+
+pub const MAGIC: &[u8; 4] = b"\x00\xffKA";
+/// Oldest and newest container versions seen in real documents (Affinity 1.x writes 8,
+/// Affinity 3 writes 12). Version 7 is described by afread but no sample exists.
+pub const VERSIONS: std::ops::RangeInclusive = 8..=12;
+/// `Prsn` (stored byte-reversed): documents. Asset, brush and style libraries share the magic.
+const DOCUMENT_KIND: &[u8; 4] = b"nsrP";
+
+/// A save appends one table; real files have one to a few hundred.
+const MAX_TABLES: usize = 4096;
+/// zstd window ceiling: real documents use a few MiB; this stops a header from reserving gigabytes.
+const MAX_ZSTD_WINDOW: u64 = 64 << 20;
+
+/// Decompression budget for one import. Every entry declares its size, which is checked against
+/// these limits before anything is allocated, and the decoded length must match it exactly.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Limits {
+ /// Largest single entry (`doc.dat` or one tile).
+ pub max_entry: usize,
+ /// Total bytes extracted over the whole import.
+ pub max_total: usize,
+}
+
+impl Default for Limits {
+ fn default() -> Self {
+ Self { max_entry: 256 << 20, max_total: 1 << 30 }
+ }
+}
+
+/// The container header, all integers little-endian.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Header {
+ pub version: u16,
+ /// Seen as 0, 4 or 8 in real files; bits 0 and 1 mark container variants that are rejected.
+ pub flags: u16,
+ pub(crate) fat_offset: u64,
+ pub(crate) thumbnail_offset: u64,
+ /// Save time in Unix seconds, as written by the application.
+ pub saved: u32,
+}
+
+/// One FAT record, as of the newest table that mentions its id.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Entry {
+ pub id: u32,
+ pub name: String,
+ offset: u64,
+ size: u64,
+ compressed: u64,
+ crc: u32,
+ compression: u8,
+}
+
+impl Entry {
+ /// Decompressed size declared by the table.
+ pub fn size(&self) -> u64 {
+ self.size
+ }
+}
+
+#[derive(Debug)]
+pub struct Archive<'a> {
+ bytes: &'a [u8],
+ pub header: Header,
+ /// Head revision of every named, non-deleted entry.
+ entries: HashMap,
+ /// Number of tables (saves) in the chain.
+ pub revisions: usize,
+ extracted: usize,
+ limits: Limits,
+}
+
+pub(crate) struct Cursor<'a> {
+ bytes: &'a [u8],
+ pub(crate) pos: usize,
+}
+
+impl<'a> Cursor<'a> {
+ pub(crate) fn new(bytes: &'a [u8], pos: usize) -> Self {
+ Self { bytes, pos }
+ }
+ pub(crate) fn remaining(&self) -> usize {
+ self.bytes.len().saturating_sub(self.pos)
+ }
+ pub(crate) fn take(&mut self, n: usize) -> Result<&'a [u8], Error> {
+ let end = self.pos.checked_add(n).ok_or(Error::Malformed("length overflow"))?;
+ let s = self.bytes.get(self.pos..end).ok_or(Error::Malformed("truncated data"))?;
+ self.pos = end;
+ Ok(s)
+ }
+ pub(crate) fn array(&mut self) -> Result<[u8; N], Error> {
+ let s = self.take(N)?;
+ let mut a = [0u8; N];
+ a.copy_from_slice(s);
+ Ok(a)
+ }
+ pub(crate) fn u8(&mut self) -> Result {
+ Ok(self.array::<1>()?[0])
+ }
+ pub(crate) fn u16(&mut self) -> Result {
+ Ok(u16::from_le_bytes(self.array()?))
+ }
+ pub(crate) fn u32(&mut self) -> Result {
+ Ok(u32::from_le_bytes(self.array()?))
+ }
+ pub(crate) fn u64(&mut self) -> Result {
+ Ok(u64::from_le_bytes(self.array()?))
+ }
+}
+
+fn offset(v: u64) -> Result {
+ usize::try_from(v).map_err(|_| Error::Malformed("offset beyond addressable memory"))
+}
+
+/// True when `bytes` start with the Affinity container signature (documents and libraries).
+pub fn is_affinity(bytes: &[u8]) -> bool {
+ bytes.starts_with(MAGIC)
+}
+
+/// Check the signature, version and document kind.
+pub fn header(bytes: &[u8]) -> Result {
+ if !is_affinity(bytes) {
+ return Err(Error::Malformed("missing container signature"));
+ }
+ let mut c = Cursor::new(bytes, 4);
+ let version = c.u16()?;
+ let flags = c.u16()?;
+ if !VERSIONS.contains(&version) {
+ return Err(Error::Unsupported("unknown container version"));
+ }
+ if flags & 3 != 0 {
+ return Err(Error::Unsupported("container variant"));
+ }
+ if c.take(4)? != DOCUMENT_KIND {
+ return Err(Error::Unsupported("this Affinity file is a library (assets, brushes or styles), not a document"));
+ }
+ if c.take(4)? != b"#Inf" {
+ return Err(Error::Malformed("missing information header"));
+ }
+ let fat_offset = c.u64()?;
+ let thumbnail_offset = c.u64()?;
+ c.take(16)?;
+ let saved = u32::try_from(c.u64()?).unwrap_or(0);
+ c.take(8)?;
+ if c.take(4)? != b"Prot" {
+ return Err(Error::Malformed("missing protocol header"));
+ }
+ Ok(Header { version, flags, fat_offset, thumbnail_offset, saved })
+}
+
+impl<'a> Archive<'a> {
+ pub fn open(bytes: &'a [u8], limits: Limits) -> Result {
+ let header = header(bytes)?;
+ // Newest record per id: (table date, table index, record).
+ let mut latest: HashMap)> = HashMap::new();
+ let mut names: HashMap = HashMap::new();
+ let mut seen = HashSet::new();
+ let mut next = header.fat_offset;
+ let mut tables = 0usize;
+ while next != 0 {
+ if !seen.insert(next) {
+ return Err(Error::Malformed("allocation tables form a cycle"));
+ }
+ tables += 1;
+ if tables > MAX_TABLES {
+ return Err(Error::Limit("too many saved revisions"));
+ }
+ let mut c = Cursor::new(bytes, offset(next)?);
+ let tag = c.array::<4>()?;
+ let level = match &tag {
+ b"#FAT" => 1,
+ b"#FT2" => 2,
+ b"#FT3" => 3,
+ b"#FT4" => 4,
+ _ => return Err(Error::Malformed("missing allocation table")),
+ };
+ next = c.u64()?;
+ let date = c.u64()?;
+ c.take(24)?;
+ let files = c.u32()?;
+ c.take(8)?;
+ let dirs = c.u16()?;
+ c.take(1)?;
+ for _ in 0..files {
+ let id = c.u32()?;
+ let flag = c.u8()?;
+ let mut record = None;
+ match flag {
+ 0 | 1 => {
+ let offset = c.u64()?;
+ let size = c.u64()?;
+ let compressed = c.u64()?;
+ let crc = c.u32()?;
+ let stored = c.u8()?;
+ if level >= 2 {
+ c.take(4)?;
+ }
+ if level >= 4 {
+ c.take(4)?;
+ }
+ // Old tables number the methods; newer ones store the method byte itself.
+ let compression = if level <= 2 {
+ match stored {
+ 1 => 0x01,
+ 2 => 0x41,
+ 3 => 0x81,
+ 4 => 0xC1,
+ _ => 0,
+ }
+ } else {
+ stored
+ };
+ record = Some(Entry { id, name: String::new(), offset, size, compressed, crc, compression });
+ }
+ 2 => {}
+ _ => return Err(Error::Malformed("unknown allocation record")),
+ }
+ if flag == 0 {
+ let len = usize::from(c.u16()?);
+ let name = String::from_utf8_lossy(c.take(len)?).into_owned();
+ names.entry(id).or_insert(name);
+ }
+ // Equal dates: the first table in the chain (the newest) wins, as in afread.
+ let replace = latest.get(&id).is_none_or(|(d, _, _)| date > *d);
+ if replace {
+ latest.insert(id, (date, tables, record));
+ }
+ }
+ for _ in 0..dirs {
+ let len = usize::from(c.u16()?);
+ c.take(10)?;
+ c.take(len)?;
+ }
+ }
+ let mut entries = HashMap::new();
+ for (id, (_, _, record)) in latest {
+ if let (Some(mut e), Some(name)) = (record, names.get(&id)) {
+ e.name = name.clone();
+ entries.insert(e.name.clone(), e);
+ }
+ }
+ Ok(Self { bytes, header, entries, revisions: tables, extracted: 0, limits })
+ }
+
+ pub fn entry(&self, name: &str) -> Option<&Entry> {
+ self.entries.get(name)
+ }
+
+ pub fn entry_names(&self) -> impl Iterator {
+ self.entries.keys().map(String::as_str)
+ }
+
+ /// Bytes extracted so far, counted against [`Limits::max_total`].
+ pub fn extracted(&self) -> usize {
+ self.extracted
+ }
+
+ /// Extract an entry by name: decompress, undo the byte predictor and verify the CRC.
+ pub fn read(&mut self, name: &str) -> Result, Error> {
+ let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?.clone();
+ let size = usize::try_from(e.size).map_err(|_| Error::Limit("archive entry too large"))?;
+ if size > self.limits.max_entry {
+ return Err(Error::Limit("archive entry too large"));
+ }
+ let total = self.extracted.checked_add(size).ok_or(Error::Limit("document too large"))?;
+ if total > self.limits.max_total {
+ return Err(Error::Limit("document too large"));
+ }
+ let mut c = Cursor::new(self.bytes, offset(e.offset)?);
+ if c.take(4)? != b"#Fil" {
+ return Err(Error::Malformed("archive entry has no data block"));
+ }
+ let method = e.compression & 3;
+ let stored_len = if matches!(method, 1 | 2) { e.compressed } else { e.size };
+ let data = c.take(offset(stored_len)?)?;
+ let mut out = match method {
+ 1 => inflate(data, size)?,
+ 2 => unzstd(data, size)?,
+ _ => data.to_vec(),
+ };
+ if out.len() != size {
+ return Err(Error::Malformed("archive entry size mismatch"));
+ }
+ unpredict(&mut out, e.compression)?;
+ if crc32fast::hash(&out) != e.crc {
+ return Err(Error::Malformed("archive entry checksum mismatch"));
+ }
+ self.extracted = total;
+ Ok(out)
+ }
+}
+
+/// Read at most `size + 1` bytes so a stream that decodes past its declared size is caught
+/// without unbounded allocation.
+fn read_bounded(mut r: impl Read, size: usize) -> Result, Error> {
+ let mut out = Vec::with_capacity(size.min(64 << 20));
+ let cap = u64::try_from(size).unwrap_or(u64::MAX).saturating_add(1);
+ r.by_ref().take(cap).read_to_end(&mut out).map_err(|_| Error::Malformed("corrupt compressed entry"))?;
+ Ok(out)
+}
+
+fn inflate(data: &[u8], size: usize) -> Result, Error> {
+ read_bounded(flate2::read::ZlibDecoder::new(data), size)
+}
+
+fn unzstd(data: &[u8], size: usize) -> Result, Error> {
+ let mut src = data;
+ let mut out = Vec::new();
+ // Entries may hold several concatenated frames.
+ while !src.is_empty() {
+ let left = size.checked_sub(out.len()).ok_or(Error::Malformed("archive entry size mismatch"))?;
+ let decoder = ruzstd::decoding::StreamingDecoder::new_with_max_window_size(&mut src, MAX_ZSTD_WINDOW)
+ .map_err(|_| Error::Malformed("corrupt compressed entry"))?;
+ let frame = read_bounded(decoder, left)?;
+ if frame.is_empty() {
+ return Err(Error::Malformed("corrupt compressed entry"));
+ }
+ out.extend_from_slice(&frame);
+ if out.len() > size {
+ return Err(Error::Malformed("archive entry size mismatch"));
+ }
+ }
+ Ok(out)
+}
+
+/// Undo the byte predictor selected by the high bits of the compression byte.
+fn unpredict(b: &mut [u8], compression: u8) -> Result<(), Error> {
+ match (compression & 0xC0, compression & 0x20 != 0) {
+ (0x00, _) => {}
+ (0x40, _) => byte_delta(b),
+ (0x80, false) => {
+ let mut prev = 0u16;
+ for pair in b.chunks_exact_mut(2) {
+ let v = u16::from_le_bytes([pair[0], pair[1]]).wrapping_add(prev);
+ pair.copy_from_slice(&v.to_le_bytes());
+ prev = v;
+ }
+ }
+ (0x80, true) => {
+ byte_delta(b);
+ // A 64 KiB tile of 16-bit samples is stored as all high bytes, then all low bytes.
+ if b.len() == 0x10000 {
+ let planes = b.to_vec();
+ let (hi, lo) = planes.split_at(0x8000);
+ for (i, out) in b.chunks_exact_mut(4).enumerate() {
+ let (Some(h), Some(l)) = (hi.get(2 * i..2 * i + 2), lo.get(2 * i..2 * i + 2)) else {
+ return Err(Error::Malformed("tile size"));
+ };
+ out.copy_from_slice(&[l[0], h[0], l[1], h[1]]);
+ }
+ }
+ }
+ _ => return Err(Error::Unsupported("archive entry predictor")),
+ }
+ Ok(())
+}
+
+fn byte_delta(b: &mut [u8]) {
+ let mut prev = 0u8;
+ for v in b {
+ *v = v.wrapping_add(prev);
+ prev = *v;
+ }
+}
diff --git a/crates/affinity/src/geometry.rs b/crates/affinity/src/geometry.rs
new file mode 100644
index 0000000000..6a63190cc9
--- /dev/null
+++ b/crates/affinity/src/geometry.rs
@@ -0,0 +1,175 @@
+//! Outlines of curves (`PCvD` node lists), parametric shapes (`Shpe` objects) and compounds, in
+//! node space.
+
+use crate::model::{Affine, Path, Point, Reader, SubPath};
+use crate::stream::{ObjId, Tag, Value};
+
+/// Nodes per curve object.
+const MAX_NODES: usize = 4_000_000;
+
+/// The node-space outline of a curve, shape or compound node, and whether it fills even-odd.
+/// Instances (master-page or symbol copies) take the geometry of their master.
+pub(crate) fn outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine) -> Option<(Path, bool)> {
+ let s = r.s;
+ match &class.0.to_be_bytes() {
+ b"PCrv" | b"TxtC" => {
+ let crvs = s.obj(id, b"Crvs").or_else(|| s.obj(id, b"MCrM").and_then(|m| s.obj(m, b"Crvs")))?;
+ let path = curves(r, crvs)?;
+ let multi = path.subpaths.len() > 1;
+ Some((path, multi))
+ }
+ b"Comp" => {
+ // One path of all the operands' contours in the compound's space, filled even-odd: this
+ // matches add and subtract operands in every public sample; a true union of overlapping
+ // added operands would differ.
+ let mut path = Path::default();
+ for c in s.objs(id, b"Chld") {
+ let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
+ let class = s.class(c)?;
+ if s.enumeration(c, b"ComO").is_some_and(|(op, _)| op != 0 && op != 2) {
+ r.warn("compound shapes that intersect or exclude (imported as add)");
+ }
+ if let Some((p, _)) = outline(r, c, class, local.then(world)) {
+ path.subpaths.extend(p.transformed(local).subpaths);
+ }
+ }
+ Some((path, true))
+ }
+ _ => {
+ let (shape, box_owner) = match s.obj(id, b"Shpe") {
+ Some(sh) => (sh, id),
+ None => {
+ let master = s.obj(id, b"ShpM")?;
+ (s.obj(master, b"Shpe")?, master)
+ }
+ };
+ let b = s.floats::<4>(box_owner, b"ShpB")?;
+ crate::shapes::shape(r, shape, b, world).map(|p| (p, false))
+ }
+ }
+}
+
+/// `PCvD.Data`: positional `[u8, u32 count, then per subpath: bool closed, 18-byte records]`.
+/// A record is (f64 x, f64 y, u8 kind, u8 role): role 0 is an anchor, 1 the out-handle of the
+/// anchor before it, 2 the in-handle of the anchor after it. A closed subpath repeats its first
+/// anchor at the end. `CnrD` live corners are rounded on the stored polyline.
+pub(crate) fn curves(r: &mut Reader, crvs: ObjId) -> Option {
+ let s = r.s;
+ let data = s.obj(crvs, b"Data")?;
+ let mut fields = s.positional(data);
+ fields.next()?;
+ let count = match fields.next()? {
+ Value::UInt(n) => usize::try_from(*n).ok()?,
+ _ => return None,
+ };
+ let corners = s.obj(crvs, b"CnrD").and_then(|c| corner_radii(s.positional(c).collect()));
+ let mut path = Path::default();
+ let mut seen = 0usize;
+ for index in 0..count {
+ let closed = match fields.next()? {
+ Value::Bool(b) => *b,
+ _ => return None,
+ };
+ let Value::Array(records) = fields.next()? else { return None };
+ seen = seen.checked_add(records.len())?;
+ if seen > MAX_NODES {
+ r.warn("curves with more than four million nodes");
+ return None;
+ }
+ let anchors = anchors(records)?;
+ let radii = if index == 0 { corners.as_ref() } else { None };
+ if let Some(sp) = subpath(&anchors, closed, radii) {
+ path.subpaths.push(sp);
+ }
+ }
+ if corners.is_some() && count > 1 {
+ r.warn("rounded corners on curves with several subpaths (only the first is rounded)");
+ }
+ Some(path)
+}
+
+struct Anchor {
+ p: Point,
+ inh: Option,
+ out: Option,
+ /// Index of the anchor's record (live corners refer to records).
+ record: usize,
+}
+
+fn record(v: &Value) -> Option<(Point, u8)> {
+ let Value::Bytes(b) = v else { return None };
+ if b.len() != 18 {
+ return None;
+ }
+ let x = f64::from_le_bytes(b.get(0..8)?.try_into().ok()?);
+ let y = f64::from_le_bytes(b.get(8..16)?.try_into().ok()?);
+ if !x.is_finite() || !y.is_finite() {
+ return None;
+ }
+ Some((Point { x, y }, *b.get(17)?))
+}
+
+fn anchors(records: &[Value]) -> Option> {
+ let mut out: Vec = Vec::with_capacity(records.len() / 3 + 1);
+ let mut pending_in = None;
+ for (i, v) in records.iter().enumerate() {
+ let (p, role) = record(v)?;
+ match role {
+ 0 => {
+ out.push(Anchor { p, inh: pending_in.take(), out: None, record: i });
+ }
+ 1 => {
+ // A leading out-handle without an anchor is edit state only.
+ if let Some(a) = out.last_mut() {
+ a.out = Some(p);
+ }
+ }
+ 2 => pending_in = Some(p),
+ _ => return None,
+ }
+ }
+ Some(out)
+}
+
+fn subpath(anchors: &[Anchor], closed: bool, radii: Option<&Vec<(usize, f64)>>) -> Option {
+ let first = anchors.first()?;
+ if let Some(radii) = radii.filter(|r| !r.is_empty()) {
+ let corner = |a: &Anchor| radii.iter().filter(|(rec, _)| *rec == a.record).map(|(_, r)| *r).fold(0.0, f64::max);
+ let polyline = anchors.iter().all(|a| a.inh.is_none_or(|h| h == a.p) && a.out.is_none_or(|h| h == a.p));
+ if polyline {
+ let mut pts: Vec<(Point, f64)> = anchors.iter().map(|a| (a.p, corner(a))).collect();
+ // A closed subpath repeats its first anchor; its radius may be on either copy.
+ if closed
+ && pts.len() > 1
+ && pts.first().map(|p| p.0) == pts.last().map(|p| p.0)
+ && let Some((_, r)) = pts.pop()
+ && let Some(f) = pts.first_mut()
+ {
+ f.1 = f.1.max(r);
+ }
+ return Some(crate::shapes::fillet(&pts, closed));
+ }
+ }
+ let segments = anchors
+ .windows(2)
+ .filter_map(|w| {
+ let [a, b] = w else { return None };
+ Some([a.out.unwrap_or(a.p), b.inh.unwrap_or(b.p), b.p])
+ })
+ .collect();
+ Some(SubPath { start: first.p, segments, closed })
+}
+
+/// `CnrD`: positional `[u8, i32[] record indices, f64[] radii, u8[] types]`.
+fn corner_radii(fields: Vec<&Value>) -> Option> {
+ let (Some(Value::Array(idx)), Some(Value::Array(rad))) = (fields.get(1), fields.get(2)) else { return None };
+ Some(
+ idx.iter()
+ .zip(rad)
+ .filter_map(|(i, r)| match (i, r) {
+ (Value::Int(i), Value::Float(r)) if r.is_finite() && *r > 0.0 => Some((usize::try_from(*i).ok()?, *r)),
+ _ => None,
+ })
+ .collect(),
+ )
+}
diff --git a/crates/affinity/src/lib.rs b/crates/affinity/src/lib.rs
new file mode 100644
index 0000000000..9520fa2a26
--- /dev/null
+++ b/crates/affinity/src/lib.rs
@@ -0,0 +1,51 @@
+//! Reader for native Affinity documents (`.af`, and `.afdesign`/`.afphoto`/`.afpub` from
+//! Affinity 1 and 2): the archive container, the tagged object stream in `doc.dat`, and the
+//! subset of the document model PhotoCraft imports.
+//!
+//! Layouts follow the MIT-licensed afread reference and were checked against public documents
+//! saved by Affinity 1.x to 3.x (container versions 8 to 12); see the crate README for provenance
+//! and the exact supported subset. Nothing here writes Affinity files.
+#![forbid(unsafe_code)]
+#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
+
+use std::fmt;
+
+mod access;
+pub mod container;
+mod geometry;
+pub mod model;
+pub mod paint;
+pub mod preview;
+mod raster;
+mod shapes;
+pub mod stream;
+#[cfg(any(test, feature = "synth"))]
+pub mod synth;
+mod text;
+
+pub use container::{Archive, Limits, MAGIC, is_affinity};
+pub use model::{Document, read};
+pub use preview::{MAX_PREVIEW_BYTES, MAX_PREVIEW_DIMENSION, Preview, preview};
+
+/// Why a file could not be read. Messages are short reasons; callers add advice.
+#[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 {
+ match self {
+ Self::Malformed(s) => write!(f, "damaged Affinity file: {s}"),
+ Self::Unsupported(s) => write!(f, "unsupported Affinity file: {s}"),
+ Self::Limit(s) => write!(f, "Affinity file exceeds a safety limit: {s}"),
+ }
+ }
+}
+
+impl std::error::Error for Error {}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/affinity/src/model.rs b/crates/affinity/src/model.rs
new file mode 100644
index 0000000000..3579152acf
--- /dev/null
+++ b/crates/affinity/src/model.rs
@@ -0,0 +1,587 @@
+//! The document model PhotoCraft imports: spreads, artboards, layers, groups, curves, shapes,
+//! text and images, with transforms composed into document space. Anything else is reported
+//! by [`Document::warnings`] instead of being dropped silently.
+
+use std::collections::{BTreeMap, HashSet};
+
+use crate::paint::{self, Paint, Stroke};
+use crate::stream::{ObjId, Stream, Tag};
+use crate::{Archive, Error, Limits, stream};
+
+/// Affine map `x' = a·x + c·y + e`, `y' = b·x + d·y + f` (kurbo's coefficient order).
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Affine(pub [f64; 6]);
+
+impl Affine {
+ pub const IDENTITY: Self = Self([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
+
+ /// Affinity's `Xfrm`, stored row by row: (a, c, e, b, d, f).
+ pub(crate) fn from_xfrm(m: [f64; 6]) -> Self {
+ Self([m[0], m[3], m[1], m[4], m[2], m[5]])
+ }
+
+ pub fn then(self, outer: Self) -> Self {
+ let [a, b, c, d, e, f] = self.0;
+ let [oa, ob, oc, od, oe, of] = outer.0;
+ Self([oa * a + oc * b, ob * a + od * b, oa * c + oc * d, ob * c + od * d, oa * e + oc * f + oe, ob * e + od * f + of])
+ }
+
+ pub fn apply(&self, p: Point) -> Point {
+ let [a, b, c, d, e, f] = self.0;
+ Point { x: a * p.x + c * p.y + e, y: b * p.x + d * p.y + f }
+ }
+
+ /// Geometric mean of the axis scales: how much a stroke width or font size grows.
+ pub fn scale(&self) -> f64 {
+ let [a, b, c, d, ..] = self.0;
+ (a * d - b * c).abs().sqrt()
+ }
+
+ pub fn is_finite(&self) -> bool {
+ self.0.iter().all(|v| v.is_finite())
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Point {
+ pub x: f64,
+ pub y: f64,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Rect {
+ pub x0: f64,
+ pub y0: f64,
+ pub x1: f64,
+ pub y1: f64,
+}
+
+/// One cubic Bézier subpath, in document pixels.
+#[derive(Debug, Clone, PartialEq)]
+pub struct SubPath {
+ pub start: Point,
+ /// (control 1, control 2, end) per segment.
+ pub segments: Vec<[Point; 3]>,
+ pub closed: bool,
+}
+
+/// An outline in document pixels.
+#[derive(Debug, Clone, Default, PartialEq)]
+pub struct Path {
+ pub subpaths: Vec,
+}
+
+impl Path {
+ pub fn transformed(&self, m: Affine) -> Self {
+ Self {
+ subpaths: self
+ .subpaths
+ .iter()
+ .map(|s| SubPath { start: m.apply(s.start), segments: s.segments.iter().map(|seg| seg.map(|p| m.apply(p))).collect(), closed: s.closed })
+ .collect(),
+ }
+ }
+}
+
+/// Affinity's blend modes, numbered by the `Blnd` enum.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum Blend {
+ #[default]
+ Normal,
+ PassThrough,
+ Darken,
+ DarkerColor,
+ Multiply,
+ ColorBurn,
+ Lighten,
+ LighterColor,
+ Screen,
+ ColorDodge,
+ Add,
+ Overlay,
+ SoftLight,
+ HardLight,
+ VividLight,
+ PinLight,
+ LinearLight,
+ HardMix,
+ Difference,
+ Exclusion,
+ Subtract,
+ Hue,
+ Saturation,
+ Luminosity,
+ Color,
+ Average,
+ Negation,
+ Reflect,
+ Glow,
+ Erase,
+}
+
+impl Blend {
+ /// The enum (id, version) pairs observed in a document whose layers are named after their mode.
+ fn from_enum(id: u16, version: u16) -> Option {
+ use Blend::*;
+ Some(match (id, version) {
+ (0, _) => Normal,
+ (1, 0) => Darken,
+ (2, 1) => DarkerColor,
+ (2, 0) => Multiply,
+ (3, 0) => ColorBurn,
+ (4, 0) => Lighten,
+ (6, 1) => LighterColor,
+ (5, 0) => Screen,
+ (6, 0) => ColorDodge,
+ (7, 0) => Add,
+ (8, 0) => Overlay,
+ (9, 0) => SoftLight,
+ (10, 0) => HardLight,
+ (11, 0) => VividLight,
+ (12, 0) => PinLight,
+ (15, 1) => LinearLight,
+ (13, 0) => HardMix,
+ (14, 0) => Difference,
+ (15, 0) => Exclusion,
+ (16, 0) => Subtract,
+ (17, 0) => Hue,
+ (18, 0) => Saturation,
+ (19, 0) => Luminosity,
+ (20, 0) => Color,
+ (21, 0) => Average,
+ (22, 0) => Negation,
+ (23, 0) => Reflect,
+ (24, 0) => Glow,
+ (25, 0) => Erase,
+ _ => return None,
+ })
+ }
+}
+
+/// A run of text with one set of character attributes.
+#[derive(Debug, Clone, PartialEq)]
+pub struct TextRun {
+ pub text: String,
+ /// PostScript name and family of the chosen font.
+ pub postscript: String,
+ pub family: String,
+ /// CSS weight (400 regular, 700 bold).
+ pub weight: i64,
+ pub italic: bool,
+ /// Font size in document pixels, before the node's transform.
+ pub size: f64,
+ /// Tracking in em.
+ pub tracking: f64,
+ /// Fixed line pitch in document pixels, when the run overrides automatic leading.
+ pub leading: Option,
+ pub fill: Paint,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Align {
+ Left,
+ Center,
+ Right,
+ Justify,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct Text {
+ pub runs: Vec,
+ pub align: Align,
+ /// Artistic text: the first baseline's anchor point in node space (start, centre or end of the
+ /// line according to `align`). Frame text: the frame box in node space.
+ pub anchor: Point,
+ pub frame: Option,
+ /// Node space to document pixels.
+ pub transform: Affine,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum Pixels {
+ /// Straight-alpha RGBA, 8 bits per channel, row by row.
+ Rgba8(Vec),
+ /// The original file a placed image was made from (PNG, JPEG…), as embedded.
+ Encoded(Vec),
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct Image {
+ pub width: u32,
+ pub height: u32,
+ pub pixels: Pixels,
+ /// Pixel space (0..w, 0..h) to document pixels.
+ pub transform: Affine,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum Kind {
+ /// Layer container (`Scop`).
+ Layer,
+ Group,
+ /// Artboard: a rectangle that clips its children; `background` paints behind them.
+ Artboard {
+ rect: Rect,
+ background: Vec,
+ },
+ /// Curve, parametric shape or compound shape: an outline with its fills and strokes.
+ /// Children of a shape are clipped by its outline (painted over its fills, under its strokes).
+ Shape {
+ path: Path,
+ fills: Vec,
+ strokes: Vec,
+ even_odd: bool,
+ },
+ Text(Text),
+ Image(Image),
+ /// Something this reader does not import; its children are still imported.
+ Unsupported,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct Node {
+ pub class: Tag,
+ pub name: String,
+ pub visible: bool,
+ pub locked: bool,
+ pub opacity: f64,
+ pub blend: Blend,
+ pub kind: Kind,
+ /// Vector mask in document pixels: the node shows only inside it (nonzero fill).
+ pub mask: Option,
+ /// Pixel mask: grey levels (white shows the node, black hides it); outside it the node is hidden.
+ pub pixel_mask: Option,
+ /// Bottom to top.
+ pub children: Vec,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct Spread {
+ /// Spread bounds in document pixels (the canvas, or the union of the artboards).
+ pub bounds: Rect,
+ /// Pages of a Publisher-style spread (one, or two facing pages), in document pixels.
+ pub pages: Vec,
+ /// Transparent background; otherwise the page is white.
+ pub transparent: bool,
+ /// Bottom to top.
+ pub nodes: Vec,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct Document {
+ /// Pixels per inch: all geometry is in document pixels at this resolution.
+ pub dpi: f64,
+ pub spreads: Vec,
+ /// Application that last saved the file, as stored (`Affinity 3.0.2`), when present.
+ pub saved_by: Option,
+ /// Content that was not imported or was approximated, one line per kind, deduplicated.
+ pub warnings: Vec,
+}
+
+/// Deepest layer nesting followed; deeper content is reported, not imported.
+const MAX_TREE_DEPTH: usize = 128;
+/// Total layer nodes imported.
+const MAX_NODES: usize = 500_000;
+
+/// Read a document: archive, `doc.dat` and the model.
+pub fn read(bytes: &[u8], limits: Limits) -> Result {
+ let mut archive = Archive::open(bytes, limits)?;
+ let doc = archive.read("doc.dat")?;
+ let s = stream::parse(&doc)?;
+ Reader::new(&s, &mut archive).document()
+}
+
+pub(crate) struct Reader<'s, 'a, 'b> {
+ pub(crate) s: &'s Stream,
+ pub(crate) archive: &'b mut Archive<'a>,
+ pub(crate) dpi: f64,
+ warnings: BTreeMap,
+ nodes: usize,
+ active: HashSet,
+}
+
+impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
+ fn new(s: &'s Stream, archive: &'b mut Archive<'a>) -> Self {
+ Self { s, archive, dpi: 72.0, warnings: BTreeMap::new(), nodes: 0, active: HashSet::new() }
+ }
+
+ pub(crate) fn warn(&mut self, what: impl Into) {
+ *self.warnings.entry(what.into()).or_default() += 1;
+ }
+
+ fn document(mut self) -> Result {
+ let s = self.s;
+ let root = s.root;
+ self.dpi = s.obj(root, b"UVCn").and_then(|u| s.f64(u, b"UPPI")).filter(|d| *d > 0.0 && *d < 100_000.0).unwrap_or(72.0);
+ let saved_by = s.obj(root, b"NVer").map(|v| {
+ let product = s.str(v, b"Prod").unwrap_or("Affinity");
+ match (s.int(v, b"Majr"), s.int(v, b"Minr"), s.int(v, b"Bild")) {
+ (Some(a), Some(b), Some(c)) => format!("{product} {a}.{b}.{c}"),
+ _ => product.to_string(),
+ }
+ });
+ let doc = s.obj(root, b"DocR").ok_or(Error::Malformed("document has no root node"))?;
+ let mut spreads = Vec::new();
+ for spread in s.objs(doc, b"Chld") {
+ if !s.is(spread, b"Sprd") {
+ self.warn("an unknown kind of page");
+ continue;
+ }
+ let pages = pages(s, spread);
+ let default_size = s.floats::<2>(doc, b"DfSz").filter(|[w, h]| *w > 0.0 && *h > 0.0).map(|[w, h]| Rect { x0: 0.0, y0: 0.0, x1: w, y1: h });
+ let bounds = s.floats::<4>(spread, b"SprB").map(rect).or_else(|| pages.iter().copied().reduce(union)).or(default_size).unwrap_or(Rect {
+ x0: 0.0,
+ y0: 0.0,
+ x1: 0.0,
+ y1: 0.0,
+ });
+ let transparent = s.bool(spread, b"SprT").unwrap_or(false);
+ let (nodes, mask) = self.children(spread, Affine::IDENTITY, 0)?;
+ if mask.is_some() {
+ self.warn("mask layers directly on a page (imported without them)");
+ }
+ spreads.push(Spread { bounds, pages, transparent, nodes });
+ }
+ if spreads.is_empty() {
+ return Err(Error::Malformed("document has no pages"));
+ }
+ if !s.objs(doc, b"MpCh").is_empty() {
+ self.warn("master pages (their content is not placed on the pages that use them)");
+ }
+ let warnings = self.warnings.into_iter().map(|(w, n)| if n > 1 { format!("{w} ({n}×)") } else { w }).collect();
+ Ok(Document { dpi: self.dpi, spreads, saved_by, warnings })
+ }
+
+ /// The children of `parent`, and the pixel mask a mask layer among them puts on the parent.
+ fn children(&mut self, parent: ObjId, world: Affine, depth: usize) -> Result<(Vec, Option), Error> {
+ let s = self.s;
+ let mut out = Vec::new();
+ let mut mask = None;
+ for c in s.objs(parent, b"Chld") {
+ if s.is(c, b"MRst") {
+ // A mask layer inside a group or layer masks that container.
+ if s.bool(c, b"Visi") == Some(false) {
+ continue;
+ }
+ let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
+ match crate::raster::mask(self, c, local.then(world))? {
+ Some(m) if mask.is_none() => mask = Some(m),
+ Some(_) => self.warn("several pixel masks on one layer (only the first is used)"),
+ None => {}
+ }
+ continue;
+ }
+ if let Some(n) = self.node(c, world, depth + 1)? {
+ out.push(n);
+ }
+ }
+ Ok((out, mask))
+ }
+
+ fn node(&mut self, id: ObjId, parent: Affine, depth: usize) -> Result