diff --git a/Cargo.lock b/Cargo.lock index 065f9ab844..be105ba510 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1417,6 +1417,17 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-affinity" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=09dcbc225b95232998498a40ca56e24716571d53#09dcbc225b95232998498a40ca56e24716571d53" +dependencies = [ + "crc32fast", + "flate2", + "image", + "ruzstd", +] + [[package]] name = "craft-ai-agents" version = "0.1.0" @@ -3674,6 +3685,7 @@ dependencies = [ "byteorder-lite", "color_quant", "gif", + "image-webp", "moxcms", "num-traits", "png 0.18.1", @@ -5605,16 +5617,6 @@ dependencies = [ "zbus", ] -[[package]] -name = "photocraft-affinity" -version = "0.23.1" -dependencies = [ - "crc32fast", - "flate2", - "proptest", - "ruzstd", -] - [[package]] name = "photocraft-algo" version = "0.23.1" @@ -5762,12 +5764,12 @@ dependencies = [ "base64 0.22.1", "blake3", "chrono", + "craft-affinity", "craft-cms", "craft-print", "craft-psd", "exr", "flate2", - "photocraft-affinity", "photocraft-algo", "photocraft-codecs", "photocraft-color", @@ -5855,6 +5857,7 @@ name = "photocraft-io" version = "0.23.1" dependencies = [ "blake3", + "craft-affinity", "craft-cms", "craft-docpath", "craft-kra", @@ -5870,7 +5873,6 @@ dependencies = [ "kurbo 0.13.1", "lopdf", "miniz_oxide 0.9.1", - "photocraft-affinity", "photocraft-algo", "photocraft-codecs", "photocraft-color", diff --git a/Cargo.toml b/Cargo.toml index 28adb71f91..ae0f513b4d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,7 @@ photocraft-ops = { path = "crates/ops" } craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "09dcbc225b95232998498a40ca56e24716571d53" } photocraft-codecs = { path = "crates/codecs" } photocraft-raw = { path = "crates/raw" } -photocraft-affinity = { path = "crates/affinity" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "09dcbc225b95232998498a40ca56e24716571d53" } photocraft-compose = { path = "crates/compose" } photocraft-gpu = { path = "crates/gpu" } photocraft-paint = { path = "crates/paint" } @@ -182,7 +182,7 @@ opt-level = "z" opt-level = "z" [profile.wasm-release.package.photocraft-format] opt-level = "z" -[profile.wasm-release.package.photocraft-affinity] +[profile.wasm-release.package.craft-affinity] opt-level = "z" [profile.wasm-release.package.serde_json] opt-level = "z" diff --git a/book/src/formats/overview.md b/book/src/formats/overview.md index 18c94c2f67..4ae19eded2 100644 --- a/book/src/formats/overview.md +++ b/book/src/formats/overview.md @@ -5,7 +5,7 @@ External bytes enter PhotoCraft through four main paths: - `craft-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. +- `craft-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. diff --git a/crates/affinity/Cargo.toml b/crates/affinity/Cargo.toml deleted file mode 100644 index 49d859c2f8..0000000000 --- a/crates/affinity/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[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.1" - -[dev-dependencies] -proptest = { workspace = true } diff --git a/crates/affinity/README.md b/crates/affinity/README.md deleted file mode 100644 index c82911d939..0000000000 --- a/crates/affinity/README.md +++ /dev/null @@ -1,157 +0,0 @@ -# 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 (legacy `ABEn`, or current `.af` `phrp`/`aprp` properties, including converted curves), with name, solid background, any transform | artboards (nested ones as groups with a vector mask; rotated/curved boards use their bounding rectangle) | -| 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, locked or per corner) and round or straight corners, ellipses, polygons (smooth too), stars, square stars, pies, triangles, trapezoids, clouds, hearts, cogs, rounded and elliptical callouts, arrows, double stars, tears, crescents, diamonds and circular segments | 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, radial and conical 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, unrecognized -parametric shapes (imported as their bounding ellipses), corner types other than round or straight, 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: `craft-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/it/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/it/real_files.rs` - parses them; `photocraft-io`'s `tests/it/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, 1 GiB extracted per import -and 1 GiB of decoded pixels per import by default (`Limits`: extracted bytes and materialized pixels -are separate budgets, since a bitmap's declared size costs memory whatever its tiles hold), 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, 4 levels of spot colours defined through spot colours, 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. - -Compound outlines have a separate active-reference cycle check and a depth cap of 64. Across -the document, geometry expansion admits at most 500 000 combined outline calls and operand-slot -visits (including nulls and non-object values), and four million points created or copied into -compounds. Operand slots are charged before filtering, without first collecting an operand list. -A compound that crosses a limit or contains a cycle is omitted -with a warning as a whole; ordinary shared operands remain valid and keep each occurrence's transform. - -## 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 deleted file mode 100644 index ab0eaa1a49..0000000000 --- a/crates/affinity/fuzz/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -target/ -corpus/ -artifacts/ -coverage/ -Cargo.lock diff --git a/crates/affinity/fuzz/Cargo.toml b/crates/affinity/fuzz/Cargo.toml deleted file mode 100644 index 6c61c87b1f..0000000000 --- a/crates/affinity/fuzz/Cargo.toml +++ /dev/null @@ -1,41 +0,0 @@ -[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 deleted file mode 100644 index 5017719749..0000000000 --- a/crates/affinity/fuzz/fuzz_targets/import_preview.rs +++ /dev/null @@ -1,10 +0,0 @@ -#![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 deleted file mode 100644 index 63858fe717..0000000000 --- a/crates/affinity/fuzz/fuzz_targets/preview.rs +++ /dev/null @@ -1,10 +0,0 @@ -#![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, max_pixel_bytes: 64 << 20 }); -}); diff --git a/crates/affinity/fuzz/fuzz_targets/stream.rs b/crates/affinity/fuzz/fuzz_targets/stream.rs deleted file mode 100644 index 1f3895279f..0000000000 --- a/crates/affinity/fuzz/fuzz_targets/stream.rs +++ /dev/null @@ -1,11 +0,0 @@ -#![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, max_pixel_bytes: 64 << 20 }); -}); diff --git a/crates/affinity/src/access.rs b/crates/affinity/src/access.rs deleted file mode 100644 index a93ec84462..0000000000 --- a/crates/affinity/src/access.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! 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)) - } - - /// The raw slot count of an object's array field (including null slots), for charging - /// traversal work before nulls are filtered out. `None` when the field is not an array. - pub fn array_len(&self, id: ObjId, tag: &[u8; 4]) -> Option { - self.field(id, tag)?.array_len() - } - - /// 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 deleted file mode 100644 index 11e862ffa6..0000000000 --- a/crates/affinity/src/container.rs +++ /dev/null @@ -1,486 +0,0 @@ -//! 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; -/// Distinct ids the allocation tables may name; each costs a map slot even when only deleted. -const MAX_ENTRIES: usize = 1 << 22; -/// Bytes of entry names the allocation tables may name. A name is retained twice (in the entry -/// and as its map key), and tables can point many names at the same bytes. -const MAX_NAME_BYTES: usize = 32 << 20; -/// File and directory records parsed across every allocation table. Each table walks its own -/// records, and tables may start inside one another and share a long suffix, so the per-table -/// counts do not bound the work: a few thousand overlapping tables could reparse one large run -/// of records each. Real files hold a few hundred saves of a few thousand entries. -const MAX_TABLE_RECORDS: usize = 1 << 25; -/// 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, - /// Bytes of decoded pixels one import may hold: every layer's RGBA together, plus the - /// temporary planes the layer being read decodes through. The entry limits bound what is - /// extracted, not what the layers materialized out of it cost (#4960). - pub max_pixel_bytes: usize, -} - -impl Default for Limits { - fn default() -> Self { - // The gigabyte the other importers allow decoded pixels (`io`'s `MAX_PIXEL_BYTES`). - Self { max_entry: 256 << 20, max_total: 1 << 30, max_pixel_bytes: 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 name_bytes = 0usize; - let mut seen = HashSet::new(); - let mut next = header.fat_offset; - let mut tables = 0usize; - let mut records_left = MAX_TABLE_RECORDS; - 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)?; - // Charge the declared records before walking them. - let declared = usize::try_from(files).unwrap_or(usize::MAX).saturating_add(usize::from(dirs)); - records_left = records_left.checked_sub(declared).ok_or(Error::Limit("too many allocation records"))?; - 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(Box::new(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 raw = c.take(len)?; - // Only the first name per id is kept: charge and copy just that one. - if let std::collections::hash_map::Entry::Vacant(slot) = names.entry(id) { - let name = String::from_utf8_lossy(raw).into_owned(); - name_bytes = name_bytes.saturating_add(name.len()); - if name_bytes > MAX_NAME_BYTES { - return Err(Error::Limit("archive entry names too large")); - } - slot.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 { - // Deletion records are five bytes each: cap what distinct ids may retain. - if latest.len() >= MAX_ENTRIES && !latest.contains_key(&id) { - return Err(Error::Limit("too many archive entries")); - } - 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> { - self.claim(name)?.decode() - } - - /// Extract several entries, decoding them on worker threads. The entries are charged one - /// after the other exactly as the same number of [`read`](Self::read) calls would charge - /// them, and the first error in that order is the one returned. - pub(crate) fn read_many(&mut self, names: &[&str]) -> Result>, Error> { - let mut claimed = Vec::with_capacity(names.len()); - let mut refused = None; - for name in names { - match self.claim(name) { - Ok(c) => claimed.push(c), - Err(e) => { - refused = Some(e); - break; - } - } - } - let decoded = decode_all(&claimed).into_iter().collect::, _>>()?; - refused.map_or(Ok(decoded), Err) - } - - /// Check an entry against the limits, count it as extracted and locate its stored bytes. - fn claim(&mut self, name: &str) -> Result, Error> { - let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?; - 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")); - } - // Charge before decoding: a corrupt entry that fails its checksum has already cost the - // decompression, and an importer that recovers must not get it again for free. - self.extracted = total; - 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)?)?; - Ok(Claimed { data, size, compression: e.compression, crc: e.crc }) - } -} - -/// An entry that is charged and located but not yet decoded. -struct Claimed<'a> { - data: &'a [u8], - size: usize, - compression: u8, - crc: u32, -} - -impl Claimed<'_> { - fn decode(&self) -> Result, Error> { - let mut out = match self.compression & 3 { - 1 => inflate(self.data, self.size)?, - 2 => unzstd(self.data, self.size)?, - _ => self.data.to_vec(), - }; - if out.len() != self.size { - return Err(Error::Malformed("archive entry size mismatch")); - } - unpredict(&mut out, self.compression)?; - if crc32fast::hash(&out) != self.crc { - return Err(Error::Malformed("archive entry checksum mismatch")); - } - Ok(out) - } -} - -/// Most threads decoding entries at once; each zstd frame may reserve its declared window. -const MAX_DECODE_THREADS: usize = 8; -/// Fewer entries than this are decoded in place: starting a thread costs more than they do. -const MIN_PARALLEL_ENTRIES: usize = 4; - -/// Decode every entry, in parallel when there are enough of them. The results are in order. -fn decode_all(jobs: &[Claimed<'_>]) -> Vec, Error>> { - static THREADS: std::sync::OnceLock = std::sync::OnceLock::new(); - // The browser build has no threads to start. - let threads = if jobs.len() < MIN_PARALLEL_ENTRIES || cfg!(target_arch = "wasm32") { - 1 - } else { - (*THREADS.get_or_init(|| std::thread::available_parallelism().map_or(1, usize::from).min(MAX_DECODE_THREADS))).min(jobs.len()) - }; - if threads <= 1 { - return jobs.iter().map(Claimed::decode).collect(); - } - let next = std::sync::atomic::AtomicUsize::new(0); - // The workers and this thread take the next undecoded entry until none is left. - let work = || { - let mut done = Vec::new(); - loop { - let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let Some(job) = jobs.get(i) else { break }; - done.push((i, job.decode())); - } - done - }; - let mut slots: Vec, Error>>> = jobs.iter().map(|_| None).collect(); - std::thread::scope(|sc| { - // A thread that cannot be started just leaves its share to the others. - let workers: Vec<_> = (1..threads).filter_map(|_| std::thread::Builder::new().spawn_scoped(sc, work).ok()).collect(); - let mut finished = vec![work()]; - finished.extend(workers.into_iter().map(|w| w.join().unwrap_or_default())); - for (i, result) in finished.into_iter().flatten() { - if let Some(slot) = slots.get_mut(i) { - *slot = Some(result); - } - } - }); - slots.into_iter().map(|r| r.unwrap_or(Err(Error::Malformed("tile decoder stopped")))).collect() -} - -/// 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::bufread::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.as_chunks_mut::<2>().0.iter_mut() { - let v = u16::from_le_bytes(*pair).wrapping_add(prev); - *pair = 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.as_chunks_mut::<4>().0.iter_mut().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 = [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 deleted file mode 100644 index f834e50598..0000000000 --- a/crates/affinity/src/geometry.rs +++ /dev/null @@ -1,310 +0,0 @@ -//! 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; -const MAX_COMPOUND_DEPTH: usize = 64; -const MAX_OUTLINE_VISITS: usize = 500_000; -const MAX_OUTLINE_POINTS: usize = 4_000_000; -/// Curve records decoded across the document. A shared curve is decoded again for each -/// occurrence, and records that only move handles add no points. -const MAX_OUTLINE_RECORDS: usize = 8_000_000; - -/// Geometry is expanded per occurrence, since parametric outlines can depend on their world -/// transform. Bound work across the entire document instead of memoizing by object id alone. -pub(crate) struct Budget { - visits_left: usize, - points_left: usize, - records_left: usize, -} - -impl Default for Budget { - fn default() -> Self { - Self { visits_left: MAX_OUTLINE_VISITS, points_left: MAX_OUTLINE_POINTS, records_left: MAX_OUTLINE_RECORDS } - } -} - -impl Budget { - /// Charge an outline call or a raw compound operand slot before inspecting it. - fn visit(&mut self) -> Result<(), &'static str> { - self.visits_left = self.visits_left.checked_sub(1).ok_or("compound geometry budget exhausted")?; - Ok(()) - } - - /// Charge curve records before they are decoded. - fn records(&mut self, n: usize) -> Result<(), &'static str> { - self.records_left = self.records_left.checked_sub(n).ok_or("curve geometry budget exhausted")?; - Ok(()) - } - - /// Charge both leaf geometry and each copy into a compound before allocating that copy. - fn path(&mut self, path: &Path) -> Result<(), &'static str> { - let points = path.subpaths.iter().fold(0usize, |n, s| n.saturating_add(1).saturating_add(s.segments.len().saturating_mul(3))); - let Some(left) = self.points_left.checked_sub(points) else { - // Do not rebuild an expensive leaf for every subsequent root after exhaustion. - self.visits_left = 0; - return Err("compound geometry budget exhausted"); - }; - self.points_left = left; - Ok(()) - } -} - -/// 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)> { - match outline_inner(r, id, class, world, &mut Vec::new()) { - Ok(path) => path, - Err(reason) => { - r.warn(reason); - None - } - } -} - -fn outline_inner(r: &mut Reader, id: ObjId, class: Tag, world: Affine, active: &mut Vec) -> Result, &'static str> { - r.geometry_budget.visit()?; - if active.contains(&id) { - return Err("cyclic compound shape"); - } - // Independent of the layer-tree limit: Comp operands do not pass through Reader::node. - if active.len() >= MAX_COMPOUND_DEPTH { - return Err("compound depth exceeds 64 levels"); - } - if class != Tag::of(b"Comp") { - let path = leaf_outline(r, id, class, world); - if let Some((path, _)) = &path { - r.geometry_budget.path(path)?; - } - return Ok(path); - } - active.push(id); - let result = compound(r, id, world, active); - active.pop(); - result -} - -fn compound(r: &mut Reader, id: ObjId, world: Affine, active: &mut Vec) -> Result, &'static str> { - let s = r.s; - // One path of all operands' contours, filled even-odd, as before. A safety failure rejects - // the whole outline: a partial add/subtract shape could silently change its meaning. - let mut path = Path::default(); - // Charge every slot before filtering nulls or malformed values. Stream::objs would scan - // and allocate the whole list first, repeating uncharged work for each shared occurrence. - let children = if let Some(Value::Array(children)) = s.field(id, b"Chld") { children.as_slice() } else { &[] }; - for child in children { - r.geometry_budget.visit()?; - let Value::Obj(Some(c)) = child else { continue }; - let c = *c; - let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY); - let Some(class) = s.class(c) else { return Ok(None) }; - 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_inner(r, c, class, local.then(world), active)? { - r.geometry_budget.path(&p)?; - path.subpaths.extend(p.transformed(local).subpaths); - } - } - Ok(Some((path, true))) -} - -fn leaf_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)) - } - _ => { - 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) - } - } -} - -/// `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 = match s.obj(crvs, b"CnrD") { - Some(c) => { - let fields: Vec<&Value> = s.positional(c).collect(); - // The corner arrays are scanned for every occurrence of a shared curve, so charge - // them like records before they are walked. - if let Some(len) = fields.get(1).and_then(|v| v.array_len()) - && let Err(reason) = r.geometry_budget.records(len) - { - r.warn(reason); - return None; - } - corner_radii(fields) - } - None => None, - }; - 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 records = fields.next()?; - let len = records.array_len()?; - seen = seen.checked_add(len)?; - if seen > MAX_NODES { - r.warn("curves with more than four million nodes"); - return None; - } - // Charge the subpath itself as well as its records: an empty subpath adds no records - // or points, but a shared curve full of them is still walked for every occurrence. - if let Err(reason) = r.geometry_budget.records(len.saturating_add(1)) { - r.warn(reason); - return None; - } - let anchors = match records { - Value::Array(a) => anchors(a.iter().map(record)), - Value::Records { size: 18, data } => anchors(data.as_chunks::<18>().0.iter().map(record18)), - // Records of another width are no curve nodes. - _ => anchors(std::iter::repeat_n(None, len)), - }?; - 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 }; - record18(b.as_slice().try_into().ok()?) -} - -/// One 18-byte curve node: f64 x, f64 y, u8 kind, u8 role. -fn record18(b: &[u8; 18]) -> Option<(Point, u8)> { - let x = f64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]); - let y = f64::from_le_bytes([b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]]); - if !x.is_finite() || !y.is_finite() { - return None; - } - Some((Point { x, y }, b[17])) -} - -fn anchors(records: impl ExactSizeIterator>) -> Option> { - let mut out: Vec = Vec::with_capacity(records.len() / 3 + 1); - let mut pending_in = None; - for (i, v) in records.enumerate() { - let (p, role) = 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()) { - // Index each record's maximum radius once. Scanning the whole radius list per anchor - // was O(anchors * radii), which a file with large anchor and radius arrays could drive - // into quadratic work. Duplicate record indices keep the maximum, matching the prior - // fold(0.0, f64::max) behavior. - let mut radius_by_record: std::collections::HashMap = std::collections::HashMap::with_capacity(radii.len()); - for &(rec, r) in radii { - let slot = radius_by_record.entry(rec).or_insert(0.0); - *slot = slot.max(r); - } - let corner = |a: &Anchor| radius_by_record.get(&a.record).copied().unwrap_or(0.0); - 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(), - ) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn curve_records_are_charged_across_the_document() { - let mut b = Budget::default(); - assert!(b.records(MAX_OUTLINE_RECORDS).is_ok()); - assert_eq!(b.records(1), Err("curve geometry budget exhausted")); - } -} diff --git a/crates/affinity/src/lib.rs b/crates/affinity/src/lib.rs deleted file mode 100644 index 9520fa2a26..0000000000 --- a/crates/affinity/src/lib.rs +++ /dev/null @@ -1,51 +0,0 @@ -//! 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 deleted file mode 100644 index 529f118b24..0000000000 --- a/crates/affinity/src/model.rs +++ /dev/null @@ -1,705 +0,0 @@ -//! 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; - -/// Total raw `Chld` slots inspected across the whole traversal, including null slots and slots -/// reached through repeated references to a shared group. The node limit only counts produced -/// nodes, so a shared group holding a large null-filled child array could still be rescanned -/// many times; this bounds that work. Generous relative to MAX_NODES for real documents. -const MAX_CHILD_SLOTS: usize = 8_000_000; -/// Bytes of layer names the model may retain across all occurrences. -const MAX_NAME_BYTES: usize = 64 << 20; -/// Page rectangles the model may retain across all spreads (real books have a few hundred). -const MAX_PAGES: usize = 1 << 18; -/// Bytes of font names the text runs may retain across the document. -const MAX_FONT_NAME_BYTES: usize = 16 << 20; -/// Text work units (block and run slots traversed, bytes of story text retained) across all -/// text nodes of a document; real documents use a tiny fraction. -const MAX_TEXT_WORK: usize = 64 << 20; - -/// 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)?; - // The parsed stream owns copies of everything it needs: do not hold the inflated bytes - // (hundreds of MB for a large vector document) while the model is built. - drop(doc); - Reader::new(&s, &mut archive, limits).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, - child_slots: usize, - name_bytes: usize, - pages: usize, - font_name_bytes: usize, - text_work: usize, - active: HashSet, - pub(crate) geometry_budget: crate::geometry::Budget, - /// Decoded pixels still available ([`Limits::max_pixel_bytes`] less what the layers read so - /// far hold). - pixels_left: usize, -} - -impl<'s, 'a, 'b> Reader<'s, 'a, 'b> { - fn new(s: &'s Stream, archive: &'b mut Archive<'a>, limits: Limits) -> Self { - Self { - s, - archive, - dpi: 72.0, - warnings: BTreeMap::new(), - nodes: 0, - child_slots: 0, - name_bytes: 0, - pages: 0, - font_name_bytes: 0, - text_work: 0, - active: HashSet::new(), - geometry_budget: crate::geometry::Budget::default(), - pixels_left: limits.max_pixel_bytes, - } - } - - /// Admit a layer's decoded pixels before they are allocated (#4960). `rgba` is the layer's - /// output, which stays with the document; `planes` is the working set it decodes through and - /// releases. Every layer read so far is still live while this one decodes, so the peak is all - /// three together. - pub(crate) fn admit_pixels(&mut self, rgba: usize, planes: usize) -> Result<(), Error> { - let peak = rgba.saturating_add(planes); - if peak > self.pixels_left { - return Err(Error::Limit("decoded pixel layers exceed the pixel budget")); - } - self.pixels_left -= rgba; - Ok(()) - } - - 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 = self.pages(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; - // Charge every raw child slot (null slots included) against a document-wide budget - // before filtering. A shared group with a large null-filled Chld array could otherwise - // be rescanned through each reference without the node limit noticing. - self.charge_slots(s.array_len(parent, b"Chld").unwrap_or(0))?; - 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)) - } - - /// Counts raw array slots (null ones included) against [`MAX_CHILD_SLOTS`]. - pub(crate) fn charge_slots(&mut self, n: usize) -> Result<(), Error> { - self.child_slots = self.child_slots.saturating_add(n); - if self.child_slots > MAX_CHILD_SLOTS { - return Err(Error::Limit("too many child slots in the layer tree")); - } - Ok(()) - } - - fn node(&mut self, id: ObjId, parent: Affine, depth: usize) -> Result, Error> { - let s = self.s; - if depth > MAX_TREE_DEPTH { - self.warn("layers nested deeper than 128 levels"); - return Ok(None); - } - self.nodes += 1; - if self.nodes > MAX_NODES { - return Err(Error::Limit("too many layers")); - } - // A node that contains itself (a shared object linked back into its own subtree). - if !self.active.insert(id) { - self.warn("a layer that contains itself"); - return Ok(None); - } - let local = s.floats::<6>(id, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY); - let world = local.then(parent); - let class = s.class(id).unwrap_or(Tag(0)); - // A shared layer's name is copied for every occurrence, so charge the bytes first. - let name = s.str(id, b"Desc").unwrap_or_default(); - self.name_bytes = self.name_bytes.saturating_add(name.len()); - if self.name_bytes > MAX_NAME_BYTES { - return Err(Error::Limit("layer names too large")); - } - let name = name.to_string(); - let visible = s.bool(id, b"Visi").unwrap_or(true); - let locked = s.bool(id, b"Edtb").is_some_and(|e| !e); - let opacity = s.f64(id, b"Opac").map_or(1.0, |o| o.clamp(0.0, 1.0)); - let blend = match s.enumeration(id, b"Blnd") { - None if s.bool(id, b"PasT") != Some(false) && is_container(class) => Blend::PassThrough, - None => Blend::Normal, - Some((i, v)) => Blend::from_enum(i, v).unwrap_or_else(|| { - self.warn("an unknown blend mode (imported as Normal)"); - Blend::Normal - }), - }; - let kind = if !world.is_finite() { - self.warn("a layer with an invalid transform"); - Kind::Unsupported - } else { - self.kind(id, class, world, parent)? - }; - // A compound's children are its operands, already merged into its outline. - let (children, child_mask) = if class == Tag::of(b"Comp") { (Vec::new(), None) } else { self.children(id, world, depth)? }; - let (mask, attached_mask) = self.attached_masks(id, world)?; - let pixel_mask = attached_mask.or(child_mask); - self.active.remove(&id); - self.charge_slots(s.array_len(id, b"FiEf").unwrap_or(0))?; - if s.objs(id, b"FiEf").iter().any(|e| s.bool(*e, b"Enab") != Some(false)) { - self.warn("layer effects (shadows, glows, outlines, bevels…)"); - } - Ok(Some(Node { class, name, visible, locked, opacity, blend, kind, mask, pixel_mask, children })) - } - - fn kind(&mut self, id: ObjId, class: Tag, world: Affine, parent: Affine) -> Result { - let s = self.s; - Ok(match &class.0.to_be_bytes() { - b"Scop" => Kind::Layer, - b"Grup" => Kind::Group, - b"PCrv" | b"ShpN" | b"Comp" | b"SNEN" | b"SNRR" | b"ShRN" => { - // Current .af boards carry artboard properties (aprp) in phrp; older - // documents use ABEn. Converted curve boards keep those properties too. - // Other property classes also use phrp, so the field alone is not a marker. - if s.bool(id, b"ABEn") == Some(true) || s.obj(id, b"phrp").is_some_and(|p| s.is(p, b"aprp")) { - if class != Tag::of(b"ShpN") { - self.warn("a converted artboard outline (imported at its bounding box)"); - } - return Ok(self.artboard(id, world)); - } - let Some((local, even_odd)) = crate::geometry::outline(self, id, class, world) else { - self.warn(format!("a {} that could not be read", describe(class))); - return Ok(Kind::Unsupported); - }; - let (fills, strokes) = paint::node_paint(self, id, world); - Kind::Shape { path: local.transformed(world), fills, strokes, even_odd } - } - b"TxtA" | b"TxtF" | b"TxtC" => match crate::text::read(self, id, world) { - Some(t) => Kind::Text(t), - None => { - self.warn("text whose story could not be read (master-page text, or an unknown layout)"); - Kind::Unsupported - } - }, - b"ImgN" | b"Rstr" => match crate::raster::node_image(self, id, world)? { - Some(img) => Kind::Image(img), - None => Kind::Unsupported, - }, - b"EmbN" => match crate::raster::embedded(self, id, world)? { - Some(img) => { - self.warn("embedded documents and symbols (imported as pictures of them)"); - Kind::Image(img) - } - None => { - self.warn("embedded documents and symbols without a cached picture"); - Kind::Unsupported - } - }, - b"FRst" => { - // A fill layer paints its whole bitmap area; its gradient lives in page space. - let b = s.obj(id, b"Bitm"); - let size = |t: &[u8; 4]| b.and_then(|b| s.int(b, t)).map(|v| v as f64).filter(|v| *v > 0.0); - match (size(b"BmpW"), size(b"BmpH")) { - (Some(w), Some(h)) => { - let local = Path { subpaths: vec![crate::shapes::rectangle(0.0, 0.0, w, h)] }; - let fills = paint::fills(self, id, parent, b"BFFl"); - Kind::Shape { path: local.transformed(world), fills, strokes: Vec::new(), even_odd: false } - } - _ => { - self.warn("fill layers without an area"); - Kind::Unsupported - } - } - } - _ => { - self.warn(format!("{} layers", describe(class))); - Kind::Unsupported - } - }) - } - - /// Vector shapes attached to a node (`AdCh`) mask it: it shows only inside their outlines; - /// an attached mask layer is a pixel mask. Adjustments attached the same way are reported. - fn attached_masks(&mut self, id: ObjId, world: Affine) -> Result<(Option, Option), Error> { - let s = self.s; - // Every occurrence of a shared layer scans its whole attachment array, null slots included. - self.charge_slots(s.array_len(id, b"AdCh").unwrap_or(0))?; - let attached = s.objs(id, b"AdCh"); - let mut mask: Option = None; - let mut pixels: Option = None; - for a in attached { - let class = s.class(a).unwrap_or(Tag(0)); - if s.bool(a, b"Visi") == Some(false) { - continue; - } - if class == Tag::of(b"PCrv") || class == Tag::of(b"ShpN") || class == Tag::of(b"Comp") { - let local = s.floats::<6>(a, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY).then(world); - if let Some((p, _)) = crate::geometry::outline(self, a, class, local) { - mask.get_or_insert_with(Path::default).subpaths.extend(p.transformed(local).subpaths); - } - } else if class == Tag::of(b"MRst") { - let local = s.floats::<6>(a, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY).then(world); - match crate::raster::mask(self, a, local)? { - Some(m) if pixels.is_none() => pixels = Some(m), - Some(_) => self.warn("several pixel masks on one layer (only the first is used)"), - None => {} - } - } else { - self.warn(format!("{} layers attached to other layers (imported without them)", describe(class))); - } - } - Ok((mask, pixels)) - } - - fn artboard(&mut self, id: ObjId, world: Affine) -> Kind { - let s = self.s; - let b = s.floats::<4>(id, b"ShpB").map(rect).unwrap_or(Rect { x0: 0.0, y0: 0.0, x1: 0.0, y1: 0.0 }); - let corners = [Point { x: b.x0, y: b.y0 }, Point { x: b.x1, y: b.y0 }, Point { x: b.x1, y: b.y1 }, Point { x: b.x0, y: b.y1 }].map(|p| world.apply(p)); - let [a, b2, c, d, ..] = world.0; - if b2.abs() > 1e-9 || c.abs() > 1e-9 || a <= 0.0 || d <= 0.0 { - self.warn("a rotated or flipped artboard (imported at its bounding box)"); - } - let xs = corners.map(|p| p.x); - let ys = corners.map(|p| p.y); - let rect = Rect { - x0: xs.iter().copied().fold(f64::INFINITY, f64::min), - y0: ys.iter().copied().fold(f64::INFINITY, f64::min), - x1: xs.iter().copied().fold(f64::NEG_INFINITY, f64::max), - y1: ys.iter().copied().fold(f64::NEG_INFINITY, f64::max), - }; - let background = paint::fills(self, id, world, b"BFFl"); - Kind::Artboard { rect, background } - } -} - -impl Reader<'_, '_, '_> { - /// Page rectangles: `SpMd.PagR[].rctp` (Publisher 2, Affinity 3) or `SprB` split into `PagC` - /// equal pages (Publisher 1 facing spreads). A spread listed several times, or sharing one - /// large page array, is expanded into a new vector each time, so the slots scanned and the - /// rectangles retained are charged across the document. - fn pages(&mut self, spread: ObjId) -> Result, Error> { - let s = self.s; - if let Some(md) = s.obj(spread, b"SpMd") { - self.charge_slots(s.array_len(md, b"PagR").unwrap_or(0))?; - let remaining = MAX_PAGES.saturating_sub(self.pages); - let v: Vec = s - .objs(md, b"PagR") - .into_iter() - .filter_map(|p| s.floats::<4>(p, b"rctp").map(rect)) - .filter(|r| r.x1 > r.x0 && r.y1 > r.y0) - .take(remaining.saturating_add(1)) - .collect(); - if !v.is_empty() { - self.charge_pages(v.len())?; - return Ok(v); - } - } - Ok(match (s.floats::<4>(spread, b"SprB").map(rect), s.int(spread, b"PagC")) { - (Some(b), Some(n @ 2..=16)) => { - self.charge_pages(n as usize)?; - let w = (b.x1 - b.x0) / n as f64; - (0..n).map(|i| Rect { x0: b.x0 + w * i as f64, x1: b.x0 + w * (i + 1) as f64, ..b }).collect() - } - _ => Vec::new(), - }) - } - - /// Counts retained font-name bytes against [`MAX_FONT_NAME_BYTES`]; false once it is spent. - pub(crate) fn charge_font_name(&mut self, n: usize) -> bool { - self.font_name_bytes = self.font_name_bytes.saturating_add(n); - self.font_name_bytes <= MAX_FONT_NAME_BYTES - } - - /// Counts text traversal work and retained text bytes against [`MAX_TEXT_WORK`]; false once it is spent. - pub(crate) fn charge_text(&mut self, n: usize) -> bool { - self.text_work = self.text_work.saturating_add(n); - self.text_work <= MAX_TEXT_WORK - } - - /// Counts retained page rectangles against [`MAX_PAGES`]. - fn charge_pages(&mut self, n: usize) -> Result<(), Error> { - self.pages = self.pages.saturating_add(n); - if self.pages > MAX_PAGES { - return Err(Error::Limit("too many pages")); - } - Ok(()) - } -} - -pub(crate) fn union(a: Rect, b: Rect) -> Rect { - Rect { x0: a.x0.min(b.x0), y0: a.y0.min(b.y0), x1: a.x1.max(b.x1), y1: a.y1.max(b.y1) } -} - -fn is_container(class: Tag) -> bool { - class == Tag::of(b"Scop") || class == Tag::of(b"Grup") -} - -pub(crate) fn rect(v: [f64; 4]) -> Rect { - Rect { x0: v[0], y0: v[1], x1: v[2], y1: v[3] } -} - -/// A readable name for a layer class in warnings. -pub(crate) fn describe(class: Tag) -> &'static str { - match &class.0.to_be_bytes() { - b"PCrv" => "curve", - b"ShpN" | b"SNEN" | b"SNRR" | b"ShRN" => "shape", - b"Comp" => "compound", - b"Rstr" => "pixel", - b"ImgN" => "image", - b"EmbN" => "embedded document", - b"MPIN" => "master page instance", - b"FRst" => "fill", - b"MRst" => "mask", - b"Slic" | b"SlcP" => "slice", - b"3DLA" => "3D", - [_, _, b'R', b'A'] => "adjustment", - _ => "unknown", - } -} diff --git a/crates/affinity/src/paint.rs b/crates/affinity/src/paint.rs deleted file mode 100644 index 2f1fb86e2d..0000000000 --- a/crates/affinity/src/paint.rs +++ /dev/null @@ -1,417 +0,0 @@ -//! Fills, strokes and colours. Two schemas exist: Affinity 1 (`BFil` fill, `PFil` stroke paint, -//! `LSty` stroke style) and Affinity 2/3 (`BFFl`, `LIFl` and `LILn` lists with a current index). - -use crate::model::{Affine, Reader}; -use crate::stream::{ObjId, Value}; - -/// A colour as stored: RGB and grey values are encoded in the document's RGB space (sRGB unless -/// the document embeds another profile), CMYK values go through its CMYK profile. Alpha is straight. -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum Color { - Rgb { - r: f64, - g: f64, - b: f64, - a: f64, - }, - Cmyk { - c: f64, - m: f64, - y: f64, - k: f64, - a: f64, - }, - Gray { - v: f64, - a: f64, - }, - /// CIE L*a*b* (D50). - Lab { - l: f64, - a: f64, - b: f64, - alpha: f64, - }, -} - -impl Color { - pub fn alpha(&self) -> f64 { - match self { - Color::Rgb { a, .. } | Color::Cmyk { a, .. } | Color::Gray { a, .. } => *a, - Color::Lab { alpha, .. } => *alpha, - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum GradientKind { - Linear, - /// Elliptical and radial: distance from the centre in unit space. - Radial, - /// Angle around the centre. - Conical, -} - -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Stop { - pub offset: f64, - pub color: Color, - /// Affinity's midpoint bias for the segment from this stop to the next (0.5 = even blend). - pub bias: f64, -} - -impl Stop { - /// Where, between this stop (0) and the next (1), the blend reaches half way: the bias curve - /// fitted to Affinity's renders is `t^k` (bias ≥ 0.5) or `1-(1-t)^k`, with `k = 1 + 8·|bias-0.5|`. - pub fn half_point(&self) -> f64 { - let k = 1.0 + 8.0 * (self.bias - 0.5).abs(); - let h = 0.5f64.powf(1.0 / k); - if self.bias >= 0.5 { h } else { 1.0 - h } - } -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Gradient { - pub kind: GradientKind, - pub stops: Vec, - /// Unit space to document pixels: linear runs from unit (0,0) to (1,0); radial is the unit - /// circle; conical starts along unit +x and turns towards unit +y. - pub transform: Affine, -} - -#[derive(Debug, Clone, PartialEq, Default)] -pub enum Paint { - #[default] - None, - Solid(Color), - Gradient(Gradient), -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Cap { - Butt, - Round, - Square, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Join { - Miter, - Round, - Bevel, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Align { - Center, - Inside, - Outside, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Stroke { - pub paint: Paint, - /// Width in document pixels. - pub width: f64, - pub cap: Cap, - pub join: Join, - pub miter_limit: f64, - pub align: Align, - /// Dash and gap lengths in document pixels, and the phase. - pub dash: Option<(Vec, f64)>, - /// Painted below the fill instead of above it. - pub behind: bool, -} - -/// Gradient stops per gradient. -const MAX_STOPS: usize = 1024; -/// Dash and gap lengths per stroke. Affinity's editor offers three dash/gap pairs; a longer -/// pattern would be copied into every shape that shares its style. -const MAX_DASHES: usize = 64; - -/// The first `n` components of a float vector or packed `f32` record. Colours and gradient -/// positions use a few leading components; a shared colour with a huge record is decoded for -/// every occurrence, so the rest is neither converted nor copied. -fn floats(v: &Value, n: usize) -> Option> { - match v { - Value::Floats(f) => Some(f.iter().take(n).copied().collect()), - Value::Bytes(b) if b.len() % 4 == 0 => Some(f32_samples(b, n)), - _ => None, - } -} - -/// Up to `n` little-endian `f32` samples widened to `f64`. -fn f32_samples(b: &[u8], n: usize) -> Vec { - b.as_chunks::<4>().0.iter().take(n).map(|c| f64::from(f32::from_le_bytes(*c))).collect() -} - -/// Spot colours defined through spot colours. A spot colour (`Pant`) is read through its RGB -/// equivalent, else its base colour, which in real files hold plain colours. Colours are shared -/// objects, so one can link to itself, and with both links followed at every level a colour read -/// costs up to 2^(depth+1) lookups. -const MAX_SPOT_DEPTH: usize = 4; - -/// A colour object (`RGBA`, `HSLA`, `CMYK`, `GRAY`, `LABA`, `Pant`). -pub(crate) fn color(r: &mut Reader, id: ObjId) -> Option { - color_at(r, id, 0) -} - -/// [`color`] of an object `depth` spot colours down. -fn color_at(r: &mut Reader, id: ObjId, depth: usize) -> Option { - let s = r.s; - let class = s.class(id)?; - // `n` is how many components the model reads; only those are decoded and checked. - let col = |n: usize| -> Option> { - let v = floats(s.field(id, b"_col")?, n)?; - v.iter().all(|f| f.is_finite()).then_some(v) - }; - Some(match &class.0.to_be_bytes() { - b"RGBA" => { - let v = col(4)?; - Color::Rgb { r: *v.first()?, g: *v.get(1)?, b: *v.get(2)?, a: v.get(3)?.clamp(0.0, 1.0) } - } - b"HSLA" => { - let v = col(4)?; - let (r2, g, b) = hsl(*v.first()?, *v.get(1)?, *v.get(2)?); - Color::Rgb { r: r2, g, b, a: v.get(3)?.clamp(0.0, 1.0) } - } - b"CMYK" => { - let v = col(5)?; - Color::Cmyk { c: *v.first()?, m: *v.get(1)?, y: *v.get(2)?, k: *v.get(3)?, a: v.get(4)?.clamp(0.0, 1.0) } - } - b"GRAY" => { - let v = col(2)?; - Color::Gray { v: *v.first()?, a: v.get(1)?.clamp(0.0, 1.0) } - } - b"LABA" => { - let b = s.bytes(id, b"_col")?; - let u = |i: usize| -> Option { Some(f64::from(u16::from_le_bytes([*b.get(2 * i)?, *b.get(2 * i + 1)?])) / 65535.0) }; - Color::Lab { l: 100.0 * u(0)?, a: 255.0 * u(1)? - 128.0, b: 255.0 * u(2)? - 128.0, alpha: u(3)? } - } - b"Pant" => { - if depth >= MAX_SPOT_DEPTH { - r.warn("spot colours nested deeper than 4 levels (left empty)"); - return None; - } - r.warn("spot colours (imported as their RGB equivalent)"); - return s.obj(id, b"srgb").and_then(|c| color_at(r, c, depth + 1)).or_else(|| s.obj(id, b"base").and_then(|c| color_at(r, c, depth + 1))); - } - b"RegC" => Color::Cmyk { c: 1.0, m: 1.0, y: 1.0, k: 1.0, a: 1.0 }, - _ => { - r.warn("colours in an unknown model"); - return None; - } - }) -} - -fn hsl(h: f64, s: f64, l: f64) -> (f64, f64, f64) { - let c = (1.0 - (2.0 * l - 1.0).abs()) * s; - let hp = (h.rem_euclid(1.0)) * 6.0; - let x = c * (1.0 - (hp % 2.0 - 1.0).abs()); - let (r, g, b) = match hp as u32 { - 0 => (c, x, 0.0), - 1 => (x, c, 0.0), - 2 => (0.0, c, x), - 3 => (0.0, x, c), - 4 => (x, 0.0, c), - _ => (c, 0.0, x), - }; - let m = l - c / 2.0; - (r + m, g + m, b + m) -} - -/// A fill descriptor (`FDsc`) or, in Affinity 1 files, a bare `FilS`; `local` maps the node's -/// space to document pixels. -pub(crate) fn descriptor(r: &mut Reader, id: ObjId, local: Affine) -> Option { - let s = r.s; - let (fill, unit) = if s.is(id, b"FDsc") { - let unit = s.floats::<6>(id, b"FDeX").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY); - (s.obj(id, b"FDeF")?, unit) - } else { - (id, Affine::IDENTITY) - }; - match &s.class(fill)?.0.to_be_bytes() { - b"FilN" => Some(Paint::None), - b"FilS" => Some(Paint::Solid(color(r, s.obj(fill, b"Colr")?)?)), - b"FilG" => { - let kind = match s.enumeration(fill, b"Type").map(|(i, _)| i) { - Some(0) | None => GradientKind::Linear, - Some(1 | 2) => GradientKind::Radial, - Some(3) => GradientKind::Conical, - Some(_) => { - r.warn("gradients of an unknown kind (imported as linear)"); - GradientKind::Linear - } - }; - let grad = s.obj(fill, b"Grad")?; - // A shared gradient is decoded again for every occurrence: charge the arrays scanned - // and copy only as many positions as there are stops to keep. - if r.charge_slots(s.array_len(grad, b"Cols").unwrap_or(0).saturating_add(s.array_len(grad, b"Posn").unwrap_or(0))).is_err() { - r.warn("gradients beyond the document work budget (left empty)"); - return Some(Paint::None); - } - let cols = s.objs(grad, b"Cols"); - let posn: Vec> = match s.field(grad, b"Posn") { - // A position is (offset, bias): later components are not decoded. - Some(Value::Array(a)) => a.iter().filter_map(|v| floats(v, 2)).take(MAX_STOPS).collect(), - Some(Value::Records { size, data }) if *size % 4 == 0 && *size > 0 => { - data.chunks_exact(usize::from(*size)).map(|b| f32_samples(b, 2)).take(MAX_STOPS).collect() - } - _ => Vec::new(), - }; - let mut stops = Vec::new(); - for (c, p) in cols.iter().zip(&posn).take(MAX_STOPS) { - let color = color(r, *c)?; - let offset = p.first().copied().filter(|v| v.is_finite()).unwrap_or(0.0).clamp(0.0, 1.0); - let bias = p.get(1).copied().filter(|v| v.is_finite()).unwrap_or(0.5).clamp(0.0, 1.0); - stops.push(Stop { offset, color, bias }); - } - if stops.is_empty() { - return Some(Paint::None); - } - Some(Paint::Gradient(Gradient { kind, stops, transform: unit.then(local) })) - } - b"FilB" => { - r.warn("bitmap and pattern fills (left empty)"); - Some(Paint::None) - } - _ => { - r.warn("fills of an unknown kind (left empty)"); - Some(Paint::None) - } - } -} - -/// The active entry of a paint list (the `index`-th object, else the first) and how many -/// objects the list holds. Every raw slot, null ones included, is charged before the list is -/// walked: a shared layer's lists are read again for each occurrence. A list beyond the -/// document's work budget reads as empty. -fn current(r: &mut Reader, id: ObjId, list: &[u8; 4], index: &[u8; 4]) -> (Option, usize) { - let s = r.s; - let Some(Value::Array(items)) = s.field(id, list) else { return (None, 0) }; - if r.charge_slots(items.len()).is_err() { - r.warn("fill and stroke lists beyond the document work budget (left empty)"); - return (None, 0); - } - let want = s.int(id, index).and_then(|i| usize::try_from(i).ok()).unwrap_or(0); - let (mut first, mut chosen, mut count) = (None, None, 0usize); - for o in items.iter().filter_map(|v| if let Value::Obj(Some(o)) = v { Some(*o) } else { None }) { - first = first.or(Some(o)); - if count == want { - chosen = Some(o); - } - count += 1; - } - (chosen.or(first), count) -} - -/// The fills of `list` (artboard backgrounds use `BFFl`). -pub(crate) fn fills(r: &mut Reader, id: ObjId, local: Affine, list: &[u8; 4]) -> Vec { - fills_counted(r, id, local, list).0 -} - -/// [`fills`], and how many entries `list` holds. -fn fills_counted(r: &mut Reader, id: ObjId, local: Affine, list: &[u8; 4]) -> (Vec, usize) { - let (d, count) = current(r, id, list, b"BFCr"); - let d = d.or_else(|| r.s.obj(id, b"BFil")); - (d.and_then(|d| descriptor(r, d, local)).filter(|p| *p != Paint::None).into_iter().collect(), count) -} - -/// A node's fill and stroke. `local` maps the node's space to document pixels. -pub(crate) fn node_paint(r: &mut Reader, id: ObjId, local: Affine) -> (Vec, Vec) { - let s = r.s; - let (fills, fill_count) = fills_counted(r, id, local, b"BFFl"); - let (pen, style, pen_count) = if s.field(id, b"LIFl").is_some() { - let (pen, pens) = current(r, id, b"LIFl", b"LICr"); - (pen, current(r, id, b"LILn", b"LICr").0, pens) - } else { - (s.obj(id, b"PFil"), s.obj(id, b"LSty"), 0) - }; - if fill_count > 1 || pen_count > 1 { - r.warn("several fills or strokes on one object (only the active one is imported)"); - } - if s.f64(id, b"FOpc").is_some_and(|o| o < 0.999) { - r.warn("fill opacity (imported at full fill opacity)"); - } - if s.obj(id, b"Trns").is_some() { - r.warn("transparency gradients (imported without them)"); - } - let behind = matches!(s.field(id, b"DrwO"), Some(Value::Array(a)) if a.first() == Some(&Value::Enum { id: 1, version: 0 })); - let stroke = match (pen, style) { - (Some(pen), Some(style)) => stroke(r, pen, style, local, behind), - _ => None, - }; - (fills, stroke.into_iter().collect()) -} - -fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, behind: bool) -> Option { - let s = r.s; - let paint = descriptor(r, pen, local)?; - if paint == Paint::None { - return None; - } - let lsty = if s.is(ldsc, b"LDsc") { s.obj(ldsc, b"LDeL")? } else { ldsc }; - let weight = s.f64(lsty, b"Wght").filter(|w| *w > 0.0 && *w < 1e7)?; - // "Scale with object": the weight follows the object's transform; otherwise it is absolute. - let scales = s.bool(ldsc, b"LDSc").unwrap_or(true); - let width = if scales { weight * local.scale() } else { weight }; - let data = s.bytes(lsty, b"Data").unwrap_or_default(); - let miter_limit = data.get(0..8).and_then(|b| b.try_into().ok()).map(f64::from_le_bytes).filter(|m| m.is_finite() && *m >= 1.0).unwrap_or(4.0); - // Cap and join bytes are only partly understood: (0, 0) is butt/miter in every clean sample; - // (2, 2) ends plain lines square and brush lines round; joins import round, which never - // looks wrong. - let (cap, join) = match (data.get(8).copied(), data.get(9).copied(), data.get(10).copied()) { - (Some(0), Some(0), _) => (Cap::Butt, Join::Miter), - (Some(0), Some(_), _) => (Cap::Butt, Join::Round), - (Some(2), Some(2), Some(3)) => (Cap::Round, Join::Round), - (Some(2), Some(2), _) => (Cap::Square, Join::Round), - _ => (Cap::Round, Join::Round), - }; - let align = match s.int(ldsc, b"LDSa") { - Some(1) => Align::Inside, - Some(2) => Align::Outside, - _ => Align::Center, - }; - let dash = match s.field(lsty, b"Patn") { - // Each occurrence of a shared style keeps its own scaled copy: refuse long patterns - // before scanning or copying them. - Some(Value::Array(a)) if a.len() > MAX_DASHES => { - r.warn("dash patterns longer than 64 entries (imported as solid strokes)"); - None - } - // The copies are retained across the document: charge them like other shared slots. - Some(Value::Array(a)) if r.charge_slots(a.len()).is_err() => { - r.warn("dash patterns beyond the document work budget (imported as solid strokes)"); - None - } - Some(Value::Array(a)) if data.get(10) == Some(&2) || !a.is_empty() => { - let mut v: Vec = a.iter().filter_map(|x| if let Value::Float(f) = x { Some(*f) } else { None }).collect(); - while v.len() >= 2 && v.iter().rev().take(2).all(|x| *x == 0.0) { - v.truncate(v.len() - 2); - } - let valid = !v.is_empty() && v.iter().all(|x| x.is_finite() && *x >= 0.0) && v.iter().any(|x| *x > 0.0); - valid.then(|| (v.iter().map(|x| x * width).collect(), s.f64(lsty, b"Phse").unwrap_or(0.0) * width)) - } - _ => None, - }; - if s.obj(lsty, b"Brus").is_some() || s.obj(ldsc, b"LDeP").is_some() { - r.warn("brush and pressure strokes (imported as plain strokes)"); - } - Some(Stroke { paint, width, cap, join, miter_limit, align, dash, behind }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn only_the_components_a_schema_reads_are_decoded() { - // A 64 KiB record decodes to the four components asked for, not sixteen thousand. - let record = Value::Bytes(1.0f32.to_le_bytes().repeat(16_383)); - assert_eq!(floats(&record, 4), Some(vec![1.0; 4])); - assert_eq!(floats(&Value::Floats(vec![0.5; 6]), 2), Some(vec![0.5; 2])); - // Fewer components than asked for are returned as they are, for the caller to refuse. - assert_eq!(floats(&Value::Floats(vec![0.5; 3]), 5), Some(vec![0.5; 3])); - assert_eq!(floats(&Value::Bytes(vec![0; 3]), 4), None); - } -} diff --git a/crates/affinity/src/preview.rs b/crates/affinity/src/preview.rs deleted file mode 100644 index d3341eeb1c..0000000000 --- a/crates/affinity/src/preview.rs +++ /dev/null @@ -1,124 +0,0 @@ -//! The indexed PNG thumbnail Affinity stores next to the archive: Affinity's own render of the -//! document, at most 512 pixels on the long side in real files, never the document itself. - -use crate::Error; -use crate::container::header; - -pub const MAX_PREVIEW_BYTES: usize = 16 << 20; -pub const MAX_PREVIEW_DIMENSION: u32 = 4096; - -/// 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, -} - -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 le32(bytes: &[u8], offset: usize) -> Result { - let b = bytes_at(bytes, offset, 4)?; - Ok(u32::from_le_bytes(b.try_into().map_err(|_| Error::Malformed("integer"))?)) -} - -fn be32(bytes: &[u8], offset: usize) -> Result { - let b = bytes_at(bytes, offset, 4)?; - Ok(u32::from_be_bytes(b.try_into().map_err(|_| Error::Malformed("PNG integer"))?)) -} - -/// Read only the indexed `Thmb` record (identical in container versions 8 to 12), checking every PNG chunk CRC. Compressed -/// pixels must still be validated by the consuming image decoder, with allocation limits. -pub fn preview(bytes: &[u8]) -> Result, Error> { - let h = header(bytes)?; - if h.thumbnail_offset == 0 { - return Err(Error::Unsupported("no embedded preview")); - } - 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 palette, mut image_data, mut image_data_ended) = (false, false, 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 checksum_input = bytes_at(chunk, 4, chunk_size - 8)?; - if crc32fast::hash(checksum_input) != be32(chunk, chunk_size - 4)? { - return Err(Error::Malformed("PNG chunk checksum")); - } - let kind = bytes_at(chunk, 4, 4)?; - if !kind.iter().all(u8::is_ascii_alphabetic) { - return Err(Error::Malformed("PNG chunk type")); - } - match kind { - b"IHDR" if pos == 8 => {} - b"IHDR" => return Err(Error::Malformed("duplicate PNG header")), - b"PLTE" => { - if palette || image_data { - return Err(Error::Malformed("PNG palette order")); - } - palette = true; - } - b"IDAT" => { - if image_data_ended { - return Err(Error::Malformed("non-contiguous PNG image data")); - } - image_data = true; - } - b"IEND" if !image_data => return Err(Error::Malformed("PNG has no image data")), - b"IEND" => {} - _ if kind.first().is_some_and(u8::is_ascii_uppercase) => { - return Err(Error::Unsupported("unknown critical PNG chunk")); - } - _ => {} - } - if image_data && kind != b"IDAT" { - image_data_ended = true; - } - // Native sample previews are plain, single-frame PNGs. Pixel allocation limits do not - // necessarily bound aggregate compressed metadata; leave these layouts unsupported. - if matches!(kind, b"zTXt" | b"iTXt" | b"iCCP") { - return Err(Error::Unsupported("compressed PNG metadata in the preview")); - } - if matches!(kind, b"acTL" | b"fcTL" | b"fdAT") { - return Err(Error::Unsupported("animated PNG preview")); - } - 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 }) -} diff --git a/crates/affinity/src/raster.rs b/crates/affinity/src/raster.rs deleted file mode 100644 index 3749862891..0000000000 --- a/crates/affinity/src/raster.rs +++ /dev/null @@ -1,351 +0,0 @@ -//! Pixel layers (`Rstr`) and placed images (`ImgN`). A placed image keeps its original file -//! (`DyBm.Bckg` → archive entry `c/N`), which is imported as is; other pixels are planar tiles of -//! 256 bytes × 256 rows per channel, each its own archive entry. - -use std::collections::{HashMap, HashSet}; - -use crate::Error; -use crate::model::{Affine, Image, Pixels, Reader}; -use crate::stream::{self, ObjId, Tag, Value}; - -/// Pixels decoded per layer (the content's bounding box, not the canvas). -const MAX_PIXELS: u64 = 64 << 20; -const TILE: usize = 256; -const TILE_BYTES: usize = TILE * TILE; - -pub(crate) fn node_image(r: &mut Reader, id: ObjId, world: Affine) -> Result, Error> { - let s = r.s; - let Some(bitmap) = s.obj(id, b"Bitm") else { - r.warn("pixel layers without pixels"); - return Ok(None); - }; - if !s.is(bitmap, b"DyBm") { - r.warn("pixel layers stored in an unknown way"); - return Ok(None); - } - let width = s.int(bitmap, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - let height = s.int(bitmap, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - if width == 0 || height == 0 { - return Ok(None); - } - // A placed image: the original file, byte for byte. - let has_tiles = s.field(bitmap, b"Sta1").is_some(); - if let Some(name) = s.entry(bitmap, b"Bckg").filter(|n| !n.is_empty()) - && (s.is(id, b"ImgN") || !has_tiles) - { - match original(r, name) { - Ok(bytes) => return Ok(Some(Image { width, height, pixels: Pixels::Encoded(bytes), transform: world })), - Err(Error::Limit(e)) => return Err(Error::Limit(e)), - Err(_) => r.warn("an embedded image file that could not be read (its cached pixels were used)"), - } - } - // The content's bounding box, so a mostly empty canvas-sized layer stays small. - let crop = s - .field(id, b"BitR") - .and_then(|v| if let Value::Ints(i) = v { Some(i.clone()) } else { None }) - .filter(|v| v.len() == 4 && v[0] > i64::from(i32::MIN) + 1) - .map(|v| { - ( - v[0].clamp(0, i64::from(width)) as u32, - v[1].clamp(0, i64::from(height)) as u32, - v[2].clamp(0, i64::from(width)) as u32, - v[3].clamp(0, i64::from(height)) as u32, - ) - }) - .unwrap_or((0, 0, width, height)); - if s.field(bitmap, b"Bckg").is_some() && has_tiles && !s.is(id, b"ImgN") { - r.warn("edited placed images use their stored pixels"); - } - decode(r, bitmap, crop, world) -} - -/// A mask layer (`MRst`): one channel of coverage as grey pixels (white shows, black hides). -pub(crate) fn mask(r: &mut Reader, id: ObjId, world: Affine) -> Result, Error> { - let s = r.s; - let Some(bitmap) = s.obj(id, b"Bitm") else { return Ok(None) }; - let width = s.int(bitmap, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - let height = s.int(bitmap, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - if width == 0 || height == 0 || !matches!(s.enumeration(bitmap, b"Frmt"), Some((6 | 7, _))) { - r.warn("pixel masks in an unknown format (imported without them)"); - return Ok(None); - } - decode(r, bitmap, (0, 0, width, height), world) -} - -/// An embedded document or symbol instance (`EmbN`), as the picture of it Affinity caches. -pub(crate) fn embedded(r: &mut Reader, id: ObjId, world: Affine) -> Result, Error> { - let s = r.s; - let Some(cache) = s.obj(id, b"Bitm").and_then(|e| s.obj(e, b"Cach")) else { return Ok(None) }; - let Some(bbox) = s.obj(id, b"Bitm").and_then(|e| s.floats::<4>(e, b"ChBB")) else { return Ok(None) }; - let width = s.int(cache, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - let height = s.int(cache, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - if width == 0 || height == 0 { - return Ok(None); - } - let [x0, y0, x1, y1] = bbox; - // The instance's origin is the centre of the embedded content (checked against the - // thumbnails of documents with embedded documents and SVG files). - let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0); - let place = Affine([(x1 - x0) / f64::from(width), 0.0, 0.0, (y1 - y0) / f64::from(height), x0 - cx, y0 - cy]).then(world); - decode(r, cache, (0, 0, width, height), place) -} - -/// Decode the tiles of a bitmap inside `crop` (pixels), placed by `world` (bitmap pixels to document). -fn decode(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affine) -> Result, Error> { - let s = r.s; - let (x0, y0, x1, y1) = crop; - if x1 <= x0 || y1 <= y0 { - return Ok(None); - } - let (w, h) = (x1 - x0, y1 - y0); - if u64::from(w) * u64::from(h) > MAX_PIXELS { - r.warn("pixel layers larger than 64 megapixels"); - return Ok(None); - } - let format = s.enumeration(bitmap, b"Frmt").map(|(f, _)| f); - let (channels, bps) = match format { - Some(0) => (4, 1), - Some(1) => (4, 2), - Some(6) => (1, 1), - Some(7) => (1, 2), - Some(4) => { - r.warn("CMYK pixel layers (converted to RGB without the document's colour profile)"); - (5, 1) - } - _ => { - r.warn("pixel layers in grey, Lab or 32-bit formats"); - return Ok(None); - } - }; - // A layer is materialized from its declared size, whatever the tiles hold: admit the output - // and the planes it decodes through before either is allocated (#4960). - let pixels = (w as usize).checked_mul(h as usize).ok_or(Error::Limit("pixel layer size"))?; - let scratch = pixels.checked_mul(channels * bps).ok_or(Error::Limit("pixel layer size"))?; - r.admit_pixels(pixels.checked_mul(4).ok_or(Error::Limit("pixel layer size"))?, scratch)?; - let mut planes = Vec::with_capacity(channels); - let mut cache = Cache::new(); - for c in 1..=channels { - planes.push(plane(r, bitmap, c, bps, (x0, y0, w, h), &mut cache)?); - } - let rgba = interleave(&planes, channels, bps, pixels); - let transform = Affine([1.0, 0.0, 0.0, 1.0, f64::from(x0), f64::from(y0)]).then(world); - Ok(Some(Image { width: w, height: h, pixels: Pixels::Rgba8(rgba), transform })) -} - -/// Quantize a unit-range sample to a byte: the one conversion every format goes through. -fn quant(v: f64) -> u8 { - (v.clamp(0.0, 1.0) * 255.0).round() as u8 -} - -/// Interleave the decoded planes (`n` samples of `bps` bytes each) into RGBA8. -/// -/// The samples used to be widened to `f64` one pixel at a time. The tables below hold the same -/// expressions evaluated once per input value, so the bytes are identical: an 8-bit sample -/// `x / 255 * 255` rounds back to `x`, a 16-bit one goes through a 64 Ki table, and CMYK's -/// `(1 - c)(1 - k)` through a table over the 256 x 256 `(c, k)` pairs. -pub(crate) fn interleave(planes: &[Vec], channels: usize, bps: usize, n: usize) -> Vec { - let mut rgba = vec![0u8; n * 4]; - let out = rgba.as_chunks_mut::<4>().0.iter_mut(); - let p = |c: usize| planes.get(c).map_or(&[][..], Vec::as_slice); - match (channels, bps) { - (1, 1) => { - for (o, &v) in out.zip(p(0)) { - *o = [v, v, v, 255]; - } - } - (4, 1) => { - let (r, g, b, a) = (p(0), p(1), p(2), p(3)); - for ((((o, &r), &g), &b), &a) in out.zip(r).zip(g).zip(b).zip(a) { - *o = [r, g, b, a]; - } - } - (5, 1) => { - let lut = cmyk_table(); - let (c, m, y, k, a) = (p(0), p(1), p(2), p(3), p(4)); - for (((((o, &c), &m), &y), &k), &a) in out.zip(c).zip(m).zip(y).zip(k).zip(a) { - let k = usize::from(k) << 8; - *o = [lut[k | usize::from(c)], lut[k | usize::from(m)], lut[k | usize::from(y)], a]; - } - } - (_, _) => { - let lut: Vec = (0..=u16::MAX).map(|v| quant(f64::from(v) / 65535.0)).collect(); - let s16 = |c: usize| p(c).as_chunks::<2>().0.iter().map(|b| lut[usize::from(u16::from_le_bytes(*b))]); - if channels == 1 { - for (o, g) in out.zip(s16(0)) { - *o = [g, g, g, 255]; - } - } else { - for ((((o, r), g), b), a) in out.zip(s16(0)).zip(s16(1)).zip(s16(2)).zip(s16(3)) { - *o = [r, g, b, a]; - } - } - } - } - rgba -} - -/// `(1 - c)(1 - k)` quantized, indexed by `k << 8 | c`. -fn cmyk_table() -> Vec { - let mut lut = Vec::with_capacity(256 * 256); - for k in 0..=255u8 { - for c in 0..=255u8 { - lut.push(quant((1.0 - f64::from(c) / 255.0) * (1.0 - f64::from(k) / 255.0))); - } - } - lut -} - -/// The original image file: entry `c/N` is a stream whose root (`Blck`) holds it as `Data`. -fn original(r: &mut Reader, name: &str) -> Result, Error> { - let bytes = r.archive.read(name)?; - let s = stream::parse(&bytes)?; - let root = s.object(s.root).ok_or(Error::Malformed("embedded image"))?; - match root.get(Tag::of(b"Data")) { - Some(Value::Blob(b)) if !b.is_empty() => Ok(b.clone()), - _ => Err(Error::Malformed("embedded image without data")), - } -} - -fn tag(prefix: &[u8; 3], c: usize) -> [u8; 4] { - [prefix[0], prefix[1], prefix[2], b'0' + c as u8] -} - -/// Decoded tiles by archive entry name: a tile shared by several grid cells or channels is -/// extracted (and charged to the archive's budget) once. -type Cache<'s> = HashMap<&'s str, Vec>; - -/// A tile to copy into a plane once its entry is decoded: pixel column and row of its corner. -struct Place<'s> { - name: &'s str, - at: (usize, usize), -} - -/// One channel of level 0, cropped to (x0, y0, w, h) pixels; `bps` bytes per sample. -fn plane<'s>( - r: &mut Reader<'s, '_, '_>, - bitmap: ObjId, - c: usize, - bps: usize, - (x0, y0, w, h): (u32, u32, u32, u32), - cache: &mut Cache<'s>, -) -> Result, Error> { - let s = r.s; - let width = s.int(bitmap, b"BmpW").and_then(|v| usize::try_from(v).ok()).unwrap_or(0); - let height = s.int(bitmap, b"BmpH").and_then(|v| usize::try_from(v).ok()).unwrap_or(0); - let tw = s.int(bitmap, &tag(b"TWi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| (width * bps).div_ceil(TILE)); - let th = s.int(bitmap, &tag(b"THi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| height.div_ceil(TILE)); - // Borrow the file-controlled arrays: collecting the whole state array first costs its full - // length on every occurrence of a shared layer, however small the declared grid is. - let states: &[Value] = match s.field(bitmap, &tag(b"Sta", c)) { - Some(Value::Array(a)) => a, - _ => &[], - }; - // Tile references in order. Null slots are skipped, but every slot walked (null or not) is - // charged below, so a shared bitmap's long null prefix is not rescanned for free. - let mut tiles: &[Value] = match s.field(bitmap, &tag(b"Idx", c)) { - Some(Value::Array(a)) => a, - _ => &[], - }; - // The scan below runs for every occurrence of a shared bitmap, whatever it produces. - r.charge_slots(states.len().min(tw.saturating_mul(th)))?; - let row = (w as usize) * bps; - let mut out = vec![0u8; row * h as usize]; - let (bx0, bx1) = (x0 as usize * bps, (x0 + w) as usize * bps); - let (py0, py1) = (y0 as usize, (y0 + h) as usize); - let crop = (bx0, py0, bx1, py1); - // First walk the grid: flat cells are filled right away (cells never overlap, so the order - // of the copies does not matter) and the tiles that show are collected. They are extracted - // together below, on several threads, then copied. A walk that fails still extracts the - // tiles before the failing cell, as a tile-by-tile walk would have. - let mut places: Vec> = Vec::new(); - let mut wanted: Vec<&'s str> = Vec::new(); - let mut queued: HashSet<&'s str> = HashSet::new(); - let mut failure = None; - for (t, state) in states.iter().enumerate().take(tw.saturating_mul(th)) { - let state = &if let Value::UInt(u) = state { u8::try_from(*u).unwrap_or(255) } else { 255 }; - let (ty, tx) = (t / tw.max(1), t % tw.max(1)); - let fill = match state { - 0 | 1 => None, - 2 => Some(0xFF), - 4 => { - let Some(at) = tiles.iter().position(|v| matches!(v, Value::Obj(Some(_)))) else { - r.charge_slots(tiles.len())?; - failure = Some(Error::Malformed("missing pixel tile")); - break; - }; - r.charge_slots(at + 1)?; - let Some(Value::Obj(Some(blck))) = tiles.get(at) else { - failure = Some(Error::Malformed("missing pixel tile")); - break; - }; - let blck = *blck; - tiles = tiles.get(at + 1..).unwrap_or_default(); - let (ox, oy) = (tx * TILE, ty * TILE); - if ox >= bx1 || ox + TILE <= bx0 || oy >= py1 || oy + TILE <= py0 { - continue; - } - let Some(name) = s.entry(blck, b"Data") else { - failure = Some(Error::Malformed("pixel tile without data")); - break; - }; - if !cache.contains_key(name) && queued.insert(name) { - wanted.push(name); - } - places.push(Place { name, at: (ox, oy) }); - continue; - } - 3 => { - r.warn("32-bit pixel layers"); - None - } - 5 => { - r.warn("pixel layers drawn from an embedded image (left empty)"); - None - } - _ => { - failure = Some(Error::Malformed("unknown pixel tile state")); - break; - } - }; - if let Some(v) = fill { - copy(&mut out, row, crop, (tx * TILE, ty * TILE), None, v); - } - } - let decoded = r.archive.read_many(&wanted); - // A tile that fails to extract is reported before the failure of the walk after it. - for (name, mut data) in wanted.into_iter().zip(decoded?) { - // Older files wrap a tile in a one-field stream: header, then a 64 KiB blob. - if data.len() == TILE_BYTES + 22 && data.starts_with(b"\x00\xffKS") { - data = data.get(21..21 + TILE_BYTES).ok_or(Error::Malformed("pixel tile"))?.to_vec(); - } - if data.len() != TILE_BYTES { - return Err(Error::Malformed("pixel tile size")); - } - cache.insert(name, data); - } - if let Some(e) = failure { - return Err(e); - } - for place in &places { - let tile = cache.get(place.name).ok_or(Error::Malformed("pixel tile"))?; - copy(&mut out, row, crop, place.at, Some(tile), 0); - } - Ok(out) -} - -/// Copy the overlap of a tile at byte column `ox`, row `oy` into the cropped plane. `tile` is -/// the tile's bytes, or `None` to fill the overlap with `fill`. -pub(crate) fn copy(out: &mut [u8], row: usize, (bx0, py0, bx1, py1): (usize, usize, usize, usize), (ox, oy): (usize, usize), tile: Option<&[u8]>, fill: u8) { - let (xa, xb) = (ox.max(bx0), (ox + TILE).min(bx1)); - if xa >= xb { - return; - } - for y in oy.max(py0)..(oy + TILE).min(py1) { - let start = (y - py0) * row + (xa - bx0); - let Some(dst) = out.get_mut(start..start + (xb - xa)) else { continue }; - match tile.and_then(|t| t.get((y - oy) * TILE + (xa - ox)..(y - oy) * TILE + (xb - ox))) { - Some(src) => dst.copy_from_slice(src), - None => dst.fill(if tile.is_some() { 0 } else { fill }), - } - } -} diff --git a/crates/affinity/src/shapes.rs b/crates/affinity/src/shapes.rs deleted file mode 100644 index a79f7eac03..0000000000 --- a/crates/affinity/src/shapes.rs +++ /dev/null @@ -1,484 +0,0 @@ -//! Parametric shapes: Affinity stores the shape's parameters and its box, never the outline. -//! Formulas were fitted to Affinity's own renders (the document thumbnails) of public files. - -use std::f64::consts::{FRAC_PI_2, PI, TAU}; - -use crate::model::{Affine, Path, Point, Reader, SubPath}; -use crate::stream::{ObjId, Tag, Value}; - -/// Handle length of a quarter circle of radius 1. -const KAPPA: f64 = 0.552_284_749_830_793_4; -/// Vertices of a polygon or star. -const MAX_SIDES: i64 = 10_000; - -/// The last value of a tag: a shape changed from one kind to another keeps a stale first block. -/// Indexed: a shared shape is read again for every occurrence, and rescanning a large field -/// list each time multiplied into work far beyond the file's size. -fn last<'a>(r: &'a Reader, id: ObjId, tag: &[u8; 4]) -> Option<&'a Value> { - r.s.object(id)?.get_last(Tag::of(tag)) -} - -fn num(r: &Reader, id: ObjId, tag: &[u8; 4]) -> Option { - match last(r, id, tag)? { - Value::Float(f) if f.is_finite() => Some(*f), - Value::UInt(u) => Some(*u as f64), - Value::Int(i) => Some(*i as f64), - _ => None, - } -} - -fn sides(r: &Reader, id: ObjId, tag: &[u8; 4], default: f64) -> usize { - let n = num(r, id, tag).unwrap_or(default).round(); - n.clamp(3.0, MAX_SIDES as f64) as usize -} - -fn pt(x: f64, y: f64) -> Point { - Point { x, y } -} - -fn polygon(pts: impl IntoIterator) -> Option { - let mut it = pts.into_iter(); - let start = it.next()?; - let segments = it.map(|p| [p, p, p]).collect(); - Some(SubPath { start, segments, closed: true }) -} - -/// Outline of `shape` (a `Shpe` object) in the node box `b` = (x0, y0, x1, y1). -pub(crate) fn shape(r: &mut Reader, shape: ObjId, b: [f64; 4], world: Affine) -> Option<(Path, bool)> { - let [x0, y0, x1, y1] = b; - let (w, h) = (x1 - x0, y1 - y0); - let (cx, cy, rx, ry) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0, w / 2.0, h / 2.0); - let on_ellipse = |a: f64, f: f64| pt(cx + f * rx * a.cos(), cy + f * ry * a.sin()); - let class = r.s.class(shape)?; - let sub = match &class.0.to_be_bytes() { - b"ShNR" | b"ShRR" => { - // Only the four corners are read: a longer array is not scanned or copied, which - // would otherwise repeat for every occurrence of a shared shape. - let types: Vec> = match last(r, shape, b"CTyp") { - Some(Value::Array(a)) => a.iter().take(4).map(|t| if let Value::Enum { id, .. } = t { Some(*id) } else { None }).collect(), - _ => Vec::new(), - }; - let radii: Vec = match last(r, shape, b"ShCR") { - Some(Value::Floats(v)) => v.iter().take(4).map(|f| if f.is_finite() && *f > 0.0 { *f } else { 0.0 }).collect(), - _ => Vec::new(), - }; - // Corners follow the first one (top left) unless they were unlocked; then each has - // its own radius and type, clockwise from the top left. - let locked = !matches!(last(r, shape, b"Lock"), Some(Value::Bool(false))); - let corners: [(f64, Option); 4] = std::array::from_fn(|i| { - let i = if locked { 0 } else { i }; - (radii.get(i).copied().unwrap_or(0.0), types.get(i).copied().flatten()) - }); - if types.is_empty() || corners.iter().all(|(f, _)| *f == 0.0) { - polygon([pt(x0, y0), pt(x1, y0), pt(x1, y1), pt(x0, y1)])? - } else { - if corners.iter().any(|(f, t)| *f > 0.0 && !matches!(t, Some(0 | 1 | 4))) { - r.warn("rectangles with concave or other corner types (imported with round corners)"); - } - let absolute = r.s.bool(shape, b"AbSz") == Some(true); - let [a, b2, c, d, ..] = world.0; - let (sx, sy) = ((a * a + b2 * b2).sqrt(), (c * c + d * d).sqrt()); - cornered_rect( - b, - corners.map(|(f, t)| { - let (crx, cry) = if !absolute { - (f * w.min(h), f * w.min(h)) - } else if sx > 0.0 && sy > 0.0 { - // An absolute radius is in document pixels, whatever the node's scale. - (f / sx, f / sy) - } else { - (0.0, 0.0) - }; - (crx, cry, t == Some(1)) - }), - ) - } - } - b"ShpE" => ellipse(cx, cy, rx, ry), - b"ShPy" => { - let n = sides(r, shape, b"Side", 5.0); - let a = |i: usize| -FRAC_PI_2 + TAU * i as f64 / n as f64; - if r.s.object(shape).is_some_and(|_| matches!(last(r, shape, b"Smth"), Some(Value::Bool(true)))) { - // Smoothed: tangent handles of length curv·4/3·tan(π/2n) along the inscribed ellipse. - let k = num(r, shape, b"Curv").unwrap_or(0.0) * 4.0 / 3.0 * (PI / (2.0 * n as f64)).tan(); - let v = |i: usize| on_ellipse(a(i), 1.0); - let t = |i: usize| pt(-rx * a(i).sin(), ry * a(i).cos()); - let segments = (0..n) - .map(|i| { - let (p, q, tp, tq) = (v(i), v(i + 1), t(i), t(i + 1)); - [pt(p.x + k * tp.x, p.y + k * tp.y), pt(q.x - k * tq.x, q.y - k * tq.y), q] - }) - .collect(); - SubPath { start: v(0), segments, closed: true } - } else { - polygon((0..n).map(|i| on_ellipse(a(i), 1.0)))? - } - } - b"ShSt" => { - let n = sides(r, shape, b"Pnts", 5.0); - let q = num(r, shape, b"IRad").unwrap_or(0.382).clamp(0.0, 1.0); - if [b"CrcI", b"CrcO", b"CrvL", b"CrvR"].iter().any(|t| num(r, shape, t).is_some_and(|v| v.abs() > 1e-9)) { - r.warn("stars with rounded or curved points (imported with sharp points)"); - } - polygon((0..2 * n).map(|i| on_ellipse(-FRAC_PI_2 + PI * i as f64 / n as f64, if i % 2 == 0 { 1.0 } else { q })))? - } - b"ShSS" => { - let n = sides(r, shape, b"Side", 5.0); - let ri = num(r, shape, b"COut").unwrap_or(0.5).clamp(0.0, 1.0); - let step = PI / n as f64; - let (l, hw, inner) = (step.cos(), ri * step.sin(), ri * step.cos()); - polygon((0..n).flat_map(|k| { - let phi = -FRAC_PI_2 + step + TAU * k as f64 / n as f64; - let (c, s) = (phi.cos(), phi.sin()); - [(inner, -hw), (l, -hw), (l, hw), (inner, hw)].map(|(u, v)| pt(cx + rx * (u * c - v * s), cy + ry * (u * s + v * c))) - }))? - } - b"ShPi" => { - let raw_start = num(r, shape, b"AngS").unwrap_or(0.0); - let raw_end = num(r, shape, b"AngE").unwrap_or(TAU); - // Normalize in constant time. Repeatedly adding TAU can hang on finite values - // large enough that floating-point addition no longer changes the endpoint. - let start = raw_start.rem_euclid(TAU); - let delta = raw_end - raw_start; - let sweep = if raw_end >= raw_start { - delta.min(TAU) - } else if delta.is_finite() { - delta.rem_euclid(TAU) - } else { - (raw_end.rem_euclid(TAU) - start).rem_euclid(TAU) - }; - let inner = num(r, shape, b"IRad").unwrap_or(0.0).clamp(0.0, 1.0); - pie(cx, cy, rx, ry, start, start + sweep, inner) - } - b"ShpT" => { - let p = num(r, shape, b"Pos ").unwrap_or(0.5); - polygon([pt(x0 + p * w, y0), pt(x1, y1), pt(x0, y1)])? - } - b"ShTz" => { - let (l, rr) = (num(r, shape, b"PosL").unwrap_or(0.25), num(r, shape, b"PosR").unwrap_or(0.75)); - polygon([pt(x0 + l * w, y0), pt(x0 + rr * w, y0), pt(x1, y1), pt(x0, y1)])? - } - b"ShCl" => cloud(cx, cy, rx, ry, sides(r, shape, b"Bubl", 12.0)), - b"ShHt" => heart(b), - b"ShCg" => cog(r, shape, cx, cy, rx, ry), - b"ShCR" => callout_rect(r, shape, b, false), - b"ShCE" => callout_ellipse(r, shape, cx, cy, rx, ry), - b"ShDA" => arrow(r, shape, b), - b"ShDS" => double_star(r, shape, cx, cy, rx, ry), - b"ShTr" => tear(r, shape, b), - b"ShCr" => crescent(cx, cy, rx, ry), - b"ShpD" => polygon([pt(cx, y0), pt(x1, cy), pt(cx, y1), pt(x0, cy)])?, - b"ShSg" => segment(r, shape, cx, cy, rx, ry), - _ => { - r.warn("an unrecognized parametric shape (imported as its bounding ellipse)"); - ellipse(cx, cy, rx, ry) - } - }; - let mut path = Path { subpaths: vec![sub] }; - if class == Tag::of(b"ShCg") { - let hole = num(r, shape, b"Hole").unwrap_or(0.3).clamp(0.0, 0.9); - if hole > 0.0 { - path.subpaths.push(ellipse(cx, cy, rx * hole, ry * hole)); - } - return Some((path, true)); - } - Some((path, false)) -} - -fn cloud(cx: f64, cy: f64, rx: f64, ry: f64, bubbles: usize) -> SubPath { - let n = bubbles.clamp(3, 128) * 4; - let points: Vec = (0..n) - .map(|i| { - let a = TAU * i as f64 / n as f64 - FRAC_PI_2; - let lobe = (0.5 - 0.5 * (TAU * i as f64 / 4.0).cos()).powi(2); - let radius = 0.78 + 0.22 * lobe; - pt(cx + rx * radius * a.cos(), cy + ry * radius * a.sin()) - }) - .collect(); - let segments = (0..n) - .map(|i| { - let p0 = points[(i + n - 1) % n]; - let p1 = points[i]; - let p2 = points[(i + 1) % n]; - let p3 = points[(i + 2) % n]; - [pt(p1.x + (p2.x - p0.x) / 6.0, p1.y + (p2.y - p0.y) / 6.0), pt(p2.x - (p3.x - p1.x) / 6.0, p2.y - (p3.y - p1.y) / 6.0), p2] - }) - .collect(); - SubPath { start: points[0], segments, closed: true } -} - -fn heart([x0, y0, x1, y1]: [f64; 4]) -> SubPath { - let (w, h) = (x1 - x0, y1 - y0); - let p = |x: f64, y: f64| pt(x0 + x * w, y0 + y * h); - let start = p(0.5, 0.92); - let segments = vec![ - [p(0.38, 0.85), p(0.04, 0.67), p(0.04, 0.37)], - [p(0.04, 0.02), p(0.39, 0.00), p(0.5, 0.27)], - [p(0.61, 0.00), p(0.96, 0.02), p(0.96, 0.37)], - [p(0.96, 0.67), p(0.62, 0.85), start], - ]; - SubPath { start, segments, closed: true } -} - -fn cog(r: &Reader, shape: ObjId, cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath { - let teeth = sides(r, shape, b"Teth", 12.0); - let tooth = num(r, shape, b"TtSz").unwrap_or(0.3).clamp(0.05, 0.9); - let notch = num(r, shape, b"NtSz").unwrap_or(0.45).clamp(0.05, 0.95); - let tip = 1.0; - let root = (1.0 - 0.2 * tooth - 0.08 * notch).clamp(0.55, 0.95); - let mut pts = Vec::with_capacity(teeth * 4); - for i in 0..teeth { - let base = TAU * i as f64 / teeth as f64 - FRAC_PI_2; - for (offset, radius) in [(-0.5, root), (-0.32, tip), (0.32, tip), (0.5, root)] { - let a = base + offset * TAU / teeth as f64; - pts.push(pt(cx + rx * radius * a.cos(), cy + ry * radius * a.sin())); - } - } - polygon(pts).unwrap_or_else(|| rectangle_sub(cx - rx, cy - ry, cx + rx, cy + ry)) -} - -fn callout_rect(r: &Reader, shape: ObjId, [x0, y0, x1, y1]: [f64; 4], _ellipse: bool) -> SubPath { - let (w, h) = (x1 - x0, y1 - y0); - let tail_h = num(r, shape, b"TlHg").unwrap_or(0.2).clamp(0.0, 0.8) * h; - let tail_w = num(r, shape, b"TlWd").unwrap_or(0.1).clamp(0.02, 0.8) * w; - let tip_x = x0 + num(r, shape, b"TlRP").unwrap_or(0.5).clamp(0.0, 1.0) * w; - let base_x = x0 + num(r, shape, b"TlEP").unwrap_or(0.4).clamp(0.0, 1.0) * w; - let a = (base_x - tail_w / 2.0).clamp(x0, x1); - let c = (base_x + tail_w / 2.0).clamp(x0, x1); - let body_bottom = y1 - tail_h; - let radius = (w.min(body_bottom - y0) * 0.12).max(0.0); - // The three contours overlap inside the fill; no internal edge is visible in a filled shape. - // Join the tail to the rounded body in one closed outline to avoid a seam in stroked shapes. - let start = pt(x0 + radius, y0); - let segments = vec![ - [pt(x1 - radius, y0), pt(x1 - radius, y0), pt(x1 - radius, y0)], - [pt(x1 - (1.0 - KAPPA) * radius, y0), pt(x1, y0 + (1.0 - KAPPA) * radius), pt(x1, y0 + radius)], - [pt(x1, body_bottom - radius), pt(x1, body_bottom - radius), pt(x1, body_bottom - radius)], - [pt(x1, body_bottom), pt(x1, body_bottom), pt(x1 - radius, body_bottom)], - [pt(c + radius * 0.2, body_bottom), pt(tip_x, y1 - tail_h * 0.15), pt(tip_x, y1)], - [pt(tip_x, y1), pt(tip_x, y1), pt(tip_x, y1)], - [pt(tip_x, y1 - tail_h * 0.15), pt(a - radius * 0.2, body_bottom), pt(a, body_bottom)], - [pt(x0 + radius, body_bottom), pt(x0, body_bottom), pt(x0, body_bottom - radius)], - [pt(x0, y0 + radius), pt(x0, y0 + radius), pt(x0, y0 + radius)], - [pt(x0, y0 + (1.0 - KAPPA) * radius), pt(x0 + (1.0 - KAPPA) * radius, y0), start], - ]; - SubPath { start, segments, closed: true } -} - -fn callout_ellipse(r: &Reader, shape: ObjId, cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath { - let tail_h = num(r, shape, b"TlHg").unwrap_or(0.2).clamp(0.0, 0.8); - let pos = num(r, shape, b"TlEP").unwrap_or(0.25).clamp(0.0, 1.0); - let angle = num(r, shape, b"TlAn").unwrap_or(0.0); - let a0 = pos * TAU - angle; - let a1 = a0 + 0.35; - let start = pt(cx + rx * a1.cos(), cy + ry * a1.sin()); - let end = pt(cx + rx * a0.cos(), cy + ry * a0.sin()); - let tip = pt(cx + rx * (a0 + 0.18).cos() * 1.08, cy + ry * (a0 + 0.18).sin() * (1.0 + tail_h)); - // A single ellipse-like outline with a short triangular tail at its lower edge. - let mut segments = Vec::new(); - arc(cx, cy, rx, ry, a1, a0 + TAU, &mut segments); - segments.push([end, end, tip]); - segments.push([tip, tip, start]); - SubPath { start, segments, closed: true } -} - -fn arrow(r: &Reader, shape: ObjId, [x0, y0, x1, y1]: [f64; 4]) -> SubPath { - let h = y1 - y0; - let thick = num(r, shape, b"Thck").unwrap_or(0.35).clamp(0.05, 0.9) * h; - let shaft = (y0 + y1 - thick) / 2.0; - let lower = shaft + thick; - let head_start = x1 - h * 0.45; - polygon([pt(x0, shaft), pt(head_start, shaft), pt(head_start, y0), pt(x1, (y0 + y1) / 2.0), pt(head_start, y1), pt(head_start, lower), pt(x0, lower)]) - .unwrap_or_else(|| rectangle_sub(x0, shaft, x1, lower)) -} - -fn double_star(r: &Reader, shape: ObjId, cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath { - let n = sides(r, shape, b"Pnts", 6.0).saturating_mul(2).clamp(8, 64); - let inner = num(r, shape, b"IRad").unwrap_or(0.6).clamp(0.05, 0.95); - let outer = num(r, shape, b"PRad").unwrap_or(0.9).clamp(0.2, 1.0); - polygon((0..2 * n).map(|i| { - let a = -FRAC_PI_2 + PI * i as f64 / n as f64; - let radius = if i % 2 == 0 { outer } else { outer * inner }; - pt(cx + rx * radius * a.cos(), cy + ry * radius * a.sin()) - })) - .unwrap_or_else(|| rectangle_sub(cx - rx, cy - ry, cx + rx, cy + ry)) -} - -fn tear(r: &Reader, shape: ObjId, [x0, y0, x1, y1]: [f64; 4]) -> SubPath { - let (w, h) = (x1 - x0, y1 - y0); - let bulge = num(r, shape, b"Ball").unwrap_or(0.25).clamp(0.0, 0.5); - let bend = num(r, shape, b"Bend").unwrap_or(0.0).clamp(-0.5, 0.5); - let top = pt((x0 + x1) / 2.0, y0); - let bottom = pt((x0 + x1) / 2.0 + bend * w * 0.25, y1); - let segments = vec![ - [pt(x0 + w * 0.25, y0 + h * 0.42), pt(x0 + w * (0.5 - bulge), y1 - h * 0.03), bottom], - [pt(x1 - w * (0.5 - bulge), y1 - h * 0.03), pt(x1 - w * 0.25, y0 + h * 0.42), top], - ]; - SubPath { start: top, segments, closed: true } -} - -fn crescent(cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath { - let start = pt(cx, cy - ry); - let mut segments = Vec::new(); - arc(cx, cy, rx, ry, -FRAC_PI_2, -3.0 * FRAC_PI_2, &mut segments); - // The inner arc returns from the lower tip to the upper tip, leaving a crescent open to the right. - let ix = cx + rx * 0.72; - let irx = rx * 0.86; - let iry = ry * 0.82; - let from = pt(ix, cy + iry); - segments.push([from, from, from]); - let mut inner = Vec::new(); - arc(ix, cy, irx, iry, FRAC_PI_2, -FRAC_PI_2, &mut inner); - segments.extend(inner); - SubPath { start, segments, closed: true } -} - -fn segment(r: &Reader, shape: ObjId, cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath { - // Keep hostile but finite angles in a small range before constructing arc controls. - let angle = num(r, shape, b"Angl").unwrap_or(0.0).rem_euclid(TAU); - let p0 = num(r, shape, b"Pos0").unwrap_or(0.25).clamp(0.0, 1.0); - let p1 = num(r, shape, b"Pos1").unwrap_or(0.75).clamp(0.0, 1.0); - let a0 = angle + (p0 - 0.5) * TAU; - let mut a1 = angle + (p1 - 0.5) * TAU; - while a1 < a0 { - a1 += TAU; - } - let mut segments = Vec::new(); - arc(cx, cy, rx, ry, a0, a1.min(a0 + TAU), &mut segments); - let start = pt(cx + rx * a0.cos(), cy + ry * a0.sin()); - let end = pt(cx + rx * a1.cos(), cy + ry * a1.sin()); - segments.push([end, end, start]); - SubPath { start, segments, closed: true } -} - -fn rectangle_sub(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath { - rectangle(x0, y0, x1, y1) -} - -pub(crate) fn rectangle(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath { - SubPath { start: pt(x0, y0), segments: [pt(x1, y0), pt(x1, y1), pt(x0, y1)].map(|p| [p, p, p]).to_vec(), closed: true } -} - -fn ellipse(cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath { - let (kx, ky) = (KAPPA * rx, KAPPA * ry); - SubPath { - start: pt(cx + rx, cy), - segments: vec![ - [pt(cx + rx, cy + ky), pt(cx + kx, cy + ry), pt(cx, cy + ry)], - [pt(cx - kx, cy + ry), pt(cx - rx, cy + ky), pt(cx - rx, cy)], - [pt(cx - rx, cy - ky), pt(cx - kx, cy - ry), pt(cx, cy - ry)], - [pt(cx + kx, cy - ry), pt(cx + rx, cy - ky), pt(cx + rx, cy)], - ], - closed: true, - } -} - -/// A rectangle whose corners (top left, top right, bottom right, bottom left) are each rounded, -/// or cut straight across, by their (horizontal, vertical) radii. Two radii that don't fit along -/// one side shrink in proportion until they do. -fn cornered_rect([x0, y0, x1, y1]: [f64; 4], corners: [(f64, f64, bool); 4]) -> SubPath { - let fit = |r: f64, pair: f64, side: f64| if pair > side { side * (r / pair) } else { r }; - let [tl, tr, br, bl] = corners; - let (w, h) = (x1 - x0, y1 - y0); - let rx = [fit(tl.0, tl.0 + tr.0, w), fit(tr.0, tl.0 + tr.0, w), fit(br.0, bl.0 + br.0, w), fit(bl.0, bl.0 + br.0, w)]; - let ry = [fit(tl.1, tl.1 + bl.1, h), fit(tr.1, tr.1 + br.1, h), fit(br.1, tr.1 + br.1, h), fit(bl.1, tl.1 + bl.1, h)]; - let (kx, ky) = (rx.map(|r| (1.0 - KAPPA) * r), ry.map(|r| (1.0 - KAPPA) * r)); - // (where the corner leaves the previous side, its two handles, where it joins the next side) - let arcs = [ - [pt(x1 - rx[1], y0), pt(x1 - kx[1], y0), pt(x1, y0 + ky[1]), pt(x1, y0 + ry[1])], - [pt(x1, y1 - ry[2]), pt(x1, y1 - ky[2]), pt(x1 - kx[2], y1), pt(x1 - rx[2], y1)], - [pt(x0 + rx[3], y1), pt(x0 + kx[3], y1), pt(x0, y1 - ky[3]), pt(x0, y1 - ry[3])], - [pt(x0, y0 + ry[0]), pt(x0, y0 + ky[0]), pt(x0 + kx[0], y0), pt(x0 + rx[0], y0)], - ]; - let mut segments = Vec::with_capacity(8); - for ([s, c1, c2, e], straight) in arcs.into_iter().zip([tr.2, br.2, bl.2, tl.2]) { - segments.push([s, s, s]); - if s != e { - segments.push(if straight { [e, e, e] } else { [c1, c2, e] }); - } - } - SubPath { start: pt(x0 + rx[0], y0), segments, closed: true } -} - -/// Elliptical arc from angle `a0` to `a1` (radians, measured y-up as Affinity's pie angles are), -/// as cubic segments of at most a quarter turn. -fn arc(cx: f64, cy: f64, rx: f64, ry: f64, a0: f64, a1: f64, out: &mut Vec<[Point; 3]>) { - let n = ((a1 - a0).abs() / FRAC_PI_2).ceil().clamp(1.0, 8.0) as usize; - let step = (a1 - a0) / n as f64; - let k = 4.0 / 3.0 * (step / 4.0).tan(); - let p = |a: f64| pt(cx + rx * a.cos(), cy - ry * a.sin()); - let d = |a: f64| pt(-rx * a.sin(), -ry * a.cos()); - for i in 0..n { - let (s, e) = (a0 + step * i as f64, a0 + step * (i + 1) as f64); - let (ps, pe, ds, de) = (p(s), p(e), d(s), d(e)); - out.push([pt(ps.x + k * ds.x, ps.y + k * ds.y), pt(pe.x - k * de.x, pe.y - k * de.y), pe]); - } -} - -fn pie(cx: f64, cy: f64, rx: f64, ry: f64, a0: f64, a1: f64, inner: f64) -> SubPath { - let start = pt(cx + rx * a0.cos(), cy - ry * a0.sin()); - let mut segments = Vec::new(); - arc(cx, cy, rx, ry, a0, a1, &mut segments); - if inner > 0.0 { - let p = pt(cx + inner * rx * a1.cos(), cy - inner * ry * a1.sin()); - segments.push([p, p, p]); - arc(cx, cy, inner * rx, inner * ry, a1, a0, &mut segments); - } else { - let c = pt(cx, cy); - segments.push([c, c, c]); - } - SubPath { start, segments, closed: true } -} - -/// A polyline with circular corners of the given radii (Affinity's live corners on curves). -pub(crate) fn fillet(pts: &[(Point, f64)], closed: bool) -> SubPath { - let n = pts.len(); - let get = |i: isize| -> Option { - if closed { pts.get(i.rem_euclid(n as isize) as usize).map(|p| p.0) } else { usize::try_from(i).ok().and_then(|i| pts.get(i)).map(|p| p.0) } - }; - let mut corners: Vec<(Point, Point, Point, Point)> = Vec::with_capacity(n); - for (i, (p, radius)) in pts.iter().enumerate() { - let (prev, next) = (get(i as isize - 1), get(i as isize + 1)); - let (Some(a), Some(b)) = (prev, next) else { - corners.push((*p, *p, *p, *p)); - continue; - }; - let (u1, l1) = unit(*p, a); - let (u2, l2) = unit(*p, b); - let cos = (u1.x * u2.x + u1.y * u2.y).clamp(-1.0, 1.0); - let phi = cos.acos(); - if *radius <= 0.0 || phi < 1e-6 || (PI - phi) < 1e-6 { - corners.push((*p, *p, *p, *p)); - continue; - } - let t = (radius / (phi / 2.0).tan()).min(l1 / 2.0).min(l2 / 2.0); - let r = t * (phi / 2.0).tan(); - let k = 4.0 / 3.0 * ((PI - phi) / 4.0).tan() * r; - let s = pt(p.x + u1.x * t, p.y + u1.y * t); - let e = pt(p.x + u2.x * t, p.y + u2.y * t); - corners.push((s, pt(s.x - u1.x * k, s.y - u1.y * k), pt(e.x - u2.x * k, e.y - u2.y * k), e)); - } - let Some(first) = corners.first().copied() else { return SubPath { start: pt(0.0, 0.0), segments: vec![], closed } }; - let mut segments = Vec::with_capacity(2 * n); - let mut cur = first.0; - let start = cur; - for (i, (s, c1, c2, e)) in corners.iter().enumerate() { - if i > 0 { - segments.push([cur, *s, *s]); - } - if s != e { - segments.push([*c1, *c2, *e]); - } - cur = *e; - } - if closed && cur != start { - segments.push([cur, start, start]); - } - SubPath { start, segments, closed } -} - -fn unit(from: Point, to: Point) -> (Point, f64) { - let (dx, dy) = (to.x - from.x, to.y - from.y); - let l = (dx * dx + dy * dy).sqrt(); - if l > 0.0 { (pt(dx / l, dy / l), l) } else { (pt(0.0, 0.0), 0.0) } -} diff --git a/crates/affinity/src/stream.rs b/crates/affinity/src/stream.rs deleted file mode 100644 index 74f240b873..0000000000 --- a/crates/affinity/src/stream.rs +++ /dev/null @@ -1,484 +0,0 @@ -//! The tagged object stream inside `doc.dat`: a self-describing tree of objects whose fields carry -//! a type code and a four-character tag. Parsing needs no schema; unknown fields are kept, so the -//! document mapping can name what it could not import. - -use crate::Error; -use crate::container::Cursor; - -/// A four-character tag in its readable order (`Desc`, `Chld`). -#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct Tag(pub u32); - -impl Tag { - pub const fn of(s: &[u8; 4]) -> Self { - Self(u32::from_be_bytes(*s)) - } -} - -impl std::fmt::Debug for Tag { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", String::from_utf8_lossy(&self.0.to_be_bytes())) - } -} - -impl std::fmt::Display for Tag { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - std::fmt::Debug::fmt(self, f) - } -} - -/// Index of an object in [`Stream::objects`]. -pub type ObjId = usize; - -#[derive(Debug, Clone, PartialEq)] -pub enum Value { - Int(i64), - UInt(u64), - Float(f64), - Bool(bool), - Enum { - id: u16, - version: u16, - }, - Str(String), - /// Fixed-length vectors of i32/f32/f64 (points, rectangles, transforms). - Ints(Vec), - Floats(Vec), - /// Fixed-size record (curve nodes, ids) or fixed-size struct (colour components). - Bytes(Vec), - Blob(Vec), - /// Name of another archive entry (raster tiles, embedded files). - Entry(String), - Flags(u64), - /// `None` is a null object. - Obj(Option), - Array(Vec), - /// An array of fixed-size records (`0x2c`, curve nodes) held in one buffer: `size` bytes each. - /// Counts as one value per record against [`MAX_VALUES`], like the array of `Bytes` it replaces. - Records { - size: u16, - data: Vec, - }, -} - -impl Value { - /// Slot count of an array field (including null slots); `None` for a scalar. - pub fn array_len(&self) -> Option { - match self { - Value::Array(a) => Some(a.len()), - Value::Records { size, data } => Some(data.len() / usize::from(*size).max(1)), - _ => None, - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Kind { - Root, - /// Defined once and referenced by id elsewhere. - Shared, - Inline, - /// Untagged fields identified by position (curve data). - Positional, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Object { - pub class: Tag, - pub kind: Kind, - /// Class chain, most derived first (`ShpN`, `VNod`, `Node`). - pub chain: Vec, - /// Fields in stream order; positional fields have tag 0. - pub fields: Vec<(Tag, Value)>, - /// Index for objects with more than [`SCAN`] fields: (tag, index of its first occurrence, - /// index of its last occurrence) sorted by tag, so `get` and `get_last` are a binary search. - /// A shared object can be referenced by many sibling layers, and each reference used to - /// rescan all of its fields; indexing once keeps repeated lookups from multiplying into - /// quadratic work. Smaller objects have no index (and no per-object hash map to build): - /// scanning a handful of fields is cheaper. - index: Vec<(Tag, u32, u32)>, -} - -/// Objects with at most this many fields are scanned instead of indexed. -const SCAN: usize = 12; - -fn build_index(fields: &[(Tag, Value)]) -> Vec<(Tag, u32, u32)> { - if fields.len() <= SCAN { - return Vec::new(); - } - // Positional fields share tag 0 and are not looked up by tag. Sorting by (tag, index) puts - // each tag's occurrences together in stream order: the first and last of each run keep - // first-match semantics for `get` and last-match semantics for `get_last`. - let mut index: Vec<(Tag, u32, u32)> = fields.iter().zip(0u32..).filter(|((t, _), _)| t.0 != 0).map(|((t, _), i)| (*t, i, i)).collect(); - index.sort_unstable(); - index.dedup_by(|later, kept| { - let same = later.0 == kept.0; - if same { - kept.2 = later.2; - } - same - }); - index -} - -impl Object { - pub fn new(class: Tag, kind: Kind, chain: Vec, fields: Vec<(Tag, Value)>) -> Self { - let index = build_index(&fields); - Object { class, kind, chain, fields, index } - } - - pub fn get(&self, tag: Tag) -> Option<&Value> { - if tag.0 == 0 { - return None; - } - if self.fields.len() <= SCAN { - return self.fields.iter().find(|(t, _)| *t == tag).map(|(_, v)| v); - } - let at = self.index.binary_search_by_key(&tag, |e| e.0).ok()?; - self.index.get(at).and_then(|&(_, i, _)| self.fields.get(i as usize)).map(|(_, v)| v) - } - - /// The last field with `tag`, for objects that may repeat a tag (a shape changed from one - /// kind to another keeps a stale first block). Indexed like [`Object::get`], so repeated - /// lookups on a large shared object do not rescan its fields. - pub fn get_last(&self, tag: Tag) -> Option<&Value> { - if tag.0 == 0 { - return None; - } - if self.fields.len() <= SCAN { - return self.fields.iter().rev().find(|(t, _)| *t == tag).map(|(_, v)| v); - } - let at = self.index.binary_search_by_key(&tag, |e| e.0).ok()?; - self.index.get(at).and_then(|&(_, _, i)| self.fields.get(i as usize)).map(|(_, v)| v) - } - - /// Replaces the fields (the root object is filled in after it is pushed) and rebuilds the - /// tag index so `get` stays correct. - fn set_fields(&mut self, fields: Vec<(Tag, Value)>) { - self.index = build_index(&fields); - self.fields = fields; - } -} - -#[derive(Debug)] -pub struct Stream { - pub root: ObjId, - pub objects: Vec, -} - -/// Deepest object nesting accepted; real documents stay well below (each layer level adds three). -pub const MAX_DEPTH: usize = 384; - -const MAX_OBJECTS: usize = 8_000_000; - -/// Most values (fields and array elements) one stream may decode. A value takes about 40 bytes -/// in memory however few it took in the file (a bool array packs eight in a byte), so the size -/// of the input alone doesn't bound what parsing allocates: a small compressed entry could -/// otherwise ask for tens of gigabytes. Real documents stay far below. -pub const MAX_VALUES: usize = 1 << 24; - -struct Parser<'a> { - c: Cursor<'a>, - objects: Vec, - /// Shared ids, defined at first use and referenced backwards. - shared: std::collections::HashMap, - depth: usize, - /// Values decoded so far, against [`MAX_VALUES`]. - values: usize, -} - -/// Parse a stream (`00 FF 4B 53` header). Bytes after the root's terminator are ignored. -pub fn parse(bytes: &[u8]) -> Result { - let mut c = Cursor::new(bytes, 0); - if c.take(4)? != b"\x00\xffKS" { - return Err(Error::Malformed("document stream signature")); - } - let version = c.u16()?; - if version > 2 { - return Err(Error::Unsupported("document stream version")); - } - let class = Tag(c.u32()?); - c.u16()?; - if version == 2 { - c.u32()?; - } - let mut p = Parser { c, objects: Vec::new(), shared: std::collections::HashMap::new(), depth: 0, values: 0 }; - let root = p.push(Object::new(class, Kind::Root, vec![class], Vec::new()))?; - let fields = p.fields(true, class)?; - if let Some(o) = p.objects.get_mut(root) { - o.set_fields(fields); - } - Ok(Stream { root, objects: p.objects }) -} - -impl Parser<'_> { - fn push(&mut self, o: Object) -> Result { - if self.objects.len() >= MAX_OBJECTS { - return Err(Error::Limit("too many objects")); - } - self.objects.push(o); - Ok(self.objects.len() - 1) - } - - /// Counts `n` more values against [`MAX_VALUES`], before anything is allocated for them. - fn spend(&mut self, n: usize) -> Result<(), Error> { - self.values = self.values.checked_add(n).filter(|&v| v <= MAX_VALUES).ok_or(Error::Limit("too many values in the document stream"))?; - Ok(()) - } - - /// An empty array with room for `n` values, paid for first; an allocation that still fails - /// is an error, not an abort. - fn vec(&mut self, n: usize) -> Result, Error> { - self.spend(n)?; - let mut v = Vec::new(); - v.try_reserve_exact(n).map_err(|_| Error::Limit("not enough memory for the document stream"))?; - Ok(v) - } - - /// Element count of an array: each element takes at least `min` bytes, so a count the - /// remaining input cannot hold is rejected before anything is allocated. - fn count(&mut self, min: usize) -> Result { - let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?; - if n.checked_mul(min.max(1)).is_none_or(|bytes| bytes > self.c.remaining()) { - return Err(Error::Malformed("array longer than its data")); - } - Ok(n) - } - - fn fields(&mut self, tagged: bool, class: Tag) -> Result, Error> { - self.depth += 1; - if self.depth > MAX_DEPTH { - return Err(Error::Limit("objects nested too deeply")); - } - let mut out = Vec::new(); - loop { - let t = self.c.u8()?; - let code = t & 0x7F; - if code == 0 { - break; - } - self.spend(1)?; - let tag = if tagged { Tag(self.c.u32()?) } else { Tag(0) }; - let v = if t & 0x80 != 0 { self.array(code, class)? } else { self.scalar(code, tagged, class)? }; - out.push((tag, v)); - } - self.depth -= 1; - Ok(out) - } - - fn string(&mut self) -> Result { - let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("string length"))?; - Ok(String::from_utf8_lossy(self.c.take(n)?).into_owned()) - } - - fn floats(&mut self, n: usize, wide: bool) -> Result { - let mut v = Vec::with_capacity(n); - for _ in 0..n { - v.push(if wide { f64::from_le_bytes(self.c.array()?) } else { f64::from(f32::from_le_bytes(self.c.array()?)) }); - } - Ok(Value::Floats(v)) - } - - fn scalar(&mut self, code: u8, tagged: bool, class: Tag) -> Result { - let c = &mut self.c; - Ok(match code { - 0x01 => Value::UInt(c.u8()?.into()), - 0x02 => Value::UInt(c.u16()?.into()), - 0x03 | 0x2f | 0x34 => Value::UInt(c.u32()?.into()), - 0x04 => Value::UInt(c.u64()?), - 0x05 => Value::Int(i8::from_le_bytes(c.array()?).into()), - 0x06 => Value::Int(i16::from_le_bytes(c.array()?).into()), - 0x07 => Value::Int(i32::from_le_bytes(c.array()?).into()), - 0x08 => Value::Int(i64::from_le_bytes(c.array()?)), - 0x09 => Value::Float(f32::from_le_bytes(c.array()?).into()), - 0x0a => Value::Float(f64::from_le_bytes(c.array()?)), - 0x15..=0x19 => { - let n = usize::from(code - 0x13); - let mut v = Vec::with_capacity(n); - for _ in 0..n { - v.push(i32::from_le_bytes(c.array()?).into()); - } - Value::Ints(v) - } - 0x1f..=0x23 => return self.floats(usize::from(code - 0x1d), false), - 0x24..=0x28 => return self.floats(usize::from(code - 0x22), true), - 0x29 => Value::Bool(c.u8()? != 0), - 0x2a => Value::Enum { id: c.u16()?, version: c.u16()? }, - 0x2b | 0x2e => Value::Str(self.string()?), - 0x2c => { - let n = usize::from(c.u16()?); - Value::Bytes(c.take(n)?.to_vec()) - } - 0x35..=0x74 => Value::Bytes(c.take(usize::from(code - 0x34))?.to_vec()), - 0x2d => { - let n = usize::try_from(c.u32()?).map_err(|_| Error::Malformed("blob length"))?; - Value::Blob(c.take(n)?.to_vec()) - } - 0x33 => { - c.u32()?; - let n = usize::try_from(c.u32()?).map_err(|_| Error::Malformed("entry name length"))?; - Value::Entry(String::from_utf8_lossy(c.take(n)?).into_owned()) - } - 0x75 => { - c.u16()?; - let n = usize::from(c.u8()?); - if n > 8 { - return Err(Error::Malformed("flags wider than 64 bits")); - } - let mut b = [0u8; 8]; - b.get_mut(..n).ok_or(Error::Malformed("flags"))?.copy_from_slice(c.take(n)?); - Value::Flags(u64::from_le_bytes(b)) - } - 0x30 => { - let fields = self.fields(false, class)?; - let id = self.push(Object::new(class, Kind::Positional, Vec::new(), fields))?; - Value::Obj(Some(id)) - } - 0x31 | 0x32 if !tagged => return Err(Error::Malformed("object without a field tag")), - 0x31 => self.shared()?, - 0x32 => self.inline(None)?, - _ => return Err(Error::Unsupported("unknown field type in document stream")), - }) - } - - fn array(&mut self, code: u8, class: Tag) -> Result { - let min = match code { - 0x01 | 0x05 | 0x29 => 1, - 0x02 | 0x06 => 2, - 0x03 | 0x07 | 0x09 | 0x2f | 0x34 => 4, - 0x04 | 0x08 | 0x0a => 8, - 0x15..=0x19 => 4 * usize::from(code - 0x13), - 0x1f..=0x23 => 4 * usize::from(code - 0x1d), - 0x24..=0x28 => 8 * usize::from(code - 0x22), - 0x35..=0x74 => usize::from(code - 0x34), - _ => 1, - }; - match code { - 0x29 => { - let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?; - let bits = self.c.take(n.div_ceil(8))?; - let mut v = self.vec(n)?; - v.extend((0..n).map(|i| Value::Bool(bits.get(i / 8).is_some_and(|b| b >> (i % 8) & 1 != 0)))); - Ok(Value::Array(v)) - } - 0x2a => { - let n = self.count(2)?; - let version = self.c.u16()?; - let mut v = self.vec(n)?; - for _ in 0..n { - v.push(Value::Enum { id: self.c.u16()?, version }); - } - Ok(Value::Array(v)) - } - 0x2b | 0x2e => { - self.c.u32()?; - let n = self.count(4)?; - let mut v = self.vec(n)?; - for _ in 0..n { - v.push(Value::Str(self.string()?)); - } - Ok(Value::Array(v)) - } - 0x2c => { - let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?; - let size = usize::from(self.c.u16()?); - // A zero width passes the length check for any count, then costs a Value per record. - if size == 0 || n.checked_mul(size).is_none_or(|b| b > self.c.remaining()) { - return Err(Error::Malformed("array longer than its data")); - } - // Still one value per record against the budget, but a single allocation. - self.spend(n)?; - let bytes = self.c.take(n * size)?; - let mut data = Vec::new(); - data.try_reserve_exact(bytes.len()).map_err(|_| Error::Limit("not enough memory for the document stream"))?; - data.extend_from_slice(bytes); - Ok(Value::Records { size: size as u16, data }) - } - 0x32 => { - let n = self.count(1)?; - let class = Tag(self.c.u32()?); - self.c.u16()?; - let mut v = self.vec(n)?; - for _ in 0..n { - v.push(self.inline(Some(class))?); - } - Ok(Value::Array(v)) - } - 0x2d | 0x33 | 0x75 => Err(Error::Malformed("array of an unarrayable type")), - _ => { - let n = self.count(min)?; - let mut v = self.vec(n)?; - for _ in 0..n { - v.push(self.scalar(code, true, class)?); - } - Ok(Value::Array(v)) - } - } - } - - /// Inline object; `class` is given once for a whole array of them. - fn inline(&mut self, class: Option) -> Result { - match self.c.u8()? { - 0 => return Ok(Value::Obj(None)), - 1 => {} - _ => return Err(Error::Malformed("object marker")), - } - let class = match class { - Some(c) => c, - None => { - let c = Tag(self.c.u32()?); - self.c.u16()?; - c - } - }; - let fields = self.fields(true, class)?; - let id = self.push(Object::new(class, Kind::Inline, vec![class], fields))?; - Ok(Value::Obj(Some(id))) - } - - fn shared(&mut self) -> Result { - let flag = self.c.u8()?; - if flag == 0 { - return Ok(Value::Obj(None)); - } - let key = self.c.u32()?; - match flag { - 2 => return self.shared.get(&key).map(|id| Value::Obj(Some(*id))).ok_or(Error::Malformed("reference to an undefined object")), - 1 => {} - _ => return Err(Error::Malformed("object marker")), - } - if self.shared.contains_key(&key) { - return Err(Error::Malformed("object defined twice")); - } - // Register before the fields: an object's own fields may refer back to it. - let id = self.push(Object::new(Tag(0), Kind::Shared, Vec::new(), Vec::new()))?; - self.shared.insert(key, id); - let mut chain = Vec::new(); - let mut fields = Vec::new(); - loop { - match self.c.u8()? { - 0 => { - let tag = Tag(self.c.u32()?); - self.c.u16()?; - chain.push(tag); - fields.extend(self.fields(true, tag)?); - } - 1 => { - chain.push(Tag(self.c.u32()?)); - break; - } - 2 => break, - _ => return Err(Error::Malformed("object class chain")), - } - if chain.len() > 64 { - return Err(Error::Limit("object class chain too long")); - } - } - let class = chain.first().copied().unwrap_or(Tag(0)); - fields.extend(self.fields(true, class)?); - if let Some(o) = self.objects.get_mut(id) { - *o = Object::new(class, Kind::Shared, chain, fields); - } - Ok(Value::Obj(Some(id))) - } -} diff --git a/crates/affinity/src/synth.rs b/crates/affinity/src/synth.rs deleted file mode 100644 index 5b75ca0bff..0000000000 --- a/crates/affinity/src/synth.rs +++ /dev/null @@ -1,259 +0,0 @@ -//! Synthetic containers for tests and fuzz seeds (cargo feature `synth`). -//! -//! These builders write the layout the reader accepts, so tests can describe documents in a few -//! lines. They are **not** an Affinity exporter: nothing written here has been opened in Affinity. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - -use crate::stream::Tag; - -/// A field value to encode. -#[derive(Debug, Clone)] -pub enum F { - U8(u8), - U32(u32), - I32(i32), - F32(f32), - F64(f64), - Bool(bool), - Enum(u16, u16), - Str(String), - /// f64 vector of 2..6 values (points, rectangles, transforms). - F64s(Vec), - /// Fixed-size struct (colour components), 1..64 bytes. - Struct(Vec), - /// Array of fixed-size records, all `size` bytes. - Records(u16, Vec>), - U8s(Vec), - Entry(String), - /// Shared object: `Def` defines id with class chain and fields, `Ref` links back. - Def(u32, Vec, Vec<(Tag, F)>), - Ref(u32), - Null, - /// Inline object. - Obj(Tag, Vec<(Tag, F)>), - /// Positional (untagged) object. - Pos(Vec), - /// Array of shared objects / links. - Shared(Vec), - /// Array of inline objects of one class. - Objs(Tag, Vec>), - /// Raw bytes appended verbatim (malformed-input tests). - Raw(Vec), -} - -pub fn tag(s: &[u8; 4]) -> Tag { - Tag::of(s) -} - -fn put_tag(out: &mut Vec, t: Tag) { - out.extend(t.0.to_le_bytes()); -} - -fn code(f: &F) -> u8 { - match f { - F::U8(_) => 0x01, - F::U32(_) => 0x03, - F::I32(_) => 0x07, - F::F32(_) => 0x09, - F::F64(_) => 0x0a, - F::Bool(_) => 0x29, - F::Enum(..) => 0x2a, - F::Str(_) => 0x2b, - F::F64s(v) => 0x22 + v.len() as u8, - F::Struct(b) => 0x34 + b.len() as u8, - F::Records(..) => 0x80 | 0x2c, - F::U8s(_) => 0x80 | 0x01, - F::Entry(_) => 0x33, - F::Def(..) | F::Ref(_) => 0x31, - F::Null => 0x31, - F::Obj(..) => 0x32, - F::Pos(_) => 0x30, - F::Shared(_) => 0x80 | 0x31, - F::Objs(..) => 0x80 | 0x32, - F::Raw(_) => 0, - } -} - -fn payload(out: &mut Vec, f: &F) { - match f { - F::U8(v) => out.push(*v), - F::U32(v) => out.extend(v.to_le_bytes()), - F::I32(v) => out.extend(v.to_le_bytes()), - F::F32(v) => out.extend(v.to_le_bytes()), - F::F64(v) => out.extend(v.to_le_bytes()), - F::Bool(v) => out.push(u8::from(*v)), - F::Enum(id, ver) => { - out.extend(id.to_le_bytes()); - out.extend(ver.to_le_bytes()); - } - F::Str(s) => { - out.extend((s.len() as u32).to_le_bytes()); - out.extend(s.as_bytes()); - } - F::F64s(v) => v.iter().for_each(|x| out.extend(x.to_le_bytes())), - F::Struct(b) => out.extend(b), - F::Records(size, recs) => { - out.extend((recs.len() as u32).to_le_bytes()); - out.extend(size.to_le_bytes()); - recs.iter().for_each(|r| out.extend(r)); - } - F::U8s(v) => { - out.extend((v.len() as u32).to_le_bytes()); - out.extend(v); - } - F::Entry(name) => { - put_tag(out, tag(b"Data")); - out.extend((name.len() as u32).to_le_bytes()); - out.extend(name.as_bytes()); - } - F::Def(id, chain, fields) => { - out.push(1); - out.extend(id.to_le_bytes()); - // Class chain: each level but the last carries no fields here; the last ends the chain. - let (last, rest) = chain.split_last().expect("class chain"); - for t in rest { - out.push(0); - put_tag(out, *t); - out.extend(0u16.to_le_bytes()); - out.push(0); - } - out.push(1); - put_tag(out, *last); - fields_into(out, fields, true); - } - F::Ref(id) => { - out.push(2); - out.extend(id.to_le_bytes()); - } - F::Null => out.push(0), - F::Obj(class, fields) => { - out.push(1); - put_tag(out, *class); - out.extend(0u16.to_le_bytes()); - fields_into(out, fields, true); - } - F::Pos(items) => { - for f in items { - out.push(code(f)); - payload(out, f); - } - out.push(0); - } - F::Shared(items) => { - out.extend((items.len() as u32).to_le_bytes()); - items.iter().for_each(|f| payload(out, f)); - } - F::Objs(class, items) => { - out.extend((items.len() as u32).to_le_bytes()); - put_tag(out, *class); - out.extend(0u16.to_le_bytes()); - for fields in items { - out.push(1); - fields_into(out, fields, true); - } - } - F::Raw(b) => out.extend(b), - } -} - -fn fields_into(out: &mut Vec, fields: &[(Tag, F)], tagged: bool) { - for (t, f) in fields { - if let F::Raw(b) = f { - out.extend(b); - continue; - } - out.push(code(f)); - if tagged { - put_tag(out, *t); - } - payload(out, f); - } - out.push(0); -} - -/// A `doc.dat` stream with root class `Pers`. -pub fn stream(root: &[(Tag, F)]) -> Vec { - let mut out = b"\x00\xffKS".to_vec(); - out.extend(2u16.to_le_bytes()); - put_tag(&mut out, tag(b"Pers")); - out.extend(0u16.to_le_bytes()); - out.extend(30u32.to_le_bytes()); - fields_into(&mut out, root, true); - out -} - -/// How an entry is stored. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Method { - Stored, - Zlib, - Zstd, -} - -/// A version-12 container with one `#FT4` table holding `entries`, then an optional thumbnail record. -pub fn container(entries: &[(&str, &[u8], Method)], thumbnail_png: Option<&[u8]>) -> Vec { - let mut out = vec![0u8; 72]; - out[..4].copy_from_slice(crate::container::MAGIC); - out[4..6].copy_from_slice(&12u16.to_le_bytes()); - out[6..8].copy_from_slice(&4u16.to_le_bytes()); - out[8..12].copy_from_slice(b"nsrP"); - out[12..16].copy_from_slice(b"#Inf"); - out[64..68].copy_from_slice(b"Prot"); - let mut records = Vec::new(); - for (i, (name, data, method)) in entries.iter().enumerate() { - let packed = match method { - Method::Stored => data.to_vec(), - Method::Zlib => { - use std::io::Write; - let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast()); - e.write_all(data).unwrap(); - e.finish().unwrap() - } - Method::Zstd => ruzstd::encoding::compress_to_vec(*data, ruzstd::encoding::CompressionLevel::Fastest), - }; - let offset = out.len() as u64; - out.extend(b"#Fil"); - out.extend(&packed); - let mut r = Vec::new(); - r.extend((i as u32 + 1).to_le_bytes()); - r.push(0); - r.extend(offset.to_le_bytes()); - r.extend((data.len() as u64).to_le_bytes()); - r.extend((packed.len() as u64).to_le_bytes()); - r.extend(crc32fast::hash(data).to_le_bytes()); - r.push(match method { - Method::Stored => 0, - Method::Zlib => 1, - Method::Zstd => 2, - }); - r.extend(0u32.to_le_bytes()); - r.extend(0u32.to_le_bytes()); - r.extend((name.len() as u16).to_le_bytes()); - r.extend(name.as_bytes()); - records.push(r); - } - let fat = out.len() as u64; - out.extend(b"#FT4"); - out.extend(0u64.to_le_bytes()); - out.extend(1_700_000_000u64.to_le_bytes()); - out.extend([0u8; 24]); - out.extend((records.len() as u32).to_le_bytes()); - out.extend([0u8; 8]); - out.extend(0u16.to_le_bytes()); - out.push(0); - records.iter().for_each(|r| out.extend(r)); - let thumb = out.len() as u64; - out[16..24].copy_from_slice(&fat.to_le_bytes()); - if let Some(png) = thumbnail_png { - out[24..32].copy_from_slice(&thumb.to_le_bytes()); - out.extend(b"\xff\xff\xff\xffThmb"); - out.extend(1u32.to_le_bytes()); - out.extend((png.len() as u32 + 13).to_le_bytes()); - out.extend(29u32.to_le_bytes()); - out.extend(0u32.to_le_bytes()); - out.extend((png.len() as u32).to_le_bytes()); - out.push(1); - out.extend(png); - } - out -} diff --git a/crates/affinity/src/tests.rs b/crates/affinity/src/tests.rs deleted file mode 100644 index 61162454ba..0000000000 --- a/crates/affinity/src/tests.rs +++ /dev/null @@ -1,1101 +0,0 @@ -//! Unit tests on synthetic inputs; `tests/it/real_files.rs` covers public Affinity documents. - -mod preview { - use crate::container::header; - use crate::*; - use proptest::prelude::*; - - fn fixture() -> Vec { - 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]); - png.extend(crc32fast::hash(&png[12..]).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()); - 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 - } - - #[test] - fn indexed_preview_and_header() { - let b = fixture(); - assert_eq!(header(&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}"); - } - // Versions 8 to 11 store the same record (checked on public Affinity 1 and 2 files). - for version in 8..12 { - let mut legacy = b.clone(); - legacy[4..6].copy_from_slice(&(version as u16).to_le_bytes()); - assert!(preview(&legacy).is_ok()); - } - // Flags 4 and 8 occur in real files; the low two bits mark other container variants. - for (flags, ok) in [(4u16, true), (8, true), (1, false), (2, false)] { - let mut variant = b.clone(); - variant[6..8].copy_from_slice(&flags.to_le_bytes()); - assert_eq!(preview(&variant).is_ok(), ok, "flags {flags}"); - } - let mut old = b.clone(); - old[4..6].copy_from_slice(&7u16.to_le_bytes()); - assert!(matches!(preview(&old), 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_checksum_including_the_end_is_checked() { - let b = fixture(); - for at in [130, b.len() - 1] { - let mut damaged = b.clone(); - damaged[at] ^= 1; - assert_eq!(preview(&damaged).unwrap_err(), Error::Malformed("PNG chunk checksum")); - } - let mut ancillary = vec![0; 4]; - ancillary.extend(b"tEXt"); - ancillary.extend(crc32fast::hash(b"tEXt").to_be_bytes()); - let mut with_ancillary = b.clone(); - let at = b.len() - 12; - with_ancillary.splice(at..at, ancillary); - let png_length = (with_ancillary.len() - 101) as u32; - with_ancillary[84..88].copy_from_slice(&(png_length + 13).to_le_bytes()); - with_ancillary[96..100].copy_from_slice(&png_length.to_le_bytes()); - assert!(preview(&with_ancillary).is_ok()); - with_ancillary[at + 8] ^= 1; - assert_eq!(preview(&with_ancillary).unwrap_err(), Error::Malformed("PNG chunk checksum")); - } - - #[test] - fn compressed_metadata_and_animation_are_not_preview_support() { - for kind in [b"zTXt", b"iTXt", b"iCCP", b"acTL", b"fcTL", b"fdAT"] { - let mut extra = vec![0; 4]; - extra.extend(kind); - extra.extend(crc32fast::hash(kind).to_be_bytes()); - let mut b = fixture(); - let at = b.len() - 12; - b.splice(at..at, extra); - let length = (b.len() - 101) as u32; - b[84..88].copy_from_slice(&(length + 13).to_le_bytes()); - b[96..100].copy_from_slice(&length.to_le_bytes()); - assert!(matches!(preview(&b), Err(Error::Unsupported(_)))); - } - } - - #[test] - fn critical_chunks_follow_a_single_complete_png_layout() { - fn with_chunks(kinds: &[&[u8; 4]]) -> Vec { - let original = fixture(); - let mut b = original[..134].to_vec(); // File, record and complete first IHDR. - for kind in kinds { - b.extend([0; 4]); - b.extend(*kind); - b.extend(crc32fast::hash(*kind).to_be_bytes()); - } - let length = (b.len() - 101) as u32; - b[84..88].copy_from_slice(&(length + 13).to_le_bytes()); - b[96..100].copy_from_slice(&length.to_le_bytes()); - b - } - assert!(preview(&with_chunks(&[b"IDAT", b"IDAT", b"IEND"])).is_ok()); - // PNG readers must not reject an otherwise valid unknown ancillary chunk just - // because its reserved (third-letter) bit is set; future versions can define it. - assert!(preview(&with_chunks(&[b"abct", b"IDAT", b"IEND"])).is_ok()); - for kinds in [ - vec![b"IEND"], - vec![b"IDAT", b"IHDR", b"IEND"], - vec![b"PLTE", b"PLTE", b"IDAT", b"IEND"], - vec![b"IDAT", b"PLTE", b"IEND"], - vec![b"IDAT", b"tEXt", b"IDAT", b"IEND"], - vec![b"ABCD", b"IDAT", b"IEND"], - vec![b"IDAT", b"IEND", b"tEXt"], - ] { - assert!(preview(&with_chunks(&kinds)).is_err(), "{kinds:?}"); - } - } - - proptest! { - #![proptest_config(ProptestConfig::with_cases(256))] - #[test] - fn arbitrary_input_never_panics(b in prop::collection::vec(any::(), 0..2048)) { - let _ = header(&b); - let _ = preview(&b); - } - #[test] - fn mutations_never_panic(edits in prop::collection::vec((0usize..200, any::()), 0..32)) { - let mut b = fixture(); - for (i, value) in edits { if let Some(v) = b.get_mut(i) { *v = value; } } - let _ = preview(&b); - } - } -} - -mod archive { - use crate::Error; - use crate::container::{Archive, Limits}; - use crate::stream::{self, Kind, Tag, Value}; - use crate::synth::{self, F, Method, tag}; - use proptest::prelude::*; - - fn doc() -> Vec { - synth::stream(&[ - (tag(b"Desc"), F::Str("Document".into())), - (tag(b"Visi"), F::Bool(true)), - (tag(b"Xfrm"), F::F64s(vec![1.0, 0.0, 5.0, 0.0, 1.0, -2.0])), - (tag(b"Colr"), F::Def(7, vec![tag(b"RGBA")], vec![(tag(b"_col"), F::Struct([0u8; 16].to_vec()))])), - (tag(b"Same"), F::Ref(7)), - (tag(b"Null"), F::Null), - (tag(b"Kids"), F::Shared(vec![F::Def(8, vec![tag(b"Grup"), tag(b"Node")], vec![(tag(b"Desc"), F::Str("g".into()))]), F::Ref(8)])), - (tag(b"Crvs"), F::Obj(tag(b"PCvD"), vec![(tag(b"Data"), F::Pos(vec![F::U8(0), F::U32(1), F::Bool(true), F::Records(18, vec![vec![0; 18]; 4])]))])), - (tag(b"Enum"), F::Enum(2, 1)), - (tag(b"Tile"), F::Entry("d/3".into())), - (tag(b"Stat"), F::U8s(vec![4, 0, 2])), - ]) - } - - #[test] - fn every_method_round_trips_with_checksums() { - let d = doc(); - for method in [Method::Stored, Method::Zlib, Method::Zstd] { - let file = synth::container(&[("doc.dat", &d, method), ("d/3", b"tile", method)], None); - let mut a = Archive::open(&file, Limits::default()).unwrap(); - assert_eq!(a.header.version, 12); - assert_eq!(a.read("doc.dat").unwrap(), d); - assert_eq!(a.read("d/3").unwrap(), b"tile"); - assert_eq!(a.extracted(), d.len() + 4); - assert!(a.read("missing").is_err()); - } - } - - #[test] - fn the_stream_parses_into_shared_objects_and_links() { - let s = stream::parse(&doc()).unwrap(); - let root = &s.objects[s.root]; - assert_eq!(root.class, Tag::of(b"Pers")); - assert_eq!(root.get(Tag::of(b"Desc")), Some(&Value::Str("Document".into()))); - assert_eq!(root.get(Tag::of(b"Xfrm")), Some(&Value::Floats(vec![1.0, 0.0, 5.0, 0.0, 1.0, -2.0]))); - let (Some(Value::Obj(Some(a))), Some(Value::Obj(Some(b)))) = (root.get(Tag::of(b"Colr")), root.get(Tag::of(b"Same"))) else { panic!() }; - assert_eq!(a, b); - assert_eq!(s.objects[*a].class, Tag::of(b"RGBA")); - assert_eq!(s.objects[*a].kind, Kind::Shared); - let Some(Value::Array(kids)) = root.get(Tag::of(b"Kids")) else { panic!() }; - assert_eq!(kids[0], kids[1]); - let Value::Obj(Some(g)) = kids[0] else { panic!() }; - assert_eq!(s.objects[g].chain, vec![Tag::of(b"Grup"), Tag::of(b"Node")]); - assert_eq!(root.get(Tag::of(b"Enum")), Some(&Value::Enum { id: 2, version: 1 })); - assert_eq!(root.get(Tag::of(b"Tile")), Some(&Value::Entry("d/3".into()))); - assert_eq!(root.get(Tag::of(b"Null")), Some(&Value::Obj(None))); - } - - #[test] - fn checksums_sizes_and_budgets_are_enforced() { - let d = doc(); - let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None); - // Flip a byte inside the compressed payload, past the "#Fil" tag at offset 72. - let mut broken = file.clone(); - broken[90] ^= 0x55; - let mut a = Archive::open(&broken, Limits::default()).unwrap(); - assert!(a.read("doc.dat").is_err()); - let mut a = Archive::open(&file, Limits { max_entry: d.len() - 1, max_total: usize::MAX, ..Limits::default() }).unwrap(); - assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_)))); - let mut a = Archive::open(&file, Limits { max_entry: usize::MAX, max_total: d.len() + 1, ..Limits::default() }).unwrap(); - a.read("doc.dat").unwrap(); - assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_)))); - } - - #[test] - fn a_failed_read_still_spends_the_extraction_allowance() { - let d = doc(); - let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None); - let mut broken = file.clone(); - broken[90] ^= 0x55; - // Room for exactly one read: the failed attempt must use it up, so a caller that - // recovers from the checksum error cannot make the same entry decode again. - let mut a = Archive::open(&broken, Limits { max_entry: usize::MAX, max_total: d.len(), ..Limits::default() }).unwrap(); - assert!(a.read("doc.dat").is_err()); - assert_eq!(a.extracted(), d.len()); - assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_)))); - } - - #[test] - fn a_declared_size_smaller_than_the_data_is_rejected_not_truncated() { - let big = vec![7u8; 1 << 20]; - let mut file = synth::container(&[("doc.dat", &big, Method::Zlib)], None); - // Rewrite the declared size in the table to 1 KiB: decoding must stop and fail. - let fat = u64::from_le_bytes(file[16..24].try_into().unwrap()) as usize; - let size_at = fat + 59 + 5 + 8; - file[size_at..size_at + 8].copy_from_slice(&1024u64.to_le_bytes()); - let mut a = Archive::open(&file, Limits::default()).unwrap(); - assert_eq!(a.read("doc.dat").unwrap_err(), Error::Malformed("archive entry size mismatch")); - } - - #[test] - fn libraries_and_cyclic_tables_are_rejected() { - let d = doc(); - let mut file = synth::container(&[("doc.dat", &d, Method::Stored)], None); - let mut library = file.clone(); - library[8..12].copy_from_slice(b"rAsA"); - assert!(matches!(Archive::open(&library, Limits::default()), Err(Error::Unsupported(_)))); - let fat = u64::from_le_bytes(file[16..24].try_into().unwrap()); - let at = fat as usize + 4; - file[at..at + 8].copy_from_slice(&fat.to_le_bytes()); - assert_eq!(Archive::open(&file, Limits::default()).unwrap_err(), Error::Malformed("allocation tables form a cycle")); - } - - #[test] - fn allocation_records_are_charged_before_they_are_walked() { - let d = doc(); - let mut file = synth::container(&[("doc.dat", &d, Method::Stored)], None); - let fat = u64::from_le_bytes(file[16..24].try_into().unwrap()) as usize; - // The table's file count sits after its tag, next, date and 24 reserved bytes. - let files = fat + 4 + 8 + 8 + 24; - file[files..files + 4].copy_from_slice(&u32::MAX.to_le_bytes()); - assert_eq!(Archive::open(&file, Limits::default()).unwrap_err(), Error::Limit("too many allocation records")); - // A count within the budget still reaches the records (and here fails on missing data). - file[files..files + 4].copy_from_slice(&1_000_000u32.to_le_bytes()); - assert!(matches!(Archive::open(&file, Limits::default()), Err(Error::Malformed(_)))); - } - - #[test] - fn allocation_records_are_charged_across_every_table() { - let d = doc(); - let mut file = synth::container(&[("doc.dat", &d, Method::Stored), ("other.dat", &d, Method::Stored)], None); - let fat = u64::from_le_bytes(file[16..24].try_into().unwrap()) as usize; - // Chain a copy of the (valid, two-record) table after it; the copy is the last table. - let second = file.len(); - let table = file[fat..].to_vec(); - file.extend(&table); - file[fat + 4..fat + 12].copy_from_slice(&(second as u64).to_le_bytes()); - let files = second + 4 + 8 + 8 + 24; - // Each count alone is within the archive budget of 2^25; together they exceed it by one. - file[files..files + 4].copy_from_slice(&((1u32 << 25) - 1).to_le_bytes()); - assert_eq!(Archive::open(&file, Limits::default()).unwrap_err(), Error::Limit("too many allocation records")); - // Exactly the budget is allowed: the second table is walked (and fails on missing data). - file[files..files + 4].copy_from_slice(&((1u32 << 25) - 2).to_le_bytes()); - assert!(matches!(Archive::open(&file, Limits::default()), Err(Error::Malformed(_)))); - // Directory records count too: one more (after the file count and 8 bytes) is over. - file[files + 12..files + 14].copy_from_slice(&1u16.to_le_bytes()); - assert_eq!(Archive::open(&file, Limits::default()).unwrap_err(), Error::Limit("too many allocation records")); - } - - #[test] - fn hostile_streams_fail_cleanly() { - let deep = (0..2000).fold(Vec::new(), |inner, _| vec![(tag(b"Chld"), F::Obj(tag(b"Grup"), inner))]); - assert_eq!(stream::parse(&synth::stream(&deep)).unwrap_err(), Error::Limit("objects nested too deeply")); - // An array claiming four billion elements in a few bytes. - let huge = synth::stream(&[(tag(b"Big_"), F::Raw(vec![0x81, b'_', b'g', b'i', b'B', 0xff, 0xff, 0xff, 0xff, 0]))]); - assert_eq!(stream::parse(&huge).unwrap_err(), Error::Malformed("array longer than its data")); - let forward = synth::stream(&[(tag(b"Link"), F::Ref(99))]); - assert!(stream::parse(&forward).is_err()); - let twice = synth::stream(&[(tag(b"A___"), F::Def(1, vec![tag(b"RGBA")], vec![])), (tag(b"B___"), F::Def(1, vec![tag(b"RGBA")], vec![]))]); - assert!(stream::parse(&twice).is_err()); - let unknown = synth::stream(&[(tag(b"X___"), F::Raw(vec![0x0b, 1, 2, 3, 4]))]); - assert!(matches!(stream::parse(&unknown), Err(Error::Unsupported(_)))); - let d = doc(); - for end in 0..d.len() { - assert!(stream::parse(&d[..end]).is_err(), "{end}"); - } - } - - #[test] - fn fixed_records_of_zero_width_are_rejected_before_any_value_is_made() { - // Four million records of no bytes each pass a length check that multiplies by the width. - let mut f = vec![0x80 | 0x2c]; - f.extend(tag(b"Big_").0.to_le_bytes()); - f.extend(4_000_000u32.to_le_bytes()); - f.extend(0u16.to_le_bytes()); - let d = synth::stream(&[(tag(b"Big_"), F::Raw(f))]); - assert_eq!(stream::parse(&d).unwrap_err(), Error::Malformed("array longer than its data")); - } - - #[test] - fn a_small_compressed_entry_cannot_make_the_stream_allocate_gigabytes() { - // Each decoded value takes about 40 bytes, and a bool array packs eight in a byte: 16 MiB - // of zero bits, a few KiB once compressed, would ask for 2^27 values (about 4 GiB). An - // array of one-byte values just past the budget fails the same way, before allocating. - let field = |code: u8, n: u32, data: usize| { - let mut f = vec![0x80 | code]; - f.extend(tag(b"Big_").0.to_le_bytes()); - f.extend(n.to_le_bytes()); - f.resize(f.len() + data, 0); - F::Raw(f) - }; - let bools = 1u32 << 27; - let bytes = u32::try_from(stream::MAX_VALUES).unwrap() + 1; - for f in [field(0x29, bools, (bools / 8) as usize), field(0x01, bytes, bytes as usize)] { - let d = synth::stream(&[(tag(b"Big_"), f)]); - let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None); - assert!(file.len() < d.len() / 100, "{} of {}", file.len(), d.len()); - let entry = Archive::open(&file, Limits::default()).unwrap().read("doc.dat").unwrap(); - assert_eq!(stream::parse(&entry).unwrap_err(), Error::Limit("too many values in the document stream")); - } - } - - proptest! { - #![proptest_config(ProptestConfig::with_cases(512))] - #[test] - fn mutated_containers_and_streams_never_panic(edits in prop::collection::vec((0usize..4096, any::()), 1..24)) { - let d = doc(); - for method in [Method::Stored, Method::Zlib, Method::Zstd] { - let mut file = synth::container(&[("doc.dat", &d, method)], None); - for (i, v) in &edits { - let n = file.len(); - file[i % n] = *v; - } - if let Ok(bytes) = Archive::open(&file, Limits::default()).and_then(|mut a| a.read("doc.dat")) { - let _ = stream::parse(&bytes); - } - } - let mut s = d.clone(); - for (i, v) in &edits { - let n = s.len(); - s[i % n] = *v; - } - let _ = stream::parse(&s); - } - } -} - -mod shapes { - use crate::container::Limits; - use crate::model::{Document, Kind, Path, Point, SubPath}; - use crate::stream::Tag; - use crate::synth::{self, F, Method, tag}; - - fn shape(id: u32, class: &[u8; 4], parameters: Vec<(Tag, F)>) -> F { - F::Def( - id, - vec![tag(b"ShpN")], - vec![(tag(b"ShpB"), F::F64s(vec![0.0, 0.0, 10.0, 20.0])), (tag(b"Shpe"), F::Def(id + 10_000, vec![tag(class)], parameters))], - ) - } - - /// Reads a document whose one page holds the object `top` from `definitions`, on a thread of - /// its own, and fails the test when reading takes more than 20 s. - fn read(definitions: Vec, top: u32) -> Document { - let data = synth::stream(&[ - (tag(b"Defs"), F::Shared(definitions)), - ( - tag(b"DocR"), - F::Def( - 1, - vec![tag(b"DocN")], - vec![( - tag(b"Chld"), - F::Shared(vec![F::Def( - 2, - vec![tag(b"Sprd")], - vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 400.0, 300.0])), (tag(b"Chld"), F::Shared(vec![F::Ref(top)]))], - )]), - )], - ), - ), - ]); - let bytes = synth::container(&[("doc.dat", &data, Method::Zlib)], None); - let (tx, rx) = std::sync::mpsc::channel(); - std::thread::spawn(move || tx.send(crate::model::read(&bytes, Limits::default())).ok()); - rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap_or_else(|_| panic!("reading the document did not finish")).unwrap() - } - - #[test] - fn empty_subpaths_of_a_shared_curve_are_charged_for_every_occurrence() { - // One curve of 100k empty subpaths, placed 100 times: no records and no points, but - // ten million subpaths walked unless each one is charged. - let mut data = vec![F::U8(0), F::U32(100_000)]; - for _ in 0..100_000 { - data.extend([F::Bool(false), F::Records(18, Vec::new())]); - } - let curve = F::Def(5, vec![tag(b"PCrv")], vec![(tag(b"Crvs"), F::Obj(tag(b"PCvD"), vec![(tag(b"Data"), F::Pos(data))]))]); - let group = F::Def(6, vec![tag(b"Grup")], vec![(tag(b"Chld"), F::Shared((0..100).map(|_| F::Ref(5)).collect()))]); - let d = read(vec![curve, group], 6); - assert!(d.warnings.iter().any(|w| w.contains("curve geometry budget exhausted")), "{:?}", d.warnings); - } - - fn path(document: &Document) -> &Path { - match &document.spreads[0].nodes[0].kind { - Kind::Shape { path, .. } => path, - other => panic!("expected shape, got {other:?}"), - } - } - - #[test] - fn artistic_text_reads_its_characters_runs_and_anchor() { - let glyphs = F::Obj(tag(b"Glyp"), vec![(tag(b"Utf8"), F::Str("Hi".into()))]); - let run = F::Obj(tag(b"Item"), vec![]); - let attributes = F::Obj(tag(b"GAtt"), vec![(tag(b"Runs"), F::Objs(tag(b"Runs"), vec![vec![(tag(b"Indx"), F::I32(2)), (tag(b"Item"), run)]]))]); - let block = vec![(tag(b"Glyp"), glyphs), (tag(b"GAtt"), attributes)]; - let text = F::Def( - 100, - vec![tag(b"TxtA")], - vec![ - (tag(b"TxtH"), F::Obj(tag(b"ArFr"), vec![(tag(b"FrmB"), F::F64s(vec![0.0, 0.0, 100.0, 50.0]))])), - (tag(b"StSt"), F::Obj(tag(b"StSt"), vec![(tag(b"Blok"), F::Objs(tag(b"Blok"), vec![block]))])), - ], - ); - let document = read(vec![text], 100); - let Kind::Text(t) = &document.spreads[0].nodes[0].kind else { panic!("expected text") }; - assert_eq!(t.runs.len(), 1); - assert_eq!(t.runs[0].text, "Hi"); - assert_eq!(t.align, crate::model::Align::Left); - assert_eq!(t.anchor, Point { x: 0.0, y: 0.0 }); - assert!(t.frame.is_none()); - } - - #[test] - fn a_shared_story_placed_many_times_is_charged_against_the_text_budget() { - // One ~1 MiB story referenced 100 times would retain ~100 MiB of text without a budget. - let glyphs = F::Obj(tag(b"Glyp"), vec![(tag(b"Utf8"), F::Str("a".repeat((1 << 20) - 1)))]); - let run = F::Obj(tag(b"Item"), vec![]); - let attributes = F::Obj(tag(b"GAtt"), vec![(tag(b"Runs"), F::Objs(tag(b"Runs"), vec![vec![(tag(b"Indx"), F::I32(1 << 20)), (tag(b"Item"), run)]]))]); - let block = vec![(tag(b"Glyp"), glyphs), (tag(b"GAtt"), attributes)]; - let text = F::Def( - 100, - vec![tag(b"TxtA")], - vec![ - (tag(b"TxtH"), F::Obj(tag(b"ArFr"), vec![(tag(b"FrmB"), F::F64s(vec![0.0, 0.0, 100.0, 50.0]))])), - (tag(b"StSt"), F::Obj(tag(b"StSt"), vec![(tag(b"Blok"), F::Objs(tag(b"Blok"), vec![block]))])), - ], - ); - let group = F::Def(101, vec![tag(b"Grup")], vec![(tag(b"Chld"), F::Shared((0..100).map(|_| F::Ref(100)).collect()))]); - let d = read(vec![text, group], 101); - assert!(d.warnings.iter().any(|w| w.contains("document text budget")), "{:?}", d.warnings); - } - - #[test] - fn text_past_the_character_limit_is_not_charged_so_a_later_text_node_survives() { - // 64 references to one segment of 1 MiB + 1 characters: only the first is scanned (the - // block is cut at the character limit), so only that scan is charged to the text budget. - let frame = || (tag(b"TxtH"), F::Obj(tag(b"ArFr"), vec![(tag(b"FrmB"), F::F64s(vec![0.0, 0.0, 100.0, 50.0]))])); - let segment = F::Def(200, vec![tag(b"Segm")], vec![(tag(b"Utf8"), F::Str("a".repeat((1 << 20) + 1)))]); - let mut refs = vec![segment]; - refs.extend((0..63).map(|_| F::Ref(200))); - let big_block = vec![(tag(b"Glyp"), F::Obj(tag(b"Glyp"), vec![(tag(b"Mixd"), F::Shared(refs))]))]; - let big = - F::Def(100, vec![tag(b"TxtA")], vec![frame(), (tag(b"StSt"), F::Obj(tag(b"StSt"), vec![(tag(b"Blok"), F::Objs(tag(b"Blok"), vec![big_block]))]))]); - let run = F::Obj(tag(b"Item"), vec![]); - let attributes = F::Obj(tag(b"GAtt"), vec![(tag(b"Runs"), F::Objs(tag(b"Runs"), vec![vec![(tag(b"Indx"), F::I32(2)), (tag(b"Item"), run)]]))]); - let small_block = vec![(tag(b"Glyp"), F::Obj(tag(b"Glyp"), vec![(tag(b"Utf8"), F::Str("ok".into()))])), (tag(b"GAtt"), attributes)]; - let small = F::Def( - 101, - vec![tag(b"TxtA")], - vec![frame(), (tag(b"StSt"), F::Obj(tag(b"StSt"), vec![(tag(b"Blok"), F::Objs(tag(b"Blok"), vec![small_block]))]))], - ); - let group = F::Def(102, vec![tag(b"Grup")], vec![(tag(b"Chld"), F::Shared(vec![F::Ref(100), F::Ref(101)]))]); - let d = read(vec![big, small, group], 102); - assert!(!d.warnings.iter().any(|w| w.contains("document text budget")), "{:?}", d.warnings); - fn collect(nodes: &[crate::model::Node], out: &mut Vec) { - for n in nodes { - if let Kind::Text(t) = &n.kind { - out.push(t.runs.iter().map(|r| r.text.as_str()).collect()); - } - collect(&n.children, out); - } - } - let mut texts = Vec::new(); - collect(&d.spreads[0].nodes, &mut texts); - assert!(texts.iter().any(|t| t == "ok"), "{texts:?}"); - } - - #[test] - fn pie_angles_with_huge_finite_values_do_not_loop_or_emit_nonfinite_points() { - let document = read(vec![shape(100, b"ShPi", vec![(tag(b"AngS"), F::F64(1.0e308)), (tag(b"AngE"), F::F64(-1.0e308))])], 100); - for subpath in &path(&document).subpaths { - assert!(subpath.start.x.is_finite() && subpath.start.y.is_finite()); - assert!(subpath.segments.len() <= 20); - assert!(subpath.segments.iter().flatten().all(|point| point.x.is_finite() && point.y.is_finite())); - } - } - - #[test] - fn wrapped_pie_angles_keep_the_same_geometry_as_the_positive_span() { - let make = |end| read(vec![shape(100, b"ShPi", vec![(tag(b"AngS"), F::F64(0.0)), (tag(b"AngE"), F::F64(end))])], 100); - assert_eq!(path(&make(-std::f64::consts::FRAC_PI_2)), path(&make(3.0 * std::f64::consts::FRAC_PI_2))); - } - - /// A 10×20 rectangle (`ShNR`) with the given parameters, read back as its outline. - fn rectangle(parameters: Vec<(Tag, F)>) -> (SubPath, Vec) { - let node = - F::Def(3, vec![tag(b"ShpN")], vec![(tag(b"ShpB"), F::F64s(vec![0.0, 0.0, 10.0, 20.0])), (tag(b"Shpe"), F::Def(4, vec![tag(b"ShNR")], parameters))]); - let spread = F::Def(2, vec![tag(b"Sprd")], vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 400.0, 300.0])), (tag(b"Chld"), F::Shared(vec![node]))]); - let data = synth::stream(&[(tag(b"DocR"), F::Def(1, vec![tag(b"DocN")], vec![(tag(b"Chld"), F::Shared(vec![spread]))]))]); - let doc = crate::read(&synth::container(&[("doc.dat", &data, Method::Zlib)], None), Limits::default()).unwrap(); - let Kind::Shape { path, .. } = &doc.spreads[0].nodes[0].kind else { panic!("expected a shape") }; - (path.subpaths[0].clone(), doc.warnings) - } - - /// `CTyp`: an array of corner-type enums (top left, top right, bottom right, bottom left). - fn corner_types(ids: [u16; 4]) -> F { - let mut raw = vec![0xaa]; - raw.extend(tag(b"CTyp").0.to_le_bytes()); - raw.extend(4u32.to_le_bytes()); - raw.extend(0u16.to_le_bytes()); - raw.extend(ids.iter().flat_map(|id| id.to_le_bytes())); - F::Raw(raw) - } - - #[test] - fn unlocked_rectangle_corners_keep_their_own_radius_and_type() { - let p = |x: f64, y: f64| Point { x, y }; - // Relative radii scale by 10. Round 5, round 1, straight 3, none. - let corners = |lock: Option| { - let mut fields = vec![(tag(b"ShCR"), F::F64s(vec![0.5, 0.1, 0.3, 0.0])), (tag(b"CTyp"), corner_types([0, 0, 1, 4]))]; - fields.extend(lock.map(|l| (tag(b"Lock"), F::Bool(l)))); - rectangle(fields) - }; - - let (sub, warnings) = corners(Some(false)); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(sub.start, p(5.0, 0.0)); - let ends: Vec = sub.segments.iter().map(|s| s[2]).collect(); - assert_eq!(ends, [p(9.0, 0.0), p(10.0, 1.0), p(10.0, 17.0), p(7.0, 20.0), p(0.0, 20.0), p(0.0, 5.0), p(5.0, 0.0)]); - assert_eq!(sub.segments[3], [p(7.0, 20.0); 3], "the straight corner is a line"); - assert_ne!(sub.segments[1][0], p(9.0, 0.0), "the round corner is a curve"); - - // Locked (the default): every corner follows the top left one. - let (sub, _) = corners(None); - assert_eq!(sub.segments.len(), 8); - assert_eq!(sub.segments[3][2], p(5.0, 20.0)); - } -} - -/// Aggregate materialized-pixel admission (#4960). The entry limits bound what the archive -/// extracts; these cover what the decoded layers and their working planes cost, which is declared -/// by each bitmap's `BmpW`/`BmpH` and needs no tile data at all. -mod pixels { - use crate::Error; - use crate::container::Limits; - use crate::model::{Document, Kind}; - use crate::synth::{self, F, Method, tag}; - - /// A `Rstr` pixel layer whose bitmap declares `w`×`h` pixels and holds no tiles. - fn layer(id: u32, w: i32, h: i32) -> F { - F::Def( - id, - vec![tag(b"Rstr")], - vec![ - (tag(b"Desc"), F::Str(format!("Layer {id}"))), - (tag(b"Bitm"), F::Def(id + 1, vec![tag(b"DyBm")], vec![(tag(b"BmpW"), F::I32(w)), (tag(b"BmpH"), F::I32(h)), (tag(b"Frmt"), F::Enum(0, 0))])), - ], - ) - } - - /// A document whose one page holds a pixel layer per `sizes` entry. - fn document(sizes: &[(i32, i32)]) -> Vec { - let children: Vec = sizes.iter().enumerate().map(|(i, &(w, h))| layer(10 + 2 * i as u32, w, h)).collect(); - let data = synth::stream(&[( - tag(b"DocR"), - F::Def( - 1, - vec![tag(b"DocN")], - vec![( - tag(b"Chld"), - F::Shared(vec![F::Def( - 2, - vec![tag(b"Sprd")], - vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 256.0, 256.0])), (tag(b"Chld"), F::Shared(children))], - )]), - )], - ), - )]); - synth::container(&[("doc.dat", &data, Method::Zlib)], None) - } - - fn imported_layers(d: &Document) -> usize { - d.spreads[0].nodes.iter().filter(|n| matches!(n.kind, Kind::Image(_))).count() - } - - /// A 64×64 layer costs 16 KiB of RGBA and 16 KiB of planes, so 40 KiB admits one and not two. - const ONE_LAYER: usize = 40 << 10; - - #[test] - fn a_pixel_layer_within_the_budget_imports() { - let limits = Limits { max_pixel_bytes: ONE_LAYER, ..Limits::default() }; - let d = crate::model::read(&document(&[(64, 64)]), limits).unwrap(); - assert_eq!(imported_layers(&d), 1, "{:?}", d.warnings); - } - - #[test] - fn layers_past_the_pixel_budget_are_rejected_before_they_are_allocated() { - let limits = Limits { max_pixel_bytes: ONE_LAYER, ..Limits::default() }; - // The document is a few hundred bytes: the sizes are in the headers, not the entries. - let bytes = document(&[(64, 64), (64, 64)]); - assert!(bytes.len() < 4096, "the fixture is {} bytes", bytes.len()); - assert!(matches!(crate::model::read(&bytes, limits), Err(Error::Limit(_))), "the second layer materialized"); - // Two layers fit once the budget covers their pixels together. - let room = Limits { max_pixel_bytes: ONE_LAYER + (32 << 10), ..Limits::default() }; - assert_eq!(imported_layers(&crate::model::read(&bytes, room).unwrap()), 2); - } - - #[test] - fn a_declared_size_larger_than_the_budget_is_rejected_on_its_own() { - // 2048×2048 is 16 MiB of RGBA and 16 MiB of planes, past a 1 MiB budget. - let limits = Limits { max_pixel_bytes: 1 << 20, ..Limits::default() }; - assert!( - matches!(crate::model::read(&document(&[(2048, 2048)]), limits), Err(Error::Limit(_))), - "16 MiB of declared pixels materialized under a 1 MiB budget" - ); - } -} - -/// Spot colours that link to themselves or to each other. Each document is read on a 1 MiB -/// stack, the smallest main-thread stack PhotoCraft runs on (Windows), first in a child process -/// that must finish within 20 s. A stack overflow aborts the process it happens in, so unbounded -/// recursion fails the one test that caused it instead of taking the other tests in the binary -/// down with it. -mod spot_colours { - use std::io::{Read, Write}; - use std::process::{Command, Stdio}; - use std::time::{Duration, Instant}; - - use crate::container::Limits; - use crate::model::{Document, Kind}; - use crate::paint::{Color, Paint}; - use crate::stream::Tag; - use crate::synth::{self, F, Method, tag}; - - /// A one-page document whose page holds `top`, read in a child process first and then here. - fn read(top: Vec) -> Document { - let spread = F::Def(2, vec![tag(b"Sprd")], vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 400.0, 300.0])), (tag(b"Chld"), F::Shared(top))]); - let data = synth::stream(&[(tag(b"DocR"), F::Def(1, vec![tag(b"DocN")], vec![(tag(b"Chld"), F::Shared(vec![spread]))]))]); - let bytes = synth::container(&[("doc.dat", &data, Method::Zlib)], None); - let test = std::thread::current().name().unwrap_or("reader").to_owned(); - read_in_child(&bytes, &test); - read_on_small_stack(bytes, &test).unwrap() - } - - /// Reads on a 1 MiB thread named after the test, so a stack overflow message names the test. - fn read_on_small_stack(bytes: Vec, test: &str) -> Result { - let reader = std::thread::Builder::new().name(test.to_owned()).stack_size(1 << 20).spawn(move || crate::read(&bytes, Limits::default())).unwrap(); - reader.join().unwrap_or_else(|panic| std::panic::resume_unwind(panic)) - } - - /// Set in the child process to the name of the test it reads for. - const CHILD: &str = "PHOTOCRAFT_AFFINITY_READ_CHILD"; - - /// Runs `read_child` in a new process of this test binary on `bytes` and fails the test if - /// that process crashes, panics or takes over 20 s, or never read the document. - fn read_in_child(bytes: &[u8], test: &str) { - let mut child = Command::new(std::env::current_exe().unwrap()) - .args(["tests::spot_colours::read_child", "--exact", "--ignored", "--nocapture", "--test-threads=1"]) - .env(CHILD, test) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let drain = |mut pipe: Box| { - std::thread::spawn(move || { - let mut text = String::new(); - let _ = pipe.read_to_string(&mut text); - text - }) - }; - let stdout = drain(Box::new(child.stdout.take().unwrap())); - let stderr = drain(Box::new(child.stderr.take().unwrap())); - // Fed from a thread, so a child that never reads cannot block the deadline below; a child - // that dies first breaks the pipe and is reported by its exit status. - let (mut stdin, input) = (child.stdin.take().unwrap(), bytes.to_vec()); - let feed = std::thread::spawn(move || { - let _ = stdin.write_all(&input); - }); - let deadline = Instant::now() + Duration::from_secs(20); - let status = loop { - if let Some(status) = child.try_wait().unwrap() { - break Some(status); - } - if Instant::now() >= deadline { - let _ = child.kill(); - let _ = child.wait(); - break None; - } - std::thread::sleep(Duration::from_millis(10)); - }; - feed.join().unwrap(); - let output = format!("{}{}", stdout.join().unwrap(), stderr.join().unwrap()); - match status { - None => panic!("reading the document did not finish within 20 s:\n{output}"), - Some(status) if !status.success() => panic!("reading the document failed in a child process ({status}):\n{output}"), - // A filter that matched no test would also exit successfully, having read nothing. - Some(_) => assert!(output.contains(&format!("read {} bytes", bytes.len())), "the child process did not read the document:\n{output}"), - } - } - - /// Not a test of its own: `read_in_child` runs it in a child process to read the document on - /// its stdin. Without the variable, as when run with `--ignored`, it does nothing. - #[test] - #[ignore = "run by read_in_child in a child process"] - fn read_child() { - let Some(test) = std::env::var_os(CHILD) else { return }; - let mut bytes = Vec::new(); - std::io::stdin().read_to_end(&mut bytes).unwrap(); - let len = bytes.len(); - let _ = read_on_small_stack(bytes, &test.to_string_lossy()); - println!("read {len} bytes"); - } - - /// An ellipse filled with `colour`. - fn filled(id: u32, colour: F) -> F { - F::Def( - id, - vec![tag(b"ShpN")], - vec![ - (tag(b"ShpB"), F::F64s(vec![0.0, 0.0, 1.0, 1.0])), - (tag(b"Shpe"), F::Def(id + 1_000_000, vec![tag(b"ShpE")], vec![])), - (tag(b"BFFl"), F::Shared(vec![F::Def(id + 2_000_000, vec![tag(b"FilS")], vec![(tag(b"Colr"), colour)])])), - ], - ) - } - - fn spot(id: u32, fields: Vec<(Tag, F)>) -> F { - F::Def(id, vec![tag(b"Pant")], fields) - } - - fn fills(doc: &Document) -> &[Paint] { - match &doc.spreads[0].nodes[0].kind { - Kind::Shape { fills, .. } => fills, - other => panic!("expected a shape, got {other:?}"), - } - } - - fn warned(doc: &Document, what: &str) -> bool { - doc.warnings.iter().any(|w| w.contains(what)) - } - - #[test] - fn a_spot_colour_that_is_its_own_rgb_equivalent_is_refused() { - let doc = read(vec![filled(10, spot(20, vec![(tag(b"srgb"), F::Ref(20))]))]); - assert!(fills(&doc).is_empty(), "{:?}", fills(&doc)); - assert!(warned(&doc, "spot colours nested deeper than 4 levels"), "{:?}", doc.warnings); - } - - #[test] - fn spot_colours_that_are_each_others_base_and_rgb_equivalent_are_refused() { - let doc = read(vec![filled(10, spot(20, vec![(tag(b"base"), spot(21, vec![(tag(b"srgb"), F::Ref(20))]))]))]); - assert!(fills(&doc).is_empty(), "{:?}", fills(&doc)); - assert!(warned(&doc, "spot colours nested deeper than 4 levels"), "{:?}", doc.warnings); - } - - #[test] - fn spot_colours_of_spot_colours_do_not_take_exponential_time() { - // Each level's RGB equivalent and base are the next level, and the last is in an unknown - // model, so both are followed everywhere: 2^41 colour reads before the fix. - fn level(id: u32, left: u32) -> F { - if left == 0 { - return F::Def(id, vec![tag(b"XXXX")], vec![]); - } - spot(id, vec![(tag(b"srgb"), level(id + 1, left - 1)), (tag(b"base"), F::Ref(id + 1))]) - } - let doc = read(vec![filled(10, level(100, 40))]); - assert!(fills(&doc).is_empty(), "{:?}", fills(&doc)); - } - - /// `spots` spot colours, each defined through the next, around an opaque RGB colour. - fn spots(id: u32, spots: u32) -> F { - if spots == 0 { - let rgba: Vec = [1.0f32, 0.5, 0.25, 1.0].iter().flat_map(|c| c.to_le_bytes()).collect(); - return F::Def(id, vec![tag(b"RGBA")], vec![(tag(b"_col"), F::Struct(rgba))]); - } - spot(id, vec![(tag(b"srgb"), self::spots(id + 1, spots - 1))]) - } - - #[test] - fn spot_colours_nest_four_levels_and_no_deeper() { - let doc = read(vec![filled(10, spots(100, 4))]); - assert_eq!(fills(&doc), [Paint::Solid(Color::Rgb { r: 1.0, g: 0.5, b: 0.25, a: 1.0 })]); - let doc = read(vec![filled(10, spots(100, 5))]); - assert!(fills(&doc).is_empty(), "{:?}", fills(&doc)); - assert!(warned(&doc, "spot colours nested deeper than 4 levels"), "{:?}", doc.warnings); - } -} - -/// The raster fast paths against the code they replaced. -mod raster_identity { - use crate::raster::{copy, interleave}; - - /// Deterministic filler (xorshift). - fn bytes(n: usize, mut x: u64) -> Vec { - (0..n) - .map(|_| { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - (x >> 24) as u8 - }) - .collect() - } - - /// The per-pixel `f64` conversion `decode` used before the tables. - fn reference(planes: &[Vec], channels: usize, bps: usize, n: usize) -> Vec { - let sample = |p: &Vec, i: usize| -> f64 { - if bps == 2 { - f64::from(u16::from_le_bytes([p.get(2 * i).copied().unwrap_or(0), p.get(2 * i + 1).copied().unwrap_or(0)])) / 65535.0 - } else { - f64::from(p.get(i).copied().unwrap_or(0)) / 255.0 - } - }; - let mut rgba = vec![0u8; n * 4]; - for (i, px) in rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() { - let v: Vec = planes.iter().map(|p| sample(p, i)).collect(); - let (r, g, b, a) = if channels == 1 { - (v[0], v[0], v[0], 1.0) - } else if channels == 5 { - let k = 1.0 - v[3]; - ((1.0 - v[0]) * k, (1.0 - v[1]) * k, (1.0 - v[2]) * k, v[4]) - } else { - (v[0], v[1], v[2], v[3]) - }; - px.copy_from_slice(&[r, g, b, a].map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8)); - } - rgba - } - - #[test] - fn eight_bit_samples_round_trip() { - // Every byte through every position of the 4-channel and the grey path. - let ramp: Vec = (0..=255).collect(); - let planes = vec![ramp.clone(), ramp.iter().rev().copied().collect(), ramp.clone(), ramp.iter().rev().copied().collect()]; - assert_eq!(interleave(&planes, 4, 1, 256), reference(&planes, 4, 1, 256)); - assert_eq!(interleave(&planes[..1], 1, 1, 256), reference(&planes[..1], 1, 1, 256)); - } - - #[test] - fn sixteen_bit_samples_are_exhaustive() { - // All 65536 values in each channel position (rotated so the channels differ). - let all: Vec = (0..=u16::MAX).flat_map(u16::to_le_bytes).collect(); - let rot = |k: usize| -> Vec { (0..=u16::MAX).flat_map(|v| v.wrapping_add((k * 4099) as u16).to_le_bytes()).collect() }; - let planes = vec![all, rot(1), rot(2), rot(3)]; - assert_eq!(interleave(&planes, 4, 2, 65536), reference(&planes, 4, 2, 65536)); - assert_eq!(interleave(&planes[..1], 1, 2, 65536), reference(&planes[..1], 1, 2, 65536)); - } - - #[test] - fn cmyk_is_exhaustive_over_colour_and_black() { - // Every (c, k) pair in each of the c, m and y positions; alpha is arbitrary. - let n = 256 * 256; - let k: Vec = (0..n).map(|i| (i >> 8) as u8).collect(); - let c: Vec = (0..n).map(|i| i as u8).collect(); - let m: Vec = (0..n).map(|i| (i as u8).wrapping_mul(7).wrapping_add(3)).collect(); - let y: Vec = (0..n).map(|i| (i as u8).wrapping_mul(13).wrapping_add(250)).collect(); - let planes = vec![c, m, y, k, bytes(n, 9)]; - assert_eq!(interleave(&planes, 5, 1, n), reference(&planes, 5, 1, n)); - } - - #[test] - fn random_planes_match_for_every_format() { - for (channels, bps) in [(1, 1), (1, 2), (4, 1), (4, 2), (5, 1)] { - let n = 5000; - let planes: Vec> = (0..channels).map(|c| bytes(n * bps, 1 + c as u64)).collect(); - assert_eq!(interleave(&planes, channels, bps, n), reference(&planes, channels, bps, n), "{channels}x{bps}"); - } - } - - /// The per-byte closure copy `plane` used before the row copies. - fn copy_reference( - out: &mut [u8], - row: usize, - (bx0, py0, bx1, py1): (usize, usize, usize, usize), - (ox, oy): (usize, usize), - at: impl Fn(usize, usize) -> u8, - ) { - for y in oy.max(py0)..(oy + 256).min(py1) { - for x in ox.max(bx0)..(ox + 256).min(bx1) { - if let Some(b) = out.get_mut((y - py0) * row + (x - bx0)) { - *b = at(x - ox, y - oy); - } - } - } - } - - #[test] - fn tile_copy_matches_the_byte_loop_for_every_crop() { - let tile = bytes(256 * 256, 77); - // Crops that cut the tile on each side, sit inside it, and miss it. - for &(bx0, bx1, py0, py1) in - &[(0, 600, 0, 600), (10, 300, 20, 200), (100, 150, 100, 130), (256, 512, 0, 256), (0, 256, 300, 400), (255, 257, 255, 257), (300, 301, 0, 1)] - { - for &(ox, oy) in &[(0, 0), (256, 0), (0, 256), (256, 256), (512, 256)] { - let row = bx1 - bx0; - let mut old = vec![0xAAu8; row * (py1 - py0)]; - let mut new = old.clone(); - copy_reference(&mut old, row, (bx0, py0, bx1, py1), (ox, oy), |x, y| tile[y * 256 + x]); - copy(&mut new, row, (bx0, py0, bx1, py1), (ox, oy), Some(&tile), 0); - assert_eq!(old, new, "tile {ox},{oy} crop {bx0}..{bx1} x {py0}..{py1}"); - copy_reference(&mut old, row, (bx0, py0, bx1, py1), (ox, oy), |_, _| 0xFF); - copy(&mut new, row, (bx0, py0, bx1, py1), (ox, oy), None, 0xFF); - assert_eq!(old, new, "fill {ox},{oy} crop {bx0}..{bx1} x {py0}..{py1}"); - } - } - } -} - -/// `Archive::read_many` against the same reads made one at a time. -mod read_many { - use crate::synth::{self, Method}; - use crate::{Archive, Error, Limits}; - - fn entry(i: usize) -> Vec { - (0..4096 + i * 37).map(|b| (b * 31 + i * 7) as u8).collect() - } - - fn archive(count: usize, method: Method) -> Vec { - let datas: Vec> = (0..count).map(entry).collect(); - let names: Vec = (0..count).map(|i| format!("d/{i}")).collect(); - let entries: Vec<(&str, &[u8], Method)> = names.iter().zip(&datas).map(|(n, d)| (n.as_str(), d.as_slice(), method)).collect(); - synth::container(&entries, None) - } - - #[test] - fn matches_serial_reads_and_charges_the_same() { - for method in [Method::Stored, Method::Zlib, Method::Zstd] { - for count in [1, 3, 4, 5, 40] { - let file = archive(count, method); - let names: Vec = (0..count).map(|i| format!("d/{i}")).collect(); - let names: Vec<&str> = names.iter().map(String::as_str).collect(); - let mut one = Archive::open(&file, Limits::default()).unwrap(); - let serial: Vec> = names.iter().map(|n| one.read(n).unwrap()).collect(); - let mut many = Archive::open(&file, Limits::default()).unwrap(); - assert_eq!(many.read_many(&names).unwrap(), serial); - assert_eq!(many.extracted(), one.extracted()); - assert_eq!(serial[count - 1], entry(count - 1)); - } - } - } - - #[test] - fn the_limit_stops_at_the_same_entry_as_serial_reads() { - let file = archive(12, Method::Zstd); - let names: Vec = (0..12).map(|i| format!("d/{i}")).collect(); - let names: Vec<&str> = names.iter().map(String::as_str).collect(); - let limits = Limits { max_total: (0..7).map(|i| entry(i).len()).sum(), ..Limits::default() }; - let mut one = Archive::open(&file, limits).unwrap(); - let failed = names.iter().position(|n| one.read(n).is_err()).unwrap(); - assert_eq!(failed, 7); - let mut many = Archive::open(&file, limits).unwrap(); - assert!(matches!(many.read_many(&names), Err(Error::Limit(_)))); - assert_eq!(many.extracted(), one.extracted()); - } - - #[test] - fn the_first_failing_entry_in_order_is_reported() { - let mut file = archive(12, Method::Stored); - // Flip a data byte of entry 2 (checksum failure); entry 9 is missing from the list. - let at = file.windows(4).position(|w| w == b"#Fil").unwrap(); - let second = at + 4 + entry(0).len(); - let third = second + 4 + entry(1).len(); - file[third + 4 + 10] ^= 0xFF; - let names: Vec = (0..12).map(|i| if i == 9 { "gone".to_string() } else { format!("d/{i}") }).collect(); - let names: Vec<&str> = names.iter().map(String::as_str).collect(); - let mut a = Archive::open(&file, Limits::default()).unwrap(); - assert_eq!(a.read_many(&names).unwrap_err(), Error::Malformed("archive entry checksum mismatch")); - // Without the corrupt entry the missing one is what fails. - let intact = archive(12, Method::Stored); - let mut a = Archive::open(&intact, Limits::default()).unwrap(); - assert_eq!(a.read_many(&names).unwrap_err(), Error::Malformed("missing archive entry")); - } -} - -/// Object lookup and record arrays against the structures they replaced. -mod stream_storage { - use crate::stream::{self, Kind, Object, Tag, Value}; - use crate::synth::{self, F, tag}; - - /// The per-object map `Object::get` used before: first occurrence of each real tag. - fn reference(fields: &[(Tag, Value)], t: Tag) -> Option<&Value> { - let mut index = std::collections::HashMap::new(); - for (i, (ft, _)) in fields.iter().enumerate() { - if ft.0 != 0 { - index.entry(*ft).or_insert(i); - } - } - index.get(&t).map(|&i| &fields[i].1) - } - - #[test] - fn lookup_keeps_first_match_for_every_object_size() { - for n in 0..60u32 { - // Tags repeat (n % 7 distinct tags) and every fifth field is positional (tag 0). - let fields: Vec<(Tag, Value)> = (0..n).map(|i| (if i % 5 == 0 { Tag(0) } else { Tag(100 + i % 7) }, Value::UInt(u64::from(i)))).collect(); - let object = Object::new(Tag(1), Kind::Inline, vec![Tag(1)], fields.clone()); - for t in 0..120 { - assert_eq!(object.get(Tag(t)), reference(&fields, Tag(t)), "{n} fields, tag {t}"); - } - } - } - - #[test] - fn last_lookup_keeps_last_match_for_every_object_size() { - for n in 0..60u32 { - let fields: Vec<(Tag, Value)> = (0..n).map(|i| (if i % 5 == 0 { Tag(0) } else { Tag(100 + i % 7) }, Value::UInt(u64::from(i)))).collect(); - let object = Object::new(Tag(1), Kind::Inline, vec![Tag(1)], fields.clone()); - for t in 0..120 { - let expected = if t == 0 { None } else { fields.iter().rev().find(|(k, _)| *k == Tag(t)).map(|(_, v)| v) }; - assert_eq!(object.get_last(Tag(t)), expected, "{n} fields, tag {t}"); - } - } - } - - #[test] - fn a_fixed_size_array_is_one_buffer_and_one_value_per_record() { - let records: Vec = (0..18 * 5).map(|i| i as u8).collect(); - let bytes = synth::stream(&[(tag(b"Nods"), F::Records(18, records.chunks(18).map(<[u8]>::to_vec).collect()))]); - let s = stream::parse(&bytes).unwrap(); - let root = s.object(s.root).unwrap(); - assert_eq!(root.get(Tag::of(b"Nods")), Some(&Value::Records { size: 18, data: records })); - assert_eq!(root.get(Tag::of(b"Nods")).and_then(Value::array_len), Some(5)); - } -} diff --git a/crates/affinity/src/text.rs b/crates/affinity/src/text.rs deleted file mode 100644 index 7403d99f6e..0000000000 --- a/crates/affinity/src/text.rs +++ /dev/null @@ -1,244 +0,0 @@ -//! Artistic and frame text: the story's characters with their font, size, colour, tracking and -//! leading, the paragraph alignment and the first baseline. Layout (line breaks in frames, kerning, -//! OpenType features) is left to the importing application. - -use crate::model::{Affine, Align, Point, Reader, Text, TextRun, rect}; -use crate::paint::{self, Paint}; -use crate::stream::{ObjId, Stream, Value}; - -/// Characters read per text node (stories are split into blocks; this caps hostile ones). -const MAX_CHARS: usize = 1 << 20; - -pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option { - let s = r.s; - let story = s.obj(id, b"StSt")?; - let frame = s.obj(id, b"TxtH")?; - let artistic = s.is(frame, b"ArFr"); - let bounds = s.floats::<4>(frame, b"FrmB").map(rect)?; - let mut runs = Vec::new(); - let mut align = None; - let mut total = 0usize; - let mut placeholders = false; - // Shared structures are traversed once per occurrence: charge the raw slots (nulls and empty - // blocks included) before collecting them, against a document-wide budget. - if !r.charge_text(s.array_len(story, b"Blok").unwrap_or(0)) { - r.warn("text beyond the document text budget (left out)"); - return None; - } - 'blocks: for block in s.objs(story, b"Blok") { - let glyphs = s.obj(block, b"Glyp")?; - let runs_n = s.obj(block, b"GAtt").and_then(|g| s.array_len(g, b"Runs")).unwrap_or(0); - if !r.charge_text(1 + runs_n + s.array_len(glyphs, b"Mixd").unwrap_or(0)) { - r.warn("text beyond the document text budget (truncated)"); - break; - } - // Applied to `align` only once this block passes the character limit below, so a discarded - // block does not set the alignment of the text kept from earlier blocks. - // Scanning the paragraph runs (null slots included) is charged before it is done. - let mut block_align = None; - if align.is_none() - && let Some(p) = s.obj(block, b"PAtt") - { - if r.charge_text(s.array_len(p, b"Runs").unwrap_or(0)) { - block_align = s.objs(p, b"Runs").first().copied().and_then(|run| s.obj(run, b"Item")).map(|p| paragraph_align(r, p)); - } else { - r.warn("text beyond the document text budget (paragraph alignment left out)"); - } - } - // `block_chars` scans the `Utf8` string, or walks each segment's `Glys` slots (nulls included) and `Utf8` text, and stops at the character limit: charge only that scan, first. - let slots = scan_cost(s, glyphs, room(total)); - if !r.charge_text(slots) { - r.warn("text beyond the document text budget (truncated)"); - break; - } - let chars = block_chars(s, glyphs, total, &mut placeholders); - total = total.checked_add(chars.len())?; - if total > MAX_CHARS { - r.warn("text longer than a million characters (truncated)"); - break; - } - if align.is_none() { - align = block_align; - } - let mut start = 0usize; - for run in s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default() { - let end = usize::try_from(s.int(run, b"Indx")?).ok()?.min(chars.len()); - if end <= start { - continue; - } - let text: String = chars.get(start..end)?.iter().filter(|c| **c != '\0' && **c != '\u{FFFC}').collect(); - start = end; - let Some(attrs) = s.obj(run, b"Item") else { continue }; - if !text.is_empty() { - if !r.charge_text(text.len()) { - r.warn("text beyond the document text budget (truncated)"); - break 'blocks; - } - runs.push(run_attrs(r, attrs, text, world)); - } - } - } - if placeholders { - r.warn("text fields such as page numbers (left out of the text)"); - } - let align = align.unwrap_or(Align::Left); - let first_baseline = bounds.y0 + s.f64(frame, b"ArtV").unwrap_or(0.0); - let anchor_x = match align { - Align::Center => (bounds.x0 + bounds.x1) / 2.0, - Align::Right => bounds.x1, - _ => bounds.x0, - }; - if !artistic { - if s.objs(frame, b"ColW").len() > 1 || s.array_len(frame, b"ColW").is_some_and(|n| n > 1) { - r.warn("text frames with several columns (imported as one column)"); - } - if s.class(id) == Some(crate::stream::Tag::of(b"TxtC")) { - r.warn("text frames with a curved outline (imported as rectangular frames)"); - } - } - Some(Text { runs, align, anchor: Point { x: anchor_x, y: first_baseline }, frame: if artistic { None } else { Some(bounds) }, transform: world }) -} - -/// One past the allowance is enough to trip the check in `read`; `block_chars` stops there. -fn room(total: usize) -> usize { - MAX_CHARS.saturating_sub(total).saturating_add(1) -} - -/// The bytes of `t` that holding `want` characters of it scans, and the characters taken. -fn prefix(t: &str, want: usize) -> (usize, usize) { - t.char_indices().enumerate().find(|(n, _)| *n == want).map_or((t.len(), t.chars().count()), |(n, (i, _))| (i, n)) -} - -/// What `block_chars` scans for a block, in the units `charge_text` takes: the `Utf8` bytes it -/// reads, or per segment its `Glys` slots (nulls included) and the `Utf8` bytes it reads, up to the -/// character allowance `room`; text past it is never scanned, so it is not charged. -fn scan_cost(s: &Stream, glyphs: ObjId, room: usize) -> usize { - if let Some(t) = s.str(glyphs, b"Utf8") { - return prefix(t, room).0; - } - let (mut len, mut cost) = (0usize, 0usize); - for seg in s.objs(glyphs, b"Mixd") { - if len >= room { - break; - } - let inline = s.objs(seg, b"Glys").len(); - len += inline.min(room - len); - cost = cost.saturating_add(s.array_len(seg, b"Glys").unwrap_or(0)); - let (bytes, chars) = prefix(s.str(seg, b"Utf8").unwrap_or_default(), room.saturating_sub(len)); - len += chars; - cost = cost.saturating_add(bytes); - } - cost -} - -/// The characters of one text block. A block without a UTF-8 string is a list of segments: each -/// inline object (page number, anchor) takes one `U+FFFC` before its segment's text. Stops once -/// `total` plus these characters would pass the cap. -fn block_chars(s: &Stream, glyphs: ObjId, total: usize, placeholders: &mut bool) -> Vec { - let room = room(total); - match s.str(glyphs, b"Utf8") { - Some(t) => t.chars().take(room).collect(), - None => { - // Inline objects (page numbers, anchors) each take one index before the segment text. - let mut v = Vec::new(); - // Shared segments repeated by reference must not expand beyond the allowance first. - for seg in s.objs(glyphs, b"Mixd") { - if v.len() >= room { - break; - } - let inline = s.objs(seg, b"Glys").len(); - v.extend(std::iter::repeat_n('\u{FFFC}', inline.min(room - v.len()))); - *placeholders |= inline > 0; - v.extend(s.str(seg, b"Utf8").unwrap_or_default().chars().take(room.saturating_sub(v.len()))); - } - v - } - } -} - -fn slot(v: Option<&Value>, i: usize, f: impl Fn(&Value) -> Option) -> Option { - match v? { - Value::Array(a) => a.get(i).and_then(f), - _ => None, - } -} - -fn float(v: &Value) -> Option { - match v { - Value::Float(f) if f.is_finite() => Some(*f), - _ => None, - } -} - -fn int(v: &Value) -> Option { - match v { - Value::Int(i) => Some(*i), - Value::UInt(u) => i64::try_from(*u).ok(), - _ => None, - } -} - -/// Longest font name kept; real PostScript and family names are far shorter. -const MAX_FONT_NAME: usize = 256; - -/// A font name for one run. Runs repeat the same shared string, so its copies are charged -/// against a document-wide byte budget; an overlong name or an exhausted budget leaves it empty. -fn font_name(r: &mut Reader, font: Option, tag: &[u8; 4]) -> String { - let name = font.and_then(|f| r.s.str(f, tag)).unwrap_or_default(); - if name.len() > MAX_FONT_NAME { - r.warn("font names longer than 256 bytes (left empty)"); - return String::new(); - } - if !r.charge_font_name(name.len()) { - r.warn("font names beyond the document metadata budget (left empty)"); - return String::new(); - } - name.to_string() -} - -fn run_attrs(r: &mut Reader, attrs: ObjId, text: String, world: Affine) -> TextRun { - let s = r.s; - let doubles = s.field(attrs, b"Doub"); - let ints = s.field(attrs, b"Ints"); - let size = slot(doubles, 0, float).filter(|v| *v > 0.0 && *v < 1e6).unwrap_or(12.0 * r.dpi / 72.0); - let tracking = slot(doubles, 4, float).unwrap_or(0.0); - let leading = (slot(ints, 4, int) == Some(1)).then(|| slot(doubles, 13, float)).flatten().filter(|v| *v > 0.0); - let objects = match s.field(attrs, b"Objs") { - Some(Value::Array(a)) => a.iter().map(|v| if let Value::Obj(o) = v { *o } else { None }).collect(), - _ => Vec::new(), - }; - let fill = objects.first().copied().flatten().and_then(|f| paint::descriptor(r, f, world)).unwrap_or(Paint::None); - if objects.get(1).copied().flatten().and_then(|f| paint::descriptor(r, f, world)).is_some_and(|p| p != Paint::None) { - r.warn("outlined (stroked) text"); - } - if slot(doubles, 10, float).is_some_and(|h| (h - 1.0).abs() > 1e-3) { - r.warn("horizontally scaled text"); - } - let font = s.obj(attrs, b"DFnt"); - let postscript = font_name(r, font, b"Post"); - let family = font_name(r, font, b"Famy"); - TextRun { - text, - postscript, - family, - weight: font.and_then(|f| s.int(f, b"Wegt")).unwrap_or(400), - italic: font.and_then(|f| s.bool(f, b"Ital")).unwrap_or(false), - size, - tracking, - leading, - fill, - } -} - -fn paragraph_align(r: &mut Reader, p: ObjId) -> Align { - match slot(r.s.field(p, b"Ints"), 0, int) { - Some(1) => Align::Center, - Some(2) => Align::Right, - Some(3) => Align::Justify, - Some(0) | None => Align::Left, - Some(_) => { - r.warn("an unknown paragraph alignment (imported as left)"); - Align::Left - } - } -} diff --git a/crates/affinity/tests/it/compound_limits.rs b/crates/affinity/tests/it/compound_limits.rs deleted file mode 100644 index 6801f7f6d6..0000000000 --- a/crates/affinity/tests/it/compound_limits.rs +++ /dev/null @@ -1,214 +0,0 @@ -//! #6423: compound operands form a graph, not necessarily a tree. -#![cfg(feature = "synth")] -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - -use photocraft_affinity::model::{Document, Kind}; -use photocraft_affinity::synth::{self, F, Method, tag}; -use photocraft_affinity::{Limits, read}; -use std::time::{Duration, Instant}; - -fn compound(id: u32, children: Vec) -> F { - F::Def(id, vec![tag(b"Comp")], vec![(tag(b"Chld"), F::Shared(children))]) -} - -fn rectangle() -> F { - F::Def(100, vec![tag(b"ShpN")], vec![(tag(b"ShpB"), F::F64s(vec![0.0, 0.0, 10.0, 20.0])), (tag(b"Shpe"), F::Def(101, vec![tag(b"ShNR")], vec![]))]) -} - -fn document_bytes(definitions: Vec, roots: Vec) -> Vec { - let data = synth::stream(&[ - (tag(b"Defs"), F::Shared(definitions)), - ( - tag(b"DocR"), - F::Def( - 1, - vec![tag(b"DocN")], - vec![( - tag(b"Chld"), - F::Shared(vec![F::Def( - 2, - vec![tag(b"Sprd")], - vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 400.0, 300.0])), (tag(b"Chld"), F::Shared(roots))], - )]), - )], - ), - ), - ]); - synth::container(&[("doc.dat", &data, Method::Zlib)], None) -} - -fn document(definitions: Vec, roots: Vec) -> Document { - read(&document_bytes(definitions, roots), Limits::default()).unwrap() -} - -// A stack overflow aborts rather than unwinds. Keep that failure (and an exponential hang) -// inside a child process, so the regression fails without killing the entire test runner. -fn isolated(name: &str, check: impl FnOnce()) { - if std::env::var("PHOTOCRAFT_COMPOUND_CASE").as_deref() == Ok(name) { - check(); - return; - } - // The harness names a test by its module path below the crate root. - let test = module_path!().split_once("::").map_or(name.to_string(), |(_, m)| format!("{m}::{name}")); - let mut child = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", &test, "--nocapture"]) - .env("PHOTOCRAFT_COMPOUND_CASE", name) - .spawn() - .unwrap(); - let start = Instant::now(); - loop { - if let Some(status) = child.try_wait().unwrap() { - assert!(status.success(), "compound import failed: {status}"); - break; - } - if start.elapsed() > Duration::from_secs(10) { - child.kill().unwrap(); - child.wait().unwrap(); - panic!("compound import exceeded ten seconds"); - } - std::thread::sleep(Duration::from_millis(20)); - } -} - -fn unsupported(doc: &Document, warning: &str) { - assert!(matches!(doc.spreads[0].nodes[0].kind, Kind::Unsupported)); - assert!(doc.warnings.iter().any(|w| w.contains(warning)), "{:?}", doc.warnings); -} - -#[test] -fn self_referencing_compound_is_reported_without_aborting() { - isolated("self_referencing_compound_is_reported_without_aborting", || { - let doc = document(vec![], vec![compound(10, vec![F::Ref(10)]), rectangle()]); - unsupported(&doc, "cyclic compound"); - assert!(matches!(doc.spreads[0].nodes[1].kind, Kind::Shape { .. }), "a cycle must not poison unrelated shapes"); - }); -} - -#[test] -fn indirectly_cyclic_compound_is_not_imported_as_a_partial_shape() { - isolated("indirectly_cyclic_compound_is_not_imported_as_a_partial_shape", || { - let doc = document(vec![rectangle()], vec![compound(10, vec![F::Ref(100), compound(11, vec![F::Ref(10)])])]); - unsupported(&doc, "cyclic compound"); - }); -} - -fn nested(levels: u32, repeated: bool) -> Document { - // Flat definitions bypass the stream parser's nesting cap: only references form the depth. - let mut definitions = vec![rectangle()]; - let mut previous = 100; - for id in 200..200 + levels { - let children = if repeated { vec![F::Ref(previous), F::Ref(previous)] } else { vec![F::Ref(previous)] }; - definitions.push(compound(id, children)); - previous = id; - } - document(definitions, vec![F::Ref(previous)]) -} - -#[test] -fn deep_compound_graph_is_bounded_on_a_small_stack() { - isolated("deep_compound_graph_is_bounded_on_a_small_stack", || { - std::thread::Builder::new().stack_size(512 * 1024).spawn(|| unsupported(&nested(1000, false), "compound depth")).unwrap().join().unwrap(); - }); -} - -#[test] -fn shared_operands_cannot_expand_exponentially() { - isolated("shared_operands_cannot_expand_exponentially", || unsupported(&nested(40, true), "compound geometry budget")); -} - -#[test] -fn shared_empty_operands_also_have_a_work_limit() { - isolated("shared_empty_operands_also_have_a_work_limit", || { - let mut definitions = vec![compound(100, vec![])]; - let mut previous = 100; - for id in 200..240 { - definitions.push(compound(id, vec![F::Ref(previous), F::Ref(previous)])); - previous = id; - } - unsupported(&document(definitions, vec![F::Ref(previous)]), "compound geometry budget"); - }); -} - -#[test] -fn geometry_budget_is_shared_across_layer_roots() { - isolated("geometry_budget_is_shared_across_layer_roots", || { - let mut definitions = vec![rectangle()]; - let mut previous = 100; - for id in 200..214 { - definitions.push(compound(id, vec![F::Ref(previous), F::Ref(previous)])); - previous = id; - } - let mut roots = vec![F::Ref(previous); 12]; - roots.push(F::Ref(100)); - let doc = document(definitions, roots); - let nodes = &doc.spreads[0].nodes; - assert!(matches!(nodes[0].kind, Kind::Shape { .. }), "a modest shared graph still imports"); - assert!(matches!(nodes.last().unwrap().kind, Kind::Unsupported), "later roots cannot reset the exhausted budget"); - assert!(doc.warnings.iter().any(|w| w.contains("compound geometry budget"))); - }); -} - -#[test] -fn ordinary_shared_operands_keep_both_transformed_copies() { - let mut translated = compound(201, vec![F::Ref(100)]); - let F::Def(_, _, fields) = &mut translated else { unreachable!() }; - fields.push((tag(b"Xfrm"), F::F64s(vec![1.0, 0.0, 30.0, 0.0, 1.0, 40.0]))); - let doc = document(vec![rectangle(), compound(200, vec![F::Ref(100)]), translated], vec![compound(202, vec![F::Ref(200), F::Ref(201)])]); - assert!(doc.warnings.is_empty(), "{:?}", doc.warnings); - let Kind::Shape { path, .. } = &doc.spreads[0].nodes[0].kind else { panic!("expected compound outline") }; - assert_eq!(path.subpaths.len(), 2); - for (a, b) in path.subpaths[0].segments.iter().flatten().zip(path.subpaths[1].segments.iter().flatten()) { - assert_eq!(b.x, a.x + 30.0); - assert_eq!(b.y, a.y + 40.0); - } -} - -#[test] -fn null_operand_slots_cannot_bypass_geometry_budget() { - isolated("null_operand_slots_cannot_bypass_geometry_budget", || { - let bytes = document_bytes(vec![compound(10, vec![F::Null; 1_000_000])], vec![F::Ref(10); 20_000]); - let start = Instant::now(); - let doc = read(&bytes, Limits::default()).unwrap(); - eprintln!("one million nulls / 20,000 placements: {} bytes, read {:.3}s", bytes.len(), start.elapsed().as_secs_f64()); - unsupported(&doc, "compound geometry budget"); - assert_eq!(doc.spreads[0].nodes.len(), 20_000); - assert!(doc.spreads[0].nodes.iter().all(|n| matches!(n.kind, Kind::Unsupported))); - }); -} - -#[test] -fn null_operand_slots_share_budget_across_layer_roots() { - isolated("null_operand_slots_share_budget_across_layer_roots", || { - let doc = document(vec![compound(10, vec![F::Null; 1_000])], vec![F::Ref(10); 1_000]); - assert!(matches!(doc.spreads[0].nodes[0].kind, Kind::Shape { .. }), "a small empty compound remains valid"); - assert!(matches!(doc.spreads[0].nodes.last().unwrap().kind, Kind::Unsupported)); - assert!(doc.warnings.iter().any(|w| w.contains("compound geometry budget"))); - }); -} - -#[test] -fn null_operand_slots_cannot_leave_a_partial_shape() { - isolated("null_operand_slots_cannot_leave_a_partial_shape", || { - let mut slots = vec![F::Ref(100)]; - slots.extend(vec![F::Null; 1_000_000]); - let doc = document(vec![rectangle(), compound(10, slots)], vec![F::Ref(10)]); - unsupported(&doc, "compound geometry budget"); - }); -} - -#[test] -fn non_object_operand_slots_also_consume_budget() { - isolated("non_object_operand_slots_also_consume_budget", || { - let comp = F::Def(10, vec![tag(b"Comp")], vec![(tag(b"Chld"), F::U8s(vec![0; 1_000_000]))]); - unsupported(&document(vec![comp], vec![F::Ref(10)]), "compound geometry budget"); - }); -} - -#[test] -fn ordinary_null_operand_slots_preserve_shared_contours() { - let doc = document(vec![rectangle(), compound(10, vec![F::Null, F::Ref(100), F::Null, F::Ref(100), F::Null])], vec![F::Ref(10)]); - assert!(doc.warnings.is_empty(), "{:?}", doc.warnings); - let Kind::Shape { path, .. } = &doc.spreads[0].nodes[0].kind else { panic!("expected compound outline") }; - assert_eq!(path.subpaths.len(), 2); - assert_eq!(path.subpaths[0], path.subpaths[1]); -} diff --git a/crates/affinity/tests/it/main.rs b/crates/affinity/tests/it/main.rs deleted file mode 100644 index 5d0a5740b8..0000000000 --- a/crates/affinity/tests/it/main.rs +++ /dev/null @@ -1,4 +0,0 @@ -//! The crate's integration tests, linked into one test binary. - -mod compound_limits; -mod real_files; diff --git a/crates/affinity/tests/it/real_files.rs b/crates/affinity/tests/it/real_files.rs deleted file mode 100644 index 302c75aba0..0000000000 --- a/crates/affinity/tests/it/real_files.rs +++ /dev/null @@ -1,83 +0,0 @@ -//! Public Affinity documents: the pinned set `cargo xtask corpus --affinity` fetches into -//! `corpus/affinity`, or any folder of `.af`/`.afdesign`/`.afphoto`/`.afpub` files named by -//! `AFFINITY_SAMPLES` (searched recursively). Without either, these tests do nothing. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - -use std::path::{Path, PathBuf}; - -use photocraft_affinity::{Archive, Limits, stream}; - -fn files(dir: &Path, out: &mut Vec) { - for e in std::fs::read_dir(dir).into_iter().flatten().flatten() { - let p = e.path(); - if p.is_dir() { - files(&p, out); - } else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| ["af", "afdesign", "afphoto", "afpub", "aftemplate"].contains(&e)) - && std::fs::read(&p).is_ok_and(|b| b.starts_with(photocraft_affinity::MAGIC)) - { - out.push(p); - } - } -} - -fn samples() -> Option { - let pinned = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus/affinity"); - std::env::var_os("AFFINITY_SAMPLES").map(PathBuf::from).or_else(|| pinned.join("SOURCES.md").exists().then_some(pinned)) -} - -#[test] -fn public_documents_parse_completely() { - let Some(dir) = samples() else { return }; - let mut paths = Vec::new(); - files(&dir, &mut paths); - assert!(!paths.is_empty(), "no Affinity documents under {dir:?}"); - let mut failures = Vec::new(); - for p in &paths { - let bytes = std::fs::read(p).unwrap(); - let result = Archive::open(&bytes, Limits::default()).and_then(|mut a| { - let doc = a.read("doc.dat")?; - stream::parse(&doc).map(|s| s.objects.len()) - }); - match result { - Ok(n) => assert!(n > 0), - Err(e) => failures.push(format!("{}: {e}", p.display())), - } - } - assert!(failures.is_empty(), "{} of {} failed:\n{}", failures.len(), paths.len(), failures.join("\n")); - eprintln!("{} Affinity documents parsed", paths.len()); -} - -#[test] -fn public_documents_map_to_the_model() { - let Some(dir) = samples() else { return }; - let mut paths = Vec::new(); - files(&dir, &mut paths); - let mut warnings = std::collections::BTreeMap::::new(); - let mut failures = Vec::new(); - let (mut nodes, mut docs) = (0usize, 0usize); - fn count(n: &[photocraft_affinity::model::Node]) -> usize { - n.iter().map(|n| 1 + count(&n.children)).sum() - } - for p in &paths { - let bytes = std::fs::read(p).unwrap(); - if !bytes.starts_with(photocraft_affinity::MAGIC) { - continue; - } - match photocraft_affinity::read(&bytes, Limits::default()) { - Ok(d) => { - docs += 1; - nodes += d.spreads.iter().map(|s| count(&s.nodes)).sum::(); - for w in d.warnings { - let key = w.split(" (").next().unwrap_or(&w).to_string(); - *warnings.entry(key).or_default() += 1; - } - } - Err(e) => failures.push(format!("{}: {e}", p.display())), - } - } - eprintln!("{docs} documents, {nodes} nodes"); - for (w, n) in &warnings { - eprintln!("{n:4} documents: {w}"); - } - assert!(failures.is_empty(), "{}", failures.join("\n")); -} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 31fbce89d3..2b7546dd47 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -64,7 +64,7 @@ winsafe = { version = "=0.0.29", default-features = false, features = ["kernel"] photocraft-ipp = { workspace = true } [dev-dependencies] -photocraft-affinity = { workspace = true, features = ["synth"] } +craft-affinity = { workspace = true, features = ["synth"] } photocraft-io = { workspace = true, features = ["testgen"] } # Synthetic camera raw files for the open tests. photocraft-raw = { workspace = true, features = ["testgen"] } diff --git a/crates/engine/tests/it/affinity.rs b/crates/engine/tests/it/affinity.rs index 06c4bf4e66..5f85803263 100644 --- a/crates/engine/tests/it/affinity.rs +++ b/crates/engine/tests/it/affinity.rs @@ -89,7 +89,7 @@ fn warningless_auxiliary_paths_cannot_silently_use_a_thumbnail() { /// A minimal native document: one 10×10 px red square at (5, 5) on a 40×20 page. fn native() -> Vec { - use photocraft_affinity::synth::{self, F, Method, tag}; + use craft_affinity::synth::{self, F, Method, tag}; let node = |x: f64, y: f64| { let mut r = x.to_le_bytes().to_vec(); r.extend(y.to_le_bytes()); diff --git a/crates/engine/tests/it/current_affinity_artboards.rs b/crates/engine/tests/it/current_affinity_artboards.rs index 8348b4065f..3f8eeeea21 100644 --- a/crates/engine/tests/it/current_affinity_artboards.rs +++ b/crates/engine/tests/it/current_affinity_artboards.rs @@ -5,7 +5,7 @@ mod fixture; use fixture::{Marker, document}; -use photocraft_affinity::synth::Method; +use craft_affinity::synth::Method; use photocraft_doc::{LayerContent, LayerId}; use photocraft_engine::{Session, file_cmds::open_bytes_as}; use photocraft_geom::{Point, Rect}; diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 190dc83b8d..5d0dbc410e 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -31,7 +31,7 @@ photocraft-algo = { workspace = true } craft-psd = { workspace = true } photocraft-codecs = { workspace = true } photocraft-raw = { workspace = true } -photocraft-affinity = { workspace = true } +craft-affinity = { workspace = true } photocraft-text = { workspace = true } photocraft-paint = { workspace = true } photocraft-vector = { workspace = true } @@ -73,7 +73,7 @@ resvg = { version = "0.48", default-features = false, features = ["text", "raste lopdf = { version = "0.38", default-features = false } miniz_oxide = "0.9" crc32fast = "1.5" -photocraft-affinity = { workspace = true, features = ["synth"] } +craft-affinity = { workspace = true, features = ["synth"] } flate2 = { workspace = true } craft-psd = { workspace = true, features = ["testgen"] } photocraft-raw = { workspace = true, features = ["testgen"] } diff --git a/crates/io/src/affinity.rs b/crates/io/src/affinity.rs index 927fa142d6..6c7255c7d2 100644 --- a/crates/io/src/affinity.rs +++ b/crates/io/src/affinity.rs @@ -1,13 +1,13 @@ //! Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`): the native layers, curves, -//! shapes, artboards, text, images and masks `photocraft-affinity` reads, mapped to PhotoCraft +//! shapes, artboards, text, images and masks `craft-affinity` reads, mapped to PhotoCraft //! layers (groups, shape layers, type layers, embedded smart objects, pixel layers, layer and //! vector masks). What could not be mapped is listed in the warnings. A file whose native data //! can't be read opens as its embedded preview, with a warning saying why. use std::sync::Arc; -use photocraft_affinity::model::{self as af, Align, Blend, Kind, Pixels}; -use photocraft_affinity::paint::{self as ap, Cap, GradientKind, Join}; +use craft_affinity::model::{self as af, Align, Blend, Kind, Pixels}; +use craft_affinity::paint::{self as ap, Cap, GradientKind, Join}; use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, SampleType}; use photocraft_doc::text::{CharStyle, ParagraphRun, ParagraphStyle, TextAlign, TextRun, TextShape}; use photocraft_doc::vector::{Knot, LineCap, LineJoin, Path, ShapeLayer, ShapeStroke, StrokeAlign, Subpath, VectorMask}; @@ -19,7 +19,7 @@ use photocraft_raster::Surface; use crate::{ImportResult, IoError}; -pub use photocraft_affinity::is_affinity; +pub use craft_affinity::is_affinity; /// Extensions recognized as Affinity documents. pub const EXTENSIONS: &[&str] = &["af", "afphoto", "afdesign", "afpub"]; @@ -43,7 +43,7 @@ pub fn has_extension(name: &str) -> bool { } pub(crate) fn import(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt) -> Result { - match photocraft_affinity::read(bytes, photocraft_affinity::Limits::default()) { + match craft_affinity::read(bytes, craft_affinity::Limits::default()) { Ok(d) => { let mut b = Builder::new(name, &d)?; b.ctl = *ctl; @@ -70,8 +70,8 @@ pub(crate) fn import(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrup } /// The embedded preview, for files whose native document can't be read. -fn preview(name: &str, bytes: &[u8], native: &photocraft_affinity::Error) -> Result { - let p = photocraft_affinity::preview(bytes).map_err(|e| IoError::Unsupported(format!("{native}; its embedded preview can't be read either ({e})")))?; +fn preview(name: &str, bytes: &[u8], native: &craft_affinity::Error) -> Result { + let p = craft_affinity::preview(bytes).map_err(|e| IoError::Unsupported(format!("{native}; its embedded preview can't be read either ({e})")))?; 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() @@ -283,7 +283,7 @@ impl Builder<'_> { } let children: Vec = n.children.iter().filter_map(|c| self.layer(c, to_doc, false)).collect(); let mut l = match &n.kind { - Kind::Layer | Kind::Group => self.group(n, children), + Kind::Layer | Kind::Group | Kind::Table(_) | Kind::MasterInstance { .. } => self.group(n, children), Kind::Unsupported if children.is_empty() => return None, Kind::Unsupported => self.group(n, children), Kind::Shape { path, fills, strokes, even_odd } => { @@ -305,7 +305,7 @@ impl Builder<'_> { g } } - Kind::Artboard { rect, background } => { + Kind::Artboard { rect, background, .. } => { let r = self.bbox(to_doc, *rect); let bg = match background.first() { Some(ap::Paint::Solid(c)) => { @@ -559,6 +559,7 @@ impl Builder<'_> { fn pixels(&mut self, img: &af::Image) -> Option<(u32, u32, Vec)> { match &img.pixels { Pixels::Rgba8(v) => Some((img.width, img.height, v.clone())), + Pixels::Cmyka8(v) => Some((img.width, img.height, Pixels::cmyka8_to_rgba8(v))), Pixels::Encoded(bytes) => { let opts = photocraft_codecs::DecodeOptions { limits: photocraft_codecs::Limits { max_width: 65_535, max_height: 65_535, max_pixels: MAX_PIXELS, max_alloc: 512 << 20 }, @@ -596,7 +597,7 @@ impl Builder<'_> { m, Some(surface), )), - Pixels::Rgba8(_) => LayerContent::Raster(surface), + Pixels::Rgba8(_) | Pixels::Cmyka8(_) => LayerContent::Raster(surface), }) } @@ -679,6 +680,8 @@ fn default_name(k: &Kind) -> String { Kind::Shape { .. } => "Shape", Kind::Text(_) => "Text", Kind::Image(_) => "Image", + Kind::Table(_) => "Table", + Kind::MasterInstance { .. } => "Master", Kind::Unsupported => "Group", } .into() @@ -719,7 +722,7 @@ mod tests { .into_iter() .enumerate() .map(|(i, (width, height, pixels))| af::Node { - class: photocraft_affinity::synth::tag(b"ImgN"), + class: craft_affinity::synth::tag(b"ImgN"), name: format!("Image {i}"), visible: true, locked: false, @@ -781,7 +784,7 @@ mod tests { fn node(kind: Kind) -> af::Node { af::Node { - class: photocraft_affinity::synth::tag(b"ImgN"), + class: craft_affinity::synth::tag(b"ImgN"), name: "n".into(), visible: true, locked: false, diff --git a/crates/io/tests/it/affinity.rs b/crates/io/tests/it/affinity.rs index 070a38910e..84fe6438d2 100644 --- a/crates/io/tests/it/affinity.rs +++ b/crates/io/tests/it/affinity.rs @@ -24,7 +24,7 @@ fn chunk(kind: &[u8; 4], data: &[u8]) -> Vec { /// A synthetic record envelope, not an Affinity document writer (there is no object graph). fn file(png: &[u8]) -> Vec { let mut b = vec![0; 72]; - b[..4].copy_from_slice(photocraft_affinity::MAGIC); + b[..4].copy_from_slice(craft_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"); @@ -196,7 +196,7 @@ proptest! { mod native { use super::*; - use photocraft_affinity::synth::{self, F, Method, tag}; + use craft_affinity::synth::{self, F, Method, tag}; use photocraft_doc::LayerContent; fn rgba(r: f32, g: f32, b: f32, a: f32) -> F { diff --git a/crates/io/tests/it/affinity_artboards.rs b/crates/io/tests/it/affinity_artboards.rs index 26a9a3c7e5..8c8841c114 100644 --- a/crates/io/tests/it/affinity_artboards.rs +++ b/crates/io/tests/it/affinity_artboards.rs @@ -5,7 +5,7 @@ mod fixture; use fixture::{Marker, document}; -use photocraft_affinity::synth::Method; +use craft_affinity::synth::Method; use photocraft_doc::Document; use photocraft_geom::Rect; use photocraft_io::{ExportOptions, export, import}; diff --git a/crates/io/tests/it/affinity_corpus.rs b/crates/io/tests/it/affinity_corpus.rs index 52579e7fe7..8c05e4b063 100644 --- a/crates/io/tests/it/affinity_corpus.rs +++ b/crates/io/tests/it/affinity_corpus.rs @@ -112,7 +112,7 @@ fn public_affinity_documents_match_their_render_reference() { }; photocraft_codecs::decode(&corpus(&path)).unwrap() } else { - photocraft_codecs::decode(photocraft_affinity::preview(&bytes).unwrap().png).unwrap() + photocraft_codecs::decode(craft_affinity::preview(&bytes).unwrap().png).unwrap() }; let (tw, th) = reference.dimensions(); let png = export(&r.document, "x.png", &ExportOptions::default()).unwrap().bytes; diff --git a/crates/io/tests/support/current_affinity.rs b/crates/io/tests/support/current_affinity.rs index 73588f9aa9..e4cb49e604 100644 --- a/crates/io/tests/support/current_affinity.rs +++ b/crates/io/tests/support/current_affinity.rs @@ -1,7 +1,7 @@ //! Original synthetic reader fixtures. No private document bytes or artwork are used. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -use photocraft_affinity::synth::{self, F, Method, tag}; +use craft_affinity::synth::{self, F, Method, tag}; #[derive(Clone, Copy)] pub enum Marker { diff --git a/docs/architecture.md b/docs/architecture.md index efbae5b4de..b4abe6d766 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -126,7 +126,7 @@ photocraft/ │ ├─ psd/ craft-psd PSD/PSB read + write; its OWN format-level model; depends on nothing in this workspace │ ├─ adobe-assets/ photocraft-adobe-assets .abr .asl .aco/.ase .grd .pat .csh .atn .cube/.3dl, ACR .xmp presets (standalone, like psd) │ ├─ codecs/ photocraft-codecs flat raster decode/encode at format-supported depths; AVIF encode only (feature `avif`), HEIF/HEIC decode only (feature `heif`); no JPEG XL -│ ├─ affinity/ photocraft-affinity bounded native Affinity reader: archive, object stream, layers, vectors, text, pixels (standalone; read only) +│ ├─ affinity/ craft-affinity bounded native Affinity reader: archive, object stream, layers, vectors, text, pixels (shared in craft-libs) │ ├─ 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)