diff --git a/README.md b/README.md index c09e03a34d..692ef29615 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit model (cues with exact tick times): SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and TTML / IMSC1 / DFXP readers and writers, and CEA-608 / CEA-708 byte-pair coding. Carved from FilmCraft. +- [`craft-cdr`](crates/cdr/README.md): bounded reader and writer of `.cdr` drawings: versions 1 to + 27 and `.cmx` files read into one drawing model (pages, layers, groups, shapes, fills and + outlines), and version 15 `.cdr` files written. - [`craft-cfb`](crates/cfb/README.md): clean-room Compound File Binary ([MS-CFB], OLE structured storage) reader and writer: the container of legacy Office files, Outlook messages, encrypted OOXML packages and AAF. Bounded on hostile input; what the streams hold stays with each format. diff --git a/crates/cdr/Cargo.toml b/crates/cdr/Cargo.toml index edeb8d72e2..f208a7ef47 100644 --- a/crates/cdr/Cargo.toml +++ b/crates/cdr/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-cdr" -description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing" +description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing; writer for version 15 .cdr drawings" version.workspace = true edition.workspace = true license.workspace = true @@ -11,7 +11,7 @@ repository.workspace = true workspace = true [features] -# Synthetic-file builders for tests and fuzz seeds; not a .cdr writer. +# Synthetic-file builders for tests and fuzz seeds, of every version; `write` is the crate's writer. synth = [] [dependencies] diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 7c3ddadbb5..fba2839184 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -1,7 +1,8 @@ # Where each layout comes from -The reader relies on the record layouts below. Code cites a row by its id (`R1` ...), and -`tests/it/provenance.rs` fails when a cited id has no row here. +The reader relies on the record layouts below, and the writer (`src/write.rs`) lays out version 15 +files by the same rows, with R64 to R73 for what only the writer needs. Code cites a row by its id +(`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row here. Sources: @@ -18,8 +19,9 @@ Sources: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT, and RFC 1951 (DEFLATE), https://www.rfc-editor.org/rfc/rfc1951 - **F**: the magic database of the `file` utility (BSD-2-Clause), - https://github.com/file/file/blob/b778217dbd35/magic/Magdir/images and - https://github.com/file/file/blob/b778217dbd35/magic/Magdir/riff + https://github.com/file/file/blob/b778217dbd35/magic/Magdir/images, + https://github.com/file/file/blob/b778217dbd35/magic/Magdir/riff and + https://github.com/file/file/blob/b778217dbd35/magic/Magdir/archive - **PR**: the PRONOM registry's signatures for versions 1.0, 2.0 and 4.0, https://pronom.nationalarchives.gov.uk/fmt/467.xml, https://pronom.nationalarchives.gov.uk/fmt/466.xml and @@ -130,3 +132,13 @@ file is committed. | R61 | Field 4 of instruction 9: the page's width and height, u32 each in coordinate units. Without it, field 1 gives the drawing's bounds: a u16 page number, a u32, then the left, top, right and bottom edges as i32 in coordinate units; the page takes the bounds' size and is centered on them (VectorCraft's own choice). Without either, the page has no size, and the importer gives it 612 × 792 pt as it does a `.cdr` page without one (VectorCraft's own size) | CN "page: instructions"; S: none of the CX files has field 4; in all nine with 32-bit coordinates, the four edges in field 1 match the extent of the file's curves | public-notes (field 4), sample (field 1) | | R62 | A layer's name: field 4 as a u32 count and UTF-16 units, or field 1 from byte 12 as a u16 count and 8-bit characters (read as Windows-1252, VectorCraft's own choice); a layer without a name is left unnamed, as a `.cdr` layer is. A curve: field 1 its rendering attributes, field 2 a u16 point count, the points as i32 x and y, then a type byte for each as R16; coordinates are from the page's center, y up. A field 2 too short for its count is read as whole points with their type bytes when its length is a multiple of 9, and the curve is left out as damaged otherwise (VectorCraft's own rule) | CN "page: instructions" and "Coordinates"; S: the 8-bit names `Layer 1`, `Desktop`, `Grid` and `Guides` of the CX files (the last three hold nothing in every file); every curve of the CX files has field 2 of exactly 2 + 9 bytes per point | sample (8-bit names, curves), public-notes (field 4) | | R63 | Rendering attributes: a mask (1 fill, 2 outline, 4 lens, 8 canvas, 16 container; lenses, canvases and containers are not read, with a warning), then a field list for the fill when the mask names it and one for the outline. The fill's field 1 is a u16 type and a field list; type 0 is no fill, type 1 a uniform fill whose field 1 is the color entry (u16) and a screen (u16); other types (2 fountain and more) are not read. The outline's field 1 is its `rotl` entry (u16) | CN "Rendering attributes"; S: masks 1, 2 and 3, fill types 1, 2 and 6, and uniform fills with a 4-byte field 1 in the CX files | sample | +| R64 | A package of versions 14 to 16 starts with a stored member `mimetype` holding `application/x-vnd.corel.draw.document+zip`; in versions 14 and 15 the RIFF file follows in `content/riffData.cdr` (R25) | F `archive` L1902-L1906 (a first member named `mimetype` at offset 30, stored, with no extra field), L2071-L2077 (the text at offsets 50 and 62); S: every file of LT `testset/15` | public-spec | +| R65 | A `trfd` record has a fourth header field, 0xFFFF, after where its offsets lie; in version 15 its offsets table starts at byte 16; each entry starts with the tag 1300 and a u32 before its type, and a matrix entry ends with 8 bytes after the six f64. The specification names the u32 `len_body`; every sample entry holds 0 there, and the writer writes 0 | KF L1079-L1106 (the 0xFFFF field), L1134-L1141 (the tag and `len_body`); S: every `trfd` record of the 15 files of LT `testset/15` without text (96 bytes, the offsets 24 and 96) | public-spec (the u32 after the tag and the 8 bytes at the end: sample) | +| R66 | A fill's property list from version 13 ends with an empty property (type 0, length 0), then two u16, the overprint flag (u32), an angle and a u32, inside the list's length; a uniform fill's record ends with 8 bytes after the list. The specification names 0, 45 degrees and 60 as the usual values of the first u16, the angle and the last u32, and lists 0, 1 and 13 for the flag | K L1100-L1121 (the 8 bytes), L1122-L1186 (the list and its end); S: the uniform fills of LT `square_blackfill_nooutline_transparency50percent_cdr15.cdr`, whose lists hold 0 in the flag, 45 degrees and 60 there | public-spec | +| R67 | Byte 2 of an object's `flgs` holds 0x08 when the object carries argument 8000 and 0x10 when it is a clipping container (argument 8005); the group of `LIST clpt` that a container clips has 0x80 there | S: LT `square_blackfill_nooutline_transparency50percent_cdr15.cdr` (0x08), `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (0x10 on the container, 0x80 on the clipped group) and `square_blackfill_nooutline_cdr15.cdr` (0 on a plain object) | sample (the reader does not use these bits) | +| R68 | Bit 2 of a point's type byte marks a node that can be edited. In most of the specification's samples it is set on move points and on line and curve ends and clear on control points and on the end that closes a subpath, with exceptions in a few samples of versions 13 and 14; the writer uses that common pattern. A closed subpath ends with an explicit line or curve end at its move point's coordinates, carrying bit 3 | K L2747-L2789 (`can_modify`, `is_closing_path`, from the specification's notes on its sample files) | public-spec (the reader does not use bit 2) | +| R69 | In a version 1300 uniform transparency record (R47), the u32 at byte 105 is a fill id, followed by 8 bytes. The sample's record also holds 261 as a u32 at byte 0, 0xFFFFFFFF at byte 57, 100.0 as an f64 at byte 69 and 2 at byte 81, and 0 in every other byte outside the fields R47 names | KF L707-L745 (`fill_id`); S: the record of LT `square_blackfill_nooutline_transparency50percent_cdr15.cdr` names fill 1, a uniform fill of RGB 255, 255, 255 | public-spec (the field), sample (the white fill and the other values, which the writer writes as the sample holds them; the reader does not use them) | +| R70 | Argument 40050 of a layer is a 16-byte id, different for each layer. The other pages hold an entry for each of the master page's guides, desktop and grid layers: a layer with byte 2 of its flags set and the master layer's object type, name and id, holding nothing; the guides and desktop entries come before the page's own layers and the grid entry after them. The master page holds a guides, a desktop and a grid layer, the grid hidden and locked | K L873-L883 (the id, and the master page's layers named from the other pages by the same id); S: LT `square_blackfill_nooutline_cdr15.cdr` (the master page's three layers, and the entries on its page, in that order, with the master layers' ids) | public-spec (the id), sample (the entries and their order; the reader does not use the id, and leaves the entries out as empty layers that are not drawing layers) | +| R71 | An `outl` chunk from version 13 holds records up to the one of id 1, whose length the specification's samples give as the bytes left in the chunk less 8. In the version 15 samples the id 1 record holds 130 bytes, 8 bytes follow it, and its body holds an f64 1 at bytes 16 and 48, 45 degrees at byte 84 and 60 at byte 88; the writer writes that layout and those values. A record of id 2 holds a color property list that ends at its empty property, without the fields R66 names after a fill's list | KF L1158-L1244 (the records, type 2 a color property list, and the id 1 length in its samples); S: the 18 `outl` chunks of the LT `testset/15` files without text (each 237 bytes, the id 1 record 130 bytes long with those values and 8 bytes of 0 after it, the id 2 record 43 bytes long) | public-spec (the record types and the length), sample (the values; the reader does not use them) | +| R72 | In the version 15 samples an `mcfg` chunk starts with the tag 1300 and the length of the rest of the chunk, then 4 bytes of 0 (the 12 bytes R10 names), and each `fild` chunk sits in a `LIST filc` of its own inside `LIST filt` | S: the 15 LT `testset/15` files without text (every `mcfg` starts with 1300 and its size less 8; each of their 31 `fild` chunks is the only chunk of a `LIST filc`) | sample (the reader skips the 12 bytes and finds `fild` chunks at any depth) | +| R73 | The specification reads the id in a container's argument 8005 (R46) as the stored u32 plus 1, halved, and the `spnd` id as stored. Sample files hold the same stored u32 in both places, even ids included, which the halved reading would not match. The writer numbers containers 1, 2, 3 and so on, and writes the same number in the clipped group's `spnd` | KF L799-L807 (`powerclip_id`), L2305-L2312 (`spnd`); S: the container and `spnd` of LT `powerclipsquare_blackfill_whiterectangleinside.cdr` of `testset/12` (156091928) and `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (1), the eight UC files `corel_powerclip_*` of versions 7 to 13 (47834832) and TDF 114901 (515235504) | sample (the halved reading: not followed) | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index 7a842a3abc..37a3424e2e 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -1,10 +1,12 @@ # craft-cdr -A bounded Rust reader for `.cdr` drawings of versions 1 to 27 (and `.cdt` templates). +A bounded Rust reader for `.cdr` drawings of versions 1 to 27 (and `.cdt` templates), and a +writer of version 15 drawings. It reads the `WL` files of versions 1 and 2, the RIFF chunk tree of versions 3 and later with its compressed lists, the ZIP packages that versions 14 and later save (with the data streams of versions 16 and later) and the records listed below, and hands the engine a drawing in points, -with each object's transform. It does not write `.cdr` files. +with each object's transform. `write` writes a drawing back out as a `.cdr` file of version 15 +(see [Writing](#writing)). ## What is read @@ -95,9 +97,68 @@ arrowheads and lenses are not read; the drawing's `warnings` name each kind it h path is left out and the objects it clips are read without it. Files in big-endian byte order and files with 16-bit coordinates are refused. +## Writing + +`write` writes a drawing as a `.cdr` file of version 15: a ZIP package whose first member, +`mimetype`, names the format and whose member `content/riffData.cdr` holds the RIFF file. Each +record is laid out as the reader reads it, by the `PROVENANCE.md` rows it cites. The reader reads +the written file back as the drawing it was written from, to the precision the file stores +(1/254000 inch for coordinates, 1/255 for color components), with the changes listed below the +table. + +| In the drawing | Written as | +|---|---| +| Pages and their sizes; the drawing's page size | pages with a page size argument; `mcfg` | +| The master page's layers and the drawing's guidelines | the master page, with a guides, a desktop and a grid layer | +| Layers: name, kind, hidden and locked | layers with their flags and their kind as the object type | +| Guidelines of a layer | guideline objects in that layer | +| Groups, and clipping containers with the objects they clip | `LIST grp ` lists; containers naming groups of the document's `LIST clpt` | +| Paths, rectangles with each corner's radius, ellipses | curves, rectangles of the version 15 layout, ellipses | +| Uniform fills and outlines (width, color, caps, joins, dashes, behind the fill, scaled with the shape) | fill and outline records, one for each different fill or outline | +| RGB, CMYK, gray, registration and spot colors | color models 5, 3, 9 and 20; a spot color as its look with its tint and its name | +| The nonzero fill rule, opacity and blend modes | the winding argument and the uniform transparency argument | + +Opacity is written as the reader reads argument 8000 (R47), and the fill rule as the reader reads +argument 14001 (R52). The uniform transparency of every public sample R47 cites is 50%, and the +specifications R52 cites do not say which fill rule each winding value means, so the direction of +the opacity value and the value written for nonzero rest on the reader's own reading. Each layer +gets an id (argument 40050), and every other page names the master page's guides, desktop and grid +layers by those ids (R70); the master page's drawing layers are not named from the other pages. + +The drawing's version and warnings are not written. A group that holds no shape or container is +left out, a clipping container whose objects hold none is written as a plain shape, a subpath +without segments is left out, as the reader leaves it out, and a drawing without pages gets one +empty page. A closed subpath whose last segment ends away from its start gets a closing line to +its start, as the file closes subpaths with an explicit point. A drawing without a page size of +its own is written without `mcfg`. Guidelines on the master page's layers read back as the +drawing's guidelines. An empty layer of a page other than a drawing layer, and an empty layer of +the master page, are written and read back left out, as the reader leaves out such layers in any +file. A guideline on a hidden layer reads back hidden, and a guideline angle past the field's +range is written as the same angle within one turn. Hidden groups and objects carry the same hide +bit as hidden layers (R19); the specification's notes date that bit on groups and objects to a +later program release than version 15 files, so a program of that version may show them. A spot +color without a look is written with a black look. Dash lengths are written to whole outline +widths and spot color tints to whole percent, as the file stores them. + +Writing refuses a drawing that the reader would not read whole within the same `Limits` +(objects, coordinates, dashes, arguments, chunks, clipped chunks, nesting depth, clip nesting, +members and sizes), and groups nested deeper than the nesting depth, groups that hold nothing +included. It also refuses what the file cannot hold or the reader would read back otherwise +changed: a coordinate past 32 bits of 1/254000 inch, a number that is not finite, a page width or +height that rounds to less than one coordinate unit, a negative outline width or a positive one +that rounds to 0, a corner radius below 0 or more than a billionth past half the rectangle's +shorter side (a radius within that is written as half), a color value, tint or opacity outside 0 +to 1, more than 10 dash lengths, a negative one or one that rounds past 65,535, a pattern whose +lengths all round to 0, a name longer than 256 UTF-16 units or holding a NUL, a spot color without +a name, at a tint that rounds to 0 percent or at a tint too low for its look to read back within +one step of 1/255, objects on the master page's grid layer, and a guideline at the edge of the +coordinate range with no room for a second point on it whose rounded coordinates lie within 1 +degree of its angle. + ## Provenance -`PROVENANCE.md` lists every record layout the reader relies on, with its public source and status. +`PROVENANCE.md` lists every record layout the reader relies on, and the rows only the writer +needs, with their public sources and status. Code cites the rows by id (`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row. The test inputs are synthetic drawings built by `src/synth.rs` and `src/synth_cmx.rs` (the `synth` feature); no third-party file is committed. diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs index 8eb2d48125..5107482088 100644 --- a/crates/cdr/src/lib.rs +++ b/crates/cdr/src/lib.rs @@ -8,7 +8,10 @@ //! //! Every record layout the reader relies on is listed in `PROVENANCE.md` with its public source //! and status; code cites the row ids (R1 ...). Reading is bounded by [`Limits`], never recurses and does not -//! panic. Nothing here writes `.cdr` or `.cmx` files. +//! panic. +//! +//! [`write`] writes a [`Drawing`] as a `.cdr` file of version 15, laying out each record as the +//! reader reads it. Nothing here writes `.cmx` files. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -32,11 +35,13 @@ pub mod synth; #[cfg(any(test, feature = "synth"))] pub mod synth_cmx; mod wl; +mod write; mod zip; pub use limits::Limits; pub use model::{Drawing, Warning}; pub use preview::{Preview, PreviewFormat, preview}; +pub use write::{WRITTEN_VERSION, WriteError, write}; /// Does `bytes` look like a `.cdr` drawing: a RIFF file, a ZIP package holding one, or a `WL` file /// of version 1 or 2 whose header offsets fit the file? diff --git a/crates/cdr/src/write.rs b/crates/cdr/src/write.rs new file mode 100644 index 0000000000..99c834a25d --- /dev/null +++ b/crates/cdr/src/write.rs @@ -0,0 +1,1486 @@ +//! Writer of `.cdr` drawings of version 15: a ZIP package (R24, R25, R64) whose member +//! `content/riffData.cdr` is the RIFF file. Each record is laid out as the reader in this crate +//! reads it, by the `PROVENANCE.md` rows the code cites, so a written file reads back as the +//! drawing it was written from. Records the reader does not read are not written. +//! +//! Writing is bounded by [`Limits`]: a drawing the reader would not read whole within the same +//! limits is refused. It never recurses and does not panic. + +use std::cell::Cell; +use std::collections::HashMap; +use std::io::Write as _; +use std::rc::Rc; + +use self::WriteError as Error; +use crate::Limits; +use crate::model::{ + Blend, Cap, Color, Drawing, Flags, Geometry, Guideline, Join, LayerKind, Matrix, Object, Outline, Page, Path, Pt, Segment, Shape, SubPath, +}; + +/// Why a drawing can't be written. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum WriteError { + /// The reader would not read the file whole within the [`Limits`] it was written for. + Limit(&'static str), + /// What the file can't hold, or what the reader would read back changed. + Unwritable(&'static str), +} + +impl std::fmt::Display for WriteError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + WriteError::Limit(what) => write!(f, "past the {what} limit"), + WriteError::Unwritable(what) => write!(f, "{what} can't be written"), + } + } +} + +impl std::error::Error for WriteError {} + +/// The version written, in hundreds, as its `vrsn` chunk names it (R2). +pub const WRITTEN_VERSION: u16 = 1500; +/// The form type of version 15: `CDR` and the letter `F` (R1). +const FORM: [u8; 4] = *b"CDRF"; +/// The package member that holds the RIFF file (R25). +const MEMBER: &[u8] = b"content/riffData.cdr"; +/// The package's first member and what it holds (R64). +const MIMETYPE_NAME: &[u8] = b"mimetype"; +const MIMETYPE: &[u8] = b"application/x-vnd.corel.draw.document+zip"; +/// Coordinate units (1/254000 inch) in a point (R5). +const UNITS_PER_PT: f64 = 254_000.0 / 72.0; +/// The tag of the record layout from version 13 (R11, R12, R47). +const TAG_1300: u32 = 1300; + +/// Object types (R6, R23). +const RECTANGLE: u32 = 1; +const ELLIPSE: u32 = 2; +const CURVE: u32 = 3; +const GUIDELINE: u32 = 0x16; +/// Argument types (R6, R20, R21, R23, R46, R47, R52, R70). +const ARG_OUTLINE: u32 = 10; +const ARG_FILL: u32 = 20; +const ARG_COORDS: u32 = 30; +const ARG_NAME: u32 = 1000; +const ARG_TRANSPARENCY: u32 = 8000; +const ARG_CONTAINER: u32 = 8005; +const ARG_WINDING: u32 = 14001; +const ARG_GUIDE: u32 = 16000; +const ARG_PAGE_SIZE: u32 = 19130; +const ARG_LAYER_ID: u32 = 40050; + +/// The most clipped groups the reader reads one inside another (`build.rs`). +const MAX_CLIP_DEPTH: usize = 64; +/// Chunks the reader counts for one object list of a clipped group, as [`Writer::shape`] lays it +/// out: the list itself, then its searches (`build.rs`, `find_own`) for its `loda` (`flgs`, `lgob`, +/// `loda`), its `flgs` (`flgs`) and its `trfd` (`flgs`, `lgob`, `loda`, `trfl`, `trfd`). +const OBJECT_WALK: usize = 1 + 3 + 1 + 5; +/// Dash and gap lengths an outline record has room for: the arrowhead ids follow 20 bytes after +/// the first dash (R12). +const MAX_DASHES: usize = 10; +/// The most UTF-16 units of a name the reader keeps whole (`records.rs`). +const MAX_NAME: usize = 256; +/// Where a guideline's second point lies along it, in points: the writer's own value. +const GUIDE_REACH: f64 = 100.0; +/// How far, in degrees, the line through a guideline's two points, once rounded, may turn from +/// its stored angle: the writer's own value. +const GUIDE_TURN: f64 = 1.0; +/// How many units along the longer axis a guideline's second point is looked for in when no +/// farther point lies along its angle: past 82 units, a rounded point turns less than +/// `GUIDE_TURN`. +const GUIDE_STEPS: i32 = 128; + +/// The `.cdr` file of `drawing`, version 15, within `limits`. +/// +/// Pages, the master page's layers and the drawing's guidelines, layers with their kinds, names +/// and flags, groups, clipping containers with the objects they clip, curves, rectangles with +/// their corners, ellipses, uniform fills, outlines, the nonzero fill rule and uniform +/// transparency with its blend mode are written. Every other page names the master page's guides, +/// desktop and grid layers by their layer ids, and not its drawing layers. The drawing's `version` +/// and `warnings` are not written, and the written file reads back with these changes: +/// +/// - Groups that hold no shape or container are left out, and a container whose objects hold none +/// is written as a plain shape. A subpath without segments is left out. A drawing without pages +/// gets one empty page. +/// - A closed subpath whose last segment ends away from its start gets a closing line to its +/// start, as the file closes subpaths with an explicit point. +/// - Guidelines on the master page's layers read back as the drawing's guidelines. An empty layer +/// of the master page, and an empty layer of a page other than a drawing layer, read back left +/// out, as the reader leaves out such layers in any file. +/// - A guideline on a hidden layer reads back hidden, as the reader marks every guideline of a +/// hidden layer. A guideline angle past the field's range is written as the same angle within +/// one turn. +/// - Dash lengths are rounded to whole outline widths and spot color tints to whole percent, as +/// the file stores them. A spot color without a look is written with a black look. +/// +/// Hidden groups and objects carry the same hide bit as hidden layers (R19). The specification's +/// notes date that bit on groups and objects to a later program release than version 15 files, so +/// a program of that version may show them. +/// +/// Fails with [`WriteError::Limit`] when the reader would not read the file whole within `limits` +/// or groups nest deeper than its nesting depth, groups that hold nothing included, and with +/// [`WriteError::Unwritable`] for what the file can't hold or the reader would read back otherwise +/// changed: a coordinate past 32 bits of 1/254000 inch; a size, matrix or angle that is +/// not finite; a page width or height that rounds to less than one coordinate unit; a negative +/// outline width, or a positive one that rounds to 0; a corner radius below 0 or more than a billionth past half the rectangle's +/// shorter side (a radius within that is written as half); a color value, tint or opacity outside +/// 0 to 1; more than 10 dash lengths, one that is negative, not finite or rounds past 65,535, or a +/// pattern whose lengths all round to 0; a name longer than 256 UTF-16 units or holding a NUL; a +/// spot color without a name, at a tint that rounds to 0 percent or at a tint too low for its look +/// to read back within one step of 1/255; objects on the master page's grid layer; a guideline at +/// the edge of the coordinate range with no room for a second point on it whose rounded +/// coordinates lie within 1 degree of its angle. +pub fn write(drawing: &Drawing, limits: Limits) -> Result, Error> { + // Every package holds two members (R64). + if limits.members < 2 { + return Err(Error::Limit("package member count")); + } + let mut w = Writer::new(limits); + // The chunks the `doc` list always holds count from the start: `vrsn`, `doc `, `filt` and + // `otlt`, and `mcfg` with a page size. + w.counted.set(4 + usize::from(drawing.page_size.is_some())); + let mut pages = Out::new(0, limits, w.total.clone(), w.counted.clone()); + w.master_page(&mut pages, drawing)?; + if drawing.pages.is_empty() { + // A drawing has at least one page, with one layer. + pages.open(b"page")?; + pages.chunk(b"flgs", &PAGE_FLAGS)?; + pages.open(b"gobj")?; + w.master_refs(&mut pages, false)?; + let id = w.layer_id()?; + w.layer(&mut pages, &LayerParts { name: "Layer 1", kind: LayerKind::Drawing, flags: Flags::default(), master: false, id }, &[], [&[], &[]])?; + w.master_refs(&mut pages, true)?; + pages.close()?; + pages.close()?; + } + for page in &drawing.pages { + w.page(&mut pages, page)?; + } + let clips = w.clipped_groups()?; + // The bytes of each layer id after its count come from hashes of what is written, so + // different drawings get different ids and the same drawing the same ones (R70). + // A CRC-32 and a 64-bit FNV-1a hash of the same bytes. + let config = drawing.page_size.map(mcfg).transpose()?; + let (mut crc, mut fnv) = (crc32fast::Hasher::new(), 0xcbf2_9ce4_8422_2325_u64); + let mut hash = |part: &[u8]| { + crc.update(part); + for b in part { + fnv = (fnv ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3); + } + }; + for part in [&pages.buf[..], clips.as_ref().map_or(&[][..], |c| &c.buf), config.as_deref().unwrap_or_default()] { + hash(part); + } + // Each record as its chunk holds it: the id, then the body. + for (id, body) in w.fills.bodies.iter().chain(&w.outlines.bodies) { + hash(&id.to_le_bytes()); + hash(body); + } + let mut salt = [0u8; 12]; + for (slot, b) in salt.iter_mut().zip(crc.finalize().to_le_bytes().into_iter().chain(fnv.to_le_bytes())) { + *slot = b; + } + for &at in &w.id_at { + if let Some(slot) = pages.buf.get_mut(at + 4..at + 16) { + slot.copy_from_slice(&salt); + } + } + // The `doc` list's count starts with the RIFF header and the pages, which follow it. + // Its chunk count starts with the chunks of the pages and the clipped groups. + let streams = pages.chunks.saturating_add(clips.as_ref().map_or(0, |c| c.chunks)); + let mut doc = Out::new(0, limits, Rc::new(Cell::new(pages.buf.len().saturating_add(12))), Rc::new(Cell::new(streams))); + // The version chunk comes first (R2). + doc.chunk(b"vrsn", &WRITTEN_VERSION.to_le_bytes())?; + doc.open(b"doc ")?; + if let Some(config) = &config { + doc.chunk(b"mcfg", config)?; + } + // Each fill record in a `LIST filc` of its own (R72). + doc.open(b"filt")?; + for (id, body) in &w.fills.bodies { + doc.open(b"filc")?; + doc.chunk_of(b"fild", &[&id.to_le_bytes(), body])?; + doc.close()?; + } + doc.close()?; + doc.open(b"otlt")?; + for (id, body) in &w.outlines.bodies { + doc.chunk_of(b"outl", &[&id.to_le_bytes(), body])?; + } + doc.close()?; + // The clipped groups end the `doc` list; their bytes follow its stream in the file. + let clipped = clips.as_ref().map_or(&[][..], |c| &c.buf); + if clips.is_some() { + doc.tail(b"clpt", clipped.len())?; + } + doc.close()?; + // The reader takes the RIFF file within the input size too, once it is out of the package. + let len = 12usize.saturating_add(doc.buf.len()).saturating_add(clipped.len()).saturating_add(pages.buf.len()); + fits_stream(&limits, len)?; + let mut head = b"RIFF".to_vec(); + head.extend(len32(len - 8)?.to_le_bytes()); + head.extend(FORM); + let file = package(&[&head, &doc.buf, clipped, &pages.buf])?; + if file.len() > limits.input { + return Err(Error::Limit("input size")); + } + Ok(file) +} + +/// Checks that `n` bytes of the RIFF file fit what a read takes: it takes the file as input, as an +/// inflated package member and within the inflated bytes of the whole file. The error names the +/// smallest of those limits. +fn fits_stream(limits: &Limits, n: usize) -> Result<(), Error> { + let (max, what) = [(limits.input, "input size"), (limits.member, "member size"), (limits.inflated, "inflated size")] + .into_iter() + .min_by_key(|(max, _)| *max) + .unwrap_or((0, "input size")); + if n > max { Err(Error::Limit(what)) } else { Ok(()) } +} + +/// A u32 length field, or the size limit. +fn len32(n: usize) -> Result { + u32::try_from(n).map_err(|_| Error::Limit("output size")) +} + +/// A chunk stream being written: chunks and lists, with each list's size filled in when it closes +/// (R4). +struct Out { + buf: Vec, + /// Where each open list's size field lies. + open: Vec, + /// Lists around this stream's own in the file. + base: usize, + /// Chunks written, lists included. + chunks: usize, + limits: Limits, + /// Bytes of the RIFF file written so far, by every stream that shares the count. + total: Rc>, + /// Chunks of the RIFF file counted so far, lists included, by every stream that shares the + /// count. + counted: Rc>, + /// Bytes that follow the stream in the file and belong to its open lists (see `tail`). + after: usize, +} + +impl Out { + fn new(base: usize, limits: Limits, total: Rc>, counted: Rc>) -> Out { + Out { buf: Vec::new(), open: Vec::new(), base, chunks: 0, limits, total, counted, after: 0 } + } + + fn count(&mut self) -> Result<(), Error> { + self.chunks = self.chunks.saturating_add(1); + self.counted.set(self.counted.get().saturating_add(1)); + self.room_for_chunks(0) + } + + fn room_for_chunks(&self, more: usize) -> Result<(), Error> { + if self.counted.get().saturating_add(more) > self.limits.chunks { Err(Error::Limit("chunk count")) } else { Ok(()) } + } + + /// Checks that `lists` more lists nested in the open ones and `chunks` more chunks, lists + /// included, fit what a read takes, before anything is written. + fn fits(&self, lists: usize, chunks: usize) -> Result<(), Error> { + if self.base + self.open.len() + lists > self.limits.depth { + return Err(Error::Limit("nesting depth")); + } + self.room_for_chunks(chunks) + } + + /// Checks that `n` more bytes keep the file within what a read takes. + fn room(&self, n: usize) -> Result<(), Error> { + fits_stream(&self.limits, self.total.get().saturating_add(n)) + } + + fn put(&mut self, bytes: &[u8]) { + self.buf.extend(bytes); + self.total.set(self.total.get().saturating_add(bytes.len())); + } + + fn chunk(&mut self, id: &[u8; 4], body: &[u8]) -> Result<(), Error> { + self.chunk_of(id, &[body]) + } + + /// A chunk whose body is `parts`, one after another. + fn chunk_of(&mut self, id: &[u8; 4], parts: &[&[u8]]) -> Result<(), Error> { + let len = parts.iter().fold(0usize, |n, p| n.saturating_add(p.len())); + self.count()?; + self.room(len.saturating_add(8 + len % 2))?; + self.put(id); + self.put(&len32(len)?.to_le_bytes()); + for p in parts { + self.put(p); + } + if len % 2 == 1 { + self.put(&[0]); + } + Ok(()) + } + + /// A `loda` chunk of a record of object type `kind` (R6): length, argument count, where the + /// offsets and the types lie, the type; the arguments; the offsets with one more for the end; + /// the types in reverse. The arguments are copied straight into the stream. + fn loda(&mut self, kind: u32, args: &[(u32, Vec)]) -> Result<(), Error> { + const HEAD: usize = 20; + let body = args.iter().fold(0usize, |n, (_, a)| n.saturating_add(a.len())); + let offsets_at = HEAD.saturating_add(body); + let types_at = offsets_at.saturating_add((args.len() + 1).saturating_mul(4)); + let len = types_at.saturating_add(args.len().saturating_mul(4)); + self.count()?; + self.room(len.saturating_add(8 + len % 2))?; + self.put(b"loda"); + self.put(&len32(len)?.to_le_bytes()); + for v in [len, args.len(), offsets_at, types_at] { + self.put(&len32(v)?.to_le_bytes()); + } + self.put(&kind.to_le_bytes()); + for (_, a) in args { + self.put(a); + } + let mut at = HEAD; + for (_, a) in args { + self.put(&len32(at)?.to_le_bytes()); + at += a.len(); + } + self.put(&len32(at)?.to_le_bytes()); + for (t, _) in args.iter().rev() { + self.put(&t.to_le_bytes()); + } + if len % 2 == 1 { + self.put(&[0]); + } + Ok(()) + } + + /// Opens a list of `form`. The reader reads the chunks of a list nested at most `depth` deep. + fn open(&mut self, form: &[u8; 4]) -> Result<(), Error> { + self.count()?; + if self.base + self.open.len() + 1 > self.limits.depth { + return Err(Error::Limit("nesting depth")); + } + self.room(12)?; + self.put(b"LIST"); + self.open.push(self.buf.len()); + self.put(&[0; 4]); + self.put(form); + Ok(()) + } + + fn close(&mut self) -> Result<(), Error> { + let at = self.open.pop().ok_or(Error::Limit("output size"))?; + let len = (self.buf.len() + self.after) - at - 4; + let field = len32(len)?.to_le_bytes(); + if let Some(slot) = self.buf.get_mut(at..at + 4) { + slot.copy_from_slice(&field); + } + if len % 2 == 1 { + // A pad byte would go after the bytes kept outside the stream. + if self.after > 0 { + return Err(Error::Limit("output size")); + } + self.put(&[0]); + } + Ok(()) + } + + /// Opens a list of `form` whose chunks, `len` bytes already laid out, follow the stream in + /// the file instead of being copied into it. Nothing more is written to the stream; only the + /// lists open around it close. + fn tail(&mut self, form: &[u8; 4], len: usize) -> Result<(), Error> { + self.open(form)?; + self.room(len)?; + self.after = len; + self.total.set(self.total.get().saturating_add(len)); + self.close() + } +} + +/// Fill or outline records by their body, numbered as they are first used. +#[derive(Default)] +struct Records { + ids: HashMap, u32>, + /// Each record's id and body, in the order they were numbered; the chunk holds the id, then + /// the body. + bodies: Vec<(u32, Rc<[u8]>)>, +} + +/// What the read of the written file will count, against the limits. +struct Writer<'d> { + limits: Limits, + /// Bytes of the RIFF file written so far: the pages, the clipped groups and the fill and + /// outline tables, held together to what a read takes. + total: Rc>, + /// Chunks of the RIFF file counted so far, held to the chunk limit: the `doc` list's own, the + /// pages', the clipped groups' and the records'. + counted: Rc>, + fills: Records, + outlines: Records, + /// The next fill or outline id. + next_id: u32, + /// The objects each container clips, by the id of its `LIST clpt` group (R46), with how many + /// clipped groups the reader has open when it reads them. + clips: Vec<(u32, &'d [Object], usize)>, + /// The clipped groups open around the objects being written. + clip_depth: usize, + objects: usize, + coordinates: usize, + dashes: usize, + /// Chunks the reader steps through inside clipped groups: each group's `spnd` and flags, each + /// object or group list, each nested group's flags, and the chunks it looks at to find each + /// object's `loda`, `flgs` and `trfd`. + clip_walked: usize, + /// Layer ids given out so far, and where each layer's id lies in the pages' stream. + layer_ids: u32, + id_at: Vec, + /// The master page's guides, desktop and grid layers, which the other pages name (R70). + master_refs: Vec<(&'d str, LayerKind, Flags, [u8; 16])>, +} + +/// What a layer list carries besides its objects and guidelines. +struct LayerParts<'a> { + name: &'a str, + kind: LayerKind, + flags: Flags, + /// On the master page, or an entry that names one of its layers. + master: bool, + /// The layer id (R70). + id: [u8; 16], +} + +/// A layer of the master page as it is written. +struct MasterLayer<'a> { + name: &'a str, + kind: LayerKind, + flags: Flags, + objects: &'a [Object], + guides: [&'a [Guideline]; 2], +} + +/// A layer id before its last 12 bytes are set for the drawing: the first four count the layers +/// (R70). +const LAYER_ID: [u8; 16] = [0; 16]; + +/// The flags of a page other than the master page (R19). +const PAGE_FLAGS: [u8; 4] = [0, 0, 0, 0x90]; + +impl<'d> Writer<'d> { + fn new(limits: Limits) -> Self { + Writer { + limits, + total: Rc::new(Cell::new(0)), + counted: Rc::new(Cell::new(0)), + fills: Records::default(), + outlines: Records::default(), + next_id: 1, + clips: Vec::new(), + clip_depth: 0, + objects: 0, + coordinates: 0, + dashes: 0, + clip_walked: 0, + layer_ids: 0, + id_at: Vec::new(), + master_refs: Vec::new(), + } + } + + /// A new layer id (R70), different from every other id in the file. + fn layer_id(&mut self) -> Result<[u8; 16], Error> { + self.layer_ids = self.layer_ids.checked_add(1).ok_or(Error::Limit("output size"))?; + let mut id = LAYER_ID; + for (slot, b) in id.iter_mut().zip(self.layer_ids.to_le_bytes()) { + *slot = b; + } + Ok(id) + } + + /// The entries that name the master page's guides, desktop and grid layers on another page + /// (R70): the grid layers' when `grids`, the others' otherwise. + fn master_refs(&mut self, out: &mut Out, grids: bool) -> Result<(), Error> { + let refs: Vec<_> = self.master_refs.iter().filter(|r| (r.1 == LayerKind::Grid) == grids).copied().collect(); + for (name, kind, flags, id) in refs { + self.layer(out, &LayerParts { name, kind, flags, master: true, id }, &[], [&[], &[]])?; + } + Ok(()) + } + + /// A `loda` record, within the arguments a read takes from one. + fn loda(&self, out: &mut Out, kind: u32, args: &[(u32, Vec)]) -> Result<(), Error> { + if args.len() > self.limits.arguments { + return Err(Error::Limit("argument count")); + } + out.loda(kind, args) + } + + /// `n` more chunks the reader steps through, counted against the clipped chunks while inside + /// a clipped group. + fn walk(&mut self, n: usize) -> Result<(), Error> { + if self.clip_depth == 0 { + return Ok(()); + } + self.clip_walked = self.clip_walked.saturating_add(n); + if self.clip_walked > self.limits.clipped_chunks { Err(Error::Limit("clipped chunk count")) } else { Ok(()) } + } + + fn take_object(&mut self) -> Result<(), Error> { + self.objects += 1; + if self.objects > self.limits.objects { Err(Error::Limit("object count")) } else { Ok(()) } + } + + /// The master page (R19, R70). + fn master_page(&mut self, out: &mut Out, drawing: &'d Drawing) -> Result<(), Error> { + out.open(b"page")?; + // Byte 2 marks the master page (R19). + out.chunk(b"flgs", &[0, 0, 1, 0x90])?; + out.open(b"gobj")?; + // The reader leaves out the master page's grid layers. + for l in drawing.master.iter().filter(|l| l.kind == LayerKind::Grid) { + if draws(&l.objects, &self.limits)? { + return Err(Error::Unwritable("objects on the master page's grid layer")); + } + } + // The drawing's master layers, with a guides, a desktop and a grid layer when they have + // none. The drawing's guidelines go in the first guides layer that is shown and unlocked, + // and in a guides layer of their own when there is none. + let made = |name, kind, flags, guides| MasterLayer { name, kind, flags, objects: &[], guides: [guides, &[]] }; + let first_guides = drawing.master.iter().position(|l| l.kind == LayerKind::Guides && l.flags == Flags::default()); + let has_guides = drawing.master.iter().any(|l| l.kind == LayerKind::Guides); + let own_guides = first_guides.is_none() && (!has_guides || !drawing.guides.is_empty()); + let guides_layer = own_guides.then(|| made("Guides", LayerKind::Guides, Flags::default(), &drawing.guides[..])); + let layers = drawing.master.iter().enumerate().map(|(i, l)| MasterLayer { + name: &l.name, + kind: l.kind, + flags: l.flags, + objects: &l.objects, + guides: [&l.guides, if Some(i) == first_guides { &drawing.guides } else { &[] }], + }); + let has_desktop = drawing.master.iter().any(|l| l.kind == LayerKind::Desktop); + let desktop = (!has_desktop).then(|| made("Desktop", LayerKind::Desktop, Flags::default(), &[])); + // A grid layer, hidden and locked as sample files hold it, when they have none; the reader + // leaves out the master page's grid layers (R70). + let has_grid = drawing.master.iter().any(|l| l.kind == LayerKind::Grid); + let grid = (!has_grid).then(|| made("Grid", LayerKind::Grid, Flags { hidden: true, locked: true }, &[])); + for l in guides_layer.into_iter().chain(layers).chain(desktop).chain(grid) { + let id = self.layer_id()?; + if l.kind != LayerKind::Drawing { + self.master_refs.push((l.name, l.kind, l.flags, id)); + } + self.layer(out, &LayerParts { name: l.name, kind: l.kind, flags: l.flags, master: true, id }, l.objects, l.guides)?; + } + out.close()?; + out.close() + } + + /// A page (R19, R21, R22): its flags, its size in its own `loda`, then its layers in a `gobj` + /// list. + fn page(&mut self, out: &mut Out, page: &'d Page) -> Result<(), Error> { + out.open(b"page")?; + out.chunk(b"flgs", &PAGE_FLAGS)?; + if let Some(size) = page.size { + let size = page_size(size)?; + out.open(b"lgob")?; + self.loda(out, 0, &[(ARG_PAGE_SIZE, size)])?; + out.close()?; + } + out.open(b"gobj")?; + // The entries for the master page's layers go around the page's own, as sample files + // place them (R70). + self.master_refs(out, false)?; + for l in &page.layers { + let id = self.layer_id()?; + self.layer(out, &LayerParts { name: &l.name, kind: l.kind, flags: l.flags, master: false, id }, &l.objects, [&l.guides, &[]])?; + } + self.master_refs(out, true)?; + out.close()?; + out.close() + } + + /// A layer (R19, R9): flags, its `loda` with its kind as the object type and its name, then + /// its objects and guidelines. + fn layer(&mut self, out: &mut Out, layer: &LayerParts, objects: &'d [Object], guides: [&[Guideline]; 2]) -> Result<(), Error> { + // The kind's low bits; bit 0x10, which also marks a grid, is the lock bit here, and the + // object type names the kind. + let (kind, byte0) = match layer.kind { + LayerKind::Drawing => (0, 0), + LayerKind::Grid => (11, 0x0a), + LayerKind::Guides => (12, 0x0a), + LayerKind::Desktop => (17, 0x08), + }; + out.open(b"layr")?; + // Byte 2 is set on the master page's layers and on the entries that name them. + out.chunk(b"flgs", &flags(layer.flags, byte0, u8::from(layer.master), 0x98))?; + out.open(b"lgob")?; + // The id is the first argument: after the chunk's header and the record's 20 bytes. + self.id_at.push(out.buf.len() + 8 + 20); + self.loda(out, kind, &[(ARG_LAYER_ID, layer.id.to_vec()), (ARG_NAME, name(layer.name)?)])?; + out.close()?; + self.objects(out, objects)?; + for g in guides.into_iter().flatten() { + self.guideline(out, g)?; + } + out.close() + } + + /// A guideline object (R23). + fn guideline(&mut self, out: &mut Out, g: &Guideline) -> Result<(), Error> { + self.take_object()?; + // The points lie along the angle as stored. + let stored = angle(g.angle)?; + let (s, c) = (f64::from(i32::from_le_bytes(stored)) / 1_000_000.0).to_radians().sin_cos(); + let along = |k: f64| -> Result, Error> { Ok([coord(g.at.x + k * c)?, coord(g.at.y + k * s)?].concat()) }; + let first = along(0.0)?; + // Whether a rounded second point lies apart from the first along the stored angle, on + // either side, within `GUIDE_TURN`. + let units = |p: &[u8], i: usize| p.get(4 * i..4 * i + 4).and_then(|b| b.try_into().ok()).map_or(0.0, |b| f64::from(i32::from_le_bytes(b))); + let along_angle = |p: &Vec| { + let (dx, dy) = (units(p, 0) - units(&first, 0), units(p, 1) - units(&first, 1)); + // With room for the floating-point error of a turn of exactly `GUIDE_TURN`. + (dx != 0.0 || dy != 0.0) && (dx * s - dy * c).abs().atan2((dx * c + dy * s).abs()) <= GUIDE_TURN.to_radians() + 1e-12 + }; + // A second point on the line: the point at the full reach, on the positive side first. + // When neither side has one in the file's range, the farthest point on each side whose + // coordinates round within the range, and of the two the one farther away. Rounding moves + // monotonically along the line, so the points that round within the range form one span + // around the first point; halving the step finds its end to the last representable + // value. Short of a farthest point along the angle, which only happens within + // `GUIDE_STEPS` units of the range's edge, the farthest rounded point of the line within + // that distance that lies along the angle, on either side. + let full = [GUIDE_REACH, -GUIDE_REACH].into_iter().find_map(|k| along(k).ok().filter(along_angle)); + let stepped = || { + // Each side's run of rounded points, walked outward from the start with `along` + // itself: a step of one unit's length at a time, and a halving search for where the + // rounded point changes, so every rounded point the line passes through is reached. + let reach = f64::from(GUIDE_STEPS) / (UNITS_PER_PT * c.abs().max(s.abs())); + let unit = 1.0 / UNITS_PER_PT; + let mut best: Option<(f64, Vec)> = None; + for side in [1.0, -1.0] { + let (mut k, mut current) = (0.0, first.clone()); + loop { + let next = |k: f64| side * (k.abs() + unit).min(reach); + let mut far = next(k); + while along(far).ok().as_ref() == Some(¤t) && far.abs() < reach { + k = far; + far = next(k); + } + if along(far).ok().as_ref() == Some(¤t) { + break; + } + let (mut same, mut changed) = (k, far); + loop { + let mid = same + (changed - same) / 2.0; + if mid == same || mid == changed { + break; + } + if along(mid).ok().as_ref() == Some(¤t) { same = mid } else { changed = mid } + } + let Ok(p) = along(changed) else { break }; + if along_angle(&p) && best.as_ref().is_none_or(|b| changed.abs() > b.0.abs()) { + best = Some((changed, p.clone())); + } + (k, current) = (changed, p); + } + } + best.map(|(_, p)| p) + }; + let farthest = |end: f64| -> Option<(f64, Vec)> { + let (mut ok, mut bad) = (0.0, end); + loop { + let mid = ok + (bad - ok) / 2.0; + if mid == ok || mid == bad { + break; + } + if along(mid).is_ok() { ok = mid } else { bad = mid } + } + along(ok).ok().map(|p| (ok, p)) + }; + let second = full + .or_else(|| { + [farthest(GUIDE_REACH), farthest(-GUIDE_REACH)] + .into_iter() + .flatten() + .filter(|(_, p)| along_angle(p)) + .reduce(|a, b| if b.0.abs() > a.0.abs() { b } else { a }) + .map(|(_, p)| p) + }) + .or_else(stepped) + .ok_or(Error::Unwritable("guidelines with no room for a second point along their angle"))?; + let mut arg = vec![0; 12]; + arg.extend(stored); + arg.extend(&first); + arg.extend(second); + arg.extend(first); + out.open(b"obj ")?; + out.chunk(b"flgs", &flags(Flags { hidden: g.hidden, locked: false }, 0, 0, 0x08))?; + out.open(b"lgob")?; + self.loda(out, GUIDELINE, &[(ARG_GUIDE, arg)])?; + out.close()?; + out.close() + } + + /// `objects`, front to back, groups nested, without recursion. + fn objects(&mut self, out: &mut Out, objects: &'d [Object]) -> Result<(), Error> { + // The objects left at each level, the layer's and then each group's, with the group's + // flags. The reader leaves out a group that holds no shape or container, so a group's list + // is written only when the first one is reached: the first `written` levels have theirs. + let mut levels = vec![(objects.iter(), Flags::default())]; + let mut written = 1; + loop { + let Some((level, _)) = levels.last_mut() else { return Ok(()) }; + let Some(object) = level.next() else { + levels.pop(); + if levels.is_empty() { + return Ok(()); + } + if written > levels.len() { + written = levels.len(); + // The reader counts a group once its objects are read. + self.take_object()?; + out.close()?; + } + continue; + }; + if let Object::Group { objects, flags } = object { + // Groups nested past the depth are refused even when they hold nothing, so the + // walk holds no more levels than that. This group is `levels.len()` deep. + if levels.len() > self.limits.depth { + return Err(Error::Limit("nesting depth")); + } + if !objects.is_empty() { + levels.push((objects.iter(), *flags)); + } + continue; + } + for (_, f) in levels.get(written..).unwrap_or_default() { + self.walk(2)?; + out.open(b"grp ")?; + out.chunk(b"flgs", &flags(*f, 0, 0, 0x10))?; + } + written = levels.len(); + match object { + Object::Shape(s) => { + self.walk(OBJECT_WALK)?; + self.shape(out, s, None)?; + } + Object::Group { .. } => {} + Object::Clip { container, objects } => { + self.walk(OBJECT_WALK)?; + // The reader reads a container whose objects hold no shape as a plain shape. + if !draws(objects, &self.limits)? { + self.shape(out, container, None)?; + continue; + } + let depth = self.clip_depth + 1; + if depth > MAX_CLIP_DEPTH { + return Err(Error::Limit("clip nesting")); + } + // Ids 1, 2, 3 ..., the same in the container and its group's `spnd` (R46, R73). + let id = len32(self.clips.len() + 1)?; + if self.clips.is_empty() { + // The `doc` list's `LIST clpt`, which holds the clipped groups. + self.counted.set(self.counted.get().saturating_add(1)); + } + self.clips.push((id, objects, depth)); + self.shape(out, container, Some(id))?; + } + } + } + } + + /// The `LIST clpt` body: one group for each container, holding the objects it clips (R46); + /// `None` without containers. The groups' own objects may name more groups. + fn clipped_groups(&mut self) -> Result, Error> { + if self.clips.is_empty() { + return Ok(None); + } + // `doc` and `clpt` are around the groups. + let mut out = Out::new(2, self.limits, self.total.clone(), self.counted.clone()); + let mut i = 0; + // The reader steps through a clipped group's `spnd` and flags, then the lists of its + // objects, each time a container names the group; each container names its own. + while let Some(&(id, objects, depth)) = self.clips.get(i) { + i += 1; + self.clip_depth = depth; + self.walk(2)?; + out.open(b"grp ")?; + out.chunk(b"spnd", &id.to_le_bytes())?; + // Byte 2 marks the group a container clips (R67). + out.chunk(b"flgs", &flags(Flags::default(), 0, 0x80, 0x10))?; + self.objects(&mut out, objects)?; + out.close()?; + } + Ok(Some(out)) + } + + /// One shape's object list (R19, R22): flags, then its `loda` and its transform in a `lgob` + /// list. `clip` names the group it clips. + fn shape(&mut self, out: &mut Out, s: &Shape, clip: Option) -> Result<(), Error> { + self.take_object()?; + // The arguments the shape's `loda` takes, counted before its points are encoded: the + // outline, the fill and the coordinates, and the winding, transparency and container + // arguments it carries. + let opacity = share(s.opacity)?; + let seen_through = opacity < 1.0 || s.blend != Blend::Normal; + let arguments = 3 + usize::from(s.nonzero) + usize::from(seen_through) + usize::from(clip.is_some()); + if arguments > self.limits.arguments { + return Err(Error::Limit("argument count")); + } + // The fill and outline records the shape names, added before its points are encoded so + // that they count toward the limits first. + let outline = self.outline(s.outline.as_ref())?; + let fill = self.fill(s.fill.as_ref())?; + // The transparency record names a white uniform fill as the sample files do (R69). + let white = if seen_through { Some(self.fill(Some(&Color::Rgb([1.0; 3])))?) } else { None }; + // The object's lists, `obj `, `lgob` and `trfl`, and its chunks, those three with `flgs`, + // `loda` and `trfd`. + out.fits(3, 6)?; + let (kind, coords) = self.geometry(&s.geometry, &s.matrix)?; + let mut args = vec![(ARG_OUTLINE, outline.to_le_bytes().to_vec()), (ARG_FILL, fill.to_le_bytes().to_vec()), (ARG_COORDS, coords)]; + if s.nonzero { + args.push((ARG_WINDING, vec![1, 0, 0, 0])); + } + // Byte 2 of the flags marks an object seen through (0x08) and a clipping container (0x10) + // (R67). + let mut byte2 = 0; + if let Some(white) = white { + args.push((ARG_TRANSPARENCY, transparency(opacity, s.blend, white))); + byte2 |= 0x08; + } + if clip.is_some() { + byte2 |= 0x10; + } + if let Some(id) = clip { + // As sample files lay it out (R46). + args.push((ARG_CONTAINER, [id, 1, 0, 1].iter().flat_map(|v| v.to_le_bytes()).collect())); + } + out.open(b"obj ")?; + out.chunk(b"flgs", &flags(s.flags, 0, byte2, 0x08))?; + out.open(b"lgob")?; + self.loda(out, kind, &args)?; + out.open(b"trfl")?; + out.chunk(b"trfd", &trfd(&s.matrix)?)?; + out.close()?; + out.close()?; + out.close() + } + + /// The object type and coordinates argument of `g`, drawn through `m`. + fn geometry(&mut self, g: &Geometry, m: &Matrix) -> Result<(u32, Vec), Error> { + Ok(match g { + Geometry::Rect { w, h, radii } => (RECTANGLE, rect(*w, *h, radii, m)?), + Geometry::Ellipse { w, h } => { + // Equal start and end angles: a whole ellipse (R17). + let mut b = [coord(*w)?, coord(*h)?].concat(); + b.extend([0; 12]); + (ELLIPSE, b) + } + Geometry::Path(p) => (CURVE, self.points(p)?), + }) + } + + /// A curve's point list (R16): the count, the points, then their type bytes. + fn points(&mut self, path: &Path) -> Result, Error> { + // A subpath without segments draws nothing, and the reader leaves it out. + let drawn = || path.subpaths.iter().filter(|s| !s.segments.is_empty()); + // A closed subpath ends with a point at its start (R68): a closing line is added when its + // last segment ends elsewhere. + let adds_close = |sp: &SubPath| -> Result { + let end = match sp.segments.last() { + Some(Segment::Line(p) | Segment::Cubic(_, _, p)) => *p, + None => return Ok(false), + }; + Ok(sp.closed && [coord(end.x)?, coord(end.y)?] != [coord(sp.start.x)?, coord(sp.start.y)?]) + }; + // `n` points within the coordinate count and, at two coordinates and a type byte each, on + // top of what the file holds so far, within its size. + let fits = |n: usize| -> Result<(), Error> { + if self.coordinates.saturating_add(n) > self.limits.coordinates { + return Err(Error::Limit("coordinate count")); + } + fits_stream(&self.limits, self.total.get().saturating_add(n.saturating_mul(9)).saturating_add(4)) + }; + // A subpath takes at least a point for its start and one for each segment, so a path past + // either limit stops before its segments are looked at one by one, and the count stops + // at the segment that takes it past. + let mut n = 0usize; + for sp in drawn() { + fits(n.saturating_add(sp.segments.len()).saturating_add(1))?; + n = n.saturating_add(1); + for s in &sp.segments { + n = n.saturating_add(if matches!(s, Segment::Line(_)) { 1 } else { 3 }); + fits(n)?; + } + n = n.saturating_add(usize::from(adds_close(sp)?)); + fits(n)?; + } + fits(n)?; + self.coordinates = self.coordinates.saturating_add(n); + // The record: the count, the points, then the type bytes, which go in their own buffer. + let mut b = Vec::with_capacity(4 + n * 9); + b.extend(len32(n)?.to_le_bytes()); + let mut types: Vec = Vec::with_capacity(n); + let mut put = |p: Pt, t: u8| -> Result<(), Error> { + b.extend(coord(p.x)?); + b.extend(coord(p.y)?); + types.push(t); + Ok(()) + }; + for sp in drawn() { + let added = adds_close(sp)?; + put(sp.start, EDITABLE | if sp.closed { CLOSES } else { 0 })?; + let last = sp.segments.len().saturating_sub(1); + for (i, seg) in sp.segments.iter().enumerate() { + // The end that closes the subpath is not editable; every other end is (R68). + let end = if sp.closed && !added && i == last { CLOSES } else { EDITABLE }; + match *seg { + Segment::Line(p) => put(p, LINE | end)?, + Segment::Cubic(c1, c2, p) => { + put(c1, CONTROL)?; + put(c2, CONTROL)?; + put(p, CURVE_END | end)?; + } + } + } + if added { + put(sp.start, LINE | CLOSES)?; + } + } + b.extend(types); + Ok(b) + } + + /// The id of the fill record of `color` (R11): a uniform fill, or a fill of type 0 for none. + fn fill(&mut self, color: Option<&Color>) -> Result { + let mut body = Vec::new(); + match color { + None => body.extend(0u16.to_le_bytes()), + Some(c) => { + let props = properties(c, true)?; + body.extend(1u16.to_le_bytes()); + body.extend(TAG_1300.to_le_bytes()); + body.extend(len32(props.len())?.to_le_bytes()); + body.extend(props); + // The 8 bytes that end a uniform fill (R66). + body.extend([0; 8]); + } + } + let mut record = TAG_1300.to_le_bytes().to_vec(); + record.extend(len32(body.len())?.to_le_bytes()); + record.extend(body); + // Each fill record sits in a `LIST filc` of its own (R72). + Self::record(&mut self.fills, &mut self.next_id, record, true, &self.limits, [&self.total, &self.counted]) + } + + /// The id of the outline record of `outline` (R12, R13, R48, R49, R50); without one, an + /// outline whose line type says none. + fn outline(&mut self, outline: Option<&Outline>) -> Result { + let none = Outline { + width: 0.0, + color: Color::Gray(1.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: Vec::new(), + behind_fill: false, + scale_with: false, + }; + let o = outline.unwrap_or(&none); + // Dash and gap lengths in whole outline widths, as u16, in the room before the arrowhead + // ids (R12). + if o.dashes.len() > MAX_DASHES { + return Err(Error::Unwritable("dash patterns of more than 10 lengths")); + } + if o.dashes.iter().any(|d| !(d.is_finite() && *d >= 0.0)) { + return Err(Error::Unwritable("dash lengths that are negative or not finite")); + } + if o.dashes.iter().any(|d| d.round() > f64::from(u16::MAX)) { + return Err(Error::Unwritable("dash lengths past 65,535 outline widths")); + } + let dashes: Vec = o.dashes.iter().map(|d| d.round() as u16).collect(); + let dashed = outline.is_some() && dashes.iter().any(|d| *d > 0); + // A pattern whose lengths all round to 0 reads back as a solid line, without its lengths + // (R48). + if outline.is_some() && !dashed && !o.dashes.is_empty() { + return Err(Error::Unwritable("dash patterns whose lengths all round to 0 outline widths")); + } + if dashed { + // The reader counts an outline's dashes for every shape that uses it. + self.dashes = self.dashes.saturating_add(dashes.len()); + if self.dashes > self.limits.dashes { + return Err(Error::Limit("dash count")); + } + } + // Bit 0 no outline (R13), 1 as in the plain outlines of sample files (R49), 2 dashed (R48), + // 4 behind the fill (R49), 5 scaled with the shape (R50). + let line_type: u16 = match outline { + None => 1, + Some(o) => 0x02 | if dashed { 0x04 } else { 0 } | if o.behind_fill { 0x10 } else { 0 } | if o.scale_with { 0x20 } else { 0 }, + }; + let color = color_record(&o.color)?; + let mut body = Vec::new(); + // A library color is named in a record of type 2 (R12). + if matches!(o.color, Color::Spot { .. }) { + // An outline's list ends at its empty property (R71). + let props = properties(&o.color, false)?; + body.extend(2u32.to_le_bytes()); + body.extend(len32(props.len())?.to_le_bytes()); + body.extend(props); + } + let mut fields = Vec::new(); + for v in [line_type, cap(o.cap), join(o.join)] { + fields.extend(v.to_le_bytes()); + } + if o.width < 0.0 { + return Err(Error::Unwritable("negative outline widths")); + } + let width = coord(o.width)?; + // A width of 0 reads back as no width, which a positive width must not become. + if o.width > 0.0 && width == [0; 4] { + return Err(Error::Unwritable("outline widths that round to 0")); + } + fields.extend(width); + // The stretch, 100 percent, and 2 bytes; the nib angle and 46 bytes. + fields.extend(100u16.to_le_bytes()); + fields.extend([0; 2]); + fields.extend(angle(0.0)?); + fields.extend([0; 46]); + fields.extend(color); + fields.extend([0; 16]); + fields.extend((dashes.len() as u16).to_le_bytes()); + let mut slots = [0u8; 2 * MAX_DASHES]; + for (slot, b) in slots.iter_mut().zip(dashes.iter().flat_map(|d| d.to_le_bytes())) { + *slot = b; + } + fields.extend(slots); + // The start and end arrowhead ids (none), and the rest of the record. + fields.extend([0; 16]); + // As sample files hold them (R71): an f64 1 at bytes 16 and 48, and 45 degrees and 60 at + // bytes 84 and 88. + let one = 1f64.to_le_bytes(); + let patches: [(usize, &[u8]); 4] = [(16, &one), (48, &one), (84, &45_000_000i32.to_le_bytes()), (88, &60u32.to_le_bytes())]; + for (at, bytes) in patches { + for (slot, b) in fields.iter_mut().skip(at).zip(bytes) { + *slot = *b; + } + } + body.extend(1u32.to_le_bytes()); + body.extend(len32(fields.len())?.to_le_bytes()); + body.extend(fields); + // 8 bytes follow the record (R71). + body.extend([0; 8]); + Self::record(&mut self.outlines, &mut self.next_id, body, false, &self.limits, [&self.total, &self.counted]) + } + + /// The id of the record with `body`, adding it when it is new. Its chunk, with its header, + /// its id and its pad byte, and the list around it when `wrapped`, count toward the file's + /// bytes and chunks. + fn record( + records: &mut Records, + next_id: &mut u32, + body: Vec, + wrapped: bool, + limits: &Limits, + spent: [&Cell; 2], + ) -> Result { + if let Some(id) = records.ids.get(body.as_slice()) { + return Ok(*id); + } + let [total, counted] = spent; + let chunk = body.len().saturating_add(4); + let n = total.get().saturating_add(8).saturating_add(chunk).saturating_add(chunk % 2).saturating_add(if wrapped { 12 } else { 0 }); + fits_stream(limits, n)?; + let chunks = counted.get().saturating_add(1 + usize::from(wrapped)); + if chunks > limits.chunks { + return Err(Error::Limit("chunk count")); + } + total.set(n); + counted.set(chunks); + let id = *next_id; + *next_id = next_id.checked_add(1).ok_or(Error::Limit("output size"))?; + let body: Rc<[u8]> = body.into(); + records.bodies.push((id, body.clone())); + records.ids.insert(body, id); + Ok(id) + } +} + +/// Whether `objects` hold a shape or a container. Groups that hold only empty groups draw nothing, +/// and the reader leaves them out. Groups nested past the depth are refused, as +/// [`Writer::objects`] refuses them. +fn draws(objects: &[Object], limits: &Limits) -> Result { + let mut open = vec![objects.iter()]; + while let Some(level) = open.last_mut() { + match level.next() { + None => { + open.pop(); + } + Some(Object::Group { objects, .. }) => { + if open.len() > limits.depth { + return Err(Error::Limit("nesting depth")); + } + open.push(objects.iter()); + } + Some(_) => return Ok(true), + } + } + Ok(false) +} + +/// Point type bytes (R16): a line end, a control point, a curve end, and bit 3, which closes the +/// subpath; bit 2 marks a node that can be edited (R68). +const LINE: u8 = 0x40; +const CONTROL: u8 = 0xC0; +const CURVE_END: u8 = 0x80; +const CLOSES: u8 = 0x08; +const EDITABLE: u8 = 0x04; + +/// A `flgs` chunk (R19): bit 0x10 of byte 0 locks, bit 0x01 of byte 1 hides; byte 3 the record +/// type. +fn flags(f: Flags, byte0: u8, byte2: u8, kind: u8) -> [u8; 4] { + [byte0 | if f.locked { 0x10 } else { 0 }, u8::from(f.hidden), byte2, kind] +} + +/// A length in points as an i32 coordinate (R5). +fn coord(pt: f64) -> Result<[u8; 4], Error> { + let units = (pt * UNITS_PER_PT).round(); + if !(units.is_finite() && (f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(&units)) { + return Err(Error::Unwritable("coordinates past the file's range")); + } + Ok((units as i32).to_le_bytes()) +} + +/// A page's width and height as coordinates (R10, R21); the reader takes a size only when both +/// are above 0. +fn page_size((w, h): (f64, f64)) -> Result, Error> { + if !((w * UNITS_PER_PT).round() >= 1.0 && (h * UNITS_PER_PT).round() >= 1.0) { + return Err(Error::Unwritable("page sizes that are not above 0")); + } + Ok([coord(w)?, coord(h)?].concat()) +} + +/// An angle in degrees as i32 millionths (R7). +fn angle(deg: f64) -> Result<[u8; 4], Error> { + let fits = |v: f64| (f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(&v); + let v = (deg * 1_000_000.0).round(); + // An angle past the field's range is written as the same angle within one turn. + let v = if fits(v) { v } else { (deg.rem_euclid(360.0) * 1_000_000.0).round() }; + if !v.is_finite() { + return Err(Error::Unwritable("angles that are not finite")); + } + Ok((v as i32).to_le_bytes()) +} + +/// A finite f64, or [`WriteError::Unwritable`]. +fn finite(v: f64, what: &'static str) -> Result<[u8; 8], Error> { + if v.is_finite() { Ok(v.to_le_bytes()) } else { Err(Error::Unwritable(what)) } +} + +/// The `mcfg` chunk (R10, R72): the tag 1300, the length of the rest and 4 bytes, the page width +/// and height, then 16 bytes. +fn mcfg(size: (f64, f64)) -> Result, Error> { + let mut b = TAG_1300.to_le_bytes().to_vec(); + b.extend([0; 8]); + b.extend(page_size(size)?); + b.extend([0; 16]); + let rest = len32(b.len() - 8)?.to_le_bytes(); + if let Some(slot) = b.get_mut(4..8) { + slot.copy_from_slice(&rest); + } + Ok(b) +} + +/// A `trfd` record of one matrix (R8, R51, R65): length, count, where the offsets lie and 0xFFFF; +/// the offsets with one more for the end; then the entry: the tag 1300 and a u32 0, type 8, 6 +/// bytes, `a c tx b d ty` as f64 with the offsets in coordinate units, and 8 bytes. +fn trfd(m: &Matrix) -> Result, Error> { + const ENTRY_AT: u32 = 24; + const ENTRY_LEN: u32 = 8 + 2 + 6 + 48 + 8; + let [a, b, c, d, e, f] = m.0; + let mut out = Vec::with_capacity((ENTRY_AT + ENTRY_LEN) as usize); + for v in [ENTRY_AT + ENTRY_LEN, 1, 16, 0xFFFF, ENTRY_AT, ENTRY_AT + ENTRY_LEN] { + out.extend(v.to_le_bytes()); + } + out.extend(TAG_1300.to_le_bytes()); + out.extend([0; 4]); + out.extend(8u16.to_le_bytes()); + out.extend([0; 6]); + for v in [a, c, e * UNITS_PER_PT, b, d, f * UNITS_PER_PT] { + out.extend(finite(v, "transforms that are not finite")?); + } + out.extend([0; 8]); + Ok(out) +} + +/// Rectangle coordinates (R29): width and height in coordinate units as f64, the scale factors +/// 1 and 1, the scale-with flag clear and 7 bytes, then each corner's radius as a share of half the +/// shorter side, 16 bytes apart. +fn rect(w: f64, h: f64, radii: &[f64; 4], m: &Matrix) -> Result, Error> { + // The reader takes sizes within the range of 32-bit coordinates, as stored. + // Within half a unit of the range is the range, as conversion rounding can carry a size the + // reader gave just past it. + let max = f64::from(i32::MAX); + let stored = |v: f64| -> Result { + let u = v * UNITS_PER_PT; + if !(u.is_finite() && u.abs() <= max + 0.5) { + return Err(Error::Unwritable("coordinates past the file's range")); + } + Ok(u.clamp(-max, max)) + }; + let (wu, hu) = (stored(w)?, stored(h)?); + let half = w.abs().min(h.abs()) / 2.0; + // The reader holds a corner to half the shorter side. + if radii.iter().any(|r| !(r.is_finite() && *r >= 0.0 && *r <= half * (1.0 + 1e-9))) { + return Err(Error::Unwritable("corner radii below 0 or past half the shorter side")); + } + // The scale fields repeat the transform's scale (R29): the lengths its x and y axes take, the + // writer's own reading for a transform that also turns or skews. + let [a, b, c, d, ..] = m.0; + let (sx, sy) = (a.hypot(b), c.hypot(d)); + if !(sx.is_finite() && sy.is_finite()) { + return Err(Error::Unwritable("transforms that are not finite")); + } + let mut out = Vec::with_capacity(32 + 8 + 4 * 8 + 3 * 16); + for v in [wu, hu, sx, sy] { + out.extend(v.to_le_bytes()); + } + out.extend([0; 8]); + for (k, r) in radii.iter().enumerate() { + if k > 0 { + out.extend([0; 16]); + } + let share = if half > 0.0 { (r / half).min(1.0) } else { 0.0 }; + out.extend(share.to_le_bytes()); + } + Ok(out) +} + +/// A value from 0 to 1 as a byte from 0 to 255. +fn byte(v: f32) -> Result { + Ok((share(v)? * 255.0).round() as u8) +} + +/// `v` when it is from 0 to 1, as colors, tints and opacity are. +fn share(v: f32) -> Result { + if (0.0..=1.0).contains(&v) { Ok(v) } else { Err(Error::Unwritable("color values, tints or opacity outside 0 to 1")) } +} + +/// A 12-byte color record (R14): model, palette, 4 bytes, four value bytes. RGB is model 5 (blue, +/// green, red), CMYK model 3 (0 to 255), gray model 9, registration model 20; a library color is +/// model 21, its full-strength look mixed toward white by its tint and the tint in percent last. +/// A library color without a look is written black. +fn color_record(c: &Color) -> Result<[u8; 12], Error> { + let (model, v): (u16, [u8; 4]) = match c { + Color::Rgb([r, g, b]) => (5, [byte(*b)?, byte(*g)?, byte(*r)?, 0]), + Color::Cmyk([c, m, y, k]) => (3, [byte(*c)?, byte(*m)?, byte(*y)?, byte(*k)?]), + Color::Gray(ink) => (9, [byte(1.0 - share(*ink)?)?, 0, 0, 0]), + Color::Registration => (20, [0; 4]), + Color::Spot { tint, look, .. } => { + // The tint is stored in whole percent; at 0 the stored color is white whatever the + // look, which the reader can't take off again. + let percent = (share(*tint)? * 100.0).round(); + if percent < 1.0 { + return Err(Error::Unwritable("spot colors at a tint below 0.5 percent")); + } + let t = percent / 100.0; + let [r, g, b] = look.unwrap_or([0.0; 3]); + // The reader takes the tint off again (`records::untinted`); a low tint leaves too few + // steps of the stored byte for the look to come back within one step. + // The nearest byte to the tinted value is written, or the other byte around it when + // only that one reads back within the step. + let tinted = |v: f32| -> Result { + let ideal = (1.0 - (1.0 - share(v)?) * t) * 255.0; + let reads_back = |s: &f32| ((1.0 - (1.0 - s / 255.0) / t).clamp(0.0, 1.0) - v).abs() <= 1.0 / 255.0 + 1e-6; + match [ideal.round(), ideal.floor(), ideal.ceil()].into_iter().find(reads_back) { + Some(s) => Ok(s.clamp(0.0, 255.0) as u8), + None => Err(Error::Unwritable("spot colors at a tint too low to keep their look")), + } + }; + (21, [tinted(b)?, tinted(g)?, tinted(r)?, percent as u8]) + } + }; + let mut out = [0; 12]; + for (slot, b) in out.iter_mut().zip(model.to_le_bytes().into_iter().chain([0; 6]).chain(v)) { + *slot = b; + } + Ok(out) +} + +/// A property list (R11, R12): the color, and for a library color its name in a property of type 8 +/// (16 bytes, then the count of UTF-16 units and the units); an empty property ends it. With +/// `tail`, the fields a fill's list has after that follow (R66). +fn properties(c: &Color, tail: bool) -> Result, Error> { + let mut out = vec![1]; + out.extend(12u32.to_le_bytes()); + out.extend(color_record(c)?); + if let Color::Spot { name, .. } = c { + // A color without a name reads back as a process color. + if name.is_empty() { + return Err(Error::Unwritable("spot colors without a name")); + } + let units = units(name)?; + let mut body = vec![0; 16]; + body.extend(len32(units.len())?.to_le_bytes()); + body.extend(units.iter().flat_map(|u| u.to_le_bytes())); + out.push(8); + out.extend(len32(body.len())?.to_le_bytes()); + out.extend(body); + } + out.extend([0; 5]); + if tail { + // After a fill's list (R66): two u16, the overprint flag (u32), an angle and a u32. The + // first u16, the angle and the last u32 hold the values the specification names as usual + // (0, 45 degrees and 60); the second u16 and the flag hold 0, a value sample files hold + // there. + out.extend([0; 8]); + out.extend(45_000_000i32.to_le_bytes()); + out.extend(60u32.to_le_bytes()); + } + Ok(out) +} + +/// A name argument (R9): UTF-16LE and a closing NUL. +fn name(s: &str) -> Result, Error> { + Ok(units(s)?.into_iter().chain([0]).flat_map(u16::to_le_bytes).collect()) +} + +/// The UTF-16 units of a name the reader reads back whole: at most [`MAX_NAME`] of them, without +/// a NUL, where a name ends. +fn units(s: &str) -> Result, Error> { + let units: Vec = s.encode_utf16().take(MAX_NAME + 1).collect(); + if units.len() > MAX_NAME || units.contains(&0) { + return Err(Error::Unwritable("names longer than 256 UTF-16 units or holding a NUL")); + } + Ok(units) +} + +fn cap(c: Cap) -> u16 { + match c { + Cap::Butt => 0, + Cap::Round => 1, + Cap::Square => 2, + } +} + +fn join(j: Join) -> u16 { + match j { + Join::Miter => 0, + Join::Round => 1, + Join::Bevel => 2, + } +} + +/// Argument 8000 of a uniform transparency (R47): a record tagged 1300 whose 117-byte body holds +/// the transparency in percent (f64) at byte 61, the merge mode at byte 77 and the id of `fill` at +/// byte 105 (R69), with the other fields as the sample files hold them (R69). +fn transparency(opacity: f32, blend: Blend, fill: u32) -> Vec { + let mut body = [0u8; 117]; + let percent = (1.0 - f64::from(opacity)) * 100.0; + let fields: [(usize, &[u8]); 6] = [ + (0, &261u32.to_le_bytes()), + (57, &u32::MAX.to_le_bytes()), + (61, &percent.to_le_bytes()), + (69, &100f64.to_le_bytes()), + (77, &[merge(blend), 0, 0, 0, 2]), + (105, &fill.to_le_bytes()), + ]; + for (at, bytes) in fields { + for (slot, b) in body.iter_mut().skip(at).zip(bytes) { + *slot = *b; + } + } + let mut out = TAG_1300.to_le_bytes().to_vec(); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + out +} + +/// The merge mode byte of `blend` (R47). +fn merge(blend: Blend) -> u8 { + match blend { + Blend::Normal => 0, + Blend::Multiply => 9, + Blend::Lighten => 11, + Blend::Darken => 12, + Blend::Color => 14, + Blend::Hue => 15, + Blend::Saturation => 16, + Blend::Luminosity => 17, + Blend::Difference => 24, + Blend::Screen => 28, + Blend::Overlay => 29, + Blend::SoftLight => 30, + Blend::HardLight => 31, + Blend::ColorDodge => 33, + Blend::ColorBurn => 34, + Blend::Exclusion => 36, + } +} + +/// A ZIP archive (R24) dated 1980-01-01: the stored `mimetype` member (R64), then the RIFF file +/// made of `riff`'s parts, deflated (R25). The parts are compressed as they are, without being +/// joined first, straight into the archive after the member's header. `craft_zip::Writer` streams +/// an entry only with ZIP64 size fields, which `zip.rs` refuses, and otherwise takes one slice. +fn package(riff: &[&[u8]]) -> Result, Error> { + let size = riff.iter().map(|p| p.len()).fold(0usize, usize::saturating_add); + let mut out = Vec::new(); + let mut dir = Vec::with_capacity(160); + let at = header(&mut out, MIMETYPE_NAME, 0, crc32fast::hash(MIMETYPE), MIMETYPE.len(), MIMETYPE.len())?; + out.extend(MIMETYPE); + entry(&mut dir, &out, at, MIMETYPE_NAME)?; + // The RIFF file's CRC-32 and packed size go in its header once it is compressed. + let at = header(&mut out, MEMBER, 8, 0, 0, size)?; + let start = out.len(); + let mut crc = crc32fast::Hasher::new(); + let mut e = flate2::write::DeflateEncoder::new(out, flate2::Compression::default()); + for part in riff { + crc.update(part); + e.write_all(part).map_err(|_| Error::Limit("output size"))?; + } + let mut out = e.finish().map_err(|_| Error::Limit("output size"))?; + let fields = [crc.finalize(), len32(out.len() - start)?].map(u32::to_le_bytes).concat(); + if let Some(slot) = out.get_mut(at + 14..at + 22) { + slot.copy_from_slice(&fields); + } + entry(&mut dir, &out, at, MEMBER)?; + let dir_at = len32(out.len())?; + let dir_len = len32(dir.len())?; + out.extend(dir); + out.extend(0x0605_4b50u32.to_le_bytes()); + out.extend([0; 4]); + out.extend(2u16.to_le_bytes()); + out.extend(2u16.to_le_bytes()); + out.extend(dir_len.to_le_bytes()); + out.extend(dir_at.to_le_bytes()); + out.extend(0u16.to_le_bytes()); + Ok(out) +} + +/// A member's local header into `out`, stored (`method` 0) or deflated (8), with the CRC-32, the +/// packed size and the full size of its bytes; where the header starts. +fn header(out: &mut Vec, name: &[u8], method: u16, crc: u32, packed: usize, size: usize) -> Result { + let at = out.len(); + out.extend(0x0403_4b50u32.to_le_bytes()); + // Version needed, flags, method, time, date, CRC-32, packed and full sizes, name length. + for v in [20, 0, method, 0, 0x21] { + out.extend(v.to_le_bytes()); + } + for v in [crc, len32(packed)?, len32(size)?] { + out.extend(v.to_le_bytes()); + } + out.extend((name.len() as u16).to_le_bytes()); + // No extra field. + out.extend(0u16.to_le_bytes()); + out.extend(name); + Ok(at) +} + +/// The central directory entry into `dir` of the member whose local header is at `at` in `out`. +fn entry(dir: &mut Vec, out: &[u8], at: usize, name: &[u8]) -> Result<(), Error> { + dir.extend(0x0201_4b50u32.to_le_bytes()); + // Made by version 2.0, then the local header's fields from the version needed to the name + // length. + dir.extend(20u16.to_le_bytes()); + dir.extend(out.get(at + 4..at + 28).ok_or(Error::Limit("output size"))?); + // Extra and comment lengths, disk, internal and external attributes, then the header's offset. + dir.extend([0; 12]); + dir.extend(len32(at)?.to_le_bytes()); + dir.extend(name); + Ok(()) +} diff --git a/crates/cdr/tests/it/main.rs b/crates/cdr/tests/it/main.rs index 4fc7dcbdc9..23419e0936 100644 --- a/crates/cdr/tests/it/main.rs +++ b/crates/cdr/tests/it/main.rs @@ -6,3 +6,4 @@ mod bench; mod cmx; mod provenance; mod read; +mod write; diff --git a/crates/cdr/tests/it/write.rs b/crates/cdr/tests/it/write.rs new file mode 100644 index 0000000000..6112e035f8 --- /dev/null +++ b/crates/cdr/tests/it/write.rs @@ -0,0 +1,976 @@ +//! Writing drawings and reading them back. + +use std::io::Read as _; + +use craft_cdr::WriteError as Error; +use craft_cdr::model::{ + Blend, Cap, Color, Drawing, Flags, Geometry, Guideline, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Path, Pt, Segment, Shape, SubPath, +}; +use craft_cdr::{Limits, WRITTEN_VERSION, is_cdr, read, write}; +use proptest::prelude::*; + +/// `n` coordinate units (1/254000 inch) in points, which the file stores exactly. +fn u(n: i32) -> f64 { + f64::from(n) * (72.0 / 254_000.0) +} + +fn pt(x: i32, y: i32) -> Pt { + Pt { x: u(x), y: u(y) } +} + +/// A byte value as a color component, which the file stores exactly. +fn c(v: u8) -> f32 { + f32::from(v) / 255.0 +} + +fn moved(x: f64, y: f64) -> Matrix { + Matrix([1.0, 0.0, 0.0, 1.0, x, y]) +} + +fn layer(name: &str, objects: Vec) -> Layer { + Layer { name: name.into(), kind: LayerKind::Drawing, flags: Flags::default(), objects, guides: Vec::new() } +} + +fn rect(w: i32, h: i32, fill: Option) -> Object { + Object::Shape(Box::new(Shape::new(Geometry::Rect { w: u(w), h: u(h), radii: [0.0; 4] }, moved(10.0, -20.0), fill, None))) +} + +/// A drawing of one page and one layer holding `objects`. +fn one_layer(objects: Vec) -> Drawing { + Drawing { + version: WRITTEN_VERSION, + page_size: None, + pages: vec![Page { size: None, layers: vec![layer("A", objects)] }], + master: Vec::new(), + guides: Vec::new(), + warnings: Vec::new(), + } +} + +/// A drawing with every kind of thing the writer writes. +fn everything() -> Drawing { + let black = Outline { + width: u(5080), + color: Color::Gray(1.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: Vec::new(), + behind_fill: false, + scale_with: false, + }; + let dashed = Outline { + width: u(2540), + color: Color::Cmyk([c(0), c(128), c(255), c(13)]), + cap: Cap::Round, + join: Join::Bevel, + dashes: vec![3.0, 1.0], + behind_fill: true, + scale_with: true, + }; + let curve = Path { + subpaths: vec![ + SubPath { + start: pt(0, 0), + segments: vec![Segment::Line(pt(254_000, 0)), Segment::Cubic(pt(254_000, 50_000), pt(100_000, 254_000), pt(0, 254_000))], + closed: true, + }, + SubPath { start: pt(-1000, -1000), segments: vec![Segment::Line(pt(-5000, -9000))], closed: false }, + ], + }; + let mut path = + Shape::new(Geometry::Path(curve), Matrix([0.5, 0.25, -0.25, 2.0, 100.0, -40.0]), Some(Color::Rgb([c(255), c(64), c(0)])), Some(dashed)); + path.nonzero = true; + path.opacity = 0.75; + path.blend = Blend::Multiply; + let mut rounded = Shape::new( + Geometry::Rect { w: u(200_000), h: u(-100_000), radii: [u(10_000), u(0), u(25_000), u(50_000)] }, + moved(0.0, 0.0), + Some(Color::Registration), + Some(black.clone()), + ); + rounded.flags = Flags { hidden: true, locked: true }; + let spot = Color::Spot { name: "Sky Blue".into(), tint: 1.0, look: Some([0.0, c(255), 0.0]) }; + let ellipse = Shape::new( + Geometry::Ellipse { w: u(80_000), h: u(40_000) }, + moved(-30.0, 30.0), + Some(spot.clone()), + Some(Outline { color: spot, ..black.clone() }), + ); + let container = Shape::new(Geometry::Rect { w: u(100_000), h: u(100_000), radii: [0.0; 4] }, moved(0.0, 0.0), None, Some(black.clone())); + let inner = Object::Clip { container: Box::new(container.clone()), objects: vec![rect(10_000, 10_000, Some(Color::Gray(c(128))))] }; + let clip = Object::Clip { container: Box::new(container), objects: vec![rect(20_000, 30_000, None), inner] }; + let group = Object::Group { + objects: vec![Object::Shape(Box::new(ellipse)), rect(1000, 2000, Some(Color::Gray(0.0)))], + flags: Flags { hidden: true, locked: false }, + }; + let mut art = layer("Art", vec![Object::Shape(Box::new(path)), Object::Shape(Box::new(rounded)), group, clip]); + art.guides.push(Guideline { at: pt(0, 254_000), angle: -45.0, hidden: false }); + let mut back = layer("Back ünïcode", vec![rect(5000, 5000, Some(Color::Rgb([c(1), c(2), c(3)])))]); + back.flags = Flags { hidden: true, locked: true }; + let mut desktop = layer("Desktop", vec![rect(3000, 3000, None)]); + desktop.kind = LayerKind::Desktop; + Drawing { + version: WRITTEN_VERSION, + page_size: Some((u(2_159_000), u(2_794_000))), + pages: vec![ + Page { size: Some((u(2_159_000), u(2_794_000))), layers: vec![art, back] }, + Page { size: Some((u(1_000_000), u(500_000))), layers: vec![layer("Second", vec![rect(7000, 8000, None)])] }, + ], + master: vec![desktop], + guides: vec![Guideline { at: pt(254_000, 0), angle: 90.0, hidden: false }], + warnings: Vec::new(), + } +} + +/// Rounds every number of `d` past the precision a round trip keeps. +fn rounded(mut d: Drawing) -> Drawing { + fn r(v: &mut f64) { + *v = (*v * 1e4).round() / 1e4 + 0.0; + } + fn rc(c: &mut Color) { + let f = |v: &mut f32| *v = (*v * 1e3).round() / 1e3 + 0.0; + match c { + Color::Rgb(v) => v.iter_mut().for_each(f), + Color::Cmyk(v) => v.iter_mut().for_each(f), + Color::Gray(v) => f(v), + Color::Registration => {} + Color::Spot { tint, look, .. } => { + f(tint); + if let Some(l) = look { + l.iter_mut().for_each(f); + } + } + } + } + fn rp(p: &mut Pt) { + r(&mut p.x); + r(&mut p.y); + } + fn rs(s: &mut Shape) { + s.matrix.0.iter_mut().for_each(r); + match &mut s.geometry { + Geometry::Rect { w, h, radii } => { + r(w); + r(h); + radii.iter_mut().for_each(r); + } + Geometry::Ellipse { w, h } => { + r(w); + r(h); + } + Geometry::Path(p) => { + for sp in &mut p.subpaths { + rp(&mut sp.start); + for seg in &mut sp.segments { + match seg { + Segment::Line(a) => rp(a), + Segment::Cubic(a, b, e) => [a, b, e].into_iter().for_each(rp), + } + } + } + } + } + s.fill.iter_mut().for_each(rc); + if let Some(o) = &mut s.outline { + r(&mut o.width); + rc(&mut o.color); + } + s.opacity = (s.opacity * 1e3).round() / 1e3; + } + let mut stack: Vec<&mut Object> = Vec::new(); + for l in d.pages.iter_mut().flat_map(|p| p.layers.iter_mut()).chain(d.master.iter_mut()) { + for g in &mut l.guides { + rp(&mut g.at); + } + stack.extend(l.objects.iter_mut()); + } + while let Some(o) = stack.pop() { + match o { + Object::Shape(s) => rs(s), + Object::Group { objects, .. } => stack.extend(objects.iter_mut()), + Object::Clip { container, objects } => { + rs(container); + stack.extend(objects.iter_mut()); + } + } + } + for g in &mut d.guides { + rp(&mut g.at); + } + for (w, h) in d.pages.iter_mut().filter_map(|p| p.size.as_mut()).chain(d.page_size.as_mut()) { + r(w); + r(h); + } + d +} + +/// `d` as it reads back once written: rounded, and each closed subpath whose last segment ends away +/// from its start given a closing line to its start. +fn as_read(d: Drawing) -> Drawing { + let mut d = rounded(d); + let mut stack: Vec<&mut Object> = d.pages.iter_mut().flat_map(|p| p.layers.iter_mut()).flat_map(|l| l.objects.iter_mut()).collect(); + stack.extend(d.master.iter_mut().flat_map(|l| l.objects.iter_mut())); + while let Some(o) = stack.pop() { + let shape = match o { + Object::Shape(s) => s, + Object::Group { objects, .. } => { + stack.extend(objects.iter_mut()); + continue; + } + Object::Clip { container, objects } => { + stack.extend(objects.iter_mut()); + container + } + }; + let Geometry::Path(p) = &mut shape.geometry else { continue }; + for sp in &mut p.subpaths { + let end = sp.segments.last().map(|s| match s { + Segment::Line(e) | Segment::Cubic(_, _, e) => *e, + }); + if sp.closed && end.is_some_and(|e| e != sp.start) { + sp.segments.push(Segment::Line(sp.start)); + } + } + } + d +} + +/// The RIFF file inside a written package. +fn riff_of(file: &[u8]) -> Vec { + // The second member, after the stored `mimetype`. + let (name, data) = member(file, 0); + assert_eq!((name, data), (&b"mimetype"[..], &b"application/x-vnd.corel.draw.document+zip"[..])); + let next = 30 + name.len() + data.len(); + let (name, data) = member(file, next); + assert_eq!(name, b"content/riffData.cdr"); + let mut out = Vec::new(); + flate2::read::DeflateDecoder::new(data).read_to_end(&mut out).unwrap(); + out +} + +/// The name and packed bytes of the member whose local header is at `at`. +fn member(file: &[u8], at: usize) -> (&[u8], &[u8]) { + let le16 = |i: usize| usize::from(u16::from_le_bytes([file[at + i], file[at + i + 1]])); + let packed = u32::from_le_bytes(file[at + 18..at + 22].try_into().unwrap()) as usize; + let name = &file[at + 30..at + 30 + le16(26)]; + let start = at + 30 + le16(26) + le16(28); + (name, &file[start..start + packed]) +} + +fn count(hay: &[u8], needle: &[u8]) -> usize { + hay.windows(needle.len()).filter(|w| *w == needle).count() +} + +#[test] +fn a_written_drawing_reads_back_as_written() { + let d = everything(); + let file = write(&d, Limits::default()).unwrap(); + let back = read(&file, Limits::default()).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + assert_eq!(rounded(back), as_read(d)); +} + +#[test] +fn a_written_file_is_a_version_15_package_and_the_same_each_time() { + let file = write(&everything(), Limits::default()).unwrap(); + assert!(is_cdr(&file) && file.starts_with(b"PK\x03\x04")); + let riff = riff_of(&file); + assert_eq!(&riff[8..12], b"CDRF"); + assert_eq!(&riff[12..18], b"vrsn\x02\0"); + assert_eq!(read(&file, Limits::default()).unwrap().version, 1500); + assert_eq!(file, write(&everything(), Limits::default()).unwrap()); + // `mcfg` starts with the tag 1300 and the length of the rest (R72). + let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize; + let mcfg = riff.windows(4).position(|w| w == b"mcfg").unwrap(); + assert_eq!((le32(mcfg + 8), le32(mcfg + 12)), (1300, le32(mcfg + 4) - 8)); + // Every child of `LIST filt` is a `LIST filc` that holds one `fild` and nothing else (R72). + let padded = |size: usize| 8 + size + (size & 1); + let filt = riff.windows(12).position(|w| &w[..4] == b"LIST" && &w[8..] == b"filt").unwrap(); + let (mut at, end) = (filt + 12, filt + 8 + le32(filt + 4)); + let mut lists = 0; + while at < end { + assert_eq!((&riff[at..at + 4], &riff[at + 8..at + 12], &riff[at + 12..at + 16]), (&b"LIST"[..], &b"filc"[..], &b"fild"[..])); + assert_eq!(at + 12 + padded(le32(at + 16)), at + padded(le32(at + 4))); + at += padded(le32(at + 4)); + lists += 1; + } + assert_eq!((at, lists), (end, count(&riff, b"fild"))); + assert!(lists > 0); +} + +#[test] +fn each_container_names_its_own_clipped_group_by_the_stored_id() { + let riff = riff_of(&write(&everything(), Limits::default()).unwrap()); + let ids: Vec = + (0..riff.len() - 12).filter(|&p| &riff[p..p + 4] == b"spnd").map(|p| u32::from_le_bytes(riff[p + 8..p + 12].try_into().unwrap())).collect(); + let mut distinct = ids.clone(); + distinct.sort_unstable(); + distinct.dedup(); + assert!(ids.len() > 1 && distinct.len() == ids.len(), "{ids:?}"); + // The first u32 of each container argument (8005), from every `loda` record: a `loda` chunk's + // body starts with its own length. + let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize; + let mut named: Vec = (0..riff.len() - 28) + .filter(|&p| &riff[p..p + 4] == b"loda" && le32(p + 4) == le32(p + 8)) + .flat_map(|p| { + let loda = p + 8; + let (n, offsets, types) = (le32(loda + 4), loda + le32(loda + 8), loda + le32(loda + 12)); + (0..n).filter(move |i| le32(types + 4 * (n - 1 - i)) == 8005).map(move |i| le32(loda + le32(offsets + 4 * i)) as u32) + }) + .collect(); + named.sort_unstable(); + // Each container names its group by the group's `spnd` id unchanged, and no two name one group. + assert_eq!(named, distinct); +} + +#[test] +fn shapes_with_the_same_fill_and_outline_share_one_record_of_each() { + let fill = || Some(Color::Rgb([c(10), c(20), c(30)])); + let records = |d: &Drawing| { + let riff = riff_of(&write(d, Limits::default()).unwrap()); + (count(&riff, b"fild"), count(&riff, b"outl")) + }; + assert_eq!(records(&one_layer((0..50).map(|i| rect(1000 + i, 1000, fill())).collect())), records(&one_layer(vec![rect(1000, 1000, fill())]))); +} + +#[test] +fn a_closed_subpath_ends_at_its_start_and_its_other_nodes_can_be_edited() { + let start = pt(1234, 5678); + let open_end = SubPath { start, segments: vec![Segment::Line(pt(90_000, 5678)), Segment::Line(pt(1234, 90_000))], closed: true }; + let triangle = + |sp: SubPath| one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Path(Path { subpaths: vec![sp] }), Matrix::IDENTITY, None, None)))]); + let riff = riff_of(&write(&triangle(open_end.clone()), Limits::default()).unwrap()); + // The closing point at the start, then the type bytes: an editable closed move, two editable + // line ends and the closing line end, which is not editable. + let tail: Vec = [1234i32, 5678].iter().flat_map(|v| v.to_le_bytes()).chain([0x0C, 0x44, 0x44, 0x48]).collect(); + assert_eq!(count(&riff, &tail), 1); + // A subpath that already ends at its start is written as it is. + let mut ends_at_start = open_end; + ends_at_start.segments.push(Segment::Line(start)); + assert_eq!(riff_of(&write(&triangle(ends_at_start), Limits::default()).unwrap()), riff); +} + +#[test] +fn every_page_names_the_master_pages_guides_desktop_and_grid_by_their_ids() { + let mut d = everything(); + // A drawing layer of the master page, which the other pages do not name. The drawing has no + // grid layer of its own, as a read drawing has none. + d.master.push(layer("Master art", vec![rect(100, 100, None)])); + let riff = riff_of(&write(&d, Limits::default()).unwrap()); + let layers = layer_entries(&riff); + // Each page names the master page's guides, desktop and grid layers (object types 12, 17 and + // 11) once each, by kind, name and id: the guides and desktop before the page's own layers, + // the grid after them. + let named = |page: usize, kinds: &[usize]| { + let kept = |l: &&Entry| l.0 == page && l.1 == 1 && kinds.contains(&l.2); + let mut v: Vec<_> = layers.iter().filter(kept).map(|l| (l.2, &l.3, &l.4)).collect(); + v.sort(); + v + }; + assert_eq!(named(0, &[11, 12, 17]).len(), 3); + for page in 1..=d.pages.len() { + assert_eq!(named(page, &[11, 12, 17, 0]), named(0, &[11, 12, 17])); + let kinds: Vec = layers.iter().filter(|l| l.0 == page).map(|l| if l.1 == 0 { 0 } else { l.2 }).collect(); + let own = kinds.iter().position(|k| *k == 0).unwrap(); + assert!(kinds[..own].iter().all(|k| [12, 17].contains(k)) && kinds[own..].iter().filter(|k| **k != 0).all(|k| *k == 11), "{kinds:?}"); + assert!(kinds.ends_with(&[11]), "{kinds:?}"); + } + // The master page's layers and the pages' own layers each have their own 16-byte id. + let mut own: Vec<&[u8]> = layers.iter().filter(|l| l.0 == 0 || l.1 == 0).map(|l| &l.4[..]).collect(); + assert!(own.iter().all(|id| id.len() == 16)); + let count = own.len(); + own.sort(); + own.dedup(); + assert_eq!(own.len(), count); + // The guides layer, the first layer written, gets another id in a drawing that differs only in + // a fill color. + // A guides layer of the drawing's own master page takes the drawing's guidelines too, and is + // the only guides layer there; a hidden or locked one keeps them off it. + let guide = |x: i32| Guideline { at: pt(x, 0), angle: 90.0, hidden: false }; + let with_guides = |flags: Flags, drawing_guides: Vec| { + let mut guides = layer("Guides", Vec::new()); + guides.kind = LayerKind::Guides; + guides.flags = flags; + guides.guides = vec![guide(100)]; + Drawing { master: vec![guides], guides: drawing_guides, ..one_layer(Vec::new()) } + }; + for (flags, drawing_guides, layers) in [ + (Flags::default(), vec![guide(200)], 1), + (Flags { hidden: true, locked: false }, Vec::new(), 1), + (Flags { hidden: true, locked: false }, vec![guide(200)], 2), + (Flags { hidden: false, locked: true }, vec![guide(200)], 2), + ] { + let d = with_guides(flags, drawing_guides.clone()); + let file = write(&d, Limits::default()).unwrap(); + let entries = layer_entries(&riff_of(&file)); + assert_eq!(entries.iter().filter(|l| l.0 == 0 && l.2 == 12).count(), layers, "{flags:?}"); + // Each guideline once, the drawing's in a layer that is shown and unlocked: each guideline + // object's x (in units), and bytes 0 and 1 of the flags of the layer it is in. + let riff = riff_of(&file); + let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize; + let mut placed: Vec<(i32, u8, u8)> = (0..riff.len() - 28) + .filter(|&p| &riff[p..p + 4] == b"loda" && le32(p + 8 + 16) == 0x16) + .map(|p| { + let arg = p + 8 + le32(p + 8 + le32(p + 8 + 8)); + let layr = riff[..p].windows(8).rposition(|w| w == b"layrflgs").unwrap(); + (i32::from_le_bytes(riff[arg + 16..arg + 20].try_into().unwrap()), riff[layr + 12], riff[layr + 13]) + }) + .collect(); + placed.sort(); + let xs: Vec = placed.iter().map(|g| g.0).collect(); + assert_eq!(xs, if drawing_guides.is_empty() { vec![100] } else { vec![100, 200] }, "{flags:?}"); + assert!(placed.iter().filter(|g| g.0 == 200).all(|g| g.1 & 0x10 == 0 && g.2 == 0), "{flags:?}"); + } + let first = |c: Color| layer_entries(&riff_of(&write(&one_layer(vec![rect(100, 100, Some(c))]), Limits::default()).unwrap()))[0].4.clone(); + assert_ne!(first(Color::Gray(0.0)), first(Color::Gray(1.0))); +} + +/// A layer list of a written file: its page (0 the master page), byte 2 of its flags, its object +/// type, and its name and id arguments. +type Entry = (usize, u8, usize, Vec, Vec); + +/// The layer lists of `riff`, each `layr` with its `flgs` chunk, then `LIST lgob` with its `loda`. +fn layer_entries(riff: &[u8]) -> Vec { + let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize; + let pages: Vec = riff.windows(12).enumerate().filter(|(_, w)| &w[..4] == b"LIST" && &w[8..] == b"page").map(|(p, _)| p).collect(); + riff.windows(8) + .enumerate() + .filter(|(_, w)| w == b"layrflgs") + .map(|(p, _)| { + let page = pages.iter().filter(|&&at| at < p).count() - 1; + let loda = p + 36; + let (n, offsets, types) = (le32(loda + 4), loda + le32(loda + 8), loda + le32(loda + 12)); + let arg = |t: usize| { + let i = (0..n).find(|i| le32(types + 4 * (n - 1 - i)) == t).unwrap(); + riff[loda + le32(offsets + 4 * i)..loda + le32(offsets + 4 * i + 4)].to_vec() + }; + (page, riff[p + 14], le32(loda + 16), arg(1000), arg(40050)) + }) + .collect() +} + +#[test] +fn a_guideline_runs_along_the_angle_it_stores() { + // Starts `by` units inside a corner of the coordinate range. + let near = |by: f64| Pt { x: u(i32::MAX) - by * u(1), y: u(i32::MAX) - by * u(1) }; + let guide = |at: Pt, angle: f64| Drawing { guides: vec![Guideline { at, angle, hidden: false }], ..one_layer(Vec::new()) }; + // A quarter of a unit past the corner, on the corner itself, and less than half a unit inside + // it, the start rounds onto the corner, and no other point of the line rounds within the range + // along it. The last line runs almost level, so every point of it in the range rounds onto the + // corner too, as does the line that starts on the corner and half a unit past it. + let on_corner = Pt { x: 608_735.521_984_251_9, y: 608_735.521_984_251_9 }; + let level = [(near(-0.49), -0.9), (Pt { x: 608_735.521_984_252, y: 608_735.522_125_984_2 }, -0.00004)]; + for (at, angle) in [near(-0.25), on_corner, near(0.1), near(0.01), near(0.00025)].map(|at| (at, -45.0)).into_iter().chain(level) { + assert!(matches!(write(&guide(at, angle), Limits::default()), Err(Error::Unwritable(_))), "{at:?}"); + } + let inside = [(pt(1000, 2000), 30.0), (pt(1000, 2000), -45.0), (pt(1000, 2000), 1e20)]; + // A unit or more inside the corner, a point a whole unit or more away on each axis fits; + // at 1.25 units the farthest points in the range round off the angle and a nearer one does not. + // At -44 degrees the only point along the line turns from it by exactly a degree. At -18 + // degrees the one point along the line lies between whole units on both axes. + let between = Pt { x: u(i32::MAX) - 2.0 * u(1), y: u(i32::MAX) - 1.48 * u(1) }; + // A start a unit and a half and half a unit inside the corner lies on the edges of rounding. + let edges = Pt { x: 608_735.521_559_055_1, y: 608_735.521_842_519_8 }; + let near_corner = [(near(1000.0), -45.0), (near(1.25), -45.0), (near(1.0), -45.0), (near(1.0), -44.0), (between, -18.0), (edges, -45.0)]; + for (at, angle) in inside.into_iter().chain(near_corner) { + let corner = at.x > u(1_000_000); + let d = Drawing { guides: vec![Guideline { at, angle, hidden: false }], ..one_layer(Vec::new()) }; + let riff = riff_of(&write(&d, Limits::default()).unwrap_or_else(|e| panic!("{at:?} {angle}: {e}"))); + let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize; + let i32_at = |at: usize| f64::from(i32::from_le_bytes(riff[at..at + 4].try_into().unwrap())); + // The guideline object's `loda` (object type 0x16) and its first argument: 12 bytes, the + // angle in millionths of a degree, then the point and a second point on the line. + let loda = riff.windows(4).enumerate().map(|(p, _)| p).find(|&p| &riff[p..p + 4] == b"loda" && le32(p + 8 + 16) == 0x16).unwrap() + 8; + let arg = loda + le32(loda + le32(loda + 8)); + let a = (i32_at(arg + 12) / 1e6).to_radians(); + let (dx, dy) = (i32_at(arg + 24) - i32_at(arg + 16), i32_at(arg + 28) - i32_at(arg + 20)); + assert!(dx.hypot(dy) > if corner { 0.0 } else { 1000.0 }); + // Off the stored direction by no more than the coordinates' rounding, and, on either + // side, by no more than a degree. + assert!((dx * a.sin() - dy * a.cos()).abs() <= 1.5, "{angle}: {dx} {dy}"); + let turn = (dx * a.sin() - dy * a.cos()).abs().atan2((dx * a.cos() + dy * a.sin()).abs()); + assert!(turn <= 1f64.to_radians() + 1e-12, "{angle}: {dx} {dy}"); + } +} + +#[test] +fn an_outline_record_ends_8_bytes_before_its_chunk_and_its_color_list_at_its_empty_property() { + let spot = Color::Spot { name: "Ink".into(), tint: 1.0, look: Some([0.0; 3]) }; + let o = Outline { width: u(2540), color: spot, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new(), behind_fill: false, scale_with: false }; + let outlined = one_layer(vec![Object::Shape(Box::new(Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(o))))]); + let riff = riff_of(&write(&outlined, Limits::default()).unwrap()); + let le32 = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize; + let at = riff.windows(4).position(|w| w == b"outl").unwrap(); + let chunk = &riff[at + 8..at + 8 + le32(&riff, at + 4)]; + // The outline's id, then records (type, length, body) up to the one of type 1. + let mut p = 4; + let mut types = Vec::new(); + loop { + let (kind, len) = (le32(chunk, p), le32(chunk, p + 4)); + types.push(kind); + if kind == 1 { + assert_eq!(len, chunk.len() - p - 8 - 8); + // The body as sample files lay it out (R71): 130 bytes, an f64 1 at bytes 16 and 48, + // 45 degrees at byte 84 and 60 at byte 88. + let body = &chunk[p + 8..p + 8 + len]; + let f64_at = |at: usize| f64::from_le_bytes(body[at..at + 8].try_into().unwrap()); + assert_eq!((len, f64_at(16), f64_at(48), le32(body, 84), le32(body, 88)), (130, 1.0, 1.0, 45_000_000, 60)); + break; + } + // The color property list (type byte, length, body) ends at its first empty property. + if kind == 2 { + let mut q = p + 8; + while chunk[q] != 0 { + q += 5 + le32(chunk, q + 1); + } + assert_eq!((q + 5, le32(chunk, q + 1)), (p + 8 + len, 0)); + } + p += 8 + len; + } + assert_eq!(types, [2, 1]); +} + +#[test] +fn a_transparency_names_a_white_fill_record_of_the_file() { + let mut s = Shape::new(rect_geometry(), Matrix::IDENTITY, Some(Color::Gray(1.0)), None); + s.opacity = 0.5; + let riff = riff_of(&write(&one_layer(vec![Object::Shape(Box::new(s))]), Limits::default()).unwrap()); + let head: Vec = [1300u32, 117].iter().flat_map(|v| v.to_le_bytes()).collect(); + let at = riff.windows(head.len()).position(|w| w == head).unwrap() + head.len(); + let id = &riff[at + 105..at + 109]; + // The `fild` chunk of that id (chunk id, size, record id) holds the RGB color record of white. + let fild = riff.windows(12).position(|w| &w[..4] == b"fild" && &w[8..] == id).unwrap(); + let size = u32::from_le_bytes(riff[fild + 4..fild + 8].try_into().unwrap()) as usize; + let white = [5, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 0]; + assert_eq!(count(&riff[fild + 8..fild + 8 + size], &white), 1); +} + +#[test] +fn empty_groups_are_left_out_and_a_container_without_objects_is_a_shape() { + let container = Shape::new(Geometry::Ellipse { w: u(10_000), h: u(10_000) }, Matrix::IDENTITY, None, None); + let objects = vec![ + Object::Group { objects: Vec::new(), flags: Flags::default() }, + Object::Clip { container: Box::new(container.clone()), objects: Vec::new() }, + ]; + let back = read(&write(&one_layer(objects), Limits::default()).unwrap(), Limits::default()).unwrap(); + assert_eq!(back.pages[0].layers[0].objects, vec![Object::Shape(Box::new(container.clone()))]); + assert!(back.warnings.is_empty()); + // A container whose objects are groups that draw nothing is written as the plain shape is. + let hollow = Object::Group { objects: vec![Object::Group { objects: Vec::new(), flags: Flags::default() }], flags: Flags::default() }; + let clips_hollow = one_layer(vec![Object::Clip { container: Box::new(container.clone()), objects: vec![hollow] }]); + let file = write(&clips_hollow, Limits::default()).unwrap(); + assert_eq!(file, write(&one_layer(vec![Object::Shape(Box::new(container))]), Limits::default()).unwrap()); + // A group that holds only groups that draw nothing is written as no group at all. + assert_eq!(write(&one_layer(vec![hollow_group()]), Limits::default()).unwrap(), write(&one_layer(Vec::new()), Limits::default()).unwrap()); +} + +fn hollow_group() -> Object { + Object::Group { objects: vec![Object::Group { objects: Vec::new(), flags: Flags::default() }], flags: Flags::default() } +} + +#[test] +fn a_drawing_without_pages_is_written_with_one_empty_page() { + let d = Drawing { pages: Vec::new(), ..one_layer(Vec::new()) }; + let back = read(&write(&d, Limits::default()).unwrap(), Limits::default()).unwrap(); + assert_eq!(back.pages.len(), 1); + assert!(back.pages[0].layers.iter().all(|l| l.objects.is_empty())); + // Without a page size of its own, the drawing reads back without one. + assert_eq!(back.page_size, None); +} + +/// At the smallest value of a limit at which the reader reads `d`'s file whole, the writer writes +/// it; one below, the writer refuses it. +fn writes_at_the_readers_limit(d: &Drawing, set: fn(&mut Limits, usize)) -> usize { + let limits = |n| { + let mut l = Limits::default(); + set(&mut l, n); + l + }; + let file = write(d, Limits::default()).unwrap(); + let whole = |n| read(&file, limits(n)).is_ok_and(|b| b.warnings.is_empty()); + // The smallest value that reads whole: a read that fits a limit fits every larger one. + let (mut n, mut above) = (0, 100_000); + while n < above { + let mid = (n + above) / 2; + if whole(mid) { above = mid } else { n = mid + 1 } + } + assert!(whole(n), "{n}"); + assert_eq!(write(d, limits(n)).as_ref(), Ok(&file), "{n}"); + assert!(n > 0 && matches!(write(d, limits(n - 1)), Err(Error::Limit(_))), "{n}"); + n +} + +#[test] +fn every_limit_a_read_applies_is_applied_when_writing() { + let d = everything(); + let set: [fn(&mut Limits, usize); 10] = [ + |l, n| l.input = n, + |l, n| l.inflated = n, + |l, n| l.arguments = n, + |l, n| l.clipped_chunks = n, + |l, n| l.chunks = n, + |l, n| l.member = n, + |l, n| l.dashes = n, + |l, n| l.objects = n, + |l, n| l.coordinates = n, + |l, n| l.members = n, + ]; + for set in set { + writes_at_the_readers_limit(&d, set); + } + // Without clipped groups the outline table ends the file: an empty drawing, and one whose + // last record is an outline. + let o = Outline { + width: u(2540), + color: Color::Gray(0.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: Vec::new(), + behind_fill: false, + scale_with: false, + }; + let outlined = one_layer(vec![Object::Shape(Box::new(Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(o))))]); + let bytes: [fn(&mut Limits, usize); 3] = [|l, n| l.input = n, |l, n| l.inflated = n, |l, n| l.member = n]; + for d in [one_layer(Vec::new()), outlined] { + for set in bytes { + writes_at_the_readers_limit(&d, set); + } + } + // A group that holds only an empty group is left out, and takes nothing of the object count. + let hollow = + one_layer(vec![Object::Group { objects: vec![Object::Group { objects: Vec::new(), flags: Flags::default() }], flags: Flags::default() }]); + assert!(write(&hollow, Limits { objects: 0, ..Limits::default() }).is_ok()); +} + +#[test] +fn a_path_past_the_coordinate_count_stops_before_its_points_are_written() { + // The closing point's coordinates are past the file's range; the count is refused first. + let mut segments: Vec = (1..10).map(|i| Segment::Line(pt(i * 100, 0))).collect(); + segments.push(Segment::Line(Pt { x: 1e30, y: 0.0 })); + let path = Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed: true }] }; + let d = one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Path(path), Matrix::IDENTITY, None, None)))]); + assert!(matches!(write(&d, Limits::default()), Err(Error::Unwritable(_)))); + assert!(matches!(write(&d, Limits { coordinates: 5, ..Limits::default() }), Err(Error::Limit(_)))); + // A shape takes at least three arguments, counted before its points. + assert_eq!(write(&d, Limits { arguments: 2, ..Limits::default() }), Err(Error::Limit("argument count"))); + // So is the file's size, from the segment count: a long path refused at half its bytes. + let long = |end: Pt| { + let mut segments: Vec = (1..1000).map(|i| Segment::Line(pt(i * 100, i % 2 * 100))).collect(); + segments.push(Segment::Line(end)); + let path = Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed: true }] }; + one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Path(path), Matrix::IDENTITY, None, None)))]) + }; + let member = riff_of(&write(&long(pt(0, 100)), Limits::default()).unwrap()).len() - 1000 * 9 / 2; + assert!(matches!(write(&long(Pt { x: 1e30, y: 0.0 }), Limits::default()), Err(Error::Unwritable(_)))); + assert!(matches!(write(&long(Pt { x: 1e30, y: 0.0 }), Limits { member, ..Limits::default() }), Err(Error::Limit(_)))); + // So are the shape's nested lists: one level short of what a rectangle in its place takes. + let fits = |n| write(&one_layer(vec![rect(100, 100, None)]), Limits { depth: n, ..Limits::default() }).is_ok(); + let depth = (1..64).find(|&n| fits(n)).unwrap(); + assert_eq!(write(&d, Limits { depth: depth - 1, ..Limits::default() }), Err(Error::Limit("nesting depth"))); + // In a clipped group, every other chunk of the file counts too: one chunk short of what the + // drawing takes with a path in range, the clipped path is refused before its points. + let clipped = |path: Path| { + let container = Shape::new(rect_geometry(), Matrix::IDENTITY, None, None); + // A fill of its own, whose record counts as well. + let shape = Shape::new(Geometry::Path(path), Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + one_layer(vec![Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(shape))] }]) + }; + let Some(Object::Shape(s)) = d.pages[0].layers[0].objects.first() else { panic!("no path") }; + let Geometry::Path(past) = s.geometry.clone() else { panic!("no path") }; + let mut within = past.clone(); + within.subpaths[0].segments.pop(); + let chunks = (1..1000).find(|&n| write(&clipped(within.clone()), Limits { chunks: n, ..Limits::default() }).is_ok()).unwrap(); + assert!(matches!(write(&clipped(past.clone()), Limits::default()), Err(Error::Unwritable(_)))); + assert_eq!(write(&clipped(past), Limits { chunks: chunks - 1, ..Limits::default() }), Err(Error::Limit("chunk count"))); +} + +#[test] +fn a_rectangle_repeats_the_scale_of_its_transform() { + // Scaled by 2 and 3, then turned a quarter turn: the scale fields hold 2 and 3 (R29). + for m in [Matrix([2.0, 0.0, 0.0, 3.0, 5.0, 7.0]), Matrix([0.0, 2.0, -3.0, 0.0, 5.0, 7.0])] { + let shape = Shape::new(Geometry::Rect { w: u(1000), h: u(2000), radii: [0.0; 4] }, m, None, None); + let riff = riff_of(&write(&one_layer(vec![Object::Shape(Box::new(shape))]), Limits::default()).unwrap()); + // The record's width and height in coordinate units, then the two scale fields. + let units = |v: f64| (v * (254_000.0 / 72.0)).to_le_bytes(); + let fields = [units(u(1000)), units(u(2000)), 2.0f64.to_le_bytes(), 3.0f64.to_le_bytes()].concat(); + assert_eq!(count(&riff, &fields), 1, "{m:?}"); + } +} + +#[test] +fn the_pages_clipped_groups_and_records_share_the_byte_limit() { + // A long path on the page and another in a clipped group each fit the limit; together they do + // not, and writing stops at the second before it reaches the unwritable shape after it. + let long = || { + let segments = (1..4000).map(|i| Segment::Line(pt(i * 100, (i % 7) * 100))).collect(); + let path = Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed: false }] }; + Object::Shape(Box::new(Shape::new(Geometry::Path(path), Matrix::IDENTITY, None, None))) + }; + let container = || Box::new(Shape::new(rect_geometry(), Matrix::IDENTITY, None, None)); + let fits = one_layer(vec![long(), Object::Clip { container: container(), objects: vec![long()] }]); + let past = Shape::new(Geometry::Rect { w: 1e30, h: 1.0, radii: [0.0; 4] }, Matrix::IDENTITY, None, None); + let stops = one_layer(vec![long(), Object::Clip { container: container(), objects: vec![long(), Object::Shape(Box::new(past))] }]); + assert!(matches!(write(&stops, Limits::default()), Err(Error::Unwritable(_)))); + let member = riff_of(&write(&fits, Limits::default()).unwrap()).len() - 4000 * 9 / 2; + assert!(matches!(write(&stops, Limits { member, ..Limits::default() }), Err(Error::Limit(_)))); + // Shapes whose fills all differ: the page fits the limit, and the fill table takes it past + // before the writer reaches the unwritable shape at the end of the page. + let shapes = || (0..=255u8).map(|v| rect(1000, 1000, Some(Color::Gray(c(v))))).collect::>(); + let riff = riff_of(&write(&one_layer(shapes()), Limits::default()).unwrap()); + let filt = riff.windows(12).position(|w| &w[..4] == b"LIST" && &w[8..] == b"filt").unwrap(); + let table = u32::from_le_bytes(riff[filt + 4..filt + 8].try_into().unwrap()) as usize; + let member = riff.len() - table / 2; + let past = Shape::new(Geometry::Rect { w: 1e30, h: 1.0, radii: [0.0; 4] }, Matrix::IDENTITY, None, None); + let stops = one_layer(shapes().into_iter().chain([Object::Shape(Box::new(past))]).collect()); + assert!(matches!(write(&stops, Limits::default()), Err(Error::Unwritable(_)))); + assert!(matches!(write(&stops, Limits { member, ..Limits::default() }), Err(Error::Limit(_)))); +} + +#[test] +fn clips_nest_as_deep_as_a_read_takes() { + let nested = |depth: usize| { + let mut o = rect(100, 100, None); + for _ in 0..depth { + let container = Shape::new(Geometry::Ellipse { w: u(1000), h: u(1000) }, Matrix::IDENTITY, None, None); + o = Object::Clip { container: Box::new(container), objects: vec![o] }; + } + one_layer(vec![o]) + }; + let back = read(&write(&nested(64), Limits::default()).unwrap(), Limits::default()).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + assert_eq!(rounded(back), as_read(nested(64))); + assert_eq!(write(&nested(65), Limits::default()), Err(Error::Limit("clip nesting"))); +} + +#[test] +fn ten_dashes_fit_before_the_arrowheads_and_eleven_do_not() { + let dashed = |n: usize| { + let o = Outline { + width: u(2540), + color: Color::Gray(1.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: (1..=n).map(|d| d as f64).collect(), + behind_fill: false, + scale_with: false, + }; + one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Ellipse { w: u(1000), h: u(1000) }, Matrix::IDENTITY, None, Some(o))))]) + }; + let back = read(&write(&dashed(10), Limits::default()).unwrap(), Limits::default()).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + assert_eq!(rounded(back), as_read(dashed(10))); + assert!(matches!(write(&dashed(11), Limits::default()), Err(Error::Unwritable(_)))); +} + +#[test] +fn names_and_values_the_reader_would_change_are_refused() { + let named = |name: String| Drawing { pages: vec![Page { size: None, layers: vec![layer(&name, Vec::new())] }], ..one_layer(Vec::new()) }; + let back = read(&write(&named("é".repeat(256)), Limits::default()).unwrap(), Limits::default()).unwrap(); + assert_eq!(back.pages[0].layers[0].name, "é".repeat(256)); + assert!(back.warnings.is_empty()); + for name in ["é".repeat(257), "A\0B".to_string()] { + assert!(matches!(write(&named(name), Limits::default()), Err(Error::Unwritable(_)))); + } + let filled = |c: Color| one_layer(vec![rect(100, 100, Some(c))]); + // At a 10% tint, the stored byte nearest a black look reads back a step off, and the next one + // reads back black. + let black_tint = Color::Spot { name: "Ink".into(), tint: 0.1, look: Some([0.0; 3]) }; + let back = read(&write(&filled(black_tint.clone()), Limits::default()).unwrap(), Limits::default()).unwrap(); + assert_eq!(rounded(back), rounded(filled(black_tint))); + for c in [ + Color::Rgb([f32::NAN, 0.0, 0.0]), + Color::Gray(1.5), + Color::Spot { name: String::new(), tint: 1.0, look: None }, + Color::Spot { name: "Red".into(), tint: 0.0, look: Some([1.0, 0.0, 0.0]) }, + Color::Spot { name: "Gray".into(), tint: 0.01, look: Some([0.5, 0.5, 0.5]) }, + ] { + assert!(matches!(write(&filled(c), Limits::default()), Err(Error::Unwritable(_)))); + } + // A corner past half the shorter side, a page of no width, a dash past what a u16 holds. + let corner = Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [9.0, 0.0, 0.0, 0.0] }, Matrix::IDENTITY, None, None); + assert!(matches!(write(&one_layer(vec![Object::Shape(Box::new(corner))]), Limits::default()), Err(Error::Unwritable(_)))); + let flat = Drawing { page_size: Some((0.0, 10.0)), ..one_layer(Vec::new()) }; + assert!(matches!(write(&flat, Limits::default()), Err(Error::Unwritable(_)))); + let long = Outline { + width: 1.0, + color: Color::Gray(1.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: vec![100_000.0], + behind_fill: false, + scale_with: false, + }; + let fine = Outline { dashes: vec![0.4, 0.4], ..long.clone() }; + for o in [long, fine] { + let dashed = Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(o)); + assert!(matches!(write(&one_layer(vec![Object::Shape(Box::new(dashed))]), Limits::default()), Err(Error::Unwritable(_)))); + } + let mut see_through = Shape::new(rect_geometry(), Matrix::IDENTITY, None, None); + see_through.opacity = f32::NAN; + assert!(matches!(write(&one_layer(vec![Object::Shape(Box::new(see_through))]), Limits::default()), Err(Error::Unwritable(_)))); + let mut grid = layer("Grid", vec![rect(100, 100, None)]); + grid.kind = LayerKind::Grid; + assert!(matches!(write(&Drawing { master: vec![grid], ..one_layer(Vec::new()) }, Limits::default()), Err(Error::Unwritable(_)))); +} + +fn rect_geometry() -> Geometry { + Geometry::Rect { w: u(1000), h: u(1000), radii: [0.0; 4] } +} + +#[test] +fn a_grid_layer_keeps_its_lock_state() { + for locked in [false, true] { + let mut grid = layer("Grid", vec![rect(100, 100, None)]); + grid.kind = LayerKind::Grid; + grid.flags.locked = locked; + let d = Drawing { pages: vec![Page { size: None, layers: vec![grid] }], ..one_layer(Vec::new()) }; + let back = read(&write(&d, Limits::default()).unwrap(), Limits::default()).unwrap(); + assert_eq!((back.pages[0].layers[0].kind, back.pages[0].layers[0].flags.locked), (LayerKind::Grid, locked)); + } +} + +/// A drawing at a limit is written and read whole; one past it is refused. +#[test] +fn drawings_past_what_a_read_takes_are_refused() { + let flat = |n: i32| one_layer((0..n).map(|i| rect(100 + i, 100, None)).collect()); + let limits = Limits { objects: 10, ..Limits::default() }; + let back = read(&write(&flat(10), limits).unwrap(), limits).unwrap(); + assert!(back.warnings.is_empty()); + assert_eq!(write(&flat(11), limits), Err(Error::Limit("object count"))); + // Groups nested in groups: each one takes a list. + let nested = |depth: usize| { + let mut o = rect(100, 100, None); + for _ in 0..depth { + o = Object::Group { objects: vec![o], flags: Flags::default() }; + } + one_layer(vec![o]) + }; + // The smallest depth a read of eight nested groups takes whole is the smallest the writer + // takes, and a ninth group is refused at it. + let depth = writes_at_the_readers_limit(&nested(8), |l, n| l.depth = n); + assert_eq!(write(&nested(9), Limits { depth, ..Limits::default() }), Err(Error::Limit("nesting depth"))); + let limits = Limits { depth: 12, ..Limits::default() }; + // Groups that hold nothing are refused past the depth too, in a layer and in a clip. + let hollow = |depth: usize| { + let mut o = Object::Group { objects: Vec::new(), flags: Flags::default() }; + for _ in 0..depth { + o = Object::Group { objects: vec![o], flags: Flags::default() }; + } + o + }; + // `hollow(n)` is n + 1 groups deep. + let clip = |o| Object::Clip { container: Box::new(Shape::new(rect_geometry(), Matrix::IDENTITY, None, None)), objects: vec![o] }; + for wrap in [|o| o, clip] { + assert!(write(&one_layer(vec![wrap(hollow(11))]), limits).is_ok()); + assert_eq!(write(&one_layer(vec![wrap(hollow(12))]), limits), Err(Error::Limit("nesting depth"))); + } + let limits = Limits { coordinates: 3, ..Limits::default() }; + let line = |n: i32| { + let segments = (1..n).map(|i| Segment::Line(pt(i, i))).collect(); + let path = Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed: false }] }; + one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Path(path), Matrix::IDENTITY, None, None)))]) + }; + assert!(read(&write(&line(3), limits).unwrap(), limits).unwrap().warnings.is_empty()); + assert_eq!(write(&line(4), limits), Err(Error::Limit("coordinate count"))); +} + +#[test] +fn numbers_the_file_cant_hold_are_refused() { + let with = |s: Shape| one_layer(vec![Object::Shape(Box::new(s))]); + let far = Shape::new(Geometry::Ellipse { w: 1e9, h: 1.0 }, Matrix::IDENTITY, None, None); + assert!(matches!(write(&with(far), Limits::default()), Err(Error::Unwritable(_)))); + let nan = Shape::new(Geometry::Rect { w: f64::NAN, h: 1.0, radii: [0.0; 4] }, Matrix::IDENTITY, None, None); + assert!(matches!(write(&with(nan), Limits::default()), Err(Error::Unwritable(_)))); + let inf = Shape::new(Geometry::Ellipse { w: 1.0, h: 1.0 }, Matrix([f64::INFINITY, 0.0, 0.0, 1.0, 0.0, 0.0]), None, None); + assert!(matches!(write(&with(inf), Limits::default()), Err(Error::Unwritable(_)))); +} + +#[test] +fn values_outside_their_range_are_refused() { + let with = |s: Shape| one_layer(vec![Object::Shape(Box::new(s))]); + let outlined = |width: f64| Outline { + width, + color: Color::Gray(1.0), + cap: Cap::Butt, + join: Join::Miter, + dashes: Vec::new(), + behind_fill: false, + scale_with: false, + }; + let mut opaque = Shape::new(rect_geometry(), Matrix::IDENTITY, None, None); + opaque.opacity = 1.5; + let far = Path { subpaths: vec![SubPath { start: Pt { x: 1e9, y: 0.0 }, segments: vec![Segment::Line(pt(0, 0))], closed: false }] }; + let cases = [ + ("negative outline width", with(Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(outlined(-1.0))))), + // A width of 0 reads back as no width. + ("positive outline width that rounds to 0", with(Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(outlined(u(1) / 4.0))))), + ("negative corner radius", with(Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [-1.0, 0.0, 0.0, 0.0] }, Matrix::IDENTITY, None, None))), + ("opacity past 1", with(opaque)), + ("tint past 1", one_layer(vec![rect(100, 100, Some(Color::Spot { name: "Red".into(), tint: 1.5, look: Some([1.0, 1.0, 1.0]) }))])), + ("path point past 32 bits", with(Shape::new(Geometry::Path(far), Matrix::IDENTITY, None, None))), + ("page size past 32 bits", Drawing { page_size: Some((1e9, 10.0)), ..one_layer(Vec::new()) }), + ]; + let written: Vec<_> = + cases.iter().filter(|(_, d)| !matches!(write(d, Limits::default()), Err(Error::Unwritable(_)))).map(|(what, _)| *what).collect(); + assert!(written.is_empty(), "{written:?}"); +} + +fn arb_color() -> impl Strategy { + prop_oneof![ + any::<[u8; 3]>().prop_map(|v| Color::Rgb(v.map(c))), + any::<[u8; 4]>().prop_map(|v| Color::Cmyk(v.map(c))), + any::().prop_map(|v| Color::Gray(c(v))), + Just(Color::Registration), + ] +} + +fn arb_shape() -> impl Strategy { + let size = || (-1_000_000i32..1_000_000, -1_000_000i32..1_000_000); + let geometry = prop_oneof![ + size().prop_map(|(w, h)| Geometry::Rect { w: u(w), h: u(h), radii: [0.0; 4] }), + size().prop_map(|(w, h)| Geometry::Ellipse { w: u(w), h: u(h) }), + (prop::collection::vec(size(), 1..20), any::()).prop_map(|(pts, closed)| { + let segments = pts.iter().map(|&(x, y)| Segment::Line(pt(x, y))).collect(); + Geometry::Path(Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed }] }) + }), + ]; + (geometry, prop::option::of(arb_color()), any::(), -500i32..500) + .prop_map(|(g, fill, nonzero, x)| Shape { nonzero, ..Shape::new(g, moved(f64::from(x), -f64::from(x)), fill, None) }) +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })] + + #[test] + fn random_drawings_read_back_as_written(shapes in prop::collection::vec(arb_shape(), 0..30), grouped in 0usize..30) { + let mut objects: Vec = shapes.into_iter().map(|s| Object::Shape(Box::new(s))).collect(); + let tail = objects.split_off(grouped.min(objects.len())); + if !tail.is_empty() { + objects.push(Object::Group { objects: tail, flags: Flags::default() }); + } + let d = Drawing { page_size: Some((u(1_000_000), u(1_000_000))), ..one_layer(objects) }; + let back = read(&write(&d, Limits::default()).unwrap(), Limits::default()).unwrap(); + prop_assert!(back.warnings.is_empty()); + prop_assert_eq!(rounded(back), as_read(d)); + } + + #[test] + fn writing_never_panics( + w in prop_oneof![-1e4..1e4f64, any::()], + h in prop_oneof![-1e4..1e4f64, any::()], + m in prop_oneof![prop::array::uniform6(-1e3..1e3f64), any::<[f64; 6]>()], + dashes in prop::collection::vec(prop_oneof![-1.0..20.0f64, any::()], 0..12), + opacity in prop_oneof![-0.5..1.5f32, any::()], + ) { + let outline = + Outline { width: w, color: Color::Gray(opacity), cap: Cap::Square, join: Join::Round, dashes, behind_fill: false, scale_with: false }; + // Corners within half the shorter side, so a rectangle of a size the file holds is written. + let r = w.abs().min(h.abs()) / 4.0; + let mut s = Shape::new(Geometry::Rect { w, h, radii: [r, 0.0, r, 0.0] }, Matrix(m), Some(Color::Rgb([opacity; 3])), Some(outline)); + s.opacity = opacity; + let d = Drawing { pages: vec![Page { size: Some((w, h)), layers: vec![layer("A", vec![Object::Shape(Box::new(s))])] }], ..everything() }; + if let Ok(file) = write(&d, Limits::default()) { + prop_assert!(read(&file, Limits::default()).is_ok()); + } + } +}