From 59db4313b11dcdf54239b81af39fce216142ad45 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 07:24:53 -0800 Subject: [PATCH 01/34] File formats: open and place .cdr drawings, versions 1 to 27 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File › Open and File › Place read .cdr drawings of versions 1 to 27, and .cdt templates open as new untitled documents. A new L0 crate, vectorcraft-cdr, reads the WL files of versions 1 and 2, the RIFF chunk tree of versions 3 on with its compressed lists, and the ZIP packages of versions 14 on with their data streams. The importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides, groups, curves, paths, rectangles, ellipses, arcs and polygons with uniform fills and outlines. Versions 1 and 2 open as one page and one layer of rectangles, whole ellipses and curves. Version 3 keeps transforms, fills and outlines in each object, and a group's matrix places its objects; envelopes are not applied, with a warning. Version 4 reads as version 5 with 12-byte u16 colors and fixed-point transforms. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out, and the open warnings name each kind in every complete catalog. RIFF files that name a version before 3, drawings after 27 and encrypted, ZIP64 or split packages are refused with a message. crates/cdr/PROVENANCE.md lists the public source of each record layout. --- Cargo.lock | 11 + Cargo.toml | 1 + NOTICE | 4 + crates/cdr/Cargo.toml | 22 + crates/cdr/LICENSE-kaitai.txt | 28 + crates/cdr/PROVENANCE.md | 98 ++ crates/cdr/README.md | 66 + crates/cdr/src/build.rs | 537 +++++++ crates/cdr/src/bytes.rs | 76 + crates/cdr/src/geometry.rs | 455 ++++++ crates/cdr/src/inline.rs | 230 +++ crates/cdr/src/layout.rs | 179 +++ crates/cdr/src/lib.rs | 85 ++ crates/cdr/src/limits.rs | 134 ++ crates/cdr/src/model.rs | 191 +++ crates/cdr/src/package.rs | 147 ++ crates/cdr/src/records.rs | 537 +++++++ crates/cdr/src/riff.rs | 419 ++++++ crates/cdr/src/synth.rs | 811 +++++++++++ crates/cdr/src/wl.rs | 245 ++++ crates/cdr/src/zip.rs | 308 +++++ crates/cdr/tests/bench.rs | 66 + crates/cdr/tests/provenance.rs | 44 + crates/cdr/tests/read.rs | 1463 ++++++++++++++++++++ crates/engine/Cargo.toml | 2 + crates/engine/src/cmd/fileio.rs | 4 + crates/engine/src/cmd/fileio/cdr.rs | 321 +++++ crates/engine/src/cmd/fileio/cdr/shapes.rs | 482 +++++++ crates/engine/src/cmd/fileio/formats.rs | 13 +- crates/engine/src/cmd/fileio/load.rs | 14 +- crates/engine/src/cmd/fileio/tests_cdr.rs | 434 ++++++ crates/engine/tests/import_fuzz.rs | 123 +- crates/ui-egui/src/i18n/ca.tsv | 11 + crates/ui-egui/src/i18n/cs.tsv | 11 + crates/ui-egui/src/i18n/de.tsv | 11 + crates/ui-egui/src/i18n/el.tsv | 11 + crates/ui-egui/src/i18n/es.tsv | 11 + crates/ui-egui/src/i18n/fi.tsv | 11 + crates/ui-egui/src/i18n/fr.tsv | 11 + crates/ui-egui/src/i18n/hi.tsv | 11 + crates/ui-egui/src/i18n/hu.tsv | 11 + crates/ui-egui/src/i18n/it.tsv | 11 + crates/ui-egui/src/i18n/ja.tsv | 11 + crates/ui-egui/src/i18n/ka.tsv | 11 + crates/ui-egui/src/i18n/ko.tsv | 11 + crates/ui-egui/src/i18n/pl.tsv | 11 + crates/ui-egui/src/i18n/pt-br.tsv | 11 + crates/ui-egui/src/i18n/ru.tsv | 11 + crates/ui-egui/src/i18n/sv.tsv | 11 + crates/ui-egui/src/i18n/tests.rs | 23 + crates/ui-egui/src/i18n/tr.tsv | 11 + crates/ui-egui/src/i18n/uk.tsv | 11 + crates/ui-egui/src/i18n/vi.tsv | 11 + crates/ui-egui/src/i18n/zh-hans.tsv | 11 + crates/ui-egui/src/i18n/zh-hant.tsv | 11 + docs/architecture.md | 2 +- docs/file-format-parity.md | 5 +- docs/mcp.md | 26 +- docs/target-app-parity.md | 3 +- xtask/src/brands.rs | 5 + xtask/src/layers.rs | 1 + 61 files changed, 7844 insertions(+), 13 deletions(-) create mode 100644 crates/cdr/Cargo.toml create mode 100644 crates/cdr/LICENSE-kaitai.txt create mode 100644 crates/cdr/PROVENANCE.md create mode 100644 crates/cdr/README.md create mode 100644 crates/cdr/src/build.rs create mode 100644 crates/cdr/src/bytes.rs create mode 100644 crates/cdr/src/geometry.rs create mode 100644 crates/cdr/src/inline.rs create mode 100644 crates/cdr/src/layout.rs create mode 100644 crates/cdr/src/lib.rs create mode 100644 crates/cdr/src/limits.rs create mode 100644 crates/cdr/src/model.rs create mode 100644 crates/cdr/src/package.rs create mode 100644 crates/cdr/src/records.rs create mode 100644 crates/cdr/src/riff.rs create mode 100644 crates/cdr/src/synth.rs create mode 100644 crates/cdr/src/wl.rs create mode 100644 crates/cdr/src/zip.rs create mode 100644 crates/cdr/tests/bench.rs create mode 100644 crates/cdr/tests/provenance.rs create mode 100644 crates/cdr/tests/read.rs create mode 100644 crates/engine/src/cmd/fileio/cdr.rs create mode 100644 crates/engine/src/cmd/fileio/cdr/shapes.rs create mode 100644 crates/engine/src/cmd/fileio/tests_cdr.rs diff --git a/Cargo.lock b/Cargo.lock index 02e109b6b2..7977bfff6c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6405,6 +6405,16 @@ dependencies = [ "vectorcraft-text", ] +[[package]] +name = "vectorcraft-cdr" +version = "0.24.1" +dependencies = [ + "crc32fast", + "flate2", + "proptest", + "vectorcraft-cdr", +] + [[package]] name = "vectorcraft-cli" version = "0.24.1" @@ -6509,6 +6519,7 @@ dependencies = [ "vectorcraft-apischema", "vectorcraft-brush", "vectorcraft-cad", + "vectorcraft-cdr", "vectorcraft-color", "vectorcraft-doc", "vectorcraft-eps", diff --git a/Cargo.toml b/Cargo.toml index 29f43866c2..a4e0e50398 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,6 +58,7 @@ vectorcraft-affinity = { path = "crates/affinity" } vectorcraft-scriptcheck = { path = "crates/scriptcheck" } vectorcraft-js = { path = "crates/js" } vectorcraft-apischema = { path = "crates/apischema" } +vectorcraft-cdr = { path = "crates/cdr" } # foundation kurbo = { version = "0.13", features = ["serde"] } diff --git a/NOTICE b/NOTICE index c5c5511ba0..cd4004f0d3 100644 --- a/NOTICE +++ b/NOTICE @@ -35,6 +35,10 @@ based in part on the work of the Independent JPEG Group. WebAssembly plug-ins run in the wasmi interpreter (MIT OR Apache-2.0); its wasmparser dependency is under the Apache License 2.0 with the LLVM exception. +The .cdr reader (crates/cdr) reads the record layouts that the Kaitai Struct specification +coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy, MIT License) describes. No part +of the specification is copied into the crate; its license text is in crates/cdr/LICENSE-kaitai.txt. + Builds made with craft-fonts (the CRAFT_FONTS_DIR build option; all official releases) embed the fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC and Noto Sans Arabic in the current manifest; diff --git a/crates/cdr/Cargo.toml b/crates/cdr/Cargo.toml new file mode 100644 index 0000000000..1600164c7e --- /dev/null +++ b/crates/cdr/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "vectorcraft-cdr" +description = "Bounded reader for .cdr drawings of versions 1 to 27: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[features] +# Synthetic-file builders for tests and fuzz seeds; not a .cdr writer. +synth = [] + +[dependencies] +crc32fast = { workspace = true } +flate2 = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } +vectorcraft-cdr = { path = ".", features = ["synth"] } diff --git a/crates/cdr/LICENSE-kaitai.txt b/crates/cdr/LICENSE-kaitai.txt new file mode 100644 index 0000000000..948586e09a --- /dev/null +++ b/crates/cdr/LICENSE-kaitai.txt @@ -0,0 +1,28 @@ +The record layouts this crate reads are described in the Kaitai Struct +specification `coreldraw_cdr.ksy` +(https://github.com/kaitai-io/coreldraw_cdr.ksy, commit +9d8e2704b946961f5114115f1a488750a3c86ed0), which is published under the +license below. No part of that specification is copied into this crate; +`PROVENANCE.md` cites it by line. + +MIT License + +Copyright (c) 2020 Kaitai team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md new file mode 100644 index 0000000000..874f5bb4fc --- /dev/null +++ b/crates/cdr/PROVENANCE.md @@ -0,0 +1,98 @@ +# Where each layout comes from + +The reader relies on the record layouts below. Code cites a row by its id (`R1` ...), and +`tests/provenance.rs` fails when a cited id has no row here. + +Sources: + +- **K**: the Kaitai Struct specification `coreldraw_cdr.ksy` (MIT, notice in `LICENSE-kaitai.txt`), + https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/coreldraw_cdr.ksy +- **T**: an open-source converter's CDR format notes (MIT OR Apache-2.0), rows its authors mark + confirmed, + https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/docs/cdr-format.md +- **C**: the published object model reference for the format's drawing program, + https://community.coreldraw.com/sdk/api/draw/17 +- **P**: a web editor's published CDR notes, + https://github.com/photopea/CDR-specification/blob/f91b3c7e8c812b28473f6399e95a624a72a3d6b8/README.md +- **KR**: the README and the `bin/cdr-unpk` script of the Kaitai Struct specification (MIT), at + the same commit as K, + https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/README.md + and https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/bin/cdr-unpk +- **Z**: the PKWARE ZIP specification, APPNOTE.TXT version 6.3.10, + https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT, and RFC 1951 (DEFLATE), + https://www.rfc-editor.org/rfc/rfc1951 +- **TS**: the source of the reader that T's notes describe (MIT OR Apache-2.0), at the same commit + as T, read for where a field lies when the notes leave it open; no code is copied, + https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/crates/cdr/src/wl.rs + and https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/crates/cdr/src/parse.rs +- **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 +- **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 + https://pronom.nationalarchives.gov.uk/fmt/465.xml + +Status: `public-spec` (K, KR, C, Z, F or PR), `public-notes` (a confirmed row of T, a row of T's +table of the layouts its writer takes from sample files, TS, or P), `unconfirmed` (a row T marks as +assumed, or a point no source states; listed so it can be checked against a file). + +No public specification covers versions 1 to 4, and the files of those versions that this reader +has read are the synthetic ones `src/synth.rs` builds from the rows below. T's authors took their +rows for versions 3 and 4 from four version 3 drawings, six version 4 drawings and a set of +version 3 clip art, and their rows for versions 1 and 2 from 18 files; none of those files is +public. + +T and P are themselves notes taken from files, not specifications. Drawings of versions 7 to 18, +20, 22, 24, 26 and 27 written by the converter that T's authors publish (release 0.44.0) read back +with the pages, layers, groups, shapes, colors, outline widths, caps, joins and dashes it wrote. +That converter also reads the synthetic packages of versions 14 to 18, 20, 22, 24, 26 and 27 that +`src/synth.rs` writes, with the page, its layer and the shapes on it. Those files are not +committed. + +| Id | What the code relies on | Source | Status | +|---|---|---|---| +| R1 | `RIFF`, the body length, then the form type `CDR` or `cdr` and a version character: `1` to `9`, `A` (10) to `H` (17), `J` (18) on, `I` unused; `cdr8` is 8.01, `CDR ` is 3, `CDRX` is another format. Files of versions 23 to 27 carry `O` to `U`, which count differently from the version 24 update on (`CDRQ` with a `vrsn` of 2430, `CDRU` with 2700), so their `vrsn` chunk decides (R2) | K L68-L133; T L22 | public-spec (letters from version 23: public-notes) | +| R2 | `vrsn`: the version as a u16, in hundreds | K L276-L278 | public-spec | +| R3 | `LIST cmpr`: two (compressed, uncompressed) u32 pairs, then two blocks of `CPng`, `01 00 04 00` and a zlib stream; the first inflates to the chunk stream, the second to a pool of u32 sizes that each chunk's size field indexes | K L193-L220, L2626-L2682; P "LIST cmpr"; T L30 | public-spec | +| R4 | A chunk is an id, a u32 size and the body, padded to an even length; a `LIST` body starts with its form type; from version 7 a `LIST stlt` holds the style tables, not chunks | K L68-L78, L135-L155, L307-L334 | public-spec | +| R5 | Coordinates: i16 in 1/1000 inch before version 6, else i32 in 1/254000 inch; header fields, counts and offsets are u16 before version 6, else u32 | K L58-L66, L2688-L2700; T L145 | public-spec | +| R6 | `loda` and `lobj`: length, argument count, offsets table, types table, object type; count + 1 offsets bound the arguments; the types table runs in reverse; object types (1 rectangle, 2 ellipse, 3 curve, 0x14 polygon) and argument types (10 outline, 20 fill, 30 coordinates, 1000 name, 11000 polygon, 19130 page size) | K L335-L450, L846-L893; T L145-L157 | public-spec | +| R7 | Angles: i16 tenths of a degree before version 6, else i32 millionths of a degree | K L2835-L2855 | public-spec | +| R8 | `trfd`: length, count, offsets table; each entry has 8 bytes first from version 13, a u16 type, and type 8 is a matrix after 6 bytes (from version 6) of six f64 `a c tx b d ty`, `tx` and `ty` in coordinate units; the matrices of one record apply in file order | K L895-L953, L2808-L2834; T L201-L204 | public-spec | +| R9 | Name argument (1000): Windows-1252 up to a NUL before version 12, UTF-16LE from it | K L601-L630 | public-spec | +| R10 | `mcfg`: 12 bytes (13 on), 4 (9 to 12), 28 (6) or none, then the page width and height as coordinates | K L1670-L1765; P "mcfg" | public-spec | +| R11 | `fild` (`fill` before 7): id; from 13 a record tagged 1300 with its length, which records tagged 2400 or more may precede; the fill type u16 (0 none, 1 uniform, others not read); uniform: 2 bytes then a color before 13, from 13 a record tagged 1300 holding a property list (u8 type, u32 length, body; 0 ends it; 1 a color, 8 a palette id and a UTF-16 name, 3 a UTF-16 name) | K L1025-L1302; T L217-L220 | public-spec (2400 records: public-notes) | +| R12 | `outl`: id; from 13 records (u32 id, u32 length, body) up to id 1, whose body follows; line type, caps and join u16; 2 bytes (6 to 12); width; stretch u16; 2 bytes (6 on); nib angle; 52 bytes (6 to 12) or 46 (13 on); the color; 16 bytes (10 before 6); the dash count u16 and the dashes, in multiples of the width; the arrowhead ids 22 bytes after the first dash in 7 and 11 to 12, 20 bytes from 13. Caps 0 butt, 1 round, 2 square; joins 0 miter, 1 round, 2 bevel | K L954-L1024; T L242-L243; C `cdrOutlineLineCaps`, `cdrOutlineLineJoin` | public-spec (arrowhead places: public-notes) | +| R13 | Bit 0 of the outline's line type: no outline | T L246 | unconfirmed | +| R14 | A color record from version 5: model u16, palette u16, 4 bytes, four value bytes. Models: 2 CMYK in percent, 3 and 17 CMYK 0 to 255, 4 CMY 0 to 255, 5 blue, green, red, 9 gray 0 to 255, 20 registration, 21 blue, green, red and a tint in percent already applied; 1, 14 and 25 a library color's number (u16) and tint in percent (u16) | K L2856-L2965; T L256-L257 | public-spec (library values: public-notes) | +| R15 | Rectangle coordinates: width, height and one radius, three more radii from version 9, running counterclockwise from the corner at (width, 0) | K L674-L700; T L172-L173 | public-spec | +| R16 | Point list: u32 count (before version 6 as R39 gives it), the points, then one type byte each, the count held to what fits; type bits 7 and 6 move, line, curve end, control point; bit 3 closes the subpath | K L782-L787, L840-L845, L2701-L2807; T L170-L171, L180 | public-spec | +| R17 | Ellipse coordinates: width, height, start and end angles, pie flag (u16 before 6, else u32); the radii are half the width and height; the angles turn from the ellipse's own axes, which a negative width or height points the other way | K L754-L781; T L179 | public-spec (axis direction of a negative size: public-notes) | +| R18 | Polygon argument (11000): 4 bytes before 13, the side count u32, the next point u32 (the u32 after it when it is 0 or 1, else 4 bytes), 4 more from 13, rx and ry f64, the centre; the base curve is one side on a circle of 1000 mm from the top vertex to the vertex it runs to clockwise, copied once for each side | K L631-L655; T L182-L183 | public-spec (base curve: public-notes) | +| R19 | `flgs`: byte 3 the record type, byte 2 marks the master page; a layer's byte 0 is 0, 8 desktop, 0x0a guides, 0x1a grid; in versions 7 to 13 the master page flags its guides [2, 1, 1], desktop [0, 1, 1] and grid [0x12, 0, 1]; from 14 it flags them [0x0a, 0, 1], [8, 0, 1] and [0x1a or 0x5a, 1, 1], by byte 0 as other layers | K L1602-L1639; T L132-L133 | public-spec (master page flags: public-notes for versions 7 to 21, unconfirmed for 22 to 27) | +| R20 | Fill and outline arguments (20, 10): a u32 record id | K L452-L460, L548-L556 | public-spec | +| R21 | Page size argument (19130): width and height | K L666-L672 | public-spec | +| R22 | `LIST page` holds `LIST layr` lists, in versions 7 to 13 inside a `LIST gobj`; a layer holds `LIST obj ` and `LIST grp `; a page, layer or object keeps its own `loda` (and an object its `trfd`, in a `trfl` list) among its chunks or in a `LIST lgob` | K L1602-L1639 (record types); T L120, L129, L359, L362 | public-notes | +| R23 | Guideline (object type 0x16), argument 16000: 12 bytes, the angle in millionths of a degree, then points from the page centre; version 7 keeps them in a `guid` chunk: a u32 count, the count again, 40-byte records laid out the same way | T L159-L160 | public-notes | +| R24 | ZIP: the end of central directory record (signature `PK\5\6`, 22 bytes and a comment of up to 65,535 bytes) gives the member count and where the central directory lies; each central directory entry (46 bytes, then name, extra field and comment) gives the flags, method, CRC-32, sizes and its local header; a local header is 30 bytes, then its name and extra field, then the member's bytes. Flag bit 0 marks an encrypted member; method 0 is stored and 8 deflated; 0xFFFF and 0xFFFFFFFF mark ZIP64 fields, and a ZIP64 locator (`PK\6\7`, 20 bytes) precedes the end record of a ZIP64 archive; disk numbers other than 0 mark an archive split across files | Z 4.3.7, 4.3.12, 4.3.15, 4.3.16, 4.4.1.4, 4.4.4, 4.4.5, 4.4.7, 4.4.8, 4.4.13 | public-spec | +| R25 | Versions 14 and 15 save a ZIP package whose member `content/riffData.cdr` is the RIFF file | KR README L33, `cdr-unpk` L30; T L29, L355 | public-spec | +| R26 | From version 16 the package's member `content/root.dat` is the RIFF file; `content/dataFileList.dat` names the data streams, one per line, members of `content/data/`; a redirect's stream number counts lines from 0 | KR README L34, L40, `cdr-unpk` L34-L66; K L173-L180; T L37, L355 | public-spec | +| R27 | In a package of version 16 on, a chunk outside a compressed list whose size is 16 (in `root.dat` or in a redirected list's body) is a redirect record: stream u32, length u32, offset u32 and a reserved u32; its body is `length` bytes at `offset` of the stream; stream `0xFFFFFFFF` holds the body (at most 8 bytes) in the record after the length; a redirected list's body starts with its form type | K L144-L193; T L38-L40 | public-spec | +| R28 | Templates have the form type `CDT` and a letter of their own, `CDTQ` in version 21 with a `vrsn` of 2100; the `vrsn` chunk names the version. The reader takes any letter `A` to `Z` there | T L26 | public-notes (letters other than `Q`: unconfirmed) | +| R29 | Rectangle coordinates from version 15: width and height as f64 coordinate units, scale x and y (f64, repeating the transform's scale), the scale-with flag (u8) and 7 bytes, then the four radii as f64, 16 bytes apart (a corner type byte and 15 bytes after the first), in the order of R15. With the flag clear each radius is a share of half the shorter side; with it set the radii are multiplied by 254000 coordinate units, which makes them inches | K L674-L752; T L173-L177 | public-spec (radius share with the flag clear, scale not applied: public-notes) | +| R30 | Object type 0x25 (version 16 on) is a path: 4 bytes, two u16 counts that add up to the point count, 16 bytes, then the points and their type bytes as in R16 | K L788-L799, L892; T L157, L181 | public-spec (from version 16: public-notes) | +| R31 | Version 3 is a RIFF file with the form type `CDR ` (a space) and a `vrsn` of 300; version 4 has the form type `CDR4` and a `vrsn` chunk. Both use the 16-bit fields of R5 and R7. Their pages, layers, groups and objects are read by the rules of R19 and R22 | K L117-L134; T L44; PR fmt/465; F `riff` L786 | public-spec (pages and layers as R19 and R22: unconfirmed) | +| R32 | Version 3 counts its object types from 0: rectangle 0, ellipse 1, curve 2, text 3, bitmap 4; later versions use these plus one | T L53; TS `parse.rs` | public-notes | +| R33 | Version 3 keeps an object's transforms in argument 100 of its `lobj`: a u16, the entry count (u16), then 10-byte entries of a type (u16) and, at byte 6, where the entry's data starts, counted from the start of the argument. Type 0x8c is a matrix as R37, and the matrices apply in file order. Type 0x14 is an envelope, which this reader does not apply: the shape keeps its outline, placed by the matrices alone, and the drawing's warnings name the envelopes. A group's own `lobj` holds an argument 100 that places all of the group's objects after their own transforms | T L54-L56, L60; K L851; TS `parse.rs` | public-notes | +| R34 | Version 3 fill, argument 20: a type byte (0 none, 1 uniform, 2 and 4 fountain, 6 texture, 7 and 10 pattern); a uniform fill's color follows as R36 | K L452-L547; T L62 | public-spec | +| R35 | Version 3 outline, argument 10: a flags byte with bit 0 set when the object is outlined, the width (coordinate), the stretch (u16), the nib angle, the color as R36, 7 bytes, the dash count (u8) and 10 bytes that hold the dashes as one byte each, the join (u16 at byte 30) and the caps (u16 at byte 32) numbered as R12, then the two arrowhead ids (u32). Dashes are read in multiples of the width as R12 | K L548-L592; T L64 | public-spec (flag bit: public-notes; dash unit, and the join, which T puts in the byte at 33: unconfirmed) | +| R36 | A color before version 5: in versions 1 to 3 a model byte and four value bytes, in version 4 a model u16, four u16 values and 2 bytes. Model 1 is cyan, magenta, yellow and black in percent. Model 0 is an ink number (u16) and a tint in percent (u16): ink 0 is black at the tint, ink 1 is white, and other numbers are inks of a numbered library that the file does not store. Other models are read as R14 | K L2882-L2908; T L65-L66, L89; TS `parse.rs`, `wl.rs` | public-notes (models other than 0 and 1: unconfirmed, K and T differ on model 1) | +| R37 | A matrix of versions 3 and 4: six i32 `a c tx b d ty`, the four factors in 16.16 fixed point and `tx` and `ty` in coordinate units. A version 4 `trfd` entry of type 8 holds one where R8 has six f64 | T L55, L61; TS `parse.rs` | public-notes | +| R38 | `mcfg` of version 3: 2 bytes, then the page's two corners as four coordinates; the page size is the distance between them | K L1676-L1678, L1745-L1756; T L71 | public-spec | +| R39 | A point list before version 6 starts with a u16 count and another u16 (1 in some curves of versions 3 and 4), where K reads the two as one u32 | T L67 | public-notes | +| R40 | Versions 1 and 2 are not RIFF files. A file starts with `WL`, a marker byte, a zero byte and five u32: the start of the settings (28), the start and the end of the object records, the start of the trailer and that value minus two. F and PR give the marker `e` for version 1.0 and `m` for 2.0; T's authors also saw `d`. The reader takes these three markers and reads the three alike | T L82; F `images` L4159-L4172; PR fmt/467, fmt/466 | public-notes (which version `d` marks: unconfirmed) | +| R41 | The page's box in a file of version 1 or 2: four i16 at byte 30 (left, top, right, bottom) in 1/1000 inch around the page's centre, y pointing up | T L75-L78, L83; TS `wl.rs` | public-notes | +| R42 | The records of a file of version 1 or 2 run from the front of the stacking order to the back. A group or layer record is 28 bytes, and the low byte of its flags at byte 26 is not 0x40. A drawn object has 0x40 there and a u16 body size at byte 28; it is the body size plus 32 bytes long, and at least 118 | T L85, L86, L93; TS `wl.rs` | public-notes | +| R43 | A drawn object of version 1 or 2: a point (two i16) at byte 32; six i32 in 16.16 fixed point at 36, `a b tx c d ty`, with x' = a x + b y + tx + the point's x and y' = c x + d y + ty + the point's y; the object type at 60 (0 rectangle, 1 ellipse, 2 curve, 3 text); a byte at 67 that is not 0 when the object is outlined, the outline's width (u16) at 68 and its color at 74; the fill type at 94 (0 none, 1 uniform) and its color at 95; the shape from byte 114. Colors are as R36 | T L87-L89; TS `wl.rs` | public-notes | +| R44 | Shapes of version 1 or 2, from byte 114 of the object: a rectangle's width and height (i16), then after 2 bytes a corner radius; an ellipse's width and height, then two angles; a curve's point list as R39 and R16 | T L90, L91; TS `wl.rs` | public-notes (radius: unconfirmed; how the angles make an arc: unconfirmed, so an ellipse whose angles differ is left out) | diff --git a/crates/cdr/README.md b/crates/cdr/README.md new file mode 100644 index 0000000000..56ded19cfb --- /dev/null +++ b/crates/cdr/README.md @@ -0,0 +1,66 @@ +# vectorcraft-cdr + +A bounded Rust reader for `.cdr` drawings of versions 1 to 27 (and `.cdt` templates). +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. + +## What is read + +| In the `.cdr` file | Read as | +|---|---| +| ZIP packages: `content/riffData.cdr` (versions 14 and 15), `content/root.dat` with the data streams `content/dataFileList.dat` names (16 on) | the RIFF chunk tree; a data stream is inflated only when a chunk the reader reads, or a list it splits, points into it | +| Pages, the page size in `mcfg` or a page's own size | pages, laid out by the engine as artboards side by side | +| Layers (drawing, desktop, guides and grid layers), the master page's among them | layers by name and kind | +| Guidelines (object type 0x16, and the version 7 `guid` chunk) | guidelines at their point and angle | +| Groups (`LIST grp `) | groups | +| Curves (point lists of moves, lines and cubic curves) and paths (object type 0x25, version 16 on) | paths | +| Rectangles (one corner radius, four from version 9) | rectangles with each corner's radius | +| Ellipses, arcs and pies | ellipses, and paths for arcs and pies | +| Polygons and stars (a base side copied for each side) | paths | +| Uniform fills: CMYK, CMY, RGB, gray, registration, library colors | colors, spot colors with their tints | +| Outlines: width, caps, joins, dashes, the no-outline flag | outlines | + +Text, bitmaps, linked groups (blends, contours, brush strokes), B-spline curves, fountain, +pattern, texture and PostScript fills and outline arrowheads are not read; the drawing's +`warnings` name each kind it held. Drawings of versions after 27 are refused, and so are packages +that are encrypted, ZIP64 archives or split across files. + +## Versions 1 to 4 + +No public specification covers these versions. The reader follows the published notes that +`PROVENANCE.md` cites (rows R31 to R44), and the files of these versions it has read are the +synthetic ones that `src/synth.rs` builds from those rows. + +| Version | Read | Left out or refused | +|---|---|---| +| 1 and 2 (`WL` files) | the page size; rectangles with one corner radius, whole ellipses and curves, each with its matrix; uniform fills and outlines with their width and color, in CMYK percent and the inks black and white. The objects come in on one page and one layer, front to back | text and objects of other types, and ellipses whose two angles differ (arcs and pies), with the unsupported-objects warning; fills of other types, with the unsupported-fills warning; inks of a numbered library, which read as spot colors without a look; groups and layers, whose records are passed over; dashes, caps, joins and arrowheads, which the notes do not place | +| 3 (RIFF, form type `CDR `) | the page size from the page's corners; pages, layers and groups; rectangles, ellipses, arcs and curves with the matrices of the object and of the groups around it; uniform fills; outlines with their width, color, caps, joins and dashes | text and bitmaps; envelopes, with the envelopes warning (the objects and groups under one keep their outlines and matrices); fountain, pattern and texture fills; arrowheads | +| 4 (RIFF, form type `CDR4`) | as version 5, with the colors and the fixed-point transforms of version 4 | as version 5 | + +A file is taken for version 1 or 2 by its content only when, after `WL`, its marker byte is one of +`d`, `e` and `m`, the next byte is zero, and the record offsets of its header fit the file. The +reader reports version 2 for the marker `m` and version 1 for the other two. A RIFF file that names +a version before 3 is refused, and so is the version 4 template form type `CDST`, which reads as +not a `.cdr` drawing. + +## Provenance + +`PROVENANCE.md` lists every record layout the reader relies on, with its public source and status. +Code cites the rows by id (`R1` ...), and `tests/provenance.rs` fails when a cited id has no row. +The test inputs are synthetic drawings built by `src/synth.rs` (the `synth` feature); no +third-party file is committed. + +## Limits + +`Limits` bounds the input size, the bytes inflated from compressed lists and package members, the +size of one package member, the number of members, the nesting depth, the chunk count, the +objects, the coordinates and the outline dashes of one read. Past a limit the reader stops with an +error or leaves the rest out with a warning; it does not recurse and does not panic. Each record +of a version 1 or 2 file counts toward the chunk count, and the transform entries of a version 3 +object are held to the arguments one record may have. A package's +data stream is read once however many lines of `content/dataFileList.dat` name it. A redirected +list whose bytes overlap those of an earlier redirected list is left out with the damage warning. +Other records may share bytes, and the bytes read again may add up to the member limit; past it +the records are left out with the limit warning. diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs new file mode 100644 index 0000000000..b4909aca29 --- /dev/null +++ b/crates/cdr/src/build.rs @@ -0,0 +1,537 @@ +//! The drawing the chunk index holds: pages, layers, objects and the fills and outlines they name +//! (R19 to R23). Records are decoded only when an object refers to them. + +use std::collections::HashMap; + +use crate::bytes::Rd; +use crate::geometry; +use crate::inline; +use crate::layout::{self, Profile}; +use crate::limits::Budget; +use crate::model::{Color, Drawing, Geometry, Guideline, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape}; +use crate::records::{self, Loda}; +use crate::riff::{Chunk, Index, push}; +use crate::{Error, Warning}; + +/// Object types (R6). +const RECTANGLE: u32 = 1; +const ELLIPSE: u32 = 2; +const CURVE: u32 = 3; +const POLYGON: u32 = 0x14; +const GUIDELINE: u32 = 0x16; +const PATH: u32 = 0x25; +/// Argument types (R6, R20, R21, R33). +const ARG_OUTLINE: u32 = 10; +const ARG_FILL: u32 = 20; +const ARG_COORDS: u32 = 30; +const ARG_TRANSFORMS: u32 = 100; +const ARG_NAME: u32 = 1000; +const ARG_POLYGON: u32 = 11000; +const ARG_GUIDE: u32 = 16000; +const ARG_PAGE_SIZE: u32 = 19130; + +/// What a RIFF file that names a version before 3 is refused as. +const BEFORE_3: &str = "RIFF files of versions before 3"; + +/// What one read keeps while mapping. +struct Ctx<'a, 'b> { + ix: &'b Index<'a>, + p: Profile, + budget: &'b mut Budget, + warn: &'b mut Vec, + /// Fill and outline records by id, decoded on first use. + fill_chunks: HashMap, + outline_chunks: HashMap, + fills: HashMap>, + outlines: HashMap>, +} + +pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec) -> Result { + let root = ix.root().ok_or(Error::NotCdr)?; + let version = version(ix, root); + // A template whose `vrsn` chunk doesn't name a version read (R28). + if version == 0 { + return Err(Error::NotCdr); + } + // Versions 1 and 2 are `WL` files (R40); no source shows a RIFF file that names a version + // before 3. + if version < layout::OLDEST_RIFF { + return Err(Error::Unsupported(BEFORE_3)); + } + let p = layout::for_version(version).ok_or(Error::Version(version))?; + let mut found = Found::default(); + collect(ix, root, &mut found); + let page_size = found.mcfg.and_then(|c| page_size(ix.data(c), &p)); + let mut cx = + Ctx { ix, p, budget, warn, fill_chunks: HashMap::new(), outline_chunks: HashMap::new(), fills: HashMap::new(), outlines: HashMap::new() }; + for c in &found.fills { + if let Some(id) = Rd::new(ix.data(c)).u32() { + cx.fill_chunks.entry(id).or_insert(ix.data(c)); + } + } + for c in &found.outlines { + if let Some(id) = Rd::new(ix.data(c)).u32() { + cx.outline_chunks.entry(id).or_insert(ix.data(c)); + } + } + let mut guides = found.guid.map(|c| guid_chunk(ix.data(c), &cx.p, cx.budget, cx.warn)).unwrap_or_default(); + let mut pages = Vec::new(); + let mut master = Vec::new(); + for page in &found.pages { + let (is_master, read) = cx.page(page); + if is_master { + // Guidelines on any of the master page's layers show on every page. + for mut layer in read.layers { + guides.append(&mut layer.guides); + if !layer.objects.is_empty() && layer.kind != LayerKind::Grid { + master.push(layer); + } + } + } else { + pages.push(read); + } + } + // A file of only a master page keeps it as its page. + if pages.is_empty() && !master.is_empty() { + pages.push(Page { size: None, layers: std::mem::take(&mut master) }); + } + Ok(Drawing { version, page_size, pages, master, guides, warnings: std::mem::take(cx.warn) }) +} + +/// The version: the `vrsn` chunk's when it names one from 3 to 27, else the form type's (R1, R2). +/// A template's form type names no version, so its `vrsn` chunk decides whatever it names (R28). +/// Letters count differently from the version 24 update on (R1), so when both name a version +/// after 27 the `vrsn` chunk's is the one refused. +fn version(ix: &Index, root: &Chunk) -> u16 { + let vrsn = ix.children(root).iter().find(|c| &c.id == b"vrsn").and_then(|c| Rd::new(ix.data(c)).u16()); + match vrsn { + Some(v) if (layout::OLDEST_RIFF..=layout::NEWEST).contains(&v) => v, + Some(v) if ix.form_version == 0 => v, + Some(v) if v > layout::NEWEST && ix.form_version > layout::NEWEST => v, + _ => ix.form_version, + } +} + +#[derive(Default)] +struct Found<'i> { + fills: Vec<&'i Chunk>, + outlines: Vec<&'i Chunk>, + mcfg: Option<&'i Chunk>, + guid: Option<&'i Chunk>, + pages: Vec<&'i Chunk>, +} + +/// Every fill, outline and page in file order, and the first `mcfg` and `guid`; pages are not +/// looked into. +fn collect<'i>(ix: &'i Index, root: &'i Chunk, found: &mut Found<'i>) { + let mut stack: Vec<&Chunk> = ix.children(root).iter().rev().collect(); + while let Some(c) = stack.pop() { + match &c.id { + b"fild" | b"fill" => found.fills.push(c), + b"outl" => found.outlines.push(c), + b"mcfg" => found.mcfg = found.mcfg.or(Some(c)), + b"guid" => found.guid = found.guid.or(Some(c)), + _ if c.is_list(b"page") => found.pages.push(c), + _ => stack.extend(ix.children(c).iter().rev()), + } + } +} + +/// The page size in `mcfg` (R10); in version 3 the distance between the page's two corners, after +/// 2 bytes (R38). +fn page_size(b: &[u8], p: &Profile) -> Option<(f64, f64)> { + let mut r = Rd::at(b, p.mcfg_skip); + if p.mcfg_corners { + r.skip(2)?; + let (x0, y0, x1, y1) = (records::coord(&mut r, p)?, records::coord(&mut r, p)?, records::coord(&mut r, p)?, records::coord(&mut r, p)?); + return sane_size(x1 - x0, y1 - y0); + } + sane_size(records::coord(&mut r, p)?, records::coord(&mut r, p)?) +} + +fn sane_size(w: f64, h: f64) -> Option<(f64, f64)> { + let (w, h) = (w.abs(), h.abs()); + (w > 0.0 && h > 0.0).then_some((w, h)) +} + +/// The version 7 `guid` chunk (R23): two counts, then 40-byte records laid out as argument 16000. +/// Each guideline counts toward the objects a read maps; past them the rest are left out. +fn guid_chunk(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Vec { + let mut r = Rd::new(b); + let Some(n) = r.u32() else { return Vec::new() }; + let _again = r.u32(); + let fits = r.left() / 40; + if n as usize > fits { + push(warn, Warning::Damaged); + } + let n = (n as usize).min(fits); + let mut out = Vec::new(); + for i in 0..n { + if !budget.take_object() { + push(warn, Warning::TooDeep); + break; + } + out.extend(b.get(8 + i * 40..8 + (i + 1) * 40).and_then(|g| guideline(g, p))); + } + out +} + +/// A guideline record (R23): 12 bytes, the angle in millionths of a degree, then a point. +fn guideline(b: &[u8], p: &Profile) -> Option { + if p.short { + return None; + } + let mut r = Rd::at(b, 12); + let angle = f64::from(r.i32()?) / 1_000_000.0; + let at = Pt { x: records::coord(&mut r, p)?, y: records::coord(&mut r, p)? }; + Some(Guideline { at, angle }) +} + +/// A list's flags (R19): four bytes. +fn flags(ix: &Index, list: &Chunk) -> Option<[u8; 4]> { + let c = ix.children(list).iter().find(|c| &c.id == b"flgs")?; + ix.data(c).get(..4)?.try_into().ok() +} + +/// What a layer's flags make it (R19). Byte 0 holds the kind; versions 7 to 13 flag the master +/// page's desktop layer 0 with bytes 1 and 2 set, and its guides layer 2. +fn layer_kind(f: [u8; 4], version_below_14: bool) -> LayerKind { + let [b0, b1, b2, _] = f; + if b0 & 0x10 != 0 { + LayerKind::Grid + } else if b0 & 0x1f == 0x0a || (version_below_14 && b0 & 0x1f == 0x02) { + LayerKind::Guides + } else if b0 == 0x08 || (version_below_14 && b0 == 0 && b1 == 1 && b2 == 1) { + LayerKind::Desktop + } else { + LayerKind::Drawing + } +} + +/// The first chunk of one of `ids` that a page, layer or object keeps for itself: among its own +/// chunks, or in its `lgob` list and the `trfl` list there (R22). +fn own_chunk<'i>(ix: &'i Index, list: &'i Chunk, ids: &[&[u8; 4]]) -> Option<&'i Chunk> { + let mut stack: Vec<(&Chunk, u8)> = ix.children(list).iter().rev().map(|c| (c, 0)).collect(); + while let Some((c, depth)) = stack.pop() { + if ids.contains(&&c.id) { + return Some(c); + } + if depth < 2 && (c.is_list(b"lgob") || c.is_list(b"trfl")) { + stack.extend(ix.children(c).iter().rev().map(|k| (k, depth + 1))); + } + } + None +} + +/// The `loda` (or `lobj`) a page, layer or object keeps for itself. +fn own_loda<'i>(ix: &'i Index, list: &'i Chunk) -> Option<&'i Chunk> { + own_chunk(ix, list, &[b"loda", b"lobj"]) +} + +/// A page's layer lists in file order: its own, and those in the lists it holds, such as the +/// `gobj` list of files of versions 7 to 13 (R22). +fn page_layers<'i>(ix: &'i Index, page: &'i Chunk) -> Vec<&'i Chunk> { + let mut out = Vec::new(); + let mut stack: Vec<&Chunk> = ix.children(page).iter().rev().collect(); + while let Some(c) = stack.pop() { + if c.is_list(b"layr") { + out.push(c); + } else if c.id == crate::riff::LIST && !c.is_list(b"lgob") { + stack.extend(ix.children(c).iter().rev()); + } + } + out +} + +/// One frame of the object walk: a list's chunks, the next one to look at, and the objects so far. +struct Frame<'i> { + chunks: &'i [Chunk], + next: usize, + objects: Vec, + /// Whether its objects form a group in the frame below. + group: bool, + /// What places its objects after their own transforms: the matrices of the version 3 groups + /// around them (R33). The identity in other versions, whose objects hold their whole transform. + outer: Matrix, +} + +impl<'a, 'b> Ctx<'a, 'b> { + /// A page: whether it is the master page, and its layers. + fn page(&mut self, page: &Chunk) -> (bool, Page) { + let ix = self.ix; + let is_master = flags(ix, page).is_some_and(|f| f[2] != 0); + let size = own_loda(ix, page) + .and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)) + .and_then(|l| l.arg(ARG_PAGE_SIZE).and_then(|b| self.size_arg(b))); + let mut layers = Vec::new(); + for l in page_layers(ix, page) { + let layer = self.layer(l); + let empty = layer.objects.is_empty() && layer.guides.is_empty(); + // The entries that stand for the master page's layers hold nothing of the page's own. + if empty && (is_master || layer.kind != LayerKind::Drawing) { + continue; + } + layers.push(layer); + } + (is_master, Page { size, layers }) + } + + fn size_arg(&self, b: &[u8]) -> Option<(f64, f64)> { + let mut r = Rd::new(b); + sane_size(records::coord(&mut r, &self.p)?, records::coord(&mut r, &self.p)?) + } + + fn layer(&mut self, list: &Chunk) -> Layer { + let ix = self.ix; + let kind = flags(ix, list).map_or(LayerKind::Drawing, |f| layer_kind(f, self.p.old_master_flags)); + let loda = own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)); + let name = loda.and_then(|l| l.arg(ARG_NAME).map(|b| records::name(b, &self.p, self.warn))).unwrap_or_default(); + let mut guides = Vec::new(); + let objects = self.objects(ix.children(list), &mut guides); + Layer { name, kind, objects, guides } + } + + /// The objects of a layer's chunks, groups nested, front to back; guidelines go to `guides`. + fn objects(&mut self, chunks: &'b [Chunk], guides: &mut Vec) -> Vec { + let ix = self.ix; + let mut stack = vec![Frame { chunks, next: 0, objects: Vec::new(), group: false, outer: Matrix::IDENTITY }]; + loop { + let Some(top) = stack.last_mut() else { return Vec::new() }; + let (here, outer) = (top.chunks, top.outer); + let Some(c) = here.get(top.next) else { + let Some(done) = stack.pop() else { return Vec::new() }; + match stack.last_mut() { + // A group counts toward the objects a read maps; past them its objects stay, + // ungrouped. + Some(parent) if done.group && !done.objects.is_empty() => { + if self.budget.take_object() { + parent.objects.push(Object::Group(done.objects)); + } else { + push(self.warn, Warning::TooDeep); + parent.objects.extend(done.objects); + } + } + Some(parent) if !done.group => parent.objects.extend(done.objects), + Some(_) => {} + None => return done.objects, + } + continue; + }; + top.next += 1; + if c.is_list(b"obj ") { + if let Some(o) = self.object(c, guides, &outer) { + top.objects.push(o); + } + } else if c.is_list(b"grp ") { + let own = self.group_placement(c); + stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: true, outer: outer.after(&own) }); + } else if c.is_list(b"lnkg") { + // Linked groups (brush strokes, blends, contours) place their objects with a + // matrix of their own, which this reader doesn't apply: they are left out. + push(self.warn, Warning::UnsupportedObjects); + } else if c.id == crate::riff::LIST && !c.is_list(b"lgob") { + // Other lists under a layer are looked through (R22). + stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: false, outer }); + } + } + } + + /// The matrix a group places its objects with. Only a version 3 group has one, in the + /// transforms argument of its own `lobj` (R33); one that can't be read is damage, and the + /// group's objects stay where their own transforms put them. + fn group_placement(&mut self, list: &Chunk) -> Matrix { + if !self.p.inline_styles { + return Matrix::IDENTITY; + } + let ix = self.ix; + let Some(arg) = + own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)).and_then(|l| l.arg(ARG_TRANSFORMS)) + else { + return Matrix::IDENTITY; + }; + self.placement(arg) + } + + /// The matrices of a transforms argument (R33). An envelope among them is not applied: the + /// shapes keep their outlines, placed by the matrices alone, with the envelopes warning. + fn placement(&mut self, arg: &[u8]) -> Matrix { + match inline::transforms(arg, &self.p, &self.budget.limits, self.warn) { + Some(t) => { + if t.envelope { + push(self.warn, Warning::Envelopes); + } + t.matrix + } + None => { + push(self.warn, Warning::Damaged); + Matrix::IDENTITY + } + } + } + + /// One `LIST obj `: a shape placed by its own transform and then by `outer`, or `None` (a + /// guideline goes to `guides`). + fn object(&mut self, list: &Chunk, guides: &mut Vec, outer: &Matrix) -> Option { + let ix = self.ix; + let Some(loda) = own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)) else { + push(self.warn, Warning::Damaged); + return None; + }; + // Guidelines count toward the objects a read maps. + if !self.budget.take_object() { + push(self.warn, Warning::TooDeep); + return None; + } + if loda.kind == GUIDELINE { + guides.extend(loda.arg(ARG_GUIDE).and_then(|b| guideline(b, &self.p))); + return None; + } + if self.p.inline_styles { + return self.inline_object(&loda, outer); + } + let geometry = self.geometry(&loda)?; + // A transform that is there but can't be read is damage; the shape stays where it is. + let matrix = match own_chunk(ix, list, &[b"trfd"]) { + None => Matrix::IDENTITY, + Some(c) => records::trfd(ix.data(c), &self.p).unwrap_or_else(|| { + push(self.warn, Warning::Damaged); + Matrix::IDENTITY + }), + }; + let fill = loda.arg(ARG_FILL).and_then(id_of).and_then(|id| self.fill(id)); + let outline = loda.arg(ARG_OUTLINE).and_then(id_of).and_then(|id| self.outline(id)); + Some(Object::Shape(Box::new(Shape { geometry, matrix, fill, outline }))) + } + + /// A version 3 object, whose transforms, fill and outline are arguments of its own record + /// (R33, R34, R35). A fill or an outline that is there but can't be read is damage. + fn inline_object(&mut self, loda: &Loda, outer: &Matrix) -> Option { + let own = match loda.arg(ARG_TRANSFORMS) { + None => Matrix::IDENTITY, + Some(arg) => self.placement(arg), + }; + let geometry = self.geometry(loda)?; + let fill = loda.arg(ARG_FILL).and_then(|b| { + let read = inline::fill(b, &self.p, self.warn); + if read.is_none() { + push(self.warn, Warning::Damaged); + } + read.flatten() + }); + let outline = loda.arg(ARG_OUTLINE).and_then(|b| { + let read = inline::outline(b, &self.p, self.warn); + if read.is_none() { + push(self.warn, Warning::Damaged); + } + read.flatten() + }); + // Past the dashes a read takes, the outline is solid. + let outline = outline.map(|mut o| { + if !o.dashes.is_empty() && !self.budget.take_dashes(o.dashes.len()) { + o.dashes = Vec::new(); + push(self.warn, Warning::TooDeep); + } + o + }); + Some(Object::Shape(Box::new(Shape { geometry, matrix: outer.after(&own), fill, outline }))) + } + + fn geometry(&mut self, loda: &Loda) -> Option { + let coords = loda.arg(ARG_COORDS); + // Version 3 counts the first object types from 0, one below the later numbers (R32). + let kind = if self.p.types_from_zero && loda.kind <= 4 { loda.kind + 1 } else { loda.kind }; + // A shape without its coordinates, or a polygon without its sides, is damage like a shape + // whose coordinates can't be read. + let g = match kind { + RECTANGLE => coords.and_then(|c| geometry::rect(c, &self.p)), + ELLIPSE => coords.and_then(|c| geometry::ellipse(c, &self.p)), + CURVE => coords.and_then(|c| geometry::point_list(c, &self.p, self.budget, self.warn)).map(Geometry::Path), + PATH if self.p.paths => coords.and_then(|c| geometry::path_record(c, &self.p, self.budget, self.warn)).map(Geometry::Path), + POLYGON => coords + .and_then(|c| geometry::point_list(c, &self.p, self.budget, self.warn)) + .zip(loda.arg(ARG_POLYGON)) + .and_then(|(base, sides)| geometry::polygon(&base, sides, &self.p, self.budget, self.warn)), + _ => { + push(self.warn, Warning::UnsupportedObjects); + return None; + } + }; + if g.is_none() { + push(self.warn, Warning::Damaged); + } + g + } + + fn fill(&mut self, id: u32) -> Option { + if let Some(f) = self.fills.get(&id) { + return f.clone(); + } + // A record that is there but can't be read is damage; a missing one leaves the shape + // without a fill. + let read = self.fill_chunks.get(&id).and_then(|b| { + let read = records::fill(b, &self.p, self.warn); + if read.is_none() { + push(self.warn, Warning::Damaged); + } + read.and_then(|(_, c)| c) + }); + self.fills.insert(id, read.clone()); + read + } + + /// The outline of record `id`. Its dashes count toward the read's dashes for every shape that + /// uses it; past them the shape's outline is solid. + fn outline(&mut self, id: u32) -> Option { + if !self.outlines.contains_key(&id) { + let read = self.outline_chunks.get(&id).and_then(|b| { + let read = records::outline(b, &self.p, self.warn); + if read.is_none() { + push(self.warn, Warning::Damaged); + } + read.and_then(|(_, o)| o) + }); + // An outline with more dashes than the read may still take is kept solid. + let read = read.map(|mut o| { + if o.dashes.len() > self.budget.dashes_left() { + o.dashes = Vec::new(); + push(self.warn, Warning::TooDeep); + } + o + }); + self.outlines.insert(id, read); + } + let o = self.outlines.get(&id)?.as_ref()?; + if o.dashes.is_empty() || self.budget.take_dashes(o.dashes.len()) { + return Some(o.clone()); + } + push(self.warn, Warning::TooDeep); + Some(Outline { width: o.width, color: o.color.clone(), cap: o.cap, join: o.join, dashes: Vec::new() }) + } +} + +/// A fill or outline argument: the record id (R20). +fn id_of(b: &[u8]) -> Option { + Rd::new(b).u32() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layer_flags_name_the_kinds() { + assert_eq!(layer_kind([0, 0, 0, 0x98], true), LayerKind::Drawing); + assert_eq!(layer_kind([0x0a, 0, 0, 0x98], true), LayerKind::Guides); + assert_eq!(layer_kind([0x02, 1, 1, 0x98], true), LayerKind::Guides); + assert_eq!(layer_kind([0x08, 0, 1, 0x98], true), LayerKind::Desktop); + assert_eq!(layer_kind([0, 1, 1, 0x98], true), LayerKind::Desktop); + assert_eq!(layer_kind([0x1a, 0, 1, 0x98], true), LayerKind::Grid); + assert_eq!(layer_kind([0x12, 0, 1, 0x98], true), LayerKind::Grid); + // From version 14 the master page flags its layers by byte 0 alone. + assert_eq!(layer_kind([0x0a, 0, 1, 0x98], false), LayerKind::Guides); + assert_eq!(layer_kind([0x08, 0, 1, 0x98], false), LayerKind::Desktop); + assert_eq!(layer_kind([0x5a, 1, 1, 0x98], false), LayerKind::Grid); + assert_eq!(layer_kind([0x02, 1, 1, 0x98], false), LayerKind::Drawing); + assert_eq!(layer_kind([0, 1, 1, 0x98], false), LayerKind::Drawing); + } +} diff --git a/crates/cdr/src/bytes.rs b/crates/cdr/src/bytes.rs new file mode 100644 index 0000000000..216bd90024 --- /dev/null +++ b/crates/cdr/src/bytes.rs @@ -0,0 +1,76 @@ +//! Little-endian reads that fail instead of panicking. + +/// A cursor over one record's bytes. Every read returns `None` past the end. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Rd<'a> { + b: &'a [u8], + pos: usize, +} + +impl<'a> Rd<'a> { + pub(crate) fn new(b: &'a [u8]) -> Self { + Rd { b, pos: 0 } + } + + pub(crate) fn at(b: &'a [u8], pos: usize) -> Self { + Rd { b, pos } + } + + pub(crate) fn pos(&self) -> usize { + self.pos + } + + pub(crate) fn left(&self) -> usize { + self.b.len().saturating_sub(self.pos) + } + + pub(crate) fn skip(&mut self, n: usize) -> Option<()> { + let end = self.pos.checked_add(n)?; + (end <= self.b.len()).then(|| self.pos = end) + } + + pub(crate) fn bytes(&mut self, n: usize) -> Option<&'a [u8]> { + let end = self.pos.checked_add(n)?; + let s = self.b.get(self.pos..end)?; + self.pos = end; + Some(s) + } + + fn array(&mut self) -> Option<[u8; N]> { + self.bytes(N)?.try_into().ok() + } + + pub(crate) fn u8(&mut self) -> Option { + Some(self.array::<1>()?[0]) + } + + pub(crate) fn u16(&mut self) -> Option { + self.array().map(u16::from_le_bytes) + } + + pub(crate) fn i16(&mut self) -> Option { + self.array().map(i16::from_le_bytes) + } + + pub(crate) fn u32(&mut self) -> Option { + self.array().map(u32::from_le_bytes) + } + + pub(crate) fn i32(&mut self) -> Option { + self.array().map(i32::from_le_bytes) + } + + /// A finite f64; NaN and the infinities read as `None`. + pub(crate) fn f64(&mut self) -> Option { + self.array().map(f64::from_le_bytes).filter(|v| v.is_finite()) + } + + pub(crate) fn fourcc(&mut self) -> Option<[u8; 4]> { + self.array() + } +} + +/// The u32 at `pos` of `b`. +pub(crate) fn u32_at(b: &[u8], pos: usize) -> Option { + Rd::at(b, pos).u32() +} diff --git a/crates/cdr/src/geometry.rs b/crates/cdr/src/geometry.rs new file mode 100644 index 0000000000..cb883f7cf7 --- /dev/null +++ b/crates/cdr/src/geometry.rs @@ -0,0 +1,455 @@ +//! The coordinates argument (30) of each object type read as geometry: curves (R16), rectangles +//! (R15), ellipses and arcs (R17) and polygons (R18). + +use std::f64::consts::PI; + +use crate::Warning; +use crate::bytes::Rd; +use crate::layout::Profile; +use crate::limits::Budget; +use crate::model::{Geometry, Path, Pt, Segment, SubPath}; +use crate::records::{angle, coord}; +use crate::riff::push; + +/// The most sides a polygon record may give (VectorCraft's own bound). +const MAX_POLYGON_SIDES: u32 = 1000; +/// The base curve of a polygon lies on a circle of 1000 mm (R18), in points. +const POLYGON_UNIT_RADIUS: f64 = 1000.0 / 25.4 * 72.0; + +/// What a point type byte asks for (R16): bits 7 and 6. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Op { + Move, + Line, + Curve, + Control, +} + +fn op(t: u8) -> Op { + match t >> 6 { + 0 => Op::Move, + 1 => Op::Line, + 2 => Op::Curve, + _ => Op::Control, + } +} + +/// Bit 3 closes the subpath (R16). +const CLOSES: u8 = 0x08; + +/// A point list (R16): the count, the points, then one type byte each. The count is a u32 from +/// version 6 and a u16 followed by another u16 before it (R39). It is held to what the bytes hold; +/// `None` when the points are past the budget. +pub(crate) fn point_list(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + let count = if p.short { + let count = usize::from(r.u16()?); + r.skip(2)?; + count + } else { + r.u32()? as usize + }; + points(b, r, count, p, budget, warn) +} + +/// A path record (object type 0x25, R30): 4 bytes, two u16 counts whose sum is the point count, 16 +/// bytes, then the points and their type bytes as in a point list. +pub(crate) fn path_record(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + r.skip(4)?; + let count = usize::from(r.u16()?) + usize::from(r.u16()?); + r.skip(16)?; + points(b, r, count, p, budget, warn) +} + +/// `count` points from `r` over `b`, then their type bytes. A list cut short is read two ways: as +/// all `count` points with the type bytes after them, and as the points and type bytes the bytes +/// hold split evenly. The reading that keeps more points with a type byte wins, the first on a tie. +fn points(b: &[u8], mut r: Rd, count: usize, p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let each = 2 * p.word(); + let left = r.left(); + let split = (left / (each + 1)).min(count); + let whole = count.checked_mul(each).filter(|len| *len <= left).map(|len| (left - len).min(count)); + let stored = match whole { + Some(typed) if typed >= split => count, + _ => split, + }; + let types = b.get(r.pos() + stored * each..)?; + let n = stored.min(types.len()); + if count > n { + push(warn, Warning::Damaged); + } + if !budget.take_coordinates(n) { + push(warn, Warning::TooDeep); + return None; + } + let mut points = Vec::with_capacity(n); + for _ in 0..n { + points.push(Pt { x: coord(&mut r, p)?, y: coord(&mut r, p)? }); + } + Some(path_of(&points, types)) +} + +/// The subpaths that points and their type bytes draw. +fn path_of(points: &[Pt], types: &[u8]) -> Path { + let mut subpaths = Vec::new(); + let mut cur: Option = None; + // The last two control points: a curve end uses only those. + let mut controls: Vec = Vec::with_capacity(2); + for (&pt, &t) in points.iter().zip(types) { + let o = op(t); + if o == Op::Control { + if controls.len() == 2 { + controls.remove(0); + } + controls.push(pt); + continue; + } + if o == Op::Move || cur.is_none() { + subpaths.extend(cur.take()); + cur = Some(SubPath { start: pt, segments: Vec::new(), closed: t & CLOSES != 0 && o == Op::Move }); + controls.clear(); + if o == Op::Move { + continue; + } + } + let Some(sp) = cur.as_mut() else { continue }; + let seg = match (o, controls.as_slice()) { + (Op::Curve, [c1, c2]) => Segment::Cubic(*c1, *c2, pt), + _ => Segment::Line(pt), + }; + controls.clear(); + sp.segments.push(seg); + if t & CLOSES != 0 { + sp.closed = true; + } + } + subpaths.extend(cur); + // A closed subpath with no segments, or an open one with none, draws nothing. + subpaths.retain(|s| !s.segments.is_empty()); + Path { subpaths } +} + +/// A rectangle record (R15): width, height, then one corner radius for every corner, four from +/// version 9. +pub(crate) fn rect(b: &[u8], p: &Profile) -> Option { + if p.f64_rect { + return rect_f64(b, p); + } + let mut r = Rd::new(b); + let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?); + let first = coord(&mut r, p)?.abs(); + let mut radii = [first; 4]; + if p.four_radii { + for slot in radii.iter_mut().skip(1) { + *slot = coord(&mut r, p)?.abs(); + } + } + Some(Geometry::Rect { w, h, radii }) +} + +/// A rectangle record from version 15 (R29): width and height as f64 coordinate units, two scale +/// factors that repeat the transform's (not applied), the scale-with flag and 7 bytes, then the +/// four radii as f64 16 bytes apart. With the flag clear each radius is a share of half the shorter +/// side; with it set the radius is in inches. A corner is held to the shorter side, and sizes to +/// the range of the 32-bit coordinates of earlier versions. +fn rect_f64(b: &[u8], p: &Profile) -> Option { + let mut r = Rd::new(b); + let size = |v: f64| (v.abs() <= f64::from(i32::MAX)).then(|| v * p.unit()); + let (w, h) = (size(r.f64()?)?, size(r.f64()?)?); + r.skip(8 + 8)?; + let inches = r.u8()? != 0; + r.skip(7)?; + let short = w.abs().min(h.abs()); + let mut radii = [0.0; 4]; + for (k, slot) in radii.iter_mut().enumerate() { + if k > 0 { + r.skip(16)?; + } + let v = r.f64()?.abs(); + let radius = if inches { v * 72.0 } else { v * short / 2.0 }; + *slot = radius.min(short); + } + Some(Geometry::Rect { w, h, radii }) +} + +/// An ellipse record (R17): the box's width and height, the start and end angles and whether +/// the arc closes through the centre. Equal angles make a whole ellipse. +pub(crate) fn ellipse(b: &[u8], p: &Profile) -> Option { + let mut r = Rd::new(b); + let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?); + let (a1, a2) = (angle(&mut r, p)?, angle(&mut r, p)?); + let pie = if p.short { r.u16()? != 0 } else { r.u32()? != 0 }; + let sweep = (a2 - a1).rem_euclid(360.0); + if sweep.abs() < 1e-9 { + return Some(Geometry::Ellipse { w, h }); + } + Some(Geometry::Path(arc(w, h, a1, sweep, pie))) +} + +/// The arc of the ellipse in the box from the origin to (`w`, `h`), from `start` degrees through +/// `sweep` degrees, in the ellipse's own axes; a pie runs from the centre and closes there. The +/// radii are half the size, and a negative width or height points its axis the other way (R17), so +/// with a negative height 0 to 180 degrees is the half below the centre. +fn arc(w: f64, h: f64, start: f64, sweep: f64, pie: bool) -> Path { + let (cx, cy, rx, ry) = (w / 2.0, h / 2.0, w / 2.0, h / 2.0); + let at = |t: f64| Pt { x: cx + rx * t.cos(), y: cy + ry * t.sin() }; + let tangent = |t: f64| Pt { x: -rx * t.sin(), y: ry * t.cos() }; + let pieces = (sweep / 90.0).ceil().max(1.0) as usize; + let step = sweep.to_radians() / pieces as f64; + let k = 4.0 / 3.0 * (step / 4.0).tan(); + let t0 = start.to_radians(); + let mut segments = Vec::with_capacity(pieces + 2); + if pie { + segments.push(Segment::Line(at(t0))); + } + for i in 0..pieces { + let (a, b) = (t0 + step * i as f64, t0 + step * (i + 1) as f64); + let (p0, p1, d0, d1) = (at(a), at(b), tangent(a), tangent(b)); + segments.push(Segment::Cubic(Pt { x: p0.x + k * d0.x, y: p0.y + k * d0.y }, Pt { x: p1.x - k * d1.x, y: p1.y - k * d1.y }, p1)); + } + let start = if pie { Pt { x: cx, y: cy } } else { at(t0) }; + Path { subpaths: vec![SubPath { start, segments, closed: pie }] } +} + +/// A polygon (R18): its base curve, one side of the outline on a circle of 1000 mm with its top +/// vertex first, copied once per side and turned clockwise each time by the vertices the side +/// spans, then scaled by (`rx`, `ry`) and moved to the centre the polygon argument (11000) gives. +/// A star whose sides skip vertices draws as one outline, or as several when the side count and +/// the step share a factor. +pub(crate) fn polygon(base: &Path, b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + if !p.tagged { + r.skip(4)?; + } + let sides = r.u32()?; + // The next point: the first field, or the second when the first is 0 or 1. + let (first, second) = (r.u32()?, r.u32()?); + let next = if first > 1 { first } else { second }; + if p.tagged { + r.skip(4)?; + } + let (rx, ry) = (r.f64()?, r.f64()?); + let (cx, cy) = (coord(&mut r, p)?, coord(&mut r, p)?); + let side = base.subpaths.first()?; + if !(1..=MAX_POLYGON_SIDES).contains(&sides) { + push(warn, Warning::Damaged); + return None; + } + if !budget.take_coordinates(side.segments.len().saturating_mul(3).saturating_mul(sides as usize)) { + push(warn, Warning::TooDeep); + return None; + } + // The base curve's own unit radius, measured from its first point, keeps the scale right + // whatever unit the file's coordinates are in. + let unit = side.start.x.hypot(side.start.y); + let unit = if unit > 0.0 { unit } else { POLYGON_UNIT_RADIUS }; + let place = |q: Pt, turn: f64| { + let (s, c) = turn.sin_cos(); + let (x, y) = (q.x * c - q.y * s, q.x * s + q.y * c); + Pt { x: x / unit * POLYGON_UNIT_RADIUS * rx + cx, y: y / unit * POLYGON_UNIT_RADIUS * ry + cy } + }; + let step = side_step(side, sides, next); + let outlines = gcd(sides, step); + let each = sides / outlines; + let angle = |k: u32| -2.0 * PI * f64::from(k % sides) / f64::from(sides); + let mut subpaths = Vec::with_capacity(outlines as usize); + for o in 0..outlines { + let mut segments = Vec::with_capacity(side.segments.len() * each as usize); + for j in 0..each { + let turn = angle(o + j * step); + segments.extend(side.segments.iter().map(|s| match *s { + Segment::Line(a) => Segment::Line(place(a, turn)), + Segment::Cubic(a, b, c) => Segment::Cubic(place(a, turn), place(b, turn), place(c, turn)), + })); + } + subpaths.push(SubPath { start: place(side.start, angle(o)), segments, closed: true }); + } + Some(Geometry::Path(Path { subpaths })) +} + +/// How many vertices the base side moves on from its first point (R18): the vertex its last +/// point lies at, clockwise; else the next-point field when it names one; else 1. +fn side_step(side: &SubPath, sides: u32, next: u32) -> u32 { + let field = if (1..sides).contains(&next) { next } else { 1 }; + let Some(end) = side.segments.last().map(|s| match *s { + Segment::Line(e) | Segment::Cubic(_, _, e) => e, + }) else { + return field; + }; + let (r0, r1) = (side.start.x.hypot(side.start.y), end.x.hypot(end.y)); + if !(r0 > 0.0 && (r1 - r0).abs() <= r0 * 1e-3) { + return field; + } + let turned = (side.start.y.atan2(side.start.x) - end.y.atan2(end.x)) / (2.0 * PI / f64::from(sides)); + let k = turned.round(); + if !k.is_finite() || (turned - k).abs() > 1e-3 { + return field; + } + match k.rem_euclid(f64::from(sides)) as u32 { + 0 => field, + k => k, + } +} + +fn gcd(a: u32, b: u32) -> u32 { + let (mut a, mut b) = (a, b); + while b != 0 { + (a, b) = (b, a % b); + } + a.max(1) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pt(x: f64, y: f64) -> Pt { + Pt { x, y } + } + + #[test] + fn type_bytes_make_moves_lines_curves_and_closes() { + let points = [pt(0.0, 0.0), pt(10.0, 0.0), pt(10.0, 5.0), pt(5.0, 10.0), pt(0.0, 10.0), pt(20.0, 20.0), pt(30.0, 20.0)]; + // move (closed), line, control, control, curve end closing; move, line. + let types = [0x08, 0x40, 0xC0, 0xC0, 0x88, 0x00, 0x40]; + let path = path_of(&points, &types); + assert_eq!(path.subpaths.len(), 2); + let first = &path.subpaths[0]; + assert!(first.closed); + assert_eq!(first.segments, vec![Segment::Line(pt(10.0, 0.0)), Segment::Cubic(pt(10.0, 5.0), pt(5.0, 10.0), pt(0.0, 10.0))]); + assert!(!path.subpaths[1].closed); + } + + #[test] + fn a_point_list_short_of_type_bytes_reads_them_after_all_its_points() { + let p = crate::layout::for_version(1300).unwrap_or_else(|| panic!("profile")); + // Three points, (0, 0), (1 inch, 0) and (0, 0), and type bytes for the first two only. + let mut b = 3u32.to_le_bytes().to_vec(); + for v in [0i32, 0, 254_000, 0, 0, 0] { + b.extend(v.to_le_bytes()); + } + b.extend([0x00, 0x40]); + let mut warn = vec![]; + let path = point_list(&b, &p, &mut Budget::new(crate::Limits::default()), &mut warn).unwrap_or_else(|| panic!("path")); + assert_eq!(path.subpaths.len(), 1); + assert_eq!(path.subpaths[0].segments, vec![Segment::Line(pt(72.0, 0.0))]); + assert_eq!(warn, vec![Warning::Damaged]); + // A count past the points the bytes hold keeps the points that have a type byte. + // Eight points and their eight type bytes take the bytes of nine points. + let mut b = 9u32.to_le_bytes().to_vec(); + for i in 0..8 { + b.extend((i * 254_000i32).to_le_bytes()); + b.extend(0i32.to_le_bytes()); + } + b.extend([0x00, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40]); + let mut warn = vec![]; + let path = point_list(&b, &p, &mut Budget::new(crate::Limits::default()), &mut warn).unwrap_or_else(|| panic!("path")); + assert_eq!(path.subpaths[0].segments.len(), 7); + assert!(matches!(path.subpaths[0].segments[6], Segment::Line(end) if (end.x - 504.0).abs() < 1e-9 && end.y == 0.0)); + assert_eq!(warn, vec![Warning::Damaged]); + } + + #[test] + fn a_run_of_control_points_keeps_the_last_two() { + let points: Vec = (0..7).map(|i| pt(f64::from(i), 0.0)).collect(); + let path = path_of(&points, &[0x00, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x80]); + assert_eq!(path.subpaths[0].segments, vec![Segment::Cubic(pt(4.0, 0.0), pt(5.0, 0.0), pt(6.0, 0.0))]); + } + + #[test] + fn a_curve_end_without_two_controls_is_a_line() { + let path = path_of(&[pt(0.0, 0.0), pt(1.0, 1.0)], &[0x00, 0x80]); + assert_eq!(path.subpaths[0].segments, vec![Segment::Line(pt(1.0, 1.0))]); + } + + #[test] + fn a_quarter_arc_ends_on_the_ellipse() { + let p = arc(20.0, 10.0, 0.0, 90.0, false); + let sp = &p.subpaths[0]; + assert_eq!(sp.start, pt(20.0, 5.0)); + let Some(Segment::Cubic(_, _, end)) = sp.segments.last() else { panic!("no curve") }; + assert!((end.x - 10.0).abs() < 1e-9 && (end.y - 10.0).abs() < 1e-9); + let pie = arc(20.0, 10.0, 0.0, 180.0, true); + assert!(pie.subpaths[0].closed && pie.subpaths[0].start == pt(10.0, 5.0)); + } + + #[test] + fn a_negative_height_turns_the_arc_below_the_centre() { + let p = arc(20.0, -10.0, 0.0, 180.0, false); + let sp = &p.subpaths[0]; + assert_eq!(sp.start, pt(20.0, -5.0)); + let Some(Segment::Cubic(_, _, mid)) = sp.segments.first() else { panic!("no curve") }; + assert!((mid.x - 10.0).abs() < 1e-9 && (mid.y + 10.0).abs() < 1e-9, "{mid:?}"); + } + + /// A version 13 polygon argument: `sides`, the two next-point fields, then rx = ry = 1 at the + /// origin. + fn polygon_arg(sides: u32, first: u32, second: u32) -> Vec { + let mut b = Vec::new(); + for v in [sides, first, second, 0] { + b.extend(v.to_le_bytes()); + } + b.extend(1.0f64.to_le_bytes()); + b.extend(1.0f64.to_le_bytes()); + b.extend([0; 8]); + b + } + + /// Vertex `k` of `sides`, counted clockwise from the top, on the base circle. + fn vertex(k: u32, sides: u32) -> Pt { + let a = PI / 2.0 - 2.0 * PI * f64::from(k) / f64::from(sides); + pt(POLYGON_UNIT_RADIUS * a.cos(), POLYGON_UNIT_RADIUS * a.sin()) + } + + fn ends(sp: &SubPath) -> Vec { + sp.segments + .iter() + .map(|s| match *s { + Segment::Line(e) | Segment::Cubic(_, _, e) => e, + }) + .collect() + } + + fn close(a: &[Pt], b: &[Pt]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (p.x - q.x).abs() < 1e-6 && (p.y - q.y).abs() < 1e-6) + } + + fn star(sides: u32, step: u32, first: u32, second: u32) -> Path { + let p = crate::layout::for_version(1300).unwrap(); + let base = Path { subpaths: vec![SubPath { start: vertex(0, sides), segments: vec![Segment::Line(vertex(step, sides))], closed: false }] }; + let mut budget = Budget::new(crate::Limits::default()); + let Some(Geometry::Path(path)) = polygon(&base, &polygon_arg(sides, first, second), &p, &mut budget, &mut vec![]) else { + panic!("no polygon") + }; + path + } + + #[test] + fn a_star_whose_sides_skip_a_vertex_chains_its_points() { + // {5/2}: each side runs two vertices on, so the outline visits 2, 4, 1, 3 and 0. + let path = star(5, 2, 2, 0); + assert_eq!(path.subpaths.len(), 1); + let want: Vec = [2, 4, 1, 3, 0].iter().map(|&k| vertex(k, 5)).collect(); + assert!(close(&ends(&path.subpaths[0]), &want), "{:?}", ends(&path.subpaths[0])); + // The base side alone tells the step when the field doesn't. + assert!(close(&ends(&star(5, 2, 0, 0).subpaths[0]), &want)); + } + + #[test] + fn a_star_sharing_a_factor_with_its_sides_draws_one_outline_for_each() { + // {6/2}: two triangles, 0-2-4 and 1-3-5. + let path = star(6, 2, 0, 2); + assert_eq!(path.subpaths.len(), 2); + assert!(close(&ends(&path.subpaths[0]), &[vertex(2, 6), vertex(4, 6), vertex(0, 6)])); + assert!(close(&[path.subpaths[1].start], &[vertex(1, 6)])); + assert!(close(&ends(&path.subpaths[1]), &[vertex(3, 6), vertex(5, 6), vertex(1, 6)])); + } + + #[test] + fn a_plain_polygon_turns_one_vertex_for_each_side() { + let path = star(4, 1, 0, 1); + assert_eq!(path.subpaths.len(), 1); + assert!(close(&ends(&path.subpaths[0]), &[1, 2, 3, 0].map(|k| vertex(k, 4)))); + } +} diff --git a/crates/cdr/src/inline.rs b/crates/cdr/src/inline.rs new file mode 100644 index 0000000000..65b2fa0da9 --- /dev/null +++ b/crates/cdr/src/inline.rs @@ -0,0 +1,230 @@ +//! What a version 3 object holds as arguments where later versions name records: its transforms +//! (argument 100, R33), its fill (argument 20, R34) and its outline (argument 10, R35). + +use crate::bytes::Rd; +use crate::layout::Profile; +use crate::model::{Cap, Color, Join, Matrix, Outline}; +use crate::records::{self, angle, coord}; +use crate::riff::push; +use crate::{Limits, Warning}; + +/// Transform entry types (R33): a matrix, and an envelope. +const MATRIX: u16 = 0x8c; +const ENVELOPE: u16 = 0x14; +/// The bytes of one transform entry (R33). +const ENTRY: usize = 10; +/// The bytes an outline keeps for its dashes, one byte each (R35). +const DASH_AREA: usize = 10; + +/// The transforms of one object or group. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Placement { + /// The matrices composed in file order, in points. + pub(crate) matrix: Matrix, + /// An envelope bends the shape. The reader doesn't apply envelopes. + pub(crate) envelope: bool, +} + +/// The transforms argument (R33): a u16, the entry count, then 10-byte entries of a type and, at +/// byte 6, where the entry's data starts in the argument. The count is held to the entries the +/// argument holds and to the arguments a record may have. Entries of other types are passed over. +pub(crate) fn transforms(b: &[u8], p: &Profile, limits: &Limits, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + r.skip(2)?; + let stored = usize::from(r.u16()?); + let count = stored.min(r.left() / ENTRY).min(limits.arguments); + if count < stored { + push(warn, Warning::Damaged); + } + let mut out = Placement { matrix: Matrix::IDENTITY, envelope: false }; + for _ in 0..count { + let mut e = Rd::new(r.bytes(ENTRY)?); + let kind = e.u16()?; + e.skip(4)?; + let at = usize::from(e.u16()?); + match kind { + MATRIX => out.matrix = records::fixed_matrix(&mut Rd::at(b, at), p.unit())?.after(&out.matrix), + ENVELOPE => out.envelope = true, + _ => {} + } + } + Some(out) +} + +/// The fill argument (R34): a type byte, 0 for none and 1 for a uniform fill with its color. Fills +/// of other types read as none with a warning. The outer `None` is an argument that can't be read. +pub(crate) fn fill(b: &[u8], p: &Profile, warn: &mut Vec) -> Option> { + let mut r = Rd::new(b); + match r.u8()? { + 0 => Some(None), + 1 => Some(Some(records::color(&mut r, p, warn)?)), + _ => { + push(warn, Warning::UnsupportedFills); + Some(None) + } + } +} + +/// The outline argument (R35): a flags byte whose bit 0 is set when the object is outlined, the +/// width, the stretch, the nib angle, the color, 7 bytes, the dash count and 10 bytes that hold the +/// dashes, the join and the caps (u16 each), then the two arrowhead ids. An argument that ends +/// after its color gives a solid line with butt caps and miter joins. The outer `None` is an +/// argument that can't be read. +pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec) -> Option> { + let mut r = Rd::new(b); + if r.u8()? & 1 == 0 { + return Some(None); + } + let width = coord(&mut r, p)?.abs(); + let _stretch = r.u16()?; + let _nib = angle(&mut r, p)?; + let color = records::color(&mut r, p, warn)?; + let mut out = Outline { width, color, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new() }; + let Some(stored) = r.skip(7).and_then(|()| r.u8()).map(usize::from) else { return Some(Some(out)) }; + let Some(area) = r.bytes(DASH_AREA) else { return Some(Some(out)) }; + if stored > DASH_AREA { + push(warn, Warning::Damaged); + } + let dashes: Vec = area.iter().take(stored).map(|d| f64::from(*d)).collect(); + if dashes.iter().any(|d| *d > 0.0) { + out.dashes = dashes; + } + out.join = match r.u16() { + Some(1) => Join::Round, + Some(2) => Join::Bevel, + _ => Join::Miter, + }; + out.cap = match r.u16() { + Some(1) => Cap::Round, + Some(2) => Cap::Square, + _ => Cap::Butt, + }; + if matches!((r.u32(), r.u32()), (Some(s), Some(e)) if s != 0 || e != 0) { + push(warn, Warning::Arrowheads); + } + Some(Some(out)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn p3() -> Profile { + crate::layout::for_version(300).unwrap() + } + + /// A transforms argument of `entries` (type, data offset), then `data` from byte 4 + 10 for + /// each entry. + fn arg(count: u16, entries: &[(u16, u16)], data: &[i32]) -> Vec { + let mut b = vec![0, 0]; + b.extend(count.to_le_bytes()); + for (kind, at) in entries { + b.extend(kind.to_le_bytes()); + b.extend([0; 4]); + b.extend(at.to_le_bytes()); + b.extend([0; 2]); + } + b.extend(data.iter().flat_map(|v| v.to_le_bytes())); + b + } + + #[test] + fn matrices_compose_in_file_order_and_other_entries_are_passed_over() { + // Scale by 2, then move 1 inch right: entry types 0x8c, an unknown one and 0x8c. + let scale = [131072, 0, 0, 0, 131072, 0]; + let shift = [65536, 0, 1000, 0, 65536, 0]; + let b = arg(3, &[(MATRIX, 34), (0x99, 0), (MATRIX, 58)], &[scale, shift].concat()); + let mut w = vec![]; + let t = transforms(&b, &p3(), &Limits::default(), &mut w).unwrap(); + assert_eq!((t.matrix, t.envelope), (Matrix([2.0, 0.0, 0.0, 2.0, 72.0, 0.0]), false)); + assert!(w.is_empty()); + let b = arg(2, &[(MATRIX, 24), (ENVELOPE, 0)], &scale); + assert!(transforms(&b, &p3(), &Limits::default(), &mut vec![]).unwrap().envelope); + } + + #[test] + fn hostile_transform_arguments_do_not_read_past_their_bytes() { + let scale = [131072, 0, 0, 0, 131072, 0]; + // A count of 65,535 over one entry reads that entry, with the damage warning. + let b = arg(u16::MAX, &[(MATRIX, 14)], &scale); + let mut w = vec![]; + assert_eq!(transforms(&b, &p3(), &Limits::default(), &mut w).unwrap().matrix.0[0], 2.0); + assert_eq!(w, vec![Warning::Damaged]); + // A data offset past the argument, and one that leaves less than a matrix. + for at in [5000, 14 + 4] { + assert!(transforms(&arg(1, &[(MATRIX, at)], &scale), &p3(), &Limits::default(), &mut vec![]).is_none(), "{at}"); + } + // More entries than a record may have arguments. + let many: Vec<(u16, u16)> = vec![(0x99, 0); 100]; + let limits = Limits { arguments: 8, ..Limits::default() }; + let mut w = vec![]; + assert!(transforms(&arg(100, &many, &[]), &p3(), &limits, &mut w).is_some()); + assert_eq!(w, vec![Warning::Damaged]); + for len in 0..4 { + assert!(transforms(&b[..len], &p3(), &Limits::default(), &mut vec![]).is_none()); + } + } + + /// An outline argument: flags, width in 1/1000 inch, black, `dashes`, join, caps, arrowheads. + fn outline_arg(flags: u8, count: u8, dashes: &[u8], join: u16, cap: u16, heads: [u32; 2]) -> Vec { + let mut b = vec![flags]; + b.extend(28i16.to_le_bytes()); + b.extend([100, 0, 0, 0]); + b.extend([1, 0, 0, 0, 100]); + b.extend([0; 7]); + b.push(count); + let mut area = dashes.to_vec(); + area.resize(DASH_AREA, 0); + b.extend(area); + b.extend(join.to_le_bytes()); + b.extend(cap.to_le_bytes()); + b.extend(heads.iter().flat_map(|h| h.to_le_bytes())); + b + } + + #[test] + fn an_outline_reads_its_width_color_dashes_join_and_caps() { + let mut w = vec![]; + let o = outline(&outline_arg(1, 2, &[3, 1], 1, 2, [0, 0]), &p3(), &mut w).unwrap().unwrap(); + assert!((o.width - 2.016).abs() < 1e-9, "{}", o.width); + assert_eq!((o.color, o.join, o.cap, o.dashes), (Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Join::Round, Cap::Square, vec![3.0, 1.0])); + assert!(w.is_empty()); + // Bit 0 clear: no outline, whatever follows. + assert_eq!(outline(&outline_arg(0, 2, &[3, 1], 1, 2, [7, 0]), &p3(), &mut w), Some(None)); + assert_eq!(outline(&[0], &p3(), &mut w), Some(None)); + assert!(w.is_empty()); + outline(&outline_arg(1, 0, &[], 0, 0, [0, 9]), &p3(), &mut w).unwrap().unwrap(); + assert_eq!(w, vec![Warning::Arrowheads]); + } + + #[test] + fn a_dash_count_past_the_dash_bytes_is_held_to_them() { + let mut w = vec![]; + let o = outline(&outline_arg(1, 255, &[2; 10], 0, 0, [0, 0]), &p3(), &mut w).unwrap().unwrap(); + assert_eq!(o.dashes.len(), DASH_AREA); + assert_eq!(w, vec![Warning::Damaged]); + // An argument that ends inside the dashes keeps a solid line; one cut before the color is + // unreadable. + let full = outline_arg(1, 255, &[2; 10], 0, 0, [0, 0]); + assert_eq!(outline(&full[..25], &p3(), &mut vec![]).unwrap().unwrap().dashes, Vec::::new()); + assert_eq!(outline(&full[..12], &p3(), &mut vec![]).unwrap().unwrap().cap, Cap::Butt); + for len in 0..12 { + assert!(outline(&full[..len], &p3(), &mut vec![]).is_none(), "{len}"); + } + } + + #[test] + fn fills_read_none_uniform_and_other_types() { + let mut w = vec![]; + assert_eq!(fill(&[0], &p3(), &mut w), Some(None)); + assert_eq!(fill(&[1, 1, 100, 0, 0, 0], &p3(), &mut w), Some(Some(Color::Cmyk([1.0, 0.0, 0.0, 0.0])))); + assert!(w.is_empty()); + for kind in [2, 4, 6, 7, 10] { + let mut w = vec![]; + assert_eq!(fill(&[kind, 0, 0], &p3(), &mut w), Some(None)); + assert_eq!(w, vec![Warning::UnsupportedFills], "{kind}"); + } + assert_eq!(fill(&[], &p3(), &mut w), None); + assert_eq!(fill(&[1, 1, 100], &p3(), &mut w), None); + } +} diff --git a/crates/cdr/src/layout.rs b/crates/cdr/src/layout.rs new file mode 100644 index 0000000000..e4d4e3456d --- /dev/null +++ b/crates/cdr/src/layout.rs @@ -0,0 +1,179 @@ +//! Where the fields of each record lie, by version: one table, resolved once per file. Each field +//! names the `PROVENANCE.md` row it rests on. + +/// The layouts of one range of versions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Profile { + /// Coordinates are i16 in 1/1000 inch, record headers, counts and angles 16-bit (R5, R6, R7). + pub(crate) short: bool, + /// Bytes before the page size in `mcfg` (R10). + pub(crate) mcfg_skip: usize, + /// Bytes before a `trfd` entry's type (R8). + pub(crate) trfd_head: usize, + /// Bytes between a matrix entry's type and its six numbers (R8). + pub(crate) matrix_skip: usize, + /// Fill and outline records start with tagged records (R11, R12). + pub(crate) tagged: bool, + /// Outline: bytes after the join, after the stretch, after the nib angle and after the color + /// (R12). + pub(crate) outl_after_join: usize, + pub(crate) outl_after_stretch: usize, + pub(crate) outl_after_angle: usize, + pub(crate) outl_after_color: usize, + /// Where the start marker id lies after the first dash (R13); `None` where no source says. + pub(crate) marker_after_dash: Option, + /// Rectangles carry four corner radii, not one (R15). + pub(crate) four_radii: bool, + /// Rectangles are f64 sizes with radii as shares of half the shorter side (R29). + pub(crate) f64_rect: bool, + /// The master page flags its guides and desktop layers the way of versions 7 to 13 (R19). + pub(crate) old_master_flags: bool, + /// Object type 0x25 is a path (R30). + pub(crate) paths: bool, + /// Names are UTF-16LE, not Windows-1252 (R9). + pub(crate) utf16_names: bool, + /// An object holds its transform, fill and outline as arguments; there are no `trfd`, `fill` + /// or `outl` records (R33, R34, R35). + pub(crate) inline_styles: bool, + /// Object types count from 0: rectangle 0, ellipse 1, curve 2, text 3, bitmap 4 (R32). + pub(crate) types_from_zero: bool, + /// How a color is laid out (R14, R36). + pub(crate) color: ColorLayout, + /// A matrix is six i32 with its factors in 16.16 fixed point, not six f64 (R37). + pub(crate) fixed_matrix: bool, + /// `mcfg` holds 2 bytes and the page's two corners, not its width and height (R38). + pub(crate) mcfg_corners: bool, +} + +/// The layouts of a color. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ColorLayout { + /// A model byte and four value bytes (R36). + Bytes5, + /// A model u16, four u16 values and 2 bytes (R36). + Words12, + /// A model u16, a palette u16, 4 bytes and four value bytes (R14). + Record12, +} + +const fn profile(from: u16) -> Profile { + let short = from < 600; + Profile { + short, + inline_styles: from < 400, + types_from_zero: from < 400, + color: if from < 400 { + ColorLayout::Bytes5 + } else if from < 500 { + ColorLayout::Words12 + } else { + ColorLayout::Record12 + }, + fixed_matrix: from < 500, + mcfg_corners: from < 400, + mcfg_skip: if from >= 1300 { + 12 + } else if from >= 900 { + 4 + } else if from >= 600 && from < 700 { + 28 + } else { + 0 + }, + trfd_head: if from >= 1300 { 8 } else { 0 }, + matrix_skip: if short { 0 } else { 6 }, + tagged: from >= 1300, + outl_after_join: if from >= 600 && from < 1300 { 2 } else { 0 }, + outl_after_stretch: if short { 0 } else { 2 }, + outl_after_angle: if from >= 1300 { + 46 + } else if !short { + 52 + } else { + 0 + }, + outl_after_color: if short { 10 } else { 16 }, + marker_after_dash: if from >= 1300 { + Some(20) + } else if from == 700 || from >= 1100 { + Some(22) + } else { + None + }, + four_radii: from >= 900, + f64_rect: from >= 1500, + old_master_flags: from < 1400, + paths: from >= 1600, + utf16_names: from >= 1200, + } +} + +/// The newest version read: 27, as the `vrsn` chunk names it (R1, R2). +pub(crate) const NEWEST: u16 = 2799; + +/// The first version of each range, with its layouts. Ranges start where a field moves. +const PROFILES: &[(u16, Profile)] = &[ + (300, profile(300)), + (400, profile(400)), + (500, profile(500)), + (600, profile(600)), + (700, profile(700)), + (800, profile(800)), + (900, profile(900)), + (1100, profile(1100)), + (1200, profile(1200)), + (1300, profile(1300)), + (1400, profile(1400)), + (1500, profile(1500)), + (1600, profile(1600)), +]; + +/// The oldest version of a RIFF file read: 3 (R31). Versions 1 and 2 are not RIFF files (`wl.rs`). +pub(crate) const OLDEST_RIFF: u16 = 300; + +/// The layouts of the RIFF file of `version` (hundreds; 801 is the 8.01 variant, 2430 is 24.3), or +/// `None` outside 3 to 27. +pub(crate) fn for_version(version: u16) -> Option { + if !(OLDEST_RIFF..=NEWEST).contains(&version) { + return None; + } + PROFILES.iter().rev().find(|(from, _)| *from <= version).map(|(_, p)| *p) +} + +impl Profile { + /// Points per coordinate unit. + pub(crate) fn unit(&self) -> f64 { + if self.short { 72.0 / 1000.0 } else { 72.0 / 254_000.0 } + } + + /// Bytes of a coordinate, and of header fields and counts. + pub(crate) fn word(&self) -> usize { + if self.short { 2 } else { 4 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_version_from_3_to_27_has_one_profile() { + assert!(for_version(299).is_none() && for_version(2800).is_none()); + assert!(for_version(300).is_some_and(|p| p.short && p.inline_styles && p.types_from_zero && p.mcfg_corners && p.fixed_matrix)); + assert!(for_version(399).is_some_and(|p| p.color == ColorLayout::Bytes5)); + assert!(for_version(400).is_some_and(|p| p.short && !p.inline_styles && !p.mcfg_corners && p.fixed_matrix)); + assert!(for_version(499).is_some_and(|p| p.color == ColorLayout::Words12)); + assert!(for_version(500).is_some_and(|p| !p.fixed_matrix && !p.types_from_zero && p.color == ColorLayout::Record12)); + assert!(for_version(1300).is_some_and(|p| p.old_master_flags)); + assert!(for_version(1400).is_some_and(|p| p.tagged && !p.f64_rect && !p.old_master_flags)); + assert!(for_version(1500).is_some_and(|p| p.tagged && p.f64_rect && p.mcfg_skip == 12 && !p.paths)); + assert!(for_version(2430).is_some_and(|p| p.f64_rect && p.paths && p.utf16_names)); + assert!(for_version(500).is_some_and(|p| p.short && p.mcfg_skip == 0)); + assert!(for_version(600).is_some_and(|p| !p.short && p.mcfg_skip == 28)); + assert!(for_version(801).is_some_and(|p| p.mcfg_skip == 0 && p.marker_after_dash.is_none())); + assert!(for_version(1000).is_some_and(|p| p.mcfg_skip == 4 && p.four_radii && !p.utf16_names)); + assert!(for_version(1300).is_some_and(|p| p.tagged && p.trfd_head == 8 && p.outl_after_angle == 46)); + // The table is in order, so the search finds each range's own row. + assert!(PROFILES.windows(2).all(|w| w[0].0 < w[1].0)); + } +} diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs new file mode 100644 index 0000000000..847288b878 --- /dev/null +++ b/crates/cdr/src/lib.rs @@ -0,0 +1,85 @@ +//! Reader for `.cdr` drawings of versions 1 to 27 (`.cdr`, and `.cdt` templates): the `WL` files +//! of versions 1 and 2, the RIFF chunk tree of versions 3 on with its compressed lists, the ZIP +//! packages of versions 14 on with their data streams, then pages, layers, guidelines, groups, +//! curves, rectangles, ellipses, arcs and polygons with uniform fills and outlines. +//! +//! 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` files. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::fmt; + +mod build; +mod bytes; +mod geometry; +mod inline; +mod layout; +mod limits; +pub mod model; +mod package; +mod records; +mod riff; +#[cfg(any(test, feature = "synth"))] +pub mod synth; +mod wl; +mod zip; + +pub use limits::Limits; +pub use model::{Drawing, Warning}; + +/// 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? +pub fn is_cdr(bytes: &[u8]) -> bool { + riff::is_cdr_riff(bytes) || package::is_package(bytes) || wl::is_wl(bytes) +} + +/// Why a file can't be read. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Error { + /// Not a `.cdr` drawing. + NotCdr, + /// A drawing of a version this reader doesn't read (hundreds: 2800 is version 28). + Version(u16), + /// A container structure that doesn't parse. + Damaged(&'static str), + /// Past one of the [`Limits`]. + Limit(&'static str), + /// A file this reader doesn't open: an encrypted, ZIP64 or split package, or a RIFF file that + /// names a version before 3. + Unsupported(&'static str), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::NotCdr => write!(f, "not a CDR drawing"), + Error::Version(v) => write!(f, "version {} drawings are not read", v / 100), + Error::Damaged(what) => write!(f, "damaged {what}"), + Error::Limit(what) => write!(f, "past the {what} limit"), + Error::Unsupported(what) => write!(f, "{what} are not read"), + } + } +} + +impl std::error::Error for Error {} + +/// Read a drawing within `limits`. +pub fn read(bytes: &[u8], limits: Limits) -> Result { + if bytes.len() > limits.input { + return Err(Error::Limit("input size")); + } + let mut budget = limits::Budget::new(limits); + // Versions 1 and 2 are not RIFF files (R40). + if wl::is_wl(bytes) { + return wl::drawing(bytes, &mut budget); + } + let mut warnings = Vec::new(); + // Versions 14 on save a ZIP package around the RIFF stream (R24, R25, R26). + let (stream, streams) = if zip::is_zip(bytes) { package::open(bytes, &mut budget)? } else { (std::borrow::Cow::Borrowed(bytes), None) }; + let ix = riff::Index::build(&stream, streams, &mut budget, &mut warnings)?; + let mut drawing = build::drawing(&ix, &mut budget, &mut warnings)?; + ix.stream_warnings(&mut drawing.warnings); + Ok(drawing) +} diff --git a/crates/cdr/src/limits.rs b/crates/cdr/src/limits.rs new file mode 100644 index 0000000000..34db782b4c --- /dev/null +++ b/crates/cdr/src/limits.rs @@ -0,0 +1,134 @@ +//! What one read may take. The values are VectorCraft's own; wasm32 gets half the memory limits. + +use crate::Error; + +/// The most a read may take, checked before every allocation and descent. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Limits { + /// Bytes of input. + pub input: usize, + /// Bytes inflated from compressed lists and package members, all of one file together. + pub inflated: usize, + /// Bytes of one package member. + pub member: usize, + /// Members of a package. + pub members: usize, + /// Nested lists below the file's own. Deeper content is left out with a warning. + pub depth: usize, + /// Chunks in the index, nested ones included. + pub chunks: usize, + /// Objects mapped (shapes, groups and guidelines). + pub objects: usize, + /// Points of all curves together. + pub coordinates: usize, + /// Arguments of one `loda` record. + pub arguments: usize, + /// Dashes of all outlines together, an outline's counted again for every shape that uses it. + /// Past them a shape's outline is solid, with a warning. + pub dashes: usize, +} + +#[cfg(not(target_arch = "wasm32"))] +const MIB: usize = 1 << 20; + +impl Default for Limits { + #[cfg(not(target_arch = "wasm32"))] + fn default() -> Self { + Limits { + input: 512 * MIB, + inflated: 1024 * MIB, + member: 512 * MIB, + members: 4096, + depth: 256, + chunks: 2_000_000, + objects: 1_000_000, + coordinates: 16_000_000, + arguments: 64, + dashes: 16_000_000, + } + } + + #[cfg(target_arch = "wasm32")] + fn default() -> Self { + Limits { + input: 256 << 20, + inflated: 512 << 20, + member: 256 << 20, + members: 4096, + depth: 256, + chunks: 2_000_000, + objects: 1_000_000, + coordinates: 16_000_000, + arguments: 64, + dashes: 8_000_000, + } + } +} + +/// The running counters of one read against its [`Limits`]. +#[derive(Debug)] +pub(crate) struct Budget { + pub(crate) limits: Limits, + inflated: usize, + chunks: usize, + objects: usize, + coordinates: usize, + dashes: usize, +} + +impl Budget { + pub(crate) fn new(limits: Limits) -> Self { + Budget { limits, inflated: 0, chunks: 0, objects: 0, coordinates: 0, dashes: 0 } + } + + /// Bytes an inflate may still produce. + pub(crate) fn inflate_left(&self) -> usize { + self.limits.inflated.saturating_sub(self.inflated) + } + + pub(crate) fn take_inflated(&mut self, n: usize) -> Result<(), Error> { + self.inflated = self.inflated.checked_add(n).filter(|&t| t <= self.limits.inflated).ok_or(Error::Limit("inflated size"))?; + Ok(()) + } + + pub(crate) fn take_chunk(&mut self) -> Result<(), Error> { + self.chunks += 1; + if self.chunks > self.limits.chunks { Err(Error::Limit("chunk count")) } else { Ok(()) } + } + + /// One more object, or `false` when the drawing already holds as many as a read maps. + pub(crate) fn take_object(&mut self) -> bool { + if self.objects >= self.limits.objects { + return false; + } + self.objects += 1; + true + } + + /// `n` more curve points, or `false` past the limit (nothing is taken then). + pub(crate) fn take_coordinates(&mut self, n: usize) -> bool { + match self.coordinates.checked_add(n).filter(|&t| t <= self.limits.coordinates) { + Some(t) => { + self.coordinates = t; + true + } + None => false, + } + } + + /// Dashes the read may still take. + pub(crate) fn dashes_left(&self) -> usize { + self.limits.dashes.saturating_sub(self.dashes) + } + + /// `n` more dashes, or `false` past the limit (nothing is taken then). + pub(crate) fn take_dashes(&mut self, n: usize) -> bool { + match self.dashes.checked_add(n).filter(|&t| t <= self.limits.dashes) { + Some(t) => { + self.dashes = t; + true + } + None => false, + } + } +} diff --git a/crates/cdr/src/model.rs b/crates/cdr/src/model.rs new file mode 100644 index 0000000000..f3553ce329 --- /dev/null +++ b/crates/cdr/src/model.rs @@ -0,0 +1,191 @@ +//! What a drawing reads as. Lengths are in points (1/72 inch), from the centre of the page, with y +//! pointing up, as the file stores them. + +/// A point in points. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Pt { + pub x: f64, + pub y: f64, +} + +/// An affine map `[a, b, c, d, e, f]`: x' = a x + c y + e, y' = b x + d y + f. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Matrix(pub [f64; 6]); + +impl Matrix { + pub const IDENTITY: Matrix = Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + + /// `self` after `first`: the map that applies `first`, then `self`. + pub fn after(&self, first: &Matrix) -> Matrix { + let [a, b, c, d, e, f] = self.0; + let [p, q, r, s, t, u] = first.0; + Matrix([a * p + c * q, b * p + d * q, a * r + c * s, b * r + d * s, a * t + c * u + e, b * t + d * u + f]) + } + + pub fn apply(&self, p: Pt) -> Pt { + let [a, b, c, d, e, f] = self.0; + Pt { x: a * p.x + c * p.y + e, y: b * p.x + d * p.y + f } + } +} + +/// One segment after the previous point. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Segment { + Line(Pt), + /// Two control points, then the end point. + Cubic(Pt, Pt, Pt), +} + +#[derive(Clone, Debug, PartialEq)] +pub struct SubPath { + pub start: Pt, + pub segments: Vec, + pub closed: bool, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Path { + pub subpaths: Vec, +} + +/// The shape of an object, in its own space ([`Shape::matrix`] places it). +#[derive(Clone, Debug, PartialEq)] +pub enum Geometry { + Path(Path), + /// A rectangle from the origin to (`w`, `h`) (either may be negative). `radii` round its + /// corners counterclockwise from the one at (`w`, 0): (`w`, 0), (`w`, `h`), (0, `h`), (0, 0). + Rect { + w: f64, + h: f64, + radii: [f64; 4], + }, + /// A whole ellipse in the box from the origin to (`w`, `h`). + Ellipse { + w: f64, + h: f64, + }, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Color { + Rgb([f32; 3]), + Cmyk([f32; 4]), + /// Ink: 0 is white, 1 black. + Gray(f32), + /// Every ink at full strength. + Registration, + /// A color of a named library, printed on its own plate. `look` is its full-strength color + /// when the file stores one (an approximation in sRGB); `tint` is 0 to 1. + Spot { + name: String, + tint: f32, + look: Option<[f32; 3]>, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Cap { + Butt, + Round, + Square, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Join { + Miter, + Round, + Bevel, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Outline { + pub width: f64, + pub color: Color, + pub cap: Cap, + pub join: Join, + /// Dash and gap lengths, in outline widths; empty for a solid line. + pub dashes: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Shape { + pub geometry: Geometry, + pub matrix: Matrix, + pub fill: Option, + pub outline: Option, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Object { + Shape(Box), + Group(Vec), +} + +/// A guideline through `at`, at `angle` degrees counterclockwise from horizontal. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Guideline { + pub at: Pt, + pub angle: f64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LayerKind { + Drawing, + /// The objects left beside the pages. + Desktop, + Guides, + Grid, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Layer { + pub name: String, + pub kind: LayerKind, + /// Front to back, as the file lists them. + pub objects: Vec, + pub guides: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Page { + /// Width and height in points, when the page gives its own. + pub size: Option<(f64, f64)>, + /// Front to back, as the file lists them. + pub layers: Vec, +} + +/// What was left out or changed while reading. Each kind is listed once. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Warning { + /// Text, bitmaps, splines and other objects not read yet. + UnsupportedObjects, + /// Fountain, pattern, texture and PostScript fills. + UnsupportedFills, + /// Colors in models not read; shown black. + UnknownColors, + /// Library spot colors whose look the file doesn't store; shown black. + SpotLooks, + /// Outline arrowheads. + Arrowheads, + /// Envelopes, which are not applied: the shapes under them keep their outlines. + Envelopes, + /// Content nested deeper, or past the counts, that a read takes. + TooDeep, + /// Chunks or records that end early or don't parse. + Damaged, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Drawing { + /// In hundreds, as a RIFF file stores it: 300 to 2799. A file of version 1 or 2 stores no + /// number: it gives 200 when its marker byte is the one of version 2, and 100 otherwise. + pub version: u16, + /// Page size from the document settings, in points. + pub page_size: Option<(f64, f64)>, + pub pages: Vec, + /// Layers every page shows, from the master page. + pub master: Vec, + /// Guidelines every page shows, kept outside any layer. + pub guides: Vec, + pub warnings: Vec, +} diff --git a/crates/cdr/src/package.rs b/crates/cdr/src/package.rs new file mode 100644 index 0000000000..c46fa31e39 --- /dev/null +++ b/crates/cdr/src/package.rs @@ -0,0 +1,147 @@ +//! The packages of versions 14 on (R25, R26): a ZIP archive holding the RIFF stream as +//! `content/riffData.cdr` (14 and 15), or as `content/root.dat` with its chunk bodies in the data +//! streams that `content/dataFileList.dat` names (16 on). A data stream is inflated only when a +//! chunk the reader reads, or a list it splits, points into it. + +use std::borrow::Cow; +use std::cell::{Cell, OnceCell}; + +use crate::limits::{Budget, Limits}; +use crate::riff::push; +use crate::zip::{self, Archive}; +use crate::{Error, Warning}; + +const RIFF_DATA: &[u8] = b"content/riffData.cdr"; +const ROOT: &[u8] = b"content/root.dat"; +const DATA_FILE_LIST: &[u8] = b"content/dataFileList.dat"; +const DATA_DIR: &[u8] = b"content/data/"; + +/// Is `bytes` a ZIP archive with a `.cdr` drawing's root stream? +pub(crate) fn is_package(bytes: &[u8]) -> bool { + zip::is_zip(bytes) && Archive::open(bytes, Limits::default().members).is_ok_and(|a| a.find(RIFF_DATA).or_else(|| a.find(ROOT)).is_some()) +} + +/// The RIFF stream of the package `bytes`, and its data streams when it has them (16 on). +pub(crate) fn open<'a>(bytes: &'a [u8], budget: &mut Budget) -> Result<(Cow<'a, [u8]>, Option>), Error> { + let zip = Archive::open(bytes, budget.limits.members)?; + if let Some(i) = zip.find(RIFF_DATA) { + return Ok((member(&zip, i, budget)?, None)); + } + let root = zip.find(ROOT).ok_or(Error::NotCdr)?; + let root = member(&zip, root, budget)?; + let list = match zip.find(DATA_FILE_LIST) { + Some(i) => member(&zip, i, budget)?, + None => Cow::Borrowed(&[][..]), + }; + // One name for each line; a line feed after the last name ends it. + let list = list.strip_suffix(b"\n").unwrap_or(&list); + let mut members = Vec::new(); + if !list.is_empty() { + for line in list.split(|&b| b == b'\n') { + if members.len() == budget.limits.members { + return Err(Error::Limit("package member count")); + } + let name = line.strip_suffix(b"\r").unwrap_or(line); + let found = zip.find(&[DATA_DIR, name].concat()); + // A data stream that is encrypted or packed some other way refuses the file, as the + // root stream does. + if let Some(i) = found { + zip.check(i)?; + } + members.push(found); + } + } + let loaded = (0..zip.count()).map(|_| OnceCell::new()).collect(); + let streams = Streams { zip, members, loaded, member_limit: budget.limits.member, damaged: Cell::new(false) }; + Ok((root, Some(streams))) +} + +/// Member `i` within the member limit and, when deflated, what is left to inflate. +fn member<'a>(zip: &Archive<'a>, i: usize, budget: &mut Budget) -> Result, Error> { + let m = zip.read(i, budget.limits.member, budget.inflate_left())?; + if let Cow::Owned(v) = &m { + budget.take_inflated(v.len())?; + } + Ok(m) +} + +/// What reading one package member gave. +#[derive(Debug)] +enum Slot<'a> { + Read(Cow<'a, [u8]>), + Damaged, + PastLimit, +} + +/// The data streams of a version 16+ package, in `dataFileList.dat` order (R26). +#[derive(Debug)] +pub(crate) struct Streams<'a> { + zip: Archive<'a>, + /// The member holding each stream; `None` when the archive lacks it. + members: Vec>, + /// Each member's bytes once read, so that streams naming one member read it once. + loaded: Vec>>, + member_limit: usize, + /// A stream, or a chunk's bytes in one, could not be found. + damaged: Cell, +} + +impl<'a> Streams<'a> { + /// The member holding stream `s`; `None` when there is no such stream. + pub(crate) fn member_of(&self, s: usize) -> Option { + *self.members.get(s)? + } + + /// The size the archive gives stream `s`; `None` when there is no such stream. + pub(crate) fn size(&self, s: usize) -> Option { + Some(self.zip.size(self.member_of(s)?)) + } + + /// Stream `s`, its member read on first use within the member limit and, when deflated, + /// within `left` more inflated bytes (which it takes from). + pub(crate) fn get(&self, s: usize, left: &Cell) -> Option<&[u8]> { + let Some(i) = self.member_of(s) else { + self.damaged.set(true); + return None; + }; + let slot = self.loaded.get(i)?.get_or_init(|| { + let read = self.zip.read(i, self.member_limit, left.get()); + if !matches!(read, Err(Error::Limit(_))) { + left.set(left.get().saturating_sub(self.zip.inflate_cost(i))); + } + match read { + Ok(b) => Slot::Read(b), + Err(Error::Limit(_)) => Slot::PastLimit, + Err(_) => { + self.damaged.set(true); + Slot::Damaged + } + } + }); + match slot { + Slot::Read(b) => Some(b.as_ref()), + Slot::Damaged | Slot::PastLimit => None, + } + } + + /// Was stream `s` left out because it is past a limit? Chunks in it are then not damage. + pub(crate) fn past_limit(&self, s: usize) -> bool { + let slot = self.member_of(s).and_then(|i| self.loaded.get(i)).and_then(OnceCell::get); + matches!(slot, Some(Slot::PastLimit)) + } + + /// Mark a chunk whose stream bytes could not be found. + pub(crate) fn note_damage(&self) { + self.damaged.set(true); + } + + /// The warnings for streams that were left out. + pub(crate) fn warnings(&self, warn: &mut Vec) { + if self.damaged.get() { + push(warn, Warning::Damaged); + } + if self.loaded.iter().any(|s| matches!(s.get(), Some(Slot::PastLimit))) { + push(warn, Warning::TooDeep); + } + } +} diff --git a/crates/cdr/src/records.rs b/crates/cdr/src/records.rs new file mode 100644 index 0000000000..379b4f8340 --- /dev/null +++ b/crates/cdr/src/records.rs @@ -0,0 +1,537 @@ +//! Hand-written decoders of the records a drawing's objects refer to: the `loda` argument table +//! (R6), transforms (R8), colors (R14), fills (R11) and outlines (R12, R13). + +use crate::bytes::Rd; +use crate::layout::{ColorLayout, Profile}; +use crate::model::{Cap, Color, Join, Matrix, Outline}; +use crate::riff::push; +use crate::{Limits, Warning}; + +/// The tag of a record's current layout in tagged files (R11, R12). +const TAG_1300: u32 = 1300; +/// The most tagged records skipped before a fill's own (R11). +const MAX_SKIPPED: usize = 4; +/// The most records skipped before an outline's own (R12). +const MAX_OUTLINE_RECORDS: usize = 16; +/// The most UTF-16 units of a library color's name kept, and the most bytes or UTF-16 units of +/// a layer's. +const MAX_NAME: usize = 256; + +/// A header field: u16 in short files, u32 otherwise. +fn word(r: &mut Rd, p: &Profile) -> Option { + if p.short { r.u16().map(usize::from) } else { r.u32().map(|v| v as usize) } +} + +/// A coordinate in points. +pub(crate) fn coord(r: &mut Rd, p: &Profile) -> Option { + let raw = if p.short { f64::from(r.i16()?) } else { f64::from(r.i32()?) }; + Some(raw * p.unit()) +} + +/// An angle in degrees: tenths in short files, millionths otherwise (R7). +pub(crate) fn angle(r: &mut Rd, p: &Profile) -> Option { + if p.short { Some(f64::from(r.i16()?) / 10.0) } else { Some(f64::from(r.i32()?) / 1_000_000.0) } +} + +/// A `loda` record (R6): its object type and arguments as (type, bytes). +pub(crate) struct Loda<'a> { + pub(crate) kind: u32, + pub(crate) args: Vec<(u32, &'a [u8])>, +} + +impl<'a> Loda<'a> { + pub(crate) fn arg(&self, kind: u32) -> Option<&'a [u8]> { + self.args.iter().find(|(k, _)| *k == kind).map(|(_, b)| *b) + } +} + +pub(crate) fn loda<'a>(b: &'a [u8], p: &Profile, limits: &Limits, warn: &mut Vec) -> Option> { + let mut r = Rd::new(b); + let (_len, count, offsets_at, types_at, kind) = (word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?); + // The types table is indexed from the stored count, however many arguments are read. + let stored = count; + let count = if count > limits.arguments { + push(warn, Warning::Damaged); + limits.arguments + } else { + count + }; + let mut offsets = Vec::with_capacity(count + 1); + let mut ro = Rd::at(b, offsets_at); + for _ in 0..=count { + offsets.push(word(&mut ro, p)?); + } + let mut args = Vec::with_capacity(count); + for i in 0..count { + // The types table runs the other way: offset i pairs with type stored - 1 - i. + let kind = word(&mut Rd::at(b, types_at.checked_add((stored - 1 - i).checked_mul(p.word())?)?), p)? as u32; + let (start, end) = (*offsets.get(i)?, *offsets.get(i + 1)?); + match b.get(start..end) { + Some(body) => args.push((kind, body)), + None => push(warn, Warning::Damaged), + } + } + Some(Loda { kind: kind as u32, args }) +} + +/// The matrices of a `trfd` record composed in file order, in points (R8). +pub(crate) fn trfd(b: &[u8], p: &Profile) -> Option { + let mut r = Rd::new(b); + let (_len, count, offsets_at) = (word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?); + let mut m = Matrix::IDENTITY; + let k = p.unit(); + // Each entry takes at least its offset's bytes, which bounds the count by the record's size. + for i in 0..count.min(b.len() / p.word()) { + let at = word(&mut Rd::at(b, offsets_at.checked_add(i.checked_mul(p.word())?)?), p)?; + let mut e = Rd::at(b, at.checked_add(p.trfd_head)?); + if e.u16()? != 8 { + continue; + } + e.skip(p.matrix_skip)?; + let next = if p.fixed_matrix { + fixed_matrix(&mut e, k)? + } else { + let (a, c, tx, bb, d, ty) = (e.f64()?, e.f64()?, e.f64()?, e.f64()?, e.f64()?, e.f64()?); + Matrix([a, bb, c, d, tx * k, ty * k]) + }; + m = next.after(&m); + } + Some(m) +} + +/// A number in 16.16 fixed point. +pub(crate) fn fixed(r: &mut Rd) -> Option { + Some(f64::from(r.i32()?) / 65536.0) +} + +/// A matrix of versions 3 and 4 (R37): six i32 `a c tx b d ty`, the factors in 16.16 fixed point +/// and `tx` and `ty` in coordinate units of `k` points. +pub(crate) fn fixed_matrix(r: &mut Rd, k: f64) -> Option { + let (a, c, tx) = (fixed(r)?, fixed(r)?, f64::from(r.i32()?)); + let (b, d, ty) = (fixed(r)?, fixed(r)?, f64::from(r.i32()?)); + Some(Matrix([a, b, c, d, tx * k, ty * k])) +} + +/// A color in the layout of the file's version (R14, R36). Unknown models read as black with a +/// warning. +pub(crate) fn color(r: &mut Rd, p: &Profile, warn: &mut Vec) -> Option { + match p.color { + ColorLayout::Record12 => { + let model = r.u16()?; + let palette = r.u16()?; + r.skip(4)?; + let v: [u8; 4] = r.bytes(4)?.try_into().ok()?; + Some(model_color(model, palette, v, warn)) + } + ColorLayout::Words12 => { + let model = r.u16()?; + let w = [r.u16()?, r.u16()?, r.u16()?, r.u16()?]; + r.skip(2)?; + // The models take 8-bit values, as in the other layouts; a larger value reads as 255. + Some(early_color(model, w.map(|x| u8::try_from(x).unwrap_or(u8::MAX)), w[0], w[1], warn)) + } + ColorLayout::Bytes5 => Some(color5(r.bytes(5)?.try_into().ok()?, warn)), + } +} + +/// A 5-byte color (R36): a model byte and four value bytes. +pub(crate) fn color5(b: [u8; 5], warn: &mut Vec) -> Color { + let [model, v @ ..] = b; + early_color(u16::from(model), v, u16::from_le_bytes([v[0], v[1]]), u16::from_le_bytes([v[2], v[3]]), warn) +} + +/// A color of versions 1 to 4 (R36). Model 1 is CMYK in percent. Model 0 is a numbered ink and +/// its tint in percent: 0 is black, 1 is white, and other numbers are inks of a library the file +/// doesn't store. Other models read as in later versions. +fn early_color(model: u16, v: [u8; 4], index: u16, tint: u16, warn: &mut Vec) -> Color { + let pct = |x: f32| (x / 100.0).clamp(0.0, 1.0); + match (model, index) { + (1, _) => Color::Cmyk(v.map(|x| pct(f32::from(x)))), + (0, 0) => Color::Gray(pct(f32::from(tint))), + (0, 1) => Color::Gray(0.0), + (0, number) => { + push(warn, Warning::SpotLooks); + Color::Spot { name: format!("Spot 0:{number}"), tint: pct(f32::from(tint)), look: None } + } + _ => model_color(model, 0, v, warn), + } +} + +/// The color of `model` with the four value bytes `v`, from version 5 (R14). +fn model_color(model: u16, palette: u16, v: [u8; 4], warn: &mut Vec) -> Color { + let (v0, v1, v2, v3) = (f32::from(v[0]), f32::from(v[1]), f32::from(v[2]), f32::from(v[3])); + let pct = |x: f32| (x / 100.0).clamp(0.0, 1.0); + let byte = |x: f32| x / 255.0; + match model { + 2 => Color::Cmyk([pct(v0), pct(v1), pct(v2), pct(v3)]), + 3 | 17 => Color::Cmyk([byte(v0), byte(v1), byte(v2), byte(v3)]), + 4 => Color::Cmyk([byte(v0), byte(v1), byte(v2), 0.0]), + 5 | 21 => Color::Rgb([byte(v2), byte(v1), byte(v0)]), + 9 => Color::Gray(1.0 - byte(v0)), + 20 => Color::Registration, + 1 | 14 | 25 => { + let number = u16::from_le_bytes([v[0], v[1]]); + let tint = pct(f32::from(u16::from_le_bytes([v[2], v[3]]))); + push(warn, Warning::SpotLooks); + // Each library numbers its own colors: the name holds the palette and the number. + Color::Spot { name: format!("Spot {palette}:{number}"), tint, look: None } + } + _ => { + push(warn, Warning::UnknownColors); + Color::Rgb([0.0; 3]) + } + } +} + +/// A UTF-16 name stored as a character count and its code units. Every shape that uses the color +/// gets its own copy of the name: a name longer than [`MAX_NAME`] units keeps its first ones and a +/// hash of the whole name, with a warning, so two long names that start alike stay apart. +fn counted_utf16(r: &mut Rd, warn: &mut Vec) -> Option { + let n = r.u32()? as usize; + let b = r.bytes(n.checked_mul(2)?)?; + // Trailing NULs are padding. + let all = b.as_chunks::<2>().0; + let all = all.get(..all.iter().rposition(|c| *c != [0, 0]).map_or(0, |i| i + 1)).unwrap_or_default(); + let units = all.iter().map(|c| u16::from_le_bytes(*c)); + if all.len() <= MAX_NAME { + let units: Vec = units.collect(); + return Some(String::from_utf16_lossy(&units)); + } + push(warn, Warning::TooDeep); + // FNV-1a over the code units. + let hash = units.clone().fold(0xcbf2_9ce4_8422_2325_u64, |h, u| (h ^ u64::from(u)).wrapping_mul(0x0100_0000_01b3)); + let kept: Vec = units.take(MAX_NAME).collect(); + Some(format!("{} {hash:016x}", String::from_utf16_lossy(&kept))) +} + +/// The color of a tagged uniform fill's property list (R11): its color record, named by the +/// library name it carries. +fn property_color(b: &[u8], p: &Profile, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + let (mut found, mut name) = (None, None); + while r.left() >= 5 { + let kind = r.u8()?; + let len = r.u32()? as usize; + if kind == 0 { + break; + } + let body = r.bytes(len)?; + let mut br = Rd::new(body); + match kind { + 1 => found = color(&mut br, p, warn), + 8 => name = br.skip(16).and_then(|_| counted_utf16(&mut br, warn)), + 3 => name = name.or_else(|| counted_utf16(&mut br, warn)), + _ => {} + } + } + match (found?, name.filter(|n| !n.is_empty())) { + // A library color with its name: the record's sRGB has the tint applied already. + (Color::Rgb(rgb), Some(name)) => { + let tint = b_tint(b).unwrap_or(1.0); + Some(Color::Spot { name, tint, look: Some(untinted(rgb, tint)) }) + } + (c, _) => Some(c), + } +} + +/// The tint byte of the first color property of a property list (model 21 keeps it last). +fn b_tint(b: &[u8]) -> Option { + let mut r = Rd::new(b); + while r.left() >= 5 { + let kind = r.u8()?; + let len = r.u32()? as usize; + let body = r.bytes(len)?; + if kind == 1 { + let mut c = Rd::new(body); + return (c.u16()? == 21).then(|| f32::from(*body.get(11).unwrap_or(&100)) / 100.0).map(|t| t.clamp(0.0, 1.0)); + } + } + None +} + +/// The full-strength color behind sRGB `rgb` shown at `tint` (a tint mixes toward white). +fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] { + if tint <= 0.0 { + return rgb; + } + rgb.map(|v| (1.0 - (1.0 - v) / tint).clamp(0.0, 1.0)) +} + +/// A fill record: its id, and its color (`None`: no fill). Fills of other kinds read as none with +/// a warning (R11). +pub(crate) fn fill(b: &[u8], p: &Profile, warn: &mut Vec) -> Option<(u32, Option)> { + let mut r = Rd::new(b); + let id = r.u32()?; + let body = if p.tagged { tagged_body(&mut r)? } else { r.bytes(r.left())? }; + let mut r = Rd::new(body); + let kind = r.u16()?; + let color = match kind { + 0 => None, + 1 if p.tagged => { + if r.u32()? != TAG_1300 { + push(warn, Warning::Damaged); + return Some((id, None)); + } + // A uniform fill whose color can't be read is damage, not a fill of none. + let len = r.u32()? as usize; + Some(property_color(r.bytes(len.min(r.left()))?, p, warn)?) + } + 1 => { + r.skip(2)?; + Some(color(&mut r, p, warn)?) + } + _ => { + push(warn, Warning::UnsupportedFills); + None + } + }; + Some((id, color)) +} + +/// The body of the record tagged 1300 that follows tagged records of later layouts (R11). +fn tagged_body<'a>(r: &mut Rd<'a>) -> Option<&'a [u8]> { + for _ in 0..=MAX_SKIPPED { + let (tag, len) = (r.u32()?, r.u32()? as usize); + let body = r.bytes(len.min(r.left()))?; + if tag == TAG_1300 { + return Some(body); + } + } + None +} + +/// An outline record: its id and the outline (`None`: no outline) (R12, R13). +pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec) -> Option<(u32, Option)> { + let mut r = Rd::new(b); + let id = r.u32()?; + if p.tagged { + let mut found = false; + for _ in 0..MAX_OUTLINE_RECORDS { + let (rec, len) = (r.u32()?, r.u32()? as usize); + if rec == 1 { + found = true; + break; + } + r.skip(len)?; + } + if !found { + return None; + } + } + let (line_type, cap, join) = (r.u16()?, r.u16()?, r.u16()?); + r.skip(p.outl_after_join)?; + let width = coord(&mut r, p)?.abs(); + let _stretch = r.u16()?; + r.skip(p.outl_after_stretch)?; + let _nib = angle(&mut r, p)?; + r.skip(p.outl_after_angle)?; + let color = color(&mut r, p, warn)?; + r.skip(p.outl_after_color)?; + let count = usize::from(r.u16()?); + let first_dash = r.pos(); + let fits = r.left() / 2; + if count > fits { + push(warn, Warning::Damaged); + } + // At most 65,535; the read's dash limit is applied where shapes use them. + let dashes: Vec = (0..count.min(fits)).filter_map(|_| r.u16().map(f64::from)).collect(); + if let Some(after) = p.marker_after_dash { + let mut m = Rd::at(b, first_dash + after); + if matches!((m.u32(), m.u32()), (Some(s), Some(e)) if s != 0 || e != 0) { + push(warn, Warning::Arrowheads); + } + } + // Bit 0 of the line type: no outline (R13). + if line_type & 1 != 0 { + return Some((id, None)); + } + let cap = match cap { + 1 => Cap::Round, + 2 => Cap::Square, + _ => Cap::Butt, + }; + let join = match join { + 1 => Join::Round, + 2 => Join::Bevel, + _ => Join::Miter, + }; + let dashes = if dashes.iter().any(|d| *d > 0.0) { dashes } else { Vec::new() }; + Some((id, Some(Outline { width, color, cap, join, dashes }))) +} + +/// A name argument (R9): Windows-1252 up to a NUL before version 12, UTF-16LE from it. A name +/// longer than [`MAX_NAME`] bytes or UTF-16 units keeps its first ones (without half of a +/// surrogate pair) and a hash of the whole name, with a warning, as a library color's name does. +pub(crate) fn name(b: &[u8], p: &Profile, warn: &mut Vec) -> String { + if p.utf16_names { + let units = b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|u| *u != 0); + let (mut kept, hash) = capped(units, warn); + if hash.is_some() && kept.last().is_some_and(|u| (0xD800..0xDC00).contains(u)) { + kept.pop(); + } + with_hash(String::from_utf16_lossy(&kept), hash) + } else { + let bytes = b.iter().copied().take_while(|c| *c != 0); + let (kept, hash) = capped(bytes, warn); + with_hash(kept.into_iter().map(windows_1252).collect(), hash) + } +} + +/// The first [`MAX_NAME`] of `units`, and when there are more, an FNV-1a hash of them all, with a +/// warning. +fn capped>(units: impl Iterator + Clone, warn: &mut Vec) -> (Vec, Option) { + if units.clone().nth(MAX_NAME).is_none() { + return (units.collect(), None); + } + push(warn, Warning::TooDeep); + let hash = units.clone().fold(0xcbf2_9ce4_8422_2325_u64, |h, u| (h ^ u.into()).wrapping_mul(0x0100_0000_01b3)); + (units.take(MAX_NAME).collect(), Some(hash)) +} + +/// `name`, followed by `hash` in hexadecimal when there is one. +fn with_hash(name: String, hash: Option) -> String { + match hash { + Some(h) => format!("{name} {h:016x}"), + None => name, + } +} + +/// The characters Windows-1252 puts at 0x80 to 0x9F (U+FFFD where it has none); the other bytes +/// are Latin-1. +const CP1252_HIGH: [char; 32] = [ + '€', '\u{FFFD}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{FFFD}', 'Ž', '\u{FFFD}', '\u{FFFD}', '‘', '’', '“', '”', '•', '–', + '—', '˜', '™', 'š', '›', 'œ', '\u{FFFD}', 'ž', 'Ÿ', +]; + +fn windows_1252(c: u8) -> char { + match c { + 0x80..=0x9F => CP1252_HIGH.get(usize::from(c - 0x80)).copied().unwrap_or('\u{FFFD}'), + _ => char::from(c), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn single_byte_names_read_as_windows_1252() { + let p = crate::layout::for_version(1100).unwrap(); + assert_eq!(name(b"Caf\xe9 \x80\x96\0junk", &p, &mut vec![]), "Café €–"); + let p = crate::layout::for_version(1200).unwrap(); + assert_eq!(name(&[0x41, 0, 0x42, 0, 0, 0, 0x43, 0], &p, &mut vec![]), "AB"); + } + + /// A layer name longer than [`MAX_NAME`] bytes or UTF-16 units keeps its first ones and a hash + /// of the whole name, with a warning, in both encodings. A cut never keeps half of a surrogate + /// pair. + #[test] + fn long_layer_names_are_cut_with_a_hash() { + for version in [1100, 1200] { + let p = crate::layout::for_version(version).unwrap(); + let bytes = + |s: &str| if p.utf16_names { s.encode_utf16().flat_map(u16::to_le_bytes).collect::>() } else { s.as_bytes().to_vec() }; + let mut w = vec![]; + let a = name(&bytes(&"N".repeat(100_000)), &p, &mut w); + let b = name(&bytes(&format!("{}M", "N".repeat(99_999))), &p, &mut vec![]); + assert_ne!(a, b, "{version}"); + assert!(a.starts_with(&"N".repeat(MAX_NAME)) && a.chars().count() == MAX_NAME + 17, "{version}: {}", a.len()); + assert_eq!(w, vec![Warning::TooDeep], "{version}"); + let mut w = vec![]; + assert_eq!(name(&bytes(&"N".repeat(MAX_NAME)), &p, &mut w), "N".repeat(MAX_NAME), "{version}"); + assert!(w.is_empty(), "{version}"); + } + let p = crate::layout::for_version(1200).unwrap(); + let emoji: Vec = format!("N{}", "\u{1F600}".repeat(200)).encode_utf16().flat_map(u16::to_le_bytes).collect(); + let cut = name(&emoji, &p, &mut vec![]); + assert!(!cut.contains('\u{FFFD}'), "{cut}"); + assert_eq!(cut.chars().filter(|c| *c == '\u{1F600}').count(), (MAX_NAME - 1) / 2); + } + + #[test] + fn colors_read_in_their_models() { + let p = crate::layout::for_version(500).unwrap(); + let rec = |model: u16, v: [u8; 4]| { + let mut b = model.to_le_bytes().to_vec(); + b.extend([0; 6]); + b.extend(v); + let mut w = vec![]; + (color(&mut Rd::new(&b), &p, &mut w), w) + }; + assert_eq!(rec(2, [100, 50, 0, 10]).0, Some(Color::Cmyk([1.0, 0.5, 0.0, 0.1]))); + assert_eq!(rec(5, [255, 0, 0, 0]).0, Some(Color::Rgb([0.0, 0.0, 1.0]))); + assert_eq!(rec(9, [255, 0, 0, 0]).0, Some(Color::Gray(0.0))); + assert_eq!(rec(25, [7, 0, 40, 0]).0, Some(Color::Spot { name: "Spot 0:7".into(), tint: 0.4, look: None })); + // The same number in another library is another color. + let mut other = 25u16.to_le_bytes().to_vec(); + other.extend(3u16.to_le_bytes()); + other.extend([0; 4]); + other.extend([7, 0, 40, 0]); + assert_eq!(color(&mut Rd::new(&other), &p, &mut vec![]), Some(Color::Spot { name: "Spot 3:7".into(), tint: 0.4, look: None })); + let (c, w) = rec(6, [1, 2, 3, 4]); + assert_eq!((c, w), (Some(Color::Rgb([0.0; 3])), vec![Warning::UnknownColors])); + } + + #[test] + fn colors_of_versions_3_and_4_read_models_0_and_1() { + let read = |version: u16, model: u8, v: [u16; 4]| { + let p = crate::layout::for_version(version).unwrap(); + let b: Vec = if version < 400 { + std::iter::once(model).chain(v.map(|x| x as u8)).collect() + } else { + u16::from(model).to_le_bytes().into_iter().chain(v.iter().flat_map(|x| x.to_le_bytes())).chain([0, 0]).collect() + }; + let mut r = Rd::new(&b); + let mut w = vec![]; + let c = color(&mut r, &p, &mut w); + assert_eq!(r.left(), 0, "{version}"); + (c, w) + }; + for version in [300, 400] { + // Model 1 is CMYK in percent, not a library color as from version 5. + assert_eq!(read(version, 1, [0, 100, 50, 10]).0, Some(Color::Cmyk([0.0, 1.0, 0.5, 0.1])), "{version}"); + assert_eq!(read(version, 2, [0, 100, 50, 10]).0, Some(Color::Cmyk([0.0, 1.0, 0.5, 0.1])), "{version}"); + } + // Model 0: an ink number and a tint. Version 3 stores each as a u16 in its four bytes. + assert_eq!(read(300, 0, [0, 0, 60, 0]).0, Some(Color::Gray(0.6))); + assert_eq!(read(300, 0, [1, 0, 60, 0]).0, Some(Color::Gray(0.0))); + assert_eq!(read(300, 0, [44, 1, 60, 0]), (Some(Color::Spot { name: "Spot 0:300".into(), tint: 0.6, look: None }), vec![Warning::SpotLooks])); + assert_eq!(read(400, 0, [0, 60, 0, 0]).0, Some(Color::Gray(0.6))); + assert_eq!(read(400, 0, [1, 60, 0, 0]).0, Some(Color::Gray(0.0))); + assert_eq!(read(400, 0, [300, 60, 0, 0]), (Some(Color::Spot { name: "Spot 0:300".into(), tint: 0.6, look: None }), vec![Warning::SpotLooks])); + } + + #[test] + fn a_fixed_point_matrix_reads_its_factors_and_offsets() { + let raw: Vec = [65536i32, -32768, 1000, 131072, 16384, -500].iter().flat_map(|v| v.to_le_bytes()).collect(); + let m = fixed_matrix(&mut Rd::new(&raw), 0.5).unwrap(); + assert_eq!(m, Matrix([1.0, 2.0, -0.5, 0.25, 500.0, -250.0])); + assert!(fixed_matrix(&mut Rd::new(&raw[..23]), 0.5).is_none()); + } + + #[test] + fn long_names_that_start_alike_stay_apart() { + let read = |name: &str| { + let mut b = (name.encode_utf16().count() as u32).to_le_bytes().to_vec(); + b.extend(name.encode_utf16().flat_map(u16::to_le_bytes)); + let mut w = vec![]; + (counted_utf16(&mut Rd::new(&b), &mut w).unwrap(), w) + }; + let (a, w) = read(&"N".repeat(300)); + let (b, _) = read(&format!("{}M", "N".repeat(299))); + assert_ne!(a, b); + assert!(a.starts_with(&"N".repeat(MAX_NAME)) && a.chars().count() == MAX_NAME + 17, "{a}"); + assert_eq!(w, vec![Warning::TooDeep]); + assert_eq!(read("Sky Blue"), ("Sky Blue".to_string(), vec![])); + // Padding doesn't count toward the length or the name. + let (padded, w) = read(&format!("{}\0\0", "N".repeat(MAX_NAME - 1))); + assert_eq!((padded, w), ("N".repeat(MAX_NAME - 1), vec![])); + } + + #[test] + fn a_tint_mixes_toward_white_and_comes_off_again() { + let shown = [0.6, 0.8, 1.0]; + let base = untinted(shown, 0.5); + assert!((base[0] - 0.2).abs() < 1e-6 && (base[1] - 0.6).abs() < 1e-6 && base[2] == 1.0); + } +} diff --git a/crates/cdr/src/riff.rs b/crates/cdr/src/riff.rs new file mode 100644 index 0000000000..0298125e18 --- /dev/null +++ b/crates/cdr/src/riff.rs @@ -0,0 +1,419 @@ +//! The chunk index: one flat table of every chunk, a list's children contiguous, built without +//! recursion. Payloads are not copied: an entry names a range of the RIFF stream, of the bytes +//! inflated from `LIST cmpr`, or of a package's data stream (layouts R1 to R4, R27). + +use std::cell::Cell; +use std::collections::BTreeMap; +use std::io::Read as _; + +use crate::bytes::{Rd, u32_at}; +use crate::limits::Budget; +use crate::package::Streams; +use crate::{Error, Warning}; + +pub(crate) const LIST: [u8; 4] = *b"LIST"; +const CMPR: [u8; 4] = *b"cmpr"; +const CPNG: [u8; 4] = *b"CPng"; +/// What follows `CPng` before the zlib stream (R3). +const CPNG_HEAD: [u8; 4] = [1, 0, 4, 0]; +/// The size of a redirect record, and the stream number of one that holds its body (R27). +const REDIRECT: usize = 16; +const INLINE: u32 = u32::MAX; + +/// One chunk: 28 bytes. `start` and `len` give the payload (after a list's form type) in its +/// source: 0 is the RIFF stream followed by the inflated bytes, `s + 1` is data stream `s`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Chunk { + pub(crate) id: [u8; 4], + /// A list's form type; zeros for other chunks. + pub(crate) form: [u8; 4], + src: u32, + start: u32, + len: u32, + first: u32, + count: u32, +} + +impl Chunk { + pub(crate) fn is_list(&self, form: &[u8; 4]) -> bool { + self.id == LIST && &self.form == form + } +} + +/// Every chunk of a file, and the bytes they point into. +pub(crate) struct Index<'a> { + input: &'a [u8], + inflated: Vec, + chunks: Vec, + /// The version the form type names: hundreds, as `vrsn` stores it (0 when the `vrsn` chunk + /// decides). + pub(crate) form_version: u16, + /// A version 16+ package's data streams; chunks of 16 bytes are redirect records then. + streams: Option>, + /// Bytes that inflating may still produce. + left: Cell, + /// The bytes redirected lists have taken: (package member, start) to end. + lists: Cell>, + /// The bytes other redirected chunks have taken, the same way. + leaves: Cell>, + /// Bytes that redirects to bytes another chunk already took may still read. + shared_left: Cell, +} + +/// A list still to be split into its children. +struct Pending { + entry: usize, + src: u32, + /// Its children's bytes. + start: usize, + end: usize, + /// The size pool of a compressed list's stream (`start..end` in source 0). + pool: Option<(usize, usize)>, + depth: usize, +} + +/// What reading one chunk header gives. +enum Read { + Chunk(Chunk), + /// A redirect record whose body can't be found: the chunk is left out, its list read on. + Lost, + /// A redirect record into a data stream past a limit: the chunk is left out without the + /// damage warning. + PastLimit, + /// A redirect record to bytes another chunk took, past the shared-bytes limit: the chunk is + /// left out with the limit warning. + SharedPastLimit, +} + +/// The version the RIFF form type names (R1): `CDR5`..`CDR9`, `CDRA` (10) to `CDRH` (17) with `I` +/// unused, then `J` (18) on; `CDR ` is version 3. Some files use a lower-case `cdr`, which names +/// the same versions except that `cdr8` is the 8.01 variant. Templates of version 21 have the form +/// type `CDTQ`; for `CDT` the `vrsn` chunk names the version, so this gives 0 (R28). +pub(crate) fn form_version(form: [u8; 4]) -> Option { + let [a, b, c, v] = form; + match (&[a, b, c], v) { + (b"cdr", b'8') => Some(801), + (b"CDR" | b"cdr", b' ') => Some(300), + (b"CDR" | b"cdr", b'1'..=b'9') => Some(100 * u16::from(v - b'0')), + (b"CDR" | b"cdr", b'A'..=b'H') => Some(100 * u16::from(v - b'A' + 10)), + (b"CDR" | b"cdr", b'J'..=b'W') => Some(100 * u16::from(v - b'J' + 18)), + (b"CDT", b'A'..=b'Z') => Some(0), + _ => None, + } +} + +/// Does `bytes` start like a RIFF `.cdr` drawing (not the `CDRX` exchange variant)? +pub(crate) fn is_cdr_riff(bytes: &[u8]) -> bool { + bytes.get(..4) == Some(b"RIFF") && bytes.get(8..12).and_then(|f| f.try_into().ok()).and_then(form_version).is_some() +} + +impl<'a> Index<'a> { + pub(crate) fn build(input: &'a [u8], streams: Option>, budget: &mut Budget, warn: &mut Vec) -> Result { + if input.len() > budget.limits.input { + return Err(Error::Limit("input size")); + } + let mut r = Rd::new(input); + if r.fourcc() != Some(*b"RIFF") { + return Err(Error::NotCdr); + } + let declared = r.u32().ok_or(Error::NotCdr)? as usize; + let form = r.fourcc().ok_or(Error::NotCdr)?; + let version = form_version(form).ok_or(Error::NotCdr)?; + // A file cut short keeps what it holds: its last chunk is truncated with a warning. A + // length that ends inside the form type is damage too, and the chunks after it are read. + let end = match declared.checked_add(8) { + Some(e) if (12..=input.len()).contains(&e) => e, + _ => { + push(warn, Warning::Damaged); + input.len() + } + }; + let left = Cell::new(budget.inflate_left()); + let mut ix = Index { + input, + inflated: Vec::new(), + chunks: Vec::new(), + form_version: version, + streams, + left, + lists: Cell::default(), + leaves: Cell::default(), + shared_left: Cell::new(budget.limits.member), + }; + ix.chunks.push(Chunk { id: *b"RIFF", form, src: 0, start: 12, len: 0, first: 0, count: 0 }); + let mut queue = vec![Pending { entry: 0, src: 0, start: 12, end, pool: None, depth: 0 }]; + while let Some(p) = queue.pop() { + ix.split(p, &mut queue, budget, warn)?; + } + Ok(ix) + } + + /// The bytes `start..end` of source `src`, or `None` when the range crosses its end. A data + /// stream is read on first use. + fn span(&self, src: u32, start: usize, end: usize) -> Option<&[u8]> { + if src > 0 { + let s = self.streams.as_ref()?; + return s.get(src as usize - 1, &self.left)?.get(start..end); + } + let n = self.input.len(); + if end <= n { + self.input.get(start..end) + } else if start >= n { + self.inflated.get(start - n..end - n) + } else { + None + } + } + + pub(crate) fn data(&self, c: &Chunk) -> &[u8] { + let start = c.start as usize; + match self.span(c.src, start, start + c.len as usize) { + Some(b) => b, + None => { + if let Some(s) = &self.streams + && !self.past_limit(c.src) + { + s.note_damage(); + } + &[] + } + } + } + + /// Was source `src` a data stream left out because it is past a limit? Its chunks are then + /// left out with that warning alone. + fn past_limit(&self, src: u32) -> bool { + src > 0 && self.streams.as_ref().is_some_and(|s| s.past_limit(src as usize - 1)) + } + + pub(crate) fn children(&self, c: &Chunk) -> &[Chunk] { + let first = c.first as usize; + self.chunks.get(first..first + c.count as usize).unwrap_or_default() + } + + pub(crate) fn root(&self) -> Option<&Chunk> { + self.chunks.first() + } + + /// The warnings for data streams that were left out. + pub(crate) fn stream_warnings(&self, warn: &mut Vec) { + if let Some(s) = &self.streams { + s.warnings(warn); + } + } + + /// Split list `p` into its children, appended to the table together; their lists are queued. + fn split(&mut self, p: Pending, queue: &mut Vec, budget: &mut Budget, warn: &mut Vec) -> Result<(), Error> { + let first = self.chunks.len(); + let mut at = p.start; + let mut lists = Vec::new(); + while at < p.end { + let Some((read, next)) = self.read_chunk(p.src, at, p.end, p.pool) else { + push(warn, Warning::Damaged); + break; + }; + at = next; + // A redirect record whose body can't be found counts as well, so that lists redirected + // to again and again can't repeat such records past the limit. + budget.take_chunk()?; + let chunk = match read { + Read::Chunk(chunk) => chunk, + Read::Lost => { + push(warn, Warning::Damaged); + continue; + } + Read::PastLimit => continue, + Read::SharedPastLimit => { + push(warn, Warning::TooDeep); + continue; + } + }; + // A `LIST stlt` holds the style tables, not chunks (R4); the reader doesn't use them. + if chunk.id == LIST && chunk.form != *b"stlt" { + lists.push(self.chunks.len()); + } + self.chunks.push(chunk); + } + let count = (self.chunks.len() - first) as u32; + if let Some(parent) = self.chunks.get_mut(p.entry) { + parent.first = first as u32; + parent.count = count; + } + for i in lists { + let Some(c) = self.chunks.get(i).copied() else { continue }; + if p.depth + 1 > budget.limits.depth { + push(warn, Warning::TooDeep); + continue; + } + let (start, end) = (c.start as usize, c.start as usize + c.len as usize); + if c.form == CMPR && p.pool.is_none() { + match self.inflate_cmpr(c.src, start, end) { + Ok((s, e, pool)) => queue.push(Pending { entry: i, src: 0, start: s, end: e, pool: Some(pool), depth: p.depth + 1 }), + Err(Error::Limit(what)) => return Err(Error::Limit(what)), + Err(_) => push(warn, Warning::Damaged), + } + } else { + queue.push(Pending { entry: i, src: c.src, start, end, pool: p.pool, depth: p.depth + 1 }); + } + } + Ok(()) + } + + /// The chunk at `at` (before `end`) of source `src`, and where the next one starts. In a + /// compressed stream the size field is an index into the size pool (R3); in a version 16+ + /// package a chunk of 16 bytes outside one is a redirect record (R27). + fn read_chunk(&self, src: u32, at: usize, end: usize, pool: Option<(usize, usize)>) -> Option<(Read, usize)> { + let head = self.span(src, at, at.checked_add(8)?.min(end))?; + let id: [u8; 4] = head.get(..4)?.try_into().ok()?; + let raw = u32_at(head, 4)? as usize; + let size = match pool { + None => raw, + Some((ps, pe)) => { + let off = raw.checked_mul(4)?.checked_add(ps)?; + (off.checked_add(4)? <= pe).then_some(())?; + u32_at(self.span(0, off, off + 4)?, 0)? as usize + } + }; + let body = at + 8; + let body_end = body.checked_add(size).filter(|&e| e <= end)?; + let next = (body_end + (size & 1)).min(end); + if self.streams.is_some() && pool.is_none() && size == REDIRECT { + let read = match self.redirect(id, src, body) { + Some(read) => read, + None if self.redirect_past_limit(src, body) => Read::PastLimit, + None => Read::Lost, + }; + return Some((read, next)); + } + Some((Read::Chunk(self.chunk(id, src, body, size)?), next)) + } + + /// Chunk `id` whose body is `len` bytes at `body` of source `src`; a list's body starts with + /// its form type. + fn chunk(&self, id: [u8; 4], src: u32, body: usize, len: usize) -> Option { + let (form, start) = if id == LIST { + let f: [u8; 4] = self.span(src, body, body.checked_add(4).filter(|_| len >= 4)?)?.try_into().ok()?; + (f, body + 4) + } else { + ([0; 4], body) + }; + let len = len - (start - body); + Some(Chunk { id, form, src, start: u32::try_from(start).ok()?, len: u32::try_from(len).ok()?, first: 0, count: 0 }) + } + + /// The chunk the redirect record at `body` of `src` stands for (R27): stream, length, offset + /// and a reserved u32. Stream `0xFFFFFFFF` holds at most 8 bytes in the record itself, after + /// the length. The body is not read again as a redirect record. `None` when the body can't + /// be found. + /// + /// A redirected list whose bytes overlap those of an earlier redirected list, in any stream of + /// the same package member, is left out, so that no list is split twice. Other chunks may + /// share bytes: each one after the first to read them takes their length from the + /// shared-bytes limit (the member limit), so that many redirects to one body can't decode it + /// without end. + fn redirect(&self, id: [u8; 4], src: u32, body: usize) -> Option { + let mut r = Rd::new(self.span(src, body, body + REDIRECT)?); + let stream = r.u32()?; + let len = r.u32()? as usize; + if stream == INLINE { + return (len <= 8).then(|| self.chunk(id, src, body + 8, len).map(Read::Chunk))?; + } + let off = r.u32()? as usize; + let streams = self.streams.as_ref()?; + let size = streams.size(stream as usize)?; + let end = off.checked_add(len).filter(|&e| e <= size)?; + let member = streams.member_of(stream as usize)?; + if id == LIST { + if !claim(&self.lists, member, off, end) { + return None; + } + } else if !claim(&self.leaves, member, off, end) { + let left = self.shared_left.get(); + if len > left { + return Some(Read::SharedPastLimit); + } + self.shared_left.set(left - len); + } + // Only a list's form type is read now; other bodies are read when the mapping asks. + self.chunk(id, stream.checked_add(1)?, off, len).map(Read::Chunk) + } + + /// Does the redirect record at `body` of `src` point into a data stream past a limit? + fn redirect_past_limit(&self, src: u32, body: usize) -> bool { + let stream = self.span(src, body, body + 4).and_then(|b| u32_at(b, 0)); + stream.is_some_and(|s| s != INLINE && self.past_limit(s.saturating_add(1))) + } + + /// Inflate the two blocks of a `LIST cmpr` body at `start..end` of `src` (R3) → the chunk + /// stream and the size pool, as ranges of source 0. + fn inflate_cmpr(&mut self, src: u32, start: usize, end: usize) -> Result<(usize, usize, (usize, usize)), Error> { + let body = self.span(src, start, end).ok_or(Error::Damaged("compressed list"))?; + let mut r = Rd::new(body); + let c1 = r.u32().ok_or(Error::Damaged("compressed list"))? as usize; + r.skip(4).ok_or(Error::Damaged("compressed list"))?; + let c2 = r.u32().ok_or(Error::Damaged("compressed list"))? as usize; + let block = |at: usize, len: usize| -> Result<&[u8], Error> { + let b = body.get(at..at.checked_add(len).ok_or(Error::Damaged("compressed list"))?).ok_or(Error::Damaged("compressed list"))?; + let mut h = Rd::new(b); + if h.fourcc() != Some(CPNG) || h.fourcc() != Some(CPNG_HEAD) { + return Err(Error::Damaged("compressed block")); + } + Ok(b.get(8..).unwrap_or_default()) + }; + let second_at = c1.checked_add(16).ok_or(Error::Damaged("compressed list"))?; + let (first, second) = (block(16, c1)?.to_vec(), block(second_at, c2)?.to_vec()); + let base = self.input.len(); + let stream = self.inflate(&first)?; + let pool = self.inflate(&second)?; + Ok((base + stream.0, base + stream.1, (base + pool.0, base + pool.1))) + } + + /// Inflate zlib `data` onto the end of the inflated bytes, within what is left → its range + /// there. + fn inflate(&mut self, data: &[u8]) -> Result<(usize, usize), Error> { + let at = self.inflated.len(); + let left = self.left.get(); + let reader = flate2::read::ZlibDecoder::new(data); + // One byte past what is left tells a stream that is too long from one that just fits. + let got = match reader.take((left as u64).saturating_add(1)).read_to_end(&mut self.inflated) { + Ok(n) => n, + Err(_) => { + self.inflated.truncate(at); + return Err(Error::Damaged("compressed block")); + } + }; + if got > left { + self.inflated.truncate(at); + return Err(Error::Limit("inflated size")); + } + self.left.set(left - got); + if self.input.len().saturating_add(self.inflated.len()) > u32::MAX as usize { + return Err(Error::Limit("inflated size")); + } + Ok((at, at + got)) + } +} + +/// Take bytes `start..end` of package member `member` in `claimed`, or `false` when an earlier +/// redirect there took any of them. Empty ranges take nothing. +fn claim(claimed: &Cell>, member: usize, start: usize, end: usize) -> bool { + if start == end { + return true; + } + let mut taken = claimed.take(); + let before = taken.range(..=(member, start)).next_back().is_some_and(|(&(m, _), &e)| m == member && e > start); + let after = taken.range((member, start)..).next().is_some_and(|(&(m, s), _)| m == member && s < end); + let free = !before && !after; + if free { + taken.insert((member, start), end); + } + claimed.set(taken); + free +} + +/// Add `w` to the warnings once. +pub(crate) fn push(warn: &mut Vec, w: Warning) { + if !warn.contains(&w) { + warn.push(w); + } +} diff --git a/crates/cdr/src/synth.rs b/crates/cdr/src/synth.rs new file mode 100644 index 0000000000..bc55b4245d --- /dev/null +++ b/crates/cdr/src/synth.rs @@ -0,0 +1,811 @@ +//! Synthetic drawings for tests and fuzz seeds, built from the layouts in `PROVENANCE.md`. Not a +//! `.cdr` writer: nothing checks that other programs open these files. + +use std::io::Write as _; + +/// A chunk or a list, before it is laid out. +#[derive(Clone, Debug)] +pub enum Node { + Chunk([u8; 4], Vec), + List([u8; 4], Vec), +} + +pub fn chunk(id: &[u8; 4], data: Vec) -> Node { + Node::Chunk(*id, data) +} + +pub fn list(form: &[u8; 4], children: Vec) -> Node { + Node::List(*form, children) +} + +fn put(out: &mut Vec, id: &[u8; 4], size: u32, body: &[u8], len: usize) { + out.extend(id); + out.extend(size.to_le_bytes()); + out.extend(body); + if len % 2 == 1 { + out.push(0); + } +} + +/// `n` laid out with real sizes. +pub fn plain(n: &Node) -> Vec { + let mut out = Vec::new(); + match n { + Node::Chunk(id, data) => put(&mut out, id, data.len() as u32, data, data.len()), + Node::List(form, kids) => { + let mut body = form.to_vec(); + body.extend(kids.iter().flat_map(plain)); + put(&mut out, b"LIST", body.len() as u32, &body, body.len()); + } + } + out +} + +/// `n` laid out for a compressed stream: each size field is an index into `pool`. +fn pooled(n: &Node, pool: &mut Vec) -> Vec { + let mut out = Vec::new(); + let (id, body) = match n { + Node::Chunk(id, data) => (*id, data.clone()), + Node::List(form, kids) => { + let mut body = form.to_vec(); + for k in kids { + body.extend(pooled(k, pool)); + } + (*b"LIST", body) + } + }; + let index = pool.len() as u32; + pool.push(body.len() as u32); + put(&mut out, &id, index, &body, body.len()); + out +} + +fn zlib(data: &[u8]) -> Vec { + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + let _ = e.write_all(data); + e.finish().unwrap_or_default() +} + +/// A `LIST cmpr` holding `children` (R3). +pub fn cmpr(children: &[Node]) -> Node { + let mut pool = Vec::new(); + let stream: Vec = children.iter().flat_map(|c| pooled(c, &mut pool)).collect(); + let sizes: Vec = pool.iter().flat_map(|s| s.to_le_bytes()).collect(); + let block = |raw: &[u8]| { + let mut b = b"CPng".to_vec(); + b.extend([1, 0, 4, 0]); + b.extend(zlib(raw)); + b + }; + let (b1, b2) = (block(&stream), block(&sizes)); + let mut body = Vec::new(); + for (c, u) in [(b1.len(), stream.len()), (b2.len(), sizes.len())] { + body.extend((c as u32).to_le_bytes()); + body.extend((u as u32).to_le_bytes()); + } + body.extend(b1); + body.extend(b2); + Node::Chunk(*b"LIST", [b"cmpr".to_vec(), body].concat()) +} + +/// The form type letter of `version` (hundreds) (R1). +pub fn form(version: u16) -> [u8; 4] { + let n = (version / 100) as u8; + let c = match n { + // Version 3 has a space where later versions have their character. + 3 => b' ', + 0..=9 => b'0' + n, + 10..=17 => b'A' + n - 10, + _ => b'J' + n - 18, + }; + [b'C', b'D', b'R', c] +} + +/// A RIFF file of `version` holding `children`. +pub fn riff(version: u16, children: &[Node]) -> Vec { + let mut body = form(version).to_vec(); + for c in children { + body.extend(match c { + // A prebuilt `LIST cmpr` carries its own form type. + Node::Chunk(id, data) if id == b"LIST" => { + let mut o = Vec::new(); + put(&mut o, id, data.len() as u32, data, data.len()); + o + } + _ => plain(c), + }); + } + let mut out = b"RIFF".to_vec(); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + out +} + +/// Field writers for one version. +#[derive(Clone, Copy, Debug)] +pub struct V(pub u16); + +impl V { + pub fn short(self) -> bool { + self.0 < 600 + } + + pub fn word(self, v: usize) -> Vec { + if self.short() { (v as u16).to_le_bytes().to_vec() } else { (v as u32).to_le_bytes().to_vec() } + } + + /// Rectangle coordinates of `w` × `h` points with corners of `radius` points: coordinates + /// before version 15 (R15), from 15 f64 sizes and radii as shares of half the shorter side + /// (R29). + pub fn rect(self, w: f64, h: f64, radius: f64) -> Vec { + if self.0 < 1500 { + let n = if self.0 >= 900 { 4 } else { 1 }; + let mut out = [self.coord(w), self.coord(h)].concat(); + for _ in 0..n { + out.extend(self.coord(radius)); + } + return out; + } + let units = |pt: f64| pt / 72.0 * 254_000.0; + let mut out = Vec::new(); + for v in [units(w), units(h), 1.0, 1.0] { + out.extend(v.to_le_bytes()); + } + out.extend([0; 8]); + let share = radius / (w.abs().min(h.abs()) / 2.0); + for k in 0..4 { + if k > 0 { + out.extend([0; 16]); + } + out.extend(share.to_le_bytes()); + } + out + } + + /// A length in points as a coordinate. + pub fn coord(self, pt: f64) -> Vec { + if self.short() { + ((pt / 72.0 * 1000.0).round() as i16).to_le_bytes().to_vec() + } else { + ((pt / 72.0 * 254_000.0).round() as i32).to_le_bytes().to_vec() + } + } + + pub fn angle(self, deg: f64) -> Vec { + if self.short() { ((deg * 10.0).round() as i16).to_le_bytes().to_vec() } else { ((deg * 1_000_000.0).round() as i32).to_le_bytes().to_vec() } + } + + /// A `loda` record of object type `kind` (R6): header, arguments, offsets, then the types in + /// reverse. + pub fn loda(self, kind: u32, args: &[(u32, Vec)]) -> Vec { + let w = if self.short() { 2 } else { 4 }; + let head = 5 * w; + let mut body: Vec = Vec::new(); + let mut offsets = Vec::new(); + for (_, a) in args { + offsets.push(head + body.len()); + body.extend(a); + } + offsets.push(head + body.len()); + let offsets_at = head + body.len(); + let types_at = offsets_at + offsets.len() * w; + let total = types_at + args.len() * w; + let mut out = Vec::new(); + for f in [total, args.len(), offsets_at, types_at, kind as usize] { + out.extend(self.word(f)); + } + out.extend(body); + for o in offsets { + out.extend(self.word(o)); + } + for (t, _) in args.iter().rev() { + out.extend(self.word(*t as usize)); + } + out + } + + /// A `trfd` of `matrices` `[a, b, c, d, e, f]` with offsets in points (R8); before version 5 + /// each matrix is in fixed point (R37). + pub fn trfd(self, matrices: &[[f64; 6]]) -> Vec { + let w = if self.short() { 2 } else { 4 }; + let head = 3 * w; + let table = head; + let mut entries = Vec::new(); + let mut offsets = Vec::new(); + let first = table + matrices.len() * w; + for m in matrices { + offsets.push(first + entries.len()); + if self.0 >= 1300 { + entries.extend([0; 8]); + } + entries.extend(8u16.to_le_bytes()); + if !self.short() { + entries.extend([0; 6]); + } + if self.0 < 500 { + entries.extend(fixed_matrix(m)); + continue; + } + let unit = if self.short() { 1000.0 / 72.0 } else { 254_000.0 / 72.0 }; + let [a, b, c, d, e, f] = *m; + for v in [a, c, e * unit, b, d, f * unit] { + entries.extend(v.to_le_bytes()); + } + } + let mut out = Vec::new(); + for f in [first + entries.len(), matrices.len(), table] { + out.extend(self.word(f)); + } + for o in offsets { + out.extend(self.word(o)); + } + out.extend(entries); + out + } + + /// A curve's point list (R16). + pub fn points(self, pts: &[(f64, f64, u8)]) -> Vec { + let mut out = (pts.len() as u32).to_le_bytes().to_vec(); + for (x, y, _) in pts { + out.extend(self.coord(*x)); + out.extend(self.coord(*y)); + } + out.extend(pts.iter().map(|p| p.2)); + out + } + + /// A uniform fill record (R11) of 12-byte color `color`. + pub fn fill(self, id: u32, color: &[u8; 12]) -> Vec { + let mut out = id.to_le_bytes().to_vec(); + if self.0 >= 1300 { + let mut props = vec![1]; + props.extend(12u32.to_le_bytes()); + props.extend(color); + props.extend([0, 0, 0, 0, 0]); + let mut solid = 1300u32.to_le_bytes().to_vec(); + solid.extend((props.len() as u32).to_le_bytes()); + solid.extend(props); + let mut body = 1u16.to_le_bytes().to_vec(); + body.extend(solid); + out.extend(1300u32.to_le_bytes()); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + } else { + out.extend(1u16.to_le_bytes()); + out.extend([0, 0]); + out.extend(color); + } + out + } + + /// An outline record (R12) of `pen`, `color` and `dashes`. + pub fn outline(self, id: u32, pen: Pen, color: &[u8; 12], dashes: &[u16]) -> Vec { + let Pen { line_type, width, cap, join } = pen; + let mut out = id.to_le_bytes().to_vec(); + if self.0 >= 1300 { + out.extend(1u32.to_le_bytes()); + out.extend(0u32.to_le_bytes()); + } + for f in [line_type, cap, join] { + out.extend(f.to_le_bytes()); + } + let v = self.0; + out.extend(vec![0; if (600..1300).contains(&v) { 2 } else { 0 }]); + out.extend(self.coord(width)); + out.extend(100u16.to_le_bytes()); + out.extend(vec![0; if self.short() { 0 } else { 2 }]); + out.extend(self.angle(0.0)); + out.extend(vec![ + 0; + if v >= 1300 { + 46 + } else if self.short() { + 0 + } else { + 52 + } + ]); + out.extend(color); + out.extend(vec![0; if self.short() { 10 } else { 16 }]); + out.extend((dashes.len() as u16).to_le_bytes()); + for d in dashes { + out.extend(d.to_le_bytes()); + } + out.extend([0; 32]); + out + } +} + +/// An outline's line type (bit 0: none), width in points, cap and join. +#[derive(Clone, Copy, Debug)] +pub struct Pen { + pub line_type: u16, + pub width: f64, + pub cap: u16, + pub join: u16, +} + +/// A 12-byte color record (R14) of `model` and its four value bytes. +pub fn color(model: u16, v: [u8; 4]) -> [u8; 12] { + let mut c = [0; 12]; + c[..2].copy_from_slice(&model.to_le_bytes()); + c[8..].copy_from_slice(&v); + c +} + +/// A version 4 color (R36): `model` and its four values as u16, then 2 bytes. +pub fn color4(model: u16, v: [u16; 4]) -> [u8; 12] { + let mut c = [0; 12]; + c[..2].copy_from_slice(&model.to_le_bytes()); + for (k, x) in v.into_iter().enumerate() { + c[2 + 2 * k..4 + 2 * k].copy_from_slice(&x.to_le_bytes()); + } + c +} + +/// A color of versions 1 to 3 (R36): `model` and its four value bytes. +pub fn color3(model: u8, v: [u8; 4]) -> [u8; 5] { + [model, v[0], v[1], v[2], v[3]] +} + +/// A matrix `[a, b, c, d, e, f]` with offsets in points as six i32 `a c tx b d ty`: the factors in +/// 16.16 fixed point, the offsets in 1/1000 inch (R37). +fn fixed_matrix(m: &[f64; 6]) -> Vec { + let [a, b, c, d, e, f] = *m; + let fixed = |v: f64| (v * 65536.0).round() as i32; + let units = |pt: f64| (pt / 72.0 * 1000.0).round() as i32; + [fixed(a), fixed(c), units(e), fixed(b), fixed(d), units(f)].iter().flat_map(|v| v.to_le_bytes()).collect() +} + +/// The transforms argument (100) of a version 3 object or group (R33): one matrix entry for each +/// of `matrices` `[a, b, c, d, e, f]` with offsets in points, applied in the order given. +pub fn transforms3(matrices: &[[f64; 6]]) -> Vec { + let first = 4 + 10 * matrices.len(); + let mut out = vec![0, 0]; + out.extend((matrices.len() as u16).to_le_bytes()); + for i in 0..matrices.len() { + out.extend(0x8cu16.to_le_bytes()); + out.extend([0; 4]); + out.extend(((first + 24 * i) as u16).to_le_bytes()); + out.extend([0; 2]); + } + out.extend(matrices.iter().flat_map(fixed_matrix)); + out +} + +/// The fill argument (20) of a version 3 object (R34): the type byte, then `color` for a uniform +/// fill (type 1). +pub fn fill3(kind: u8, color: &[u8]) -> Vec { + let mut out = vec![kind]; + out.extend(color); + out +} + +/// The outline argument (10) of a version 3 object (R35) of `pen`, `color` and `dashes`; bit 0 of +/// its flags is set unless the pen's line type says no outline. +pub fn outline3(pen: Pen, color: [u8; 5], dashes: &[u8]) -> Vec { + let v = V(300); + let mut out = vec![u8::from(pen.line_type & 1 == 0)]; + out.extend(v.coord(pen.width)); + out.extend(100u16.to_le_bytes()); + out.extend(v.angle(0.0)); + out.extend(color); + out.extend([0; 7]); + out.push(dashes.len() as u8); + let mut area = dashes.to_vec(); + area.resize(10, 0); + out.extend(area); + out.extend(pen.join.to_le_bytes()); + out.extend(pen.cap.to_le_bytes()); + out.extend([0; 8]); + out +} + +/// A version 3 group (R33): its own `lobj` with the transforms that place `objects`, then the +/// objects. +pub fn group3(matrices: &[[f64; 6]], objects: Vec) -> Node { + let mut kids = vec![chunk(b"flgs", vec![0, 0, 0, 0x10]), chunk(b"lobj", V(300).loda(0, &[(100, transforms3(matrices))]))]; + kids.extend(objects); + list(b"grp ", kids) +} + +/// An object list: flags, then a `lgob` list with the `loda` and an optional transform in a `trfl` +/// list (R22). A version 3 object is a `lobj` whose type counts from 0 (R32) and whose transform is +/// its argument 100 (R33). +pub fn object(v: V, kind: u32, args: &[(u32, Vec)], matrix: Option<[f64; 6]>) -> Node { + if v.0 < 400 { + let kind = if (1..=5).contains(&kind) { kind - 1 } else { kind }; + let mut args = args.to_vec(); + args.extend(matrix.map(|m| (100, transforms3(&[m])))); + return list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 0x08]), chunk(b"lobj", v.loda(kind, &args))]); + } + let mut own = vec![chunk(b"loda", v.loda(kind, args))]; + if let Some(m) = matrix { + own.push(list(b"trfl", vec![chunk(b"trfd", v.trfd(&[m]))])); + } + list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 0x08]), list(b"lgob", own)]) +} + +/// A layer list of `kind` flags named `name` holding `objects`, its `loda` in a `lgob` list (R22). +pub fn layer(v: V, flags: [u8; 4], name: &str, objects: Vec) -> Node { + let name: Vec = + if v.0 >= 1200 { name.encode_utf16().chain([0]).flat_map(|u| u.to_le_bytes()).collect() } else { name.bytes().chain([0]).collect() }; + let mut kids = vec![chunk(b"flgs", flags.to_vec()), list(b"lgob", vec![chunk(b"loda", v.loda(0, &[(1000, name)]))])]; + kids.extend(objects); + list(b"layr", kids) +} + +/// A page list: flags (byte 2 set for the master page), then its layers in a `gobj` list (R22). +pub fn page(master: bool, layers: Vec) -> Node { + list(b"page", vec![chunk(b"flgs", vec![0, 0, u8::from(master), 0x90]), list(b"gobj", layers)]) +} + +/// The `mcfg` chunk of `version` with a page of `w` × `h` points (R10); in version 3, 2 bytes and +/// the page's top left and bottom right corners (R38). +pub fn mcfg(v: V, w: f64, h: f64) -> Node { + if v.0 < 400 { + let mut b = vec![0; 2]; + b.extend([v.coord(-w / 2.0), v.coord(h / 2.0), v.coord(w / 2.0), v.coord(-h / 2.0)].concat()); + b.extend([0; 16]); + return chunk(b"mcfg", b); + } + let skip = if v.0 >= 1300 { + 12 + } else if v.0 >= 900 { + 4 + } else if (600..700).contains(&v.0) { + 28 + } else { + 0 + }; + let mut b = vec![0; skip]; + b.extend(v.coord(w)); + b.extend(v.coord(h)); + b.extend([0; 16]); + chunk(b"mcfg", b) +} + +/// The document list and pages of the [`sample`] of `version`. +pub fn sample_content(version: u16) -> Vec { + let v = V(version); + // Before version 5 the sample's colors are CMYK in percent, model 1 (R36). + let (red, black) = + if version < 500 { (color4(1, [0, 100, 100, 0]), color4(1, [0, 0, 0, 100])) } else { (color(5, [0, 0, 255, 0]), color(2, [0, 0, 0, 100])) }; + let (round, none) = (Pen { line_type: 0, width: 2.0, cap: 1, join: 1 }, Pen { line_type: 1, width: 1.0, cap: 0, join: 0 }); + let mut settings = vec![mcfg(v, 612.0, 792.0)]; + // Version 3 keeps fills and outlines in the objects (R34, R35). + if version >= 400 { + settings.push(list(b"filt", vec![chunk(if version >= 700 { b"fild" } else { b"fill" }, v.fill(1, &red))])); + settings.push(list(b"otlt", vec![chunk(b"outl", v.outline(2, round, &black, &[])), chunk(b"outl", v.outline(3, none, &black, &[]))])); + } + let doc = list(b"doc ", settings); + // Fill 1 is red and 0 none; outline 2 is 2 pt with round caps and joins, 3 none. + let style = |fill: u32, outline: u32| { + if version >= 400 { + return vec![(20, fill.to_le_bytes().to_vec()), (10, outline.to_le_bytes().to_vec())]; + } + let fill = if fill == 1 { fill3(1, &color3(1, [0, 100, 100, 0])) } else { fill3(0, &[]) }; + vec![(20, fill), (10, outline3(if outline == 2 { round } else { none }, color3(1, [0, 0, 0, 100]), &[]))] + }; + let mut rect_args = style(1, 2); + rect_args.push((30, v.rect(100.0, 50.0, 5.0))); + let mut ellipse_args = style(1, 3); + ellipse_args.push((30, [v.coord(40.0), v.coord(-40.0), v.angle(0.0), v.angle(0.0), v.word(0)].concat())); + let mut curve_args = style(0, 2); + curve_args.push((30, v.points(&[(0.0, 0.0, 0x08), (50.0, 0.0, 0x40), (50.0, 20.0, 0xC0), (20.0, 50.0, 0xC0), (0.0, 50.0, 0x88)]))); + let mut arc_args = style(0, 2); + arc_args.push((30, [v.coord(30.0), v.coord(30.0), v.angle(0.0), v.angle(90.0), v.word(1)].concat())); + let side = POLYGON_SIDE; + let mut poly_args = style(1, 2); + poly_args.push((30, v.points(&[(0.0, side, 0x0C), (side * 0.587, side * 0.809, 0x44), (side * 0.951, side * 0.309, 0x44)]))); + let mut poly = if version >= 1300 { vec![] } else { vec![0; 4] }; + poly.extend(5u32.to_le_bytes()); + poly.extend([0; 8]); + if version >= 1300 { + poly.extend([0; 4]); + } + poly.extend(0.05f64.to_le_bytes()); + poly.extend(0.05f64.to_le_bytes()); + poly.extend([v.coord(0.0), v.coord(0.0)].concat()); + poly_args.push((11000, poly)); + let art = layer( + v, + [0, 0, 0, 0x98], + "Art", + vec![ + object(v, 1, &rect_args, Some([1.0, 0.0, 0.0, 1.0, -100.0, 100.0])), + object(v, 2, &ellipse_args, Some([1.0, 0.0, 0.0, 1.0, 50.0, -50.0])), + object(v, 3, &curve_args, None), + list(b"grp ", vec![chunk(b"flgs", vec![0, 0, 0, 0x10]), object(v, 0x14, &poly_args, None), object(v, 2, &arc_args, None)]), + object(v, 4, &[(30, [v.coord(0.0), v.coord(0.0)].concat())], None), + ], + ); + let mut guide = vec![0; 12]; + guide.extend((90_000_000i32).to_le_bytes()); + guide.extend([v.coord(36.0), v.coord(0.0), v.coord(36.0), v.coord(100.0), v.coord(36.0), v.coord(0.0)].concat()); + let guides = layer(v, [0x0a, 0, 1, 0x98], "Guides", vec![object(v, 0x16, &[(16000, guide)], None)]); + let desktop = + layer(v, [0x08, 0, 1, 0x98], "Desktop", vec![object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0))], Some([1.0, 0.0, 0.0, 1.0, 400.0, 0.0]))]); + let pages = vec![page(true, vec![guides, desktop]), page(false, vec![art])]; + std::iter::once(doc).chain(pages).collect() +} + +/// A drawing of `version` with one page of each kind of object this reader reads, a text object +/// it doesn't, a master page with a guideline and a desktop object; compressed (version 7 on) +/// when `compress`. +pub fn sample(version: u16, compress: bool) -> Vec { + let content = sample_content(version); + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + if compress { + body.push(cmpr(&content)); + } else { + body.extend(content); + } + riff(version, &body) +} + +/// The sample of `version` as the program of that version saves it: a RIFF file before 14, then +/// a package (R25, R26); `compress` compresses the RIFF stream before 16 and deflates the package +/// members. +pub fn sample_file(version: u16, compress: bool) -> Vec { + match version { + ..1400 => sample(version, compress), + 1400..1600 => package14(sample(version, compress), compress), + _ => { + // The full version chunk comes first from 16; the reader doesn't use it. + let fver: Vec = [u32::from(version), 1, 0, u32::from(version / 100)].iter().flat_map(|v| v.to_le_bytes()).collect(); + let mut body = vec![chunk(b"fver", fver), chunk(b"vrsn", version.to_le_bytes().to_vec())]; + body.extend(sample_content(version)); + package16(version, &body, compress, &[]) + } + } +} + +/// One member of a synthetic ZIP archive. +#[derive(Clone, Debug)] +pub struct Member { + pub name: String, + pub data: Vec, + pub deflate: bool, +} + +fn deflate(data: &[u8]) -> Vec { + let mut e = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default()); + let _ = e.write_all(data); + e.finish().unwrap_or_default() +} + +/// A ZIP archive of `members`, stored or deflated, with `comment` after the end record (R24). +pub fn zip(members: &[Member], comment: &[u8]) -> Vec { + let (mut out, mut dir) = (Vec::new(), Vec::new()); + for m in members { + let packed = if m.deflate { deflate(&m.data) } else { m.data.clone() }; + let method: u16 = if m.deflate { 8 } else { 0 }; + // Version needed, flags, method, time, date, CRC-32, packed and full sizes, name length. + let mut common = Vec::new(); + common.extend(20u16.to_le_bytes()); + common.extend(0u16.to_le_bytes()); + common.extend(method.to_le_bytes()); + common.extend([0; 4]); + common.extend(crc32fast::hash(&m.data).to_le_bytes()); + common.extend((packed.len() as u32).to_le_bytes()); + common.extend((m.data.len() as u32).to_le_bytes()); + common.extend((m.name.len() as u16).to_le_bytes()); + let at = out.len() as u32; + out.extend(0x0403_4b50u32.to_le_bytes()); + out.extend(&common); + out.extend(0u16.to_le_bytes()); + out.extend(m.name.as_bytes()); + out.extend(&packed); + dir.extend(0x0201_4b50u32.to_le_bytes()); + dir.extend(20u16.to_le_bytes()); + dir.extend(&common); + // Extra and comment lengths, disk, internal and external attributes, header offset. + dir.extend([0; 12]); + dir.extend(at.to_le_bytes()); + dir.extend(m.name.as_bytes()); + } + let dir_at = out.len() as u32; + let n = members.len() as u16; + out.extend(&dir); + out.extend(0x0605_4b50u32.to_le_bytes()); + out.extend([0; 4]); + out.extend(n.to_le_bytes()); + out.extend(n.to_le_bytes()); + out.extend((dir.len() as u32).to_le_bytes()); + out.extend(dir_at.to_le_bytes()); + out.extend((comment.len() as u16).to_le_bytes()); + out.extend(comment); + out +} + +/// A version 14 or 15 package: the RIFF file `riff` as `content/riffData.cdr` (R25). +pub fn package14(riff: Vec, deflate: bool) -> Vec { + zip(&[Member { name: "content/riffData.cdr".into(), data: riff, deflate }], b"") +} + +/// A version 16+ package of a drawing of `version` holding `children` (R26, R27): the chunk tree +/// in `content/root.dat`, each chunk body of more than 8 bytes moved to a data stream (the +/// document's and other chunks' to `data1.dat`, each page's to `page.dat`, each other list's +/// to a stream named after its form type) behind a redirect record, and shorter bodies kept in +/// theirs. Lists stay in the tree. `extra` members are added to the archive. +pub fn package16(version: u16, children: &[Node], deflate: bool, extra: &[Member]) -> Vec { + package16_with(version, children, deflate, extra, &[]) +} + +/// [`package16`], moving the lists whose form types are in `moved_lists` whole into their stream. +pub fn package16_with(version: u16, children: &[Node], deflate: bool, extra: &[Member], moved_lists: &[[u8; 4]]) -> Vec { + let mut members = package16_members(version, children, deflate, moved_lists); + members.extend(extra.iter().cloned()); + zip(&members, b"") +} + +/// The members of a [`package16_with`] archive. +pub fn package16_members(version: u16, children: &[Node], deflate: bool, moved_lists: &[[u8; 4]]) -> Vec { + let mut streams: Vec<(String, Vec)> = vec![("data1.dat".into(), Vec::new())]; + let mut body = form(version).to_vec(); + for c in children { + let s = match c { + Node::List(f, _) if *f != *b"doc " => { + let name = if *f == *b"page" { format!("page{}", streams.len()) } else { String::from_utf8_lossy(f).trim().to_string() }; + streams.push((format!("{name}.dat"), Vec::new())); + streams.len() - 1 + } + _ => 0, + }; + body.extend(redirected(c, s, &mut streams, moved_lists)); + } + let mut root = b"RIFF".to_vec(); + root.extend((body.len() as u32).to_le_bytes()); + root.extend(body); + let list: Vec = streams.iter().map(|(n, _)| n.clone()).collect(); + let mut members = vec![ + Member { name: "content/root.dat".into(), data: root, deflate }, + Member { name: "content/dataFileList.dat".into(), data: list.join("\n").into_bytes(), deflate }, + ]; + members.extend(streams.into_iter().map(|(n, data)| Member { name: format!("content/data/{n}"), data, deflate })); + members +} + +/// `n` laid out for `root.dat`, its bodies moved into stream `s`. +fn redirected(n: &Node, s: usize, streams: &mut [(String, Vec)], moved_lists: &[[u8; 4]]) -> Vec { + let mut out = Vec::new(); + match n { + Node::List(f, kids) if !moved_lists.contains(f) => { + let mut body = f.to_vec(); + body.extend(kids.iter().flat_map(|k| redirected(k, s, streams, moved_lists))); + put(&mut out, b"LIST", body.len() as u32, &body, body.len()); + } + _ => { + // A moved list's children are laid out in the stream by the same rule. + let (id, data) = match n { + Node::Chunk(id, data) => (*id, data.clone()), + Node::List(f, kids) => { + let mut body = f.to_vec(); + for k in kids { + body.extend(redirected(k, s, streams, moved_lists)); + } + (*b"LIST", body) + } + }; + let mut rec = Vec::new(); + if data.len() <= 8 && id != *b"LIST" { + rec.extend(u32::MAX.to_le_bytes()); + rec.extend((data.len() as u32).to_le_bytes()); + rec.extend(&data); + rec.resize(16, 0); + } else { + let Some((_, stream)) = streams.get_mut(s) else { return out }; + rec.extend((s as u32).to_le_bytes()); + rec.extend((data.len() as u32).to_le_bytes()); + rec.extend((stream.len() as u32).to_le_bytes()); + rec.extend(0u32.to_le_bytes()); + stream.extend(&data); + } + put(&mut out, &id, 16, &rec, 16); + } + } + out +} + +/// The radius the base curve of a polygon lies on, 1000 mm, in points (R18). +pub const POLYGON_SIDE: f64 = 1000.0 / 25.4 * 72.0; + +/// The shape of a drawn object in a file of version 1 or 2 (R43, R44), sizes in points. +#[derive(Clone, Debug)] +pub enum WlShape { + Rect { + w: f64, + h: f64, + radius: f64, + }, + /// The two angle fields are written as given. + Ellipse { + w: f64, + h: f64, + angles: (i16, i16), + }, + /// Points with their type bytes, as [`V::points`] takes them. + Curve(Vec<(f64, f64, u8)>), + Text, +} + +/// A drawn object's record of a version 1 or 2 file (R42, R43, R44): `shape` placed by `matrix` +/// `[a, b, c, d, e, f]` with offsets in points, a uniform fill of `fill` and an outline of a width +/// in points and a color. The record's point holds the matrix's x offset and its `ty` the y +/// offset. +pub fn wl_object(shape: WlShape, matrix: [f64; 6], fill: Option<[u8; 5]>, outline: Option<(f64, [u8; 5])>) -> Vec { + let v = V(300); + let (kind, body): (u8, Vec) = match shape { + WlShape::Rect { w, h, radius } => (0, [v.coord(w), v.coord(h), vec![0; 2], v.coord(radius)].concat()), + WlShape::Ellipse { w, h, angles } => (1, [v.coord(w), v.coord(h), angles.0.to_le_bytes().to_vec(), angles.1.to_le_bytes().to_vec()].concat()), + WlShape::Curve(points) => (2, v.points(&points)), + WlShape::Text => (3, vec![0; 30]), + }; + let mut r = vec![0u8; (114 + body.len()).max(118)]; + r[26] = 0x40; + r[27] = 0x20; + let size = (r.len() - 32) as u16; + r[28..30].copy_from_slice(&size.to_le_bytes()); + let [a, b, c, d, e, f] = matrix; + r[32..34].copy_from_slice(&v.coord(e)); + let fixed = |x: f64| ((x * 65536.0).round() as i32).to_le_bytes(); + // a, b, tx, c, d, ty: x' = a x + b y + tx, y' = c x + d y + ty. + for (k, x) in [a, c, 0.0, b, d, f / 72.0 * 1000.0].into_iter().enumerate() { + r[36 + 4 * k..40 + 4 * k].copy_from_slice(&fixed(x)); + } + r[60] = kind; + if let Some((width, color)) = outline { + r[67] = 1; + r[68..70].copy_from_slice(&v.coord(width)); + r[74..79].copy_from_slice(&color); + } + if let Some(color) = fill { + r[94] = 1; + r[95..100].copy_from_slice(&color); + } + r[114..114 + body.len()].copy_from_slice(&body); + r +} + +/// A group or layer record of a version 1 or 2 file (R42): 28 bytes. +pub fn wl_group() -> Vec { + let mut r = vec![0u8; 28]; + r[27] = 1; + r +} + +/// A file of version 1 or 2 (R40, R41): the header with `marker` (`e` or `d`, or `m` for version +/// 2), a page of `page` points, the `records` and an empty font table. +pub fn wl_file(marker: u8, page: (f64, f64), records: &[Vec]) -> Vec { + let v = V(300); + let start = 64u32; + let mut out = vec![0u8; start as usize]; + out[..4].copy_from_slice(&[b'W', b'L', marker, 0]); + let (w, h) = page; + out[30..38].copy_from_slice(&[v.coord(-w / 2.0), v.coord(h / 2.0), v.coord(w / 2.0), v.coord(-h / 2.0)].concat()); + out.extend(records.iter().flatten()); + let end = out.len() as u32; + out.extend([0; 2]); + let trailer = out.len() as u32; + for (k, offset) in [28, start, end, trailer, trailer - 2].into_iter().enumerate() { + out[4 + 4 * k..8 + 4 * k].copy_from_slice(&offset.to_le_bytes()); + } + out +} + +/// A drawing of version 1 or 2 with a group record and one of each kind of object: a rounded +/// rectangle with a fill and an outline, an ellipse, a closed curve and a text object, front to +/// back. +pub fn wl_sample(marker: u8) -> Vec { + let (red, black) = (color3(1, [0, 100, 100, 0]), color3(1, [0, 0, 0, 100])); + let curve = vec![(0.0, 0.0, 0x08), (50.0, 0.0, 0x40), (50.0, 20.0, 0xC0), (20.0, 50.0, 0xC0), (0.0, 50.0, 0x88)]; + let records = [ + wl_object(WlShape::Rect { w: 100.0, h: 50.0, radius: 5.0 }, [1.0, 0.0, 0.0, 1.0, -100.0, 100.0], Some(red), Some((2.0, black))), + wl_group(), + wl_object(WlShape::Ellipse { w: 40.0, h: -40.0, angles: (0, 0) }, [1.0, 0.0, 0.0, 1.0, 50.0, -50.0], Some(red), None), + wl_object(WlShape::Curve(curve), [2.0, 0.0, 0.0, 2.0, 0.0, 0.0], None, Some((2.0, black))), + wl_object(WlShape::Text, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some(black), None), + ]; + wl_file(marker, (612.0, 792.0), &records) +} diff --git a/crates/cdr/src/wl.rs b/crates/cdr/src/wl.rs new file mode 100644 index 0000000000..c407421c98 --- /dev/null +++ b/crates/cdr/src/wl.rs @@ -0,0 +1,245 @@ +//! Drawings of versions 1 and 2: the file before RIFF, which starts with `WL` (R40 to R44). A +//! header of offsets, the page's box, then one flat list of records: 28 bytes for a group or a +//! layer, and a longer record for each drawn object, which holds its matrix, fill, outline and +//! shape. The reader maps the rectangles, ellipses and curves onto one page with one layer and +//! keeps no groups. + +use crate::bytes::{Rd, u32_at}; +use crate::geometry; +use crate::layout::{self, Profile}; +use crate::limits::Budget; +use crate::model::{Cap, Drawing, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Shape}; +use crate::records::{self, coord, fixed}; +use crate::riff::push; +use crate::{Error, Warning}; + +/// The header: the signature, a marker byte, a zero and five u32 offsets (R40). +const HEADER: usize = 28; +/// The marker bytes seen after `WL` (R40). `m` marks version 2. +const MARKERS: [u8; 3] = *b"dem"; +/// Where the page's box lies (R41). +const PAGE_BOX: usize = 30; +/// The bytes of a group or layer record (R42). +const GROUP: usize = 28; +/// The low flag byte, at byte 26, of a drawn object (R42). +const DRAWN: u8 = 0x40; +/// The bytes after a drawn object's body size, and the least a drawn object takes with them (R42). +const AFTER_BODY: usize = 32; +const LEAST: usize = 118; +/// Where a drawn object's fields lie (R43, R44). +const POINT: usize = 32; +const KIND: usize = 60; +const OUTLINED: usize = 67; +const OUTLINE_WIDTH: usize = 68; +const OUTLINE_COLOR: usize = 74; +const FILL_KIND: usize = 94; +const FILL_COLOR: usize = 95; +const SHAPE: usize = 114; +/// Object types (R43). +const RECTANGLE: u8 = 0; +const ELLIPSE: u8 = 1; +const CURVE: u8 = 2; + +/// Where the records start and end, when `b` has a `WL` header whose offsets fit the file. +fn header(b: &[u8]) -> Option<(usize, usize)> { + if b.get(..2)? != b"WL" || !MARKERS.contains(b.get(2)?) || *b.get(3)? != 0 { + return None; + } + let (start, end) = (u32_at(b, 8)? as usize, u32_at(b, 12)? as usize); + (start >= HEADER && start <= end && end <= b.len()).then_some((start, end)) +} + +/// Does `b` start like a drawing of version 1 or 2? The two letters alone are not enough: the +/// marker byte, the zero after it and the record offsets must fit too. +pub(crate) fn is_wl(b: &[u8]) -> bool { + header(b).is_some() +} + +pub(crate) fn drawing(b: &[u8], budget: &mut Budget) -> Result { + let (start, end) = header(b).ok_or(Error::NotCdr)?; + // Lengths are i16 in 1/1000 inch, as in version 3 (R5). + let p = layout::for_version(layout::OLDEST_RIFF).ok_or(Error::NotCdr)?; + let mut warn = Vec::new(); + let mut objects = Vec::new(); + let mut at = start; + // Every step takes at least a group record's bytes, so the file's size bounds the steps. + while end - at >= GROUP { + budget.take_chunk()?; + if b.get(at + 26) != Some(&DRAWN) { + at += GROUP; + continue; + } + let len = Rd::at(b, at + 28).u16().map_or(0, |body| usize::from(body) + AFTER_BODY); + let Some(rec) = b.get(at..at + len).filter(|_| len >= LEAST && at + len <= end) else { + push(&mut warn, Warning::Damaged); + at = end; + break; + }; + at += len; + if !budget.take_object() { + push(&mut warn, Warning::TooDeep); + at = end; + break; + } + objects.extend(object(rec, &p, budget, &mut warn)); + } + if at != end { + push(&mut warn, Warning::Damaged); + } + let version = if b.get(2) == Some(&b'm') { 200 } else { 100 }; + let layer = Layer { name: String::new(), kind: LayerKind::Drawing, objects, guides: Vec::new() }; + let pages = vec![Page { size: None, layers: vec![layer] }]; + Ok(Drawing { version, page_size: page_box(b, &p), pages, master: Vec::new(), guides: Vec::new(), warnings: warn }) +} + +/// The page's size from its box (R41): left, top, right and bottom around the page's centre. +fn page_box(b: &[u8], p: &Profile) -> Option<(f64, f64)> { + let mut r = Rd::at(b, PAGE_BOX); + let (left, top, right, bottom) = (coord(&mut r, p)?, coord(&mut r, p)?, coord(&mut r, p)?, coord(&mut r, p)?); + let (w, h) = ((right - left).abs(), (top - bottom).abs()); + (w > 0.0 && h > 0.0).then_some((w, h)) +} + +/// One drawn object's record (R43, R44): a shape, or `None` with a warning for text, for an object +/// of another type and for a shape that can't be read. +fn object(rec: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let read = shape(rec, p, budget, warn); + if read.is_none() { + push(warn, Warning::Damaged); + } + read?.map(|s| Object::Shape(Box::new(s))) +} + +/// The shape of a record. The outer `None` is a record that can't be read; the inner one an object +/// the reader leaves out, with its warning. +fn shape(rec: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option> { + let k = p.unit(); + let mut r = Rd::at(rec, POINT); + let (x, y) = (f64::from(r.i16()?), f64::from(r.i16()?)); + // x' = a x + b y + tx + x of the point, y' = c x + d y + ty + y of the point. + let (a, b, tx, c, d, ty) = (fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?); + let matrix = Matrix([a, c, b, d, (tx + x) * k, (ty + y) * k]); + let body = rec.get(SHAPE..)?; + let geometry = match *rec.get(KIND)? { + RECTANGLE => rect(body, p)?, + ELLIPSE => { + let mut s = Rd::new(body); + let (w, h) = (coord(&mut s, p)?, coord(&mut s, p)?); + // Two angles follow. No source confirms how they make an arc, so an ellipse whose + // angles differ is left out. + if matches!((s.i16(), s.i16()), (Some(from), Some(to)) if from != to) { + push(warn, Warning::UnsupportedObjects); + return Some(None); + } + Geometry::Ellipse { w, h } + } + CURVE => Geometry::Path(geometry::point_list(body, p, budget, warn)?), + _ => { + push(warn, Warning::UnsupportedObjects); + return Some(None); + } + }; + let color_at = |at: usize, warn: &mut Vec| Some(records::color5(rec.get(at..at + 5)?.try_into().ok()?, warn)); + let fill = match *rec.get(FILL_KIND)? { + 0 => None, + 1 => Some(color_at(FILL_COLOR, warn)?), + _ => { + push(warn, Warning::UnsupportedFills); + None + } + }; + let outline = if *rec.get(OUTLINED)? != 0 { + let width = f64::from(Rd::at(rec, OUTLINE_WIDTH).u16()?) * k; + Some(Outline { width, color: color_at(OUTLINE_COLOR, warn)?, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new() }) + } else { + None + }; + Some(Some(Shape { geometry, matrix, fill, outline })) +} + +/// A rectangle (R44): its width and height, then after 2 bytes a corner radius, which is kept when +/// it is at most half the shorter side. +fn rect(body: &[u8], p: &Profile) -> Option { + let mut r = Rd::new(body); + let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?); + let radius = r.skip(2).and_then(|()| coord(&mut r, p)).filter(|v| *v > 0.0 && *v <= w.abs().min(h.abs()) / 2.0).unwrap_or(0.0); + Some(Geometry::Rect { w, h, radii: [radius; 4] }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Limits; + use crate::model::Color; + use crate::synth::{self, WlShape}; + + fn read(b: &[u8]) -> Result { + drawing(b, &mut Budget::new(Limits::default())) + } + + #[test] + fn the_header_is_taken_only_when_its_offsets_fit() { + let file = synth::wl_file(b'e', (612.0, 792.0), &[synth::wl_group()]); + assert!(is_wl(&file)); + // The two letters, a marker and a zero are not enough. + assert!(!is_wl(b"WLe\0")); + assert!(!is_wl(b"WLe\0 and then some text that is long enough to hold offsets")); + let with = |at: usize, v: u32| { + let mut f = file.clone(); + f[at..at + 4].copy_from_slice(&v.to_le_bytes()); + f + }; + // Records that start inside the header, start after their end, or end past the file. + assert!(!is_wl(&with(8, 27))); + assert!(!is_wl(&with(8, file.len() as u32))); + assert!(!is_wl(&with(12, file.len() as u32 + 1))); + let mut other = file.clone(); + other[2] = b'x'; + assert!(!is_wl(&other)); + other[2] = b'e'; + other[3] = 1; + assert!(!is_wl(&other)); + } + + #[test] + fn a_rectangle_keeps_a_radius_of_at_most_half_its_shorter_side() { + let p = layout::for_version(300).unwrap(); + let body = |radius: i16| [1000i16, 500, 0, radius].iter().flat_map(|v| v.to_le_bytes()).collect::>(); + let radius_of = |b: &[u8]| match rect(b, &p) { + Some(Geometry::Rect { w, h, radii }) if (w - 72.0).abs() < 1e-9 && (h - 36.0).abs() < 1e-9 => radii[0], + other => panic!("{other:?}"), + }; + assert!((radius_of(&body(200)) - 14.4).abs() < 1e-9); + for radius in [300, -5, 0] { + assert_eq!(radius_of(&body(radius)), 0.0, "{radius}"); + } + // A record that ends after the size has square corners. + assert_eq!(radius_of(&body(200)[..4]), 0.0); + assert_eq!(rect(&body(200)[..3], &p), None); + } + + #[test] + fn a_record_shorter_than_its_fields_ends_the_walk_as_damage() { + let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([1, 0, 0, 0, 100]), None); + let mut short = rect.clone(); + // A body size that leaves less than the fixed fields. + short[28..30].copy_from_slice(&((LEAST - AFTER_BODY - 1) as u16).to_le_bytes()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect.clone(), short, rect])).unwrap(); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); + assert_eq!(d.warnings, vec![Warning::Damaged]); + } + + #[test] + fn fill_types_other_than_uniform_and_unknown_inks_are_named() { + let mut textured = + synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([0, 9, 0, 50, 0]), None); + let d = read(&synth::wl_file(b'm', (612.0, 792.0), std::slice::from_ref(&textured))).unwrap(); + let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") }; + assert_eq!(s.fill, Some(Color::Spot { name: "Spot 0:9".into(), tint: 0.5, look: None })); + assert_eq!((d.version, d.warnings), (200, vec![Warning::SpotLooks])); + textured[FILL_KIND] = 5; + let d = read(&synth::wl_file(b'm', (612.0, 792.0), &[textured])).unwrap(); + let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") }; + assert_eq!((s.fill.clone(), d.warnings), (None, vec![Warning::UnsupportedFills])); + } +} diff --git a/crates/cdr/src/zip.rs b/crates/cdr/src/zip.rs new file mode 100644 index 0000000000..67994192a0 --- /dev/null +++ b/crates/cdr/src/zip.rs @@ -0,0 +1,308 @@ +//! The ZIP archives of `.cdr` drawings from version 14 on (R24): the central directory, then stored +//! and deflated members read on request. Archives that span disks, ZIP64 archives and encrypted +//! members are refused; so are directories whose members overlap or repeat a name. + +use std::borrow::Cow; +use std::io::Read as _; + +use crate::Error; +use crate::bytes::Rd; + +/// End of central directory record: signature and fixed length. +const END: u32 = 0x0605_4b50; +const END_LEN: usize = 22; +/// The longest archive comment, which the end record may be followed by. +const MAX_COMMENT: usize = 0xFFFF; +/// ZIP64 end of central directory locator, 20 bytes before the end record when present. +const ZIP64_LOCATOR: u32 = 0x0706_4b50; +/// Central directory header: signature and fixed length. +const CENTRAL: u32 = 0x0201_4b50; +const CENTRAL_LEN: usize = 46; +/// Local file header: signature and fixed length. +const LOCAL: u32 = 0x0403_4b50; +const LOCAL_LEN: usize = 30; +/// General purpose flag bit 0: the member is encrypted. +const ENCRYPTED: u16 = 1; +const STORED: u16 = 0; +const DEFLATED: u16 = 8; +/// What members packed by another method are refused as. +const OTHER_METHODS: &str = "package compression methods other than storing and deflate"; + +/// One member, as the central directory and its local header give it. +#[derive(Clone, Copy, Debug)] +struct Entry<'a> { + name: &'a [u8], + flags: u16, + method: u16, + crc: u32, + packed: usize, + size: usize, + /// Where its local header starts and where its packed bytes start. + header: usize, + data: usize, +} + +/// An archive's directory over its bytes. +#[derive(Debug)] +pub(crate) struct Archive<'a> { + bytes: &'a [u8], + entries: Vec>, + /// The entries in name order, for lookups. + by_name: Vec, +} + +/// Does `bytes` start with a local file header? +pub(crate) fn is_zip(bytes: &[u8]) -> bool { + bytes.starts_with(b"PK\x03\x04") +} + +impl<'a> Archive<'a> { + /// The directory of `bytes`, holding at most `max_entries` members. + pub(crate) fn open(bytes: &'a [u8], max_entries: usize) -> Result { + let end = find_end(bytes).ok_or(Error::Damaged("package directory"))?; + if end >= 20 && Rd::at(bytes, end - 20).u32() == Some(ZIP64_LOCATOR) { + return Err(Error::Unsupported("ZIP64 packages")); + } + let mut r = Rd::at(bytes, end + 4); + let dir = || Error::Damaged("package directory"); + let (disk, dir_disk) = (r.u16().ok_or_else(dir)?, r.u16().ok_or_else(dir)?); + let (on_disk, total) = (r.u16().ok_or_else(dir)?, r.u16().ok_or_else(dir)?); + let (dir_len, dir_at) = (r.u32().ok_or_else(dir)?, r.u32().ok_or_else(dir)?); + if total == u16::MAX || dir_len == u32::MAX || dir_at == u32::MAX { + return Err(Error::Unsupported("ZIP64 packages")); + } + if disk != 0 || dir_disk != 0 || on_disk != total { + return Err(Error::Unsupported("packages split across files")); + } + let total = usize::from(total); + if total > max_entries { + return Err(Error::Limit("package member count")); + } + let (dir_at, dir_len) = (dir_at as usize, dir_len as usize); + let dir_end = dir_at.checked_add(dir_len).filter(|&e| e <= end).ok_or_else(dir)?; + let mut r = Rd::at(bytes, dir_at); + let mut entries = Vec::with_capacity(total); + for _ in 0..total { + let e = central_entry(bytes, &mut r, dir_end)?; + entries.push(e); + } + // Each member's bytes end before the next member's header and before the directory. + let mut order: Vec<&Entry> = entries.iter().collect(); + order.sort_unstable_by_key(|e| e.header); + for (i, e) in order.iter().enumerate() { + let stop = order.get(i + 1).map_or(dir_at, |n| n.header); + if e.data.checked_add(e.packed).is_none_or(|x| x > stop) { + return Err(Error::Damaged("package members overlap")); + } + } + let mut by_name: Vec = (0..entries.len()).collect(); + by_name.sort_unstable_by_key(|&i| entries.get(i).map(|e| e.name)); + let name = |i: &usize| entries.get(*i).map(|e| e.name); + if by_name.windows(2).any(|w| name(&w[0]) == name(&w[1])) { + return Err(Error::Damaged("package member named twice")); + } + Ok(Archive { bytes, entries, by_name }) + } + + /// The member named `name`. + pub(crate) fn find(&self, name: &[u8]) -> Option { + let at = self.by_name.binary_search_by(|&i| self.entries.get(i).map(|e| e.name).cmp(&Some(name))).ok()?; + self.by_name.get(at).copied() + } + + /// The size member `i`'s directory entry gives. + pub(crate) fn size(&self, i: usize) -> usize { + self.entries.get(i).map_or(0, |e| e.size) + } + + /// How many members the archive holds. + pub(crate) fn count(&self) -> usize { + self.entries.len() + } + + /// The bytes reading member `i` may inflate: its stated size when it is deflated, else 0. + pub(crate) fn inflate_cost(&self, i: usize) -> usize { + self.entries.get(i).filter(|e| e.method == DEFLATED).map_or(0, |e| e.size) + } + + /// An error when member `i` is encrypted or packed by a method other than storing or deflate. + pub(crate) fn check(&self, i: usize) -> Result<(), Error> { + let e = self.entries.get(i).ok_or(Error::Damaged("package member"))?; + if e.flags & ENCRYPTED != 0 { + return Err(Error::Unsupported("encrypted packages")); + } + if e.method != STORED && e.method != DEFLATED { + return Err(Error::Unsupported(OTHER_METHODS)); + } + Ok(()) + } + + /// Member `i`'s bytes when they come to at most `limit`, and a deflated member's when they + /// also come to at most `inflate_left`. A stored member is borrowed; a deflated one inflates to + /// at most its stated size plus one byte, so a member that inflates past what it states stops + /// there. The length and CRC-32 must match the directory's. + pub(crate) fn read(&self, i: usize, limit: usize, inflate_left: usize) -> Result, Error> { + self.check(i)?; + let e = self.entries.get(i).ok_or(Error::Damaged("package member"))?; + if e.size > limit { + return Err(Error::Limit("package member size")); + } + if e.method == DEFLATED && e.size > inflate_left { + return Err(Error::Limit("inflated size")); + } + let packed = self.bytes.get(e.data..e.data + e.packed).ok_or(Error::Damaged("package member"))?; + let out: Cow<'a, [u8]> = match e.method { + STORED if e.packed == e.size => Cow::Borrowed(packed), + STORED => return Err(Error::Damaged("package member")), + DEFLATED => { + let mut out = Vec::new(); + let got = flate2::read::DeflateDecoder::new(packed) + .take(e.size as u64 + 1) + .read_to_end(&mut out) + .map_err(|_| Error::Damaged("package member"))?; + if got != e.size { + return Err(Error::Damaged("package member")); + } + Cow::Owned(out) + } + _ => return Err(Error::Unsupported(OTHER_METHODS)), + }; + if crc32fast::hash(&out) != e.crc { + return Err(Error::Damaged("package member")); + } + Ok(out) + } +} + +/// Where the end of central directory record starts: searched back from the end over at most the +/// longest comment, among the records whose comment reaches exactly to the end the first that +/// names members in a directory before it, else the first. A comment or a member may hold bytes +/// that look like an empty archive's end record. +fn find_end(bytes: &[u8]) -> Option { + let last = bytes.len().checked_sub(END_LEN)?; + let first = last.saturating_sub(MAX_COMMENT); + let mut found = None; + for at in (first..=last).rev() { + let mut r = Rd::at(bytes, at); + if r.u32() != Some(END) || r.skip(6).is_none() { + continue; + } + let (total, dir_len, dir_at, comment) = (r.u16(), r.u32(), r.u32(), r.u16()); + if !comment.is_some_and(|c| at + END_LEN + usize::from(c) == bytes.len()) { + continue; + } + let names_members = total.is_some_and(|t| t > 0) + && dir_len.zip(dir_at).is_some_and(|(len, dir)| { + (dir as usize).checked_add(len as usize).is_some_and(|e| e <= at) && Rd::at(bytes, dir as usize).u32() == Some(CENTRAL) + }); + if names_members { + return Some(at); + } + found = found.or(Some(at)); + } + found +} + +/// The central directory entry at `r` (before `dir_end`) and its local header. +fn central_entry<'a>(bytes: &'a [u8], r: &mut Rd<'a>, dir_end: usize) -> Result, Error> { + let dir = || Error::Damaged("package directory"); + if r.pos().checked_add(CENTRAL_LEN).is_none_or(|e| e > dir_end) || r.u32() != Some(CENTRAL) { + return Err(dir()); + } + r.skip(4).ok_or_else(dir)?; + let flags = r.u16().ok_or_else(dir)?; + let method = r.u16().ok_or_else(dir)?; + r.skip(4).ok_or_else(dir)?; + let crc = r.u32().ok_or_else(dir)?; + let (packed, size) = (r.u32().ok_or_else(dir)?, r.u32().ok_or_else(dir)?); + let name_len = usize::from(r.u16().ok_or_else(dir)?); + let extra_len = usize::from(r.u16().ok_or_else(dir)?); + let comment_len = usize::from(r.u16().ok_or_else(dir)?); + let disk = r.u16().ok_or_else(dir)?; + r.skip(6).ok_or_else(dir)?; + let header = r.u32().ok_or_else(dir)?; + if packed == u32::MAX || size == u32::MAX || header == u32::MAX { + return Err(Error::Unsupported("ZIP64 packages")); + } + if disk != 0 { + return Err(Error::Unsupported("packages split across files")); + } + let name = r.bytes(name_len).ok_or_else(dir)?; + r.skip(extra_len).and_then(|()| r.skip(comment_len)).ok_or_else(dir)?; + if r.pos() > dir_end { + return Err(dir()); + } + // The local header repeats the name; its own extra field may differ in length. + let header = header as usize; + let mut l = Rd::at(bytes, header); + let local = || Error::Damaged("package member header"); + if l.u32() != Some(LOCAL) { + return Err(local()); + } + // The signature, 22 bytes, then the name and extra field lengths. + l.skip(LOCAL_LEN - 8).ok_or_else(local)?; + let (local_name, local_extra) = (usize::from(l.u16().ok_or_else(local)?), usize::from(l.u16().ok_or_else(local)?)); + if l.bytes(local_name) != Some(name) { + return Err(local()); + } + l.skip(local_extra).ok_or_else(local)?; + Ok(Entry { name, flags, method, crc, packed: packed as usize, size: size as usize, header, data: l.pos() }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::synth::{Member, zip}; + + fn stored(name: &str, data: &[u8]) -> Member { + Member { name: name.into(), data: data.to_vec(), deflate: false } + } + + #[test] + fn stored_and_deflated_members_read_back() { + let bytes = zip(&[stored("a", b"hello"), Member { name: "b".into(), data: vec![7; 5000], deflate: true }], b""); + let a = Archive::open(&bytes, 10).unwrap(); + assert!(matches!(a.read(a.find(b"a").unwrap(), 100, 100).unwrap(), Cow::Borrowed(b"hello"))); + assert_eq!(a.read(a.find(b"b").unwrap(), 5000, 5000).unwrap().as_ref(), &[7; 5000][..]); + assert_eq!(a.read(a.find(b"b").unwrap(), 4999, 5000), Err(Error::Limit("package member size"))); + assert_eq!(a.find(b"c"), None); + // What is left to inflate holds back deflated members only. + assert_eq!(a.read(a.find(b"b").unwrap(), 5000, 4999), Err(Error::Limit("inflated size"))); + assert!(a.read(a.find(b"a").unwrap(), 100, 0).is_ok()); + } + + #[test] + fn the_end_record_is_found_behind_a_comment() { + let bytes = zip(&[stored("a", b"x")], &[b'c'; 300]); + assert!(Archive::open(&bytes, 10).is_ok()); + // A comment longer than the record says leaves no end record to find. + let mut cut = bytes.clone(); + cut.push(0); + assert_eq!(Archive::open(&cut, 10).unwrap_err(), Error::Damaged("package directory")); + // A comment that ends in bytes like an empty archive's end record: the record that names + // members in a directory is the archive's. + let mut fake = END.to_le_bytes().to_vec(); + fake.resize(END_LEN, 0); + let bytes = zip(&[stored("a", b"x")], &fake); + let a = Archive::open(&bytes, 10).unwrap(); + assert_eq!(a.count(), 1); + } + + #[test] + fn a_member_whose_crc_or_length_is_wrong_is_damage() { + let bytes = zip(&[Member { name: "a".into(), data: vec![1; 64], deflate: true }], b""); + let a = Archive::open(&bytes, 10).unwrap(); + // The directory's CRC-32 sits 16 bytes into its entry. + let dir_at = bytes.windows(4).position(|w| w == CENTRAL.to_le_bytes()).unwrap(); + let mut bad = bytes.clone(); + bad[dir_at + 16] ^= 1; + let b = Archive::open(&bad, 10).unwrap(); + assert_eq!(b.read(0, 1000, 1000).unwrap_err(), Error::Damaged("package member")); + // A stated size one short: the inflate runs past it. + let mut short = bytes.clone(); + short[dir_at + 24] -= 1; + let s = Archive::open(&short, 10).unwrap(); + assert_eq!(s.read(0, 1000, 1000).unwrap_err(), Error::Damaged("package member")); + assert!(a.read(0, 1000, 1000).is_ok()); + } +} diff --git a/crates/cdr/tests/bench.rs b/crates/cdr/tests/bench.rs new file mode 100644 index 0000000000..dd23a0a76f --- /dev/null +++ b/crates/cdr/tests/bench.rs @@ -0,0 +1,66 @@ +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +//! Read time of a large synthetic drawing. Run with +//! `cargo test --release -p vectorcraft-cdr --test bench -- --ignored --nocapture`. + +use vectorcraft_cdr::synth::{self, V, chunk, list}; +use vectorcraft_cdr::{Limits, read}; + +/// A version 13 drawing of `n` curves of 22 points each, filled and outlined, compressed when +/// `compress`. +fn many_curves(n: usize, compress: bool) -> Vec { + let v = V(1300); + let red = synth::color(5, [0, 0, 255, 0]); + let black = synth::color(2, [0, 0, 0, 100]); + let styles = list( + b"doc ", + vec![ + synth::mcfg(v, 612.0, 792.0), + list(b"filt", vec![chunk(b"fild", v.fill(1, &red))]), + list(b"otlt", vec![chunk(b"outl", v.outline(2, synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }, &black, &[]))]), + ], + ); + let objects: Vec<_> = (0..n) + .map(|i| { + let o = (i % 500) as f64; + // A move, then curves of two control points and an end point each. + let kind = |k: i32| { + if k == 0 { + 0x08 + } else if k % 3 == 0 { + 0x80 + } else { + 0xC0 + } + }; + let pts: Vec<(f64, f64, u8)> = (0..22).map(|k| (o + f64::from(k), o + f64::from(k % 5), kind(k))).collect(); + let args = vec![(20, 1u32.to_le_bytes().to_vec()), (10, 2u32.to_le_bytes().to_vec()), (30, v.points(&pts))]; + synth::object(v, 3, &args, Some([1.0, 0.0, 0.0, 1.0, o, -o])) + }) + .collect(); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "Art", objects)]); + let body = vec![styles, page]; + let mut kids = vec![chunk(b"vrsn", 1300u16.to_le_bytes().to_vec())]; + if compress { + kids.push(synth::cmpr(&body)); + } else { + kids.extend(body); + } + synth::riff(1300, &kids) +} + +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn read_a_large_drawing() { + for compress in [false, true] { + let file = many_curves(50_000, compress); + let mut times = Vec::new(); + for _ in 0..5 { + let t = std::time::Instant::now(); + let d = read(&file, Limits::default()).unwrap(); + times.push(t.elapsed().as_secs_f64() * 1000.0); + assert_eq!(d.pages.len(), 1); + } + times.sort_by(f64::total_cmp); + println!("compress={compress} bytes={} median_ms={:.1} min_ms={:.1}", file.len(), times[2], times[0]); + } +} diff --git a/crates/cdr/tests/provenance.rs b/crates/cdr/tests/provenance.rs new file mode 100644 index 0000000000..0a28df20f6 --- /dev/null +++ b/crates/cdr/tests/provenance.rs @@ -0,0 +1,44 @@ +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +//! Every layout id the code cites (`R1` ...) has a row in `PROVENANCE.md`. + +use std::collections::BTreeSet; + +/// The ids `R` in `text`. +fn ids(text: &str) -> BTreeSet { + let b = text.as_bytes(); + let mut out = BTreeSet::new(); + for (i, c) in b.iter().enumerate() { + let starts = *c == b'R' && (i == 0 || !b[i - 1].is_ascii_alphanumeric()); + if !starts { + continue; + } + let digits: String = b[i + 1..].iter().take_while(|d| d.is_ascii_digit()).map(|d| *d as char).collect(); + let ends = b.get(i + 1 + digits.len()).is_none_or(|d| !d.is_ascii_alphanumeric()); + if !digits.is_empty() && ends { + out.insert(digits.parse().unwrap()); + } + } + out +} + +#[test] +fn every_cited_layout_has_a_row() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); + let table = std::fs::read_to_string(dir.join("PROVENANCE.md")).unwrap(); + let rows: BTreeSet = table.lines().filter_map(|l| l.strip_prefix("| R")).filter_map(|l| l.split(' ').next()?.parse().ok()).collect(); + let mut cited = BTreeSet::new(); + for entry in std::fs::read_dir(dir.join("src")).unwrap() { + let path = entry.unwrap().path(); + if path.extension().is_some_and(|e| e == "rs") { + cited.extend(ids(&std::fs::read_to_string(&path).unwrap())); + } + } + assert!(!cited.is_empty()); + let missing: Vec<_> = cited.difference(&rows).collect(); + assert!(missing.is_empty(), "cited without a PROVENANCE.md row: {missing:?}"); +} + +#[test] +fn ids_are_found_only_as_whole_words() { + assert_eq!(ids("(R1, R12) RIFF R3x xR4 R"), BTreeSet::from([1, 12])); +} diff --git a/crates/cdr/tests/read.rs b/crates/cdr/tests/read.rs new file mode 100644 index 0000000000..88c015bd89 --- /dev/null +++ b/crates/cdr/tests/read.rs @@ -0,0 +1,1463 @@ +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +//! Reading synthetic drawings of every version the reader takes, plain and compressed, and +//! hostile files. + +use proptest::prelude::*; +use vectorcraft_cdr::model::{Cap, Color, Geometry, Join, LayerKind, Matrix, Object, Segment}; +use vectorcraft_cdr::synth::{self, V, chunk, list}; +use vectorcraft_cdr::{Error, Limits, Warning, read}; + +fn shapes(objects: &[Object]) -> Vec<&vectorcraft_cdr::model::Shape> { + let mut out = Vec::new(); + let mut stack: Vec<&Object> = objects.iter().rev().collect(); + while let Some(o) = stack.pop() { + match o { + Object::Shape(s) => out.push(&**s), + Object::Group(kids) => stack.extend(kids.iter().rev()), + } + } + out +} + +/// The page and layers of the sample of `version`. +fn check_pages(d: &vectorcraft_cdr::Drawing, version: u16) { + assert_eq!(d.version, version); + let (w, h) = d.page_size.unwrap(); + assert!((w - 612.0).abs() < 0.1 && (h - 792.0).abs() < 0.1, "{version}: {w} {h}"); + assert_eq!(d.pages.len(), 1, "{version}"); + let art = &d.pages[0].layers[0]; + assert_eq!((art.name.as_str(), art.kind), ("Art", LayerKind::Drawing)); + assert!(matches!(art.objects[3], Object::Group(ref g) if g.len() == 2)); + assert!(d.warnings.contains(&Warning::UnsupportedObjects)); + // The master page: its guideline every page shows, and its desktop object. + if version >= 600 { + assert_eq!(d.guides.len(), 1); + assert!((d.guides[0].angle - 90.0).abs() < 1e-9 && (d.guides[0].at.x - 36.0).abs() < 0.01); + } + assert_eq!(d.master.len(), 1); + assert_eq!(d.master[0].kind, LayerKind::Desktop); +} + +/// The shapes of the sample of `version`: rectangle, ellipse, curve, and the group's polygon and +/// arc; the text is left out. +fn check_shapes(d: &vectorcraft_cdr::Drawing, version: u16) { + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 5, "{version}"); + assert!(matches!(s[0].geometry, Geometry::Rect { radii, .. } if radii.iter().all(|r| (r - 5.0).abs() < 0.1))); + // The samples of versions 3 and 4 store their red as CMYK in percent. + let red = if version < 500 { Color::Cmyk([0.0, 1.0, 1.0, 0.0]) } else { Color::Rgb([1.0, 0.0, 0.0]) }; + assert_eq!(s[0].fill, Some(red), "{version}"); + let o = s[0].outline.as_ref().unwrap(); + assert!((o.width - 2.0).abs() < 0.05 && o.cap == Cap::Round, "{version}: {o:?}"); + assert!((s[0].matrix.0[4] + 100.0).abs() < 0.1 && (s[0].matrix.0[5] - 100.0).abs() < 0.1); + assert!(matches!(s[1].geometry, Geometry::Ellipse { .. }) && s[1].outline.is_none()); + assert!(matches!(&s[2].geometry, Geometry::Path(p) if p.subpaths[0].closed && matches!(p.subpaths[0].segments[1], Segment::Cubic(..)))); + assert!(s[2].fill.is_none()); + if version >= 600 { + let Geometry::Path(p) = &s[3].geometry else { panic!("polygon") }; + assert_eq!(p.subpaths[0].segments.len(), 10, "five sides of two segments"); + // 5 % of 1000 mm. + let r = p.subpaths[0].start.y; + assert!((r - 0.05 * synth::POLYGON_SIDE).abs() < 0.5, "{r}"); + } + assert!(matches!(&s[4].geometry, Geometry::Path(p) if p.subpaths[0].closed)); +} + +#[test] +fn every_version_from_5_to_13_reads_its_sample() { + for version in [500, 600, 700, 800, 900, 1000, 1100, 1200, 1300] { + for compress in [false, version >= 700] { + let d = read(&synth::sample(version, compress), Limits::default()).unwrap_or_else(|e| panic!("{version} {compress}: {e}")); + check_pages(&d, version); + check_shapes(&d, version); + } + } +} + +#[test] +fn versions_3_and_4_read_their_sample() { + for version in [300, 400] { + let file = synth::sample(version, false); + assert_eq!(&file[8..12], if version == 300 { b"CDR " } else { b"CDR4" }); + assert!(vectorcraft_cdr::is_cdr(&file)); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + assert!(!d.warnings.contains(&Warning::Damaged), "{version}: {:?}", d.warnings); + check_pages(&d, version); + check_shapes(&d, version); + let s = shapes(&d.pages[0].layers[0].objects); + let o = s[0].outline.as_ref().unwrap(); + assert_eq!((o.join, &o.color), (Join::Round, &Color::Cmyk([0.0, 0.0, 0.0, 1.0])), "{version}"); + // The ellipse 50 pt right of and below the page centre, and the curve where it was drawn. + assert!((s[1].matrix.0[4] - 50.0).abs() < 0.1 && (s[1].matrix.0[5] + 50.0).abs() < 0.1, "{version}: {:?}", s[1].matrix); + assert_eq!(s[2].matrix, Matrix::IDENTITY, "{version}"); + } + // The form type alone names version 3, and a `vrsn` chunk names it under another form type. + let mut plain = vec![]; + plain.extend(synth::sample_content(300)); + check_shapes(&read(&synth::riff(300, &plain), Limits::default()).unwrap(), 300); + let mut relabeled = synth::sample(300, false); + relabeled[11] = b'5'; + assert_eq!(read(&relabeled, Limits::default()).unwrap().version, 300); +} + +/// A version 3 drawing of one layer holding `objects`. +fn drawing3(objects: Vec) -> Vec { + let page = synth::page(false, vec![synth::layer(V(300), [0, 0, 0, 0x98], "L", objects)]); + synth::riff(300, &[chunk(b"vrsn", 300u16.to_le_bytes().to_vec()), page]) +} + +/// A version 3 rectangle of 10 × 10 pt with the transforms `matrices`. +fn rect3(matrices: &[[f64; 6]]) -> synth::Node { + let v = V(300); + let mut args = vec![(30, v.rect(10.0, 10.0, 0.0))]; + if !matrices.is_empty() { + args.push((100, synth::transforms3(matrices))); + } + synth::object(v, 1, &args, None) +} + +#[test] +fn version_3_groups_place_their_objects() { + let shift = |x: f64, y: f64| [1.0, 0.0, 0.0, 1.0, x, y]; + let double = [2.0, 0.0, 0.0, 2.0, 0.0, 0.0]; + // A rectangle moved 72 pt right, in a group that doubles sizes, in a group that moves 36 pt + // up; beside the inner group, a rectangle of the outer group alone; then one outside both. + let inner = synth::group3(&[double], vec![rect3(&[shift(72.0, 0.0)])]); + let outer = synth::group3(&[shift(0.0, 36.0)], vec![inner, rect3(&[])]); + let d = read(&drawing3(vec![outer, rect3(&[shift(7.2, 0.0)])]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + let objects = &d.pages[0].layers[0].objects; + assert!(matches!(&objects[0], Object::Group(g) if matches!(&g[0], Object::Group(i) if i.len() == 1) && g.len() == 2)); + let s = shapes(objects); + let close = |m: &Matrix, want: [f64; 6]| m.0.iter().zip(want).all(|(a, b)| (a - b).abs() < 0.01); + // Its own shift, then the inner group's scale, then the outer group's shift. + assert!(close(&s[0].matrix, [2.0, 0.0, 0.0, 2.0, 144.0, 36.0]), "{:?}", s[0].matrix); + assert!(close(&s[1].matrix, [1.0, 0.0, 0.0, 1.0, 0.0, 36.0]), "{:?}", s[1].matrix); + assert!(close(&s[2].matrix, [1.0, 0.0, 0.0, 1.0, 7.2, 0.0]), "{:?}", s[2].matrix); + // Two matrices of one object apply in file order. + let d = read(&drawing3(vec![rect3(&[shift(72.0, 0.0), double])]), Limits::default()).unwrap(); + assert!(close(&shapes(&d.pages[0].layers[0].objects)[0].matrix, [2.0, 0.0, 0.0, 2.0, 144.0, 0.0])); +} + +#[test] +fn version_3_objects_and_groups_under_an_envelope_keep_their_outlines_and_matrices() { + // A transforms argument of one envelope entry (type 0x14). + let mut envelope = vec![0, 0, 1, 0, 0x14, 0]; + envelope.resize(14 + 24, 0); + // A matrix that moves 72 pt right, then an envelope entry whose data follows the matrix's. + let matrix = synth::transforms3(&[[1.0, 0.0, 0.0, 1.0, 72.0, 0.0]]).split_off(14); + let mut shifted = vec![0, 0, 2, 0, 0x8c, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0x14, 0, 0, 0, 0, 0, 48, 0, 0, 0]; + shifted.extend(matrix); + shifted.resize(48 + 24, 0); + let v = V(300); + let bent = synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0)), (100, envelope.clone())], None); + let moved = synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0)), (100, shifted)], None); + let group = list(b"grp ", vec![chunk(b"lobj", v.loda(0, &[(100, envelope)])), rect3(&[])]); + let d = read(&drawing3(vec![bent, moved, group, rect3(&[])]), Limits::default()).unwrap(); + let objects = &d.pages[0].layers[0].objects; + assert_eq!(objects.len(), 4); + assert!(matches!(&objects[2], Object::Group(g) if g.len() == 1)); + let s = shapes(objects); + assert_eq!(s.len(), 4); + assert!(matches!(s[0].geometry, Geometry::Rect { .. }) && s[0].matrix == Matrix::IDENTITY); + assert!((s[1].matrix.0[4] - 72.0).abs() < 0.01 && s[1].matrix.0[5].abs() < 0.01, "{:?}", s[1].matrix); + assert_eq!(s[2].matrix, Matrix::IDENTITY); + assert_eq!(d.warnings, vec![Warning::Envelopes]); +} + +#[test] +fn version_3_object_types_count_from_0() { + let v = V(300); + // `lobj` records written with their stored types: 0 rectangle, 2 curve, 3 text, 4 bitmap. + let raw = |kind: u32, coords: Vec| list(b"obj ", vec![chunk(b"lobj", v.loda(kind, &[(30, coords)]))]); + let curve = v.points(&[(0.0, 0.0, 0x00), (10.0, 0.0, 0x40)]); + let ellipse = [v.coord(40.0), v.coord(20.0), v.angle(0.0), v.angle(0.0), v.word(0)].concat(); + let d = read( + &drawing3(vec![raw(0, v.rect(10.0, 10.0, 0.0)), raw(1, ellipse), raw(2, curve), raw(3, vec![0; 8]), raw(4, vec![0; 8])]), + Limits::default(), + ) + .unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 3); + assert!(matches!(s[0].geometry, Geometry::Rect { .. }) && matches!(s[1].geometry, Geometry::Ellipse { .. })); + assert!(matches!(&s[2].geometry, Geometry::Path(p) if p.subpaths.len() == 1)); + assert_eq!(d.warnings, vec![Warning::UnsupportedObjects]); +} + +#[test] +fn version_3_fills_and_outlines_read_from_the_object() { + let v = V(300); + let styled = |fill: Vec, outline: Vec| synth::object(v, 1, &[(20, fill), (10, outline), (30, v.rect(10.0, 10.0, 0.0))], None); + let pen = |line_type: u16| synth::Pen { line_type, width: 3.0, cap: 2, join: 2 }; + let black = synth::color3(1, [0, 0, 0, 100]); + let d = read( + &drawing3(vec![ + styled(synth::fill3(1, &synth::color3(0, [0, 0, 40, 0])), synth::outline3(pen(0), black, &[3, 1])), + styled(synth::fill3(1, &synth::color3(0, [1, 0, 100, 0])), synth::outline3(pen(1), black, &[])), + styled(synth::fill3(0, &[]), synth::outline3(pen(0), synth::color3(0, [200, 0, 80, 0]), &[])), + ]), + Limits::default(), + ) + .unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + // Ink 0 is black at its tint, ink 1 white, and another number a library ink. + assert_eq!((s[0].fill.clone(), s[1].fill.clone(), s[2].fill.clone()), (Some(Color::Gray(0.4)), Some(Color::Gray(0.0)), None)); + let o = s[0].outline.as_ref().unwrap(); + assert!((o.width - 3.0).abs() < 0.05, "{}", o.width); + assert_eq!((o.cap, o.join, &o.dashes), (Cap::Square, Join::Bevel, &vec![3.0, 1.0])); + assert!(s[1].outline.is_none()); + assert_eq!(s[2].outline.as_ref().unwrap().color, Color::Spot { name: "Spot 0:200".into(), tint: 0.8, look: None }); + assert_eq!(d.warnings, vec![Warning::SpotLooks]); + // Fountain, texture and pattern fills are named and leave the shape unfilled; a fill or an + // outline cut short is damage. + for kind in [2, 4, 6, 7, 10] { + let d = read(&drawing3(vec![styled(synth::fill3(kind, &[0; 12]), synth::outline3(pen(1), black, &[]))]), Limits::default()).unwrap(); + assert_eq!(d.warnings, vec![Warning::UnsupportedFills], "{kind}"); + assert!(shapes(&d.pages[0].layers[0].objects)[0].fill.is_none()); + } + let d = read(&drawing3(vec![styled(vec![1, 1], vec![1, 0])]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s[0].fill.is_none() && s[0].outline.is_none()); + assert_eq!(d.warnings, vec![Warning::Damaged]); +} + +#[test] +fn version_3_dashes_count_toward_the_dash_limit() { + let v = V(300); + let pen = synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }; + let dashed = + || synth::object(v, 1, &[(10, synth::outline3(pen, synth::color3(1, [0, 0, 0, 100]), &[2, 2, 2])), (30, v.rect(10.0, 10.0, 0.0))], None); + let d = read(&drawing3(vec![dashed(), dashed()]), Limits { dashes: 4, ..Limits::default() }).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!((s[0].outline.as_ref().unwrap().dashes.len(), s[1].outline.as_ref().unwrap().dashes.len()), (3, 0)); + assert_eq!(d.warnings, vec![Warning::TooDeep]); +} + +#[test] +fn hostile_version_3_transforms_are_damage() { + let v = V(300); + let with = |arg: Vec| synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0)), (100, arg)], None); + // A matrix whose data offset lies past the argument, and an argument cut inside its header. + let mut past = synth::transforms3(&[[1.0, 0.0, 0.0, 1.0, 5.0, 5.0]]); + past[10..12].copy_from_slice(&60000u16.to_le_bytes()); + for arg in [past, vec![0, 0, 9]] { + let d = read(&drawing3(vec![with(arg)]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].matrix, Matrix::IDENTITY); + assert_eq!(d.warnings, vec![Warning::Damaged]); + } + // A count of 65,535 over one entry reads that entry. + let mut many = synth::transforms3(&[[1.0, 0.0, 0.0, 1.0, 72.0, 0.0]]); + many[2..4].copy_from_slice(&u16::MAX.to_le_bytes()); + let d = read(&drawing3(vec![with(many)]), Limits::default()).unwrap(); + assert!((shapes(&d.pages[0].layers[0].objects)[0].matrix.0[4] - 72.0).abs() < 0.01); + assert_eq!(d.warnings, vec![Warning::Damaged]); +} + +#[test] +fn version_4_transforms_are_fixed_point_and_compose_in_file_order() { + let v = V(400); + let own = vec![ + chunk(b"loda", v.loda(1, &[(30, v.rect(10.0, 10.0, 0.0))])), + list(b"trfl", vec![chunk(b"trfd", v.trfd(&[[1.0, 0.0, 0.0, 1.0, 72.0, 0.0], [0.0, 2.0, -2.0, 0.0, 0.0, 0.0]]))]), + ]; + let object = list(b"obj ", vec![list(b"lgob", own)]); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object])]); + let d = read(&synth::riff(400, &[chunk(b"vrsn", 400u16.to_le_bytes().to_vec()), page]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + // Moved 72 pt right, then turned a quarter and doubled: (0, 0) lands at (0, 144). + let m = shapes(&d.pages[0].layers[0].objects)[0].matrix; + assert!(m.0.iter().zip([0.0, 2.0, -2.0, 0.0, 0.0, 144.0]).all(|(a, b)| (a - b).abs() < 0.01), "{m:?}"); +} + +#[test] +fn version_4_colors_are_words() { + let v = V(400); + let file = |fill: [u8; 12]| { + let doc = list(b"doc ", vec![list(b"filt", vec![chunk(b"fill", v.fill(1, &fill))])]); + let rect = synth::object(v, 1, &[(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect])]); + synth::riff(400, &[chunk(b"vrsn", 400u16.to_le_bytes().to_vec()), doc, page]) + }; + let fill_of = |fill: [u8; 12]| { + let d = read(&file(fill), Limits::default()).unwrap(); + (shapes(&d.pages[0].layers[0].objects)[0].fill.clone(), d.warnings) + }; + assert_eq!(fill_of(synth::color4(1, [20, 40, 60, 80])), (Some(Color::Cmyk([0.2, 0.4, 0.6, 0.8])), vec![])); + assert_eq!(fill_of(synth::color4(0, [0, 30, 0, 0])), (Some(Color::Gray(0.3)), vec![])); + assert_eq!(fill_of(synth::color4(0, [1, 30, 0, 0])), (Some(Color::Gray(0.0)), vec![])); + assert_eq!( + fill_of(synth::color4(0, [513, 30, 0, 0])), + (Some(Color::Spot { name: "Spot 0:513".into(), tint: 0.3, look: None }), vec![Warning::SpotLooks]) + ); + // The version 5 record read in the version 4 layout would take these values from other bytes. + assert_ne!(fill_of(synth::color(2, [20, 40, 60, 80])).0, Some(Color::Cmyk([0.2, 0.4, 0.6, 0.8]))); +} + +#[test] +fn the_version_3_page_size_is_the_distance_between_its_corners() { + let v = V(300); + for corners in [[-306.0, 396.0, 306.0, -396.0], [306.0, -396.0, -306.0, 396.0]] { + let mut b = vec![0xff; 2]; + b.extend(corners.iter().flat_map(|c| v.coord(*c))); + let d = read(&synth::riff(300, &[list(b"doc ", vec![chunk(b"mcfg", b)])]), Limits::default()).unwrap(); + let (w, h) = d.page_size.unwrap(); + assert!((w - 612.0).abs() < 0.1 && (h - 792.0).abs() < 0.1, "{w} {h}"); + } + // Corners that give no width, and a chunk cut inside them, give no page size. + let mut flat = vec![0; 2]; + flat.extend([v.coord(10.0), v.coord(5.0), v.coord(10.0), v.coord(-5.0)].concat()); + for b in [flat.clone(), flat[..9].to_vec()] { + assert_eq!(read(&synth::riff(300, &[list(b"doc ", vec![chunk(b"mcfg", b)])]), Limits::default()).unwrap().page_size, None); + } +} + +#[test] +fn a_point_list_before_version_6_counts_its_points_with_a_u16() { + for version in [300, 400, 500] { + let v = V(version); + let mut points = v.points(&[(0.0, 0.0, 0x00), (10.0, 0.0, 0x40), (10.0, 10.0, 0x40)]); + // The u16 after the count is 1 in some curves; as part of a u32 count it would run the + // count past the points. + points[2] = 1; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 3, &[(30, points)], None)])]); + let d = read(&synth::riff(version, &[chunk(b"vrsn", version.to_le_bytes().to_vec()), page]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(matches!(&s[0].geometry, Geometry::Path(p) if p.subpaths[0].segments.len() == 2), "{version}"); + } +} + +/// The objects of the one layer of a version 1 or 2 drawing. +fn wl_objects(d: &vectorcraft_cdr::Drawing) -> &[Object] { + assert_eq!((d.pages.len(), d.pages[0].layers.len(), d.master.len(), d.guides.len()), (1, 1, 0, 0)); + &d.pages[0].layers[0].objects +} + +#[test] +fn versions_1_and_2_read_their_sample() { + for (marker, version) in [(b'e', 100), (b'd', 100), (b'm', 200)] { + let file = synth::wl_sample(marker); + assert!(file.starts_with(b"WL") && vectorcraft_cdr::is_cdr(&file)); + let d = read(&file, Limits::default()).unwrap(); + assert_eq!(d.version, version); + let (w, h) = d.page_size.unwrap(); + assert!((w - 612.0).abs() < 0.1 && (h - 792.0).abs() < 0.1, "{w} {h}"); + // The text is left out, and the group record holds nothing. + assert_eq!(d.warnings, vec![Warning::UnsupportedObjects]); + let s = shapes(wl_objects(&d)); + assert_eq!(s.len(), 3); + // Front to back: the rounded rectangle, the ellipse, the curve. + assert!( + matches!(s[0].geometry, Geometry::Rect { w, h, radii } if (w - 100.0).abs() < 0.1 && (h - 50.0).abs() < 0.1 && radii.iter().all(|r| (r - 5.0).abs() < 0.1)) + ); + assert_eq!(s[0].fill, Some(Color::Cmyk([0.0, 1.0, 1.0, 0.0]))); + let o = s[0].outline.as_ref().unwrap(); + assert!((o.width - 2.0).abs() < 0.05, "{}", o.width); + assert_eq!((&o.color, o.cap, o.join, o.dashes.len()), (&Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Cap::Butt, Join::Miter, 0)); + assert!((s[0].matrix.0[4] + 100.0).abs() < 0.1 && (s[0].matrix.0[5] - 100.0).abs() < 0.1, "{:?}", s[0].matrix); + assert!(matches!(s[1].geometry, Geometry::Ellipse { w, h } if (w - 40.0).abs() < 0.1 && (h + 40.0).abs() < 0.1)); + assert!(s[1].outline.is_none() && (s[1].matrix.0[4] - 50.0).abs() < 0.1 && (s[1].matrix.0[5] + 50.0).abs() < 0.1); + assert!(matches!(&s[2].geometry, Geometry::Path(p) if p.subpaths[0].closed && matches!(p.subpaths[0].segments[1], Segment::Cubic(..)))); + assert!(s[2].fill.is_none() && s[2].outline.is_some()); + assert_eq!(&s[2].matrix.0[..4], &[2.0, 0.0, 0.0, 2.0]); + } +} + +#[test] +fn a_version_1_matrix_and_point_place_the_shape() { + use synth::WlShape; + // x' = 0 x - 1 y + 72 and y' = 1 x + 0 y + 36: a quarter turn, then a shift. + let turned = synth::wl_object(WlShape::Rect { w: 10.0, h: 10.0, radius: 0.0 }, [0.0, 1.0, -1.0, 0.0, 72.0, 36.0], None, None); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[turned]), Limits::default()).unwrap(); + let m = shapes(wl_objects(&d))[0].matrix; + assert!(m.0.iter().zip([0.0, 1.0, -1.0, 0.0, 72.0, 36.0]).all(|(a, b)| (a - b).abs() < 0.01), "{m:?}"); + let at = m.apply(vectorcraft_cdr::model::Pt { x: 10.0, y: 0.0 }); + assert!((at.x - 72.0).abs() < 0.01 && (at.y - 46.0).abs() < 0.01, "{at:?}"); +} + +#[test] +fn version_1_arcs_and_text_are_left_out_with_a_warning() { + use synth::WlShape; + let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + let arc = synth::wl_object(WlShape::Ellipse { w: 40.0, h: 40.0, angles: (0, 900) }, unit, None, None); + let whole = synth::wl_object(WlShape::Ellipse { w: 40.0, h: 40.0, angles: (900, 900) }, unit, None, None); + let mut other = synth::wl_object(WlShape::Text, unit, None, None); + other[60] = 9; + for (records, kept) in [(vec![arc], 0), (vec![whole], 1), (vec![synth::wl_object(WlShape::Text, unit, None, None)], 0), (vec![other], 0)] { + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &records), Limits::default()).unwrap(); + assert_eq!(wl_objects(&d).len(), kept); + assert_eq!(d.warnings.contains(&Warning::UnsupportedObjects), kept == 0); + assert!(!d.warnings.contains(&Warning::Damaged)); + } +} + +#[test] +fn hostile_version_1_files_stop_within_their_bytes_and_limits() { + use synth::WlShape; + let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + let rect = || synth::wl_object(WlShape::Rect { w: 10.0, h: 10.0, radius: 0.0 }, unit, None, None); + let file = synth::wl_sample(b'e'); + // Cut at every length: an error, or what the bytes still hold. + for len in 0..file.len() { + let _ = read(&file[..len], Limits::default()); + } + // A body size that runs past the records' end. + let mut long = rect(); + long[28..30].copy_from_slice(&u16::MAX.to_le_bytes()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect(), long]), Limits::default()).unwrap(); + assert_eq!((wl_objects(&d).len(), d.warnings.clone()), (1, vec![Warning::Damaged])); + // A point count larger than the record holds reads the points that fit. + let mut curve = synth::wl_object(WlShape::Curve(vec![(0.0, 0.0, 0x00), (10.0, 0.0, 0x40), (10.0, 10.0, 0x40)]), unit, None, None); + curve[114..116].copy_from_slice(&u16::MAX.to_le_bytes()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[curve.clone()]), Limits::default()).unwrap(); + assert_eq!((wl_objects(&d).len(), d.warnings.clone()), (1, vec![Warning::Damaged])); + // Points past the coordinate limit leave the curve out. + curve[114..116].copy_from_slice(&3u16.to_le_bytes()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[curve]), Limits { coordinates: 2, ..Limits::default() }).unwrap(); + assert_eq!(wl_objects(&d).len(), 0); + assert!(d.warnings.contains(&Warning::TooDeep)); + // Objects past the object limit are left out, and records past the chunk limit stop the read. + let many: Vec> = (0..10).map(|_| rect()).collect(); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &many), Limits { objects: 4, ..Limits::default() }).unwrap(); + assert_eq!((wl_objects(&d).len(), d.warnings.clone()), (4, vec![Warning::TooDeep])); + let groups: Vec> = (0..10).map(|_| synth::wl_group()).collect(); + assert_eq!(read(&synth::wl_file(b'e', (612.0, 792.0), &groups), Limits { chunks: 4, ..Limits::default() }), Err(Error::Limit("chunk count"))); + assert_eq!(read(&file, Limits { input: file.len() - 1, ..Limits::default() }), Err(Error::Limit("input size"))); + // Bytes left after the last whole record are damage. + let mut ragged = vec![rect()]; + ragged.push(vec![0; 5]); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &ragged), Limits::default()).unwrap(); + assert_eq!((wl_objects(&d).len(), d.warnings.clone()), (1, vec![Warning::Damaged])); +} + +#[test] +fn a_wl_prefix_alone_is_not_a_drawing() { + for bytes in [ + &b"WL"[..], + b"WLe\0", + b"WLAN settings, exported as plain text for the help desk", + // Records that start inside the header, and a marker and a fourth byte no source gives. + b"WLe\0\x1c\0\0\0\x10\0\0\0\x1c\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", + b"WLAN\x1c\0\0\0\x1c\0\0\0\x1c\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", + ] { + assert!(!vectorcraft_cdr::is_cdr(bytes)); + assert_eq!(read(bytes, Limits::default()), Err(Error::NotCdr)); + } +} + +#[test] +fn versions_outside_1_to_27_and_other_files_are_refused() { + // No source shows a RIFF file of version 1 or 2: those versions are `WL` files. + for version in [100, 200] { + let refused = read(&synth::riff(version, &[]), Limits::default()).unwrap_err(); + assert_eq!(refused, Error::Unsupported("RIFF files of versions before 3"), "{version}"); + assert_eq!(refused.to_string(), "RIFF files of versions before 3 are not read"); + } + assert_eq!(read(&synth::riff(2800, &[]), Limits::default()), Err(Error::Version(2800))); + assert_eq!(read(b"RIFF\x04\0\0\0WAVE", Limits::default()), Err(Error::NotCdr)); + assert_eq!(read(b"RIFF\x04\0\0\0CDRX", Limits::default()), Err(Error::NotCdr)); + assert!(!vectorcraft_cdr::is_cdr(b"PK\x03\x04")); + assert!(vectorcraft_cdr::is_cdr(&synth::sample(1100, true))); +} + +#[test] +fn letters_that_count_differently_take_the_vrsn_version() { + // Version 27 saves the letter `U`, which counts as 29 the older way; the next letter with a + // `vrsn` of 2800 is refused as version 28. + let mut file = synth::sample(2700, false); + file[11] = b'U'; + let d = read(&file, Limits::default()).unwrap(); + check_pages(&d, 2700); + check_shapes(&d, 2700); + let mut file = synth::riff(2800, &[chunk(b"vrsn", 2800u16.to_le_bytes().to_vec())]); + file[11] = b'V'; + assert_eq!(read(&file, Limits::default()), Err(Error::Version(2800))); +} + +#[test] +fn every_version_from_14_to_27_reads_its_package() { + for version in [1400, 1500, 1600, 1700, 1800, 2000, 2200, 2400, 2430, 2600, 2700] { + for compress in [false, true] { + let file = synth::sample_file(version, compress); + assert!(file.starts_with(b"PK\x03\x04") && vectorcraft_cdr::is_cdr(&file), "{version}"); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version} {compress}: {e}")); + assert!(!d.warnings.contains(&Warning::Damaged), "{version} {compress}: {:?}", d.warnings); + check_pages(&d, version); + check_shapes(&d, version); + } + } +} + +/// The version 17 sample's content with `extra` added after it, as a package. +fn package17(extra: Vec, members: &[synth::Member]) -> Vec { + let mut body = vec![chunk(b"vrsn", 1700u16.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(1700)); + body.extend(extra); + synth::package16(1700, &body, true, members) +} + +#[test] +fn lists_whose_bodies_move_to_a_data_stream_read_the_same() { + let mut body = vec![chunk(b"vrsn", 1700u16.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(1700)); + for moved in [*b"layr", *b"obj ", *b"page"] { + let file = synth::package16_with(1700, &body, true, &[], &[moved]); + let d = read(&file, Limits::default()).unwrap(); + assert!(!d.warnings.contains(&Warning::Damaged), "{moved:?}: {:?}", d.warnings); + check_pages(&d, 1700); + check_shapes(&d, 1700); + } +} + +#[test] +fn a_data_stream_no_chunk_reads_is_not_inflated() { + // 32 MiB of picture data that the reader doesn't use, in a stream of its own. + let bitmaps = list(b"bmpt", vec![chunk(b"bmp ", vec![0; 32 << 20])]); + let file = package17(vec![bitmaps], &[]); + assert!(file.len() < 1 << 20); + let d = read(&file, Limits { inflated: 4 << 20, ..Limits::default() }).unwrap(); + assert_eq!(d.warnings, vec![Warning::UnsupportedObjects]); + check_shapes(&d, 1700); +} + +#[test] +fn a_redirected_list_is_inflated_and_counts_toward_the_limit() { + // A list whose body is in a stream must be inflated to be split; past the limit it is left + // out with a warning, and the rest of the drawing reads. + let mut body = vec![chunk(b"vrsn", 1700u16.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(1700)); + body.push(list(b"bmpt", vec![chunk(b"bmp ", vec![0; 32 << 20])])); + let file = synth::package16_with(1700, &body, true, &[], &[*b"bmpt"]); + let d = read(&file, Limits { inflated: 4 << 20, ..Limits::default() }).unwrap(); + assert!(d.warnings.contains(&Warning::TooDeep) && !d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + check_shapes(&d, 1700); + let d = read(&file, Limits::default()).unwrap(); + assert!(!d.warnings.contains(&Warning::TooDeep)); +} + +#[test] +fn chunks_in_a_data_stream_past_a_limit_are_not_damage() { + // A record and a list in a 2 MiB stream, read with a 1 MiB member limit, stored and deflated + // with a 1 MiB inflate limit: only the limit warning. + let mcfg = synth::mcfg(V(1700), 300.0, 200.0); + let synth::Node::Chunk(_, mcfg) = mcfg else { panic!() }; + let n = mcfg.len() as u32; + let mut stream = mcfg.clone(); + stream.resize(2 << 20, 0); + stream[(1 << 20)..(1 << 20) + 4].copy_from_slice(b"fntt"); + let mut root = b"RIFF".to_vec(); + let body = doc_of(&[redirect(b"mcfg", 0, n, 0), redirect(b"LIST", 0, 4, 1 << 20)]); + root.extend(((body.len() + 4) as u32).to_le_bytes()); + root.extend(b"CDRH"); + root.extend(body); + let m = |name: &str, data: Vec, deflate: bool| synth::Member { name: name.into(), data, deflate }; + for (deflate, limits) in [(false, Limits { member: 1 << 20, ..Limits::default() }), (true, Limits { inflated: 1 << 20, ..Limits::default() })] { + let file = synth::zip( + &[ + m("content/root.dat", root.clone(), false), + m("content/dataFileList.dat", b"data1.dat".to_vec(), false), + m("content/data/data1.dat", stream.clone(), deflate), + ], + b"", + ); + let d = read(&file, limits).unwrap(); + assert_eq!(d.warnings, vec![Warning::TooDeep], "{deflate}"); + assert!(d.page_size.is_none()); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.page_size.is_some() && d.warnings.is_empty(), "{deflate}: {:?}", d.warnings); + } +} + +#[test] +fn encrypted_data_streams_and_other_methods_are_refused() { + let good = synth::sample_file(1700, false); + assert!(read(&good, Limits::default()).is_ok()); + // The directory entry of a data stream: its name's last place, 46 bytes after the entry start. + let name = b"content/data/data1.dat"; + let entry = good.windows(name.len()).rposition(|w| w == name).unwrap() - 46; + assert_eq!(&good[entry..entry + 4], b"PK\x01\x02"); + let mut encrypted = good.clone(); + encrypted[entry + 8] |= 1; + assert_eq!(read(&encrypted, Limits::default()), Err(Error::Unsupported("encrypted packages"))); + let mut other = good.clone(); + other[entry + 10] = 12; + assert_eq!(read(&other, Limits::default()), Err(Error::Unsupported("package compression methods other than storing and deflate"))); +} + +/// A version 17 package whose `root.dat` is `root` (the RIFF body after the form type) and whose +/// one data stream is `stream`. +fn raw_package(root: &[u8], stream: &[u8], list: &[u8]) -> Vec { + let mut riff = b"RIFF".to_vec(); + riff.extend(((root.len() + 4) as u32).to_le_bytes()); + riff.extend(b"CDRH"); + riff.extend(root); + let m = |name: &str, data: &[u8]| synth::Member { name: name.into(), data: data.to_vec(), deflate: false }; + synth::zip(&[m("content/root.dat", &riff), m("content/dataFileList.dat", list), m("content/data/data1.dat", stream)], b"") +} + +/// A chunk header for a redirect record of `stream`, `len` and `offset`. +fn redirect(id: &[u8; 4], stream: u32, len: u32, offset: u32) -> Vec { + let mut out = id.to_vec(); + out.extend(16u32.to_le_bytes()); + for v in [stream, len, offset, 0] { + out.extend(v.to_le_bytes()); + } + out +} + +#[test] +fn a_list_redirected_into_its_own_bytes_is_read_once() { + // The stream holds a `grp ` body whose children are lists redirected to that body again: + // the bytes are taken, so each child is damage and the list is read once. + for children in [1, 2] { + let len = 4 + 24 * children; + let mut stream = b"grp ".to_vec(); + for _ in 0..children { + stream.extend(redirect(b"LIST", 0, len, 0)); + } + let file = raw_package(&redirect(b"LIST", 0, len, 0), &stream, b"data1.dat"); + let d = read(&file, Limits { chunks: 100, ..Limits::default() }).unwrap(); + assert_eq!(d.warnings, vec![Warning::Damaged], "{children}"); + } +} + +/// A `doc ` list holding `records`, as `root.dat`'s body. +fn doc_of(records: &[Vec]) -> Vec { + let records = records.concat(); + let mut body = b"LIST".to_vec(); + body.extend(((records.len() + 4) as u32).to_le_bytes()); + body.extend(b"doc "); + body.extend(records); + body +} + +#[test] +fn records_share_bytes_within_the_member_limit() { + let mcfg = synth::mcfg(V(1700), 300.0, 200.0); + let synth::Node::Chunk(_, mcfg) = mcfg else { panic!() }; + let n = mcfg.len() as u32; + let mut stream = mcfg.clone(); + stream.extend(&mcfg); + // The same bytes, bytes that overlap them, bytes that only touch them, and the same bytes + // through a second line naming the same member: both redirects read. + for (second, list) in [ + (redirect(b"mcfg", 0, n, 0), &b"data1.dat"[..]), + (redirect(b"mcfg", 0, n, n - 1), b"data1.dat"), + (redirect(b"mcfg", 0, n, n), b"data1.dat"), + (redirect(b"mcfg", 1, n, 0), b"data1.dat\ndata1.dat"), + ] { + let file = raw_package(&doc_of(&[redirect(b"mcfg", 0, n, 0), second.clone()]), &stream, list); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.page_size.is_some() && d.warnings.is_empty(), "{:?}: {:?}", &second[8..], d.warnings); + } + // Bytes read again take from the member limit: with a limit of the stream's 1,024 bytes, a + // record of all of them reads twice, and a third read is left out with the limit warning. + let mut stream = mcfg.clone(); + stream.resize(1024, 0); + let limits = Limits { member: 1024, ..Limits::default() }; + for (reads, warnings) in [(2, vec![]), (3, vec![Warning::TooDeep])] { + let records = vec![redirect(b"mcfg", 0, 1024, 0); reads]; + let d = read(&raw_package(&doc_of(&records), &stream, b"data1.dat"), limits).unwrap(); + assert!(d.page_size.is_some(), "{reads}"); + assert_eq!(d.warnings, warnings, "{reads}"); + } +} + +#[test] +fn a_member_two_streams_name_is_inflated_once() { + // One deflated member of 2 MiB named on two lines, a list read from one and the page size + // from the other: within a 3 MiB inflate limit it is inflated once. + let mcfg = synth::mcfg(V(1700), 300.0, 200.0); + let synth::Node::Chunk(_, mcfg) = mcfg else { panic!() }; + let n = mcfg.len() as u32; + let mut stream = mcfg.clone(); + stream.resize(2 << 20, 0); + stream[(1 << 20)..(1 << 20) + 4].copy_from_slice(b"fntt"); + let mut root = b"RIFF".to_vec(); + let body = doc_of(&[redirect(b"LIST", 1, 4, 1 << 20), redirect(b"mcfg", 0, n, 0)]); + root.extend(((body.len() + 4) as u32).to_le_bytes()); + root.extend(b"CDRH"); + root.extend(body); + let m = |name: &str, data: Vec, deflate: bool| synth::Member { name: name.into(), data, deflate }; + let file = synth::zip( + &[ + m("content/root.dat", root, false), + m("content/dataFileList.dat", b"data1.dat\ndata1.dat".to_vec(), false), + m("content/data/data1.dat", stream, true), + ], + b"", + ); + let d = read(&file, Limits { inflated: 3 << 20, ..Limits::default() }).unwrap(); + assert!(d.page_size.is_some() && d.warnings.is_empty(), "{:?}", d.warnings); +} + +#[test] +fn redirects_past_their_stream_or_to_a_missing_one_are_damage() { + let mcfg = synth::mcfg(V(1700), 300.0, 200.0); + let synth::Node::Chunk(_, mcfg) = mcfg else { panic!() }; + let n = mcfg.len() as u32; + for (root, list, damaged) in [ + (redirect(b"mcfg", 0, n, 0), &b"data1.dat"[..], false), + (redirect(b"mcfg", 0, n, 0), b"data1.dat\r\n", false), + (redirect(b"mcfg", 0, n + 1, 0), b"data1.dat", true), + (redirect(b"mcfg", 0, n, u32::MAX), b"data1.dat", true), + (redirect(b"mcfg", 1, n, 0), b"data1.dat", true), + (redirect(b"mcfg", 0, n, 0), b"gone.dat", true), + (redirect(b"mcfg", 0, n, 0), b"", true), + ] { + let mut body = b"LIST".to_vec(); + body.extend(((root.len() + 4) as u32).to_le_bytes()); + body.extend(b"doc "); + body.extend(&root); + let d = read(&raw_package(&body, &mcfg, list), Limits::default()).unwrap(); + assert_eq!(d.warnings.contains(&Warning::Damaged), damaged, "{list:?} {:?}", &root[8..]); + assert_eq!(d.page_size.is_some(), !damaged); + } +} + +#[test] +fn a_redirect_record_holds_up_to_8_bytes_itself() { + let mut inline = b"vrsn".to_vec(); + inline.extend(16u32.to_le_bytes()); + inline.extend(u32::MAX.to_le_bytes()); + inline.extend(2u32.to_le_bytes()); + inline.extend(1800u16.to_le_bytes()); + inline.extend([0; 6]); + let d = read(&raw_package(&inline, b"", b""), Limits::default()).unwrap(); + assert_eq!(d.version, 1800); + // A length past the record's 8 bytes is damage, and the form type's version stands. + inline[12] = 9; + let d = read(&raw_package(&inline, b"", b""), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged)); + assert_eq!(d.version, 1700); +} + +fn zip_of(members: &[(&str, Vec)]) -> Vec { + let m: Vec<_> = members.iter().map(|(n, d)| synth::Member { name: (*n).into(), data: d.clone(), deflate: false }).collect(); + synth::zip(&m, b"") +} + +/// Where the first central directory entry starts. +fn directory(bytes: &[u8]) -> usize { + bytes.windows(4).position(|w| w == b"PK\x01\x02").unwrap() +} + +#[test] +fn hostile_packages_are_refused() { + let riff = synth::sample(1400, false); + let good = zip_of(&[("content/riffData.cdr", riff.clone())]); + assert!(read(&good, Limits::default()).is_ok()); + // More members than a read takes. + let many: Vec<(String, Vec)> = (0..4097).map(|i| (format!("m{i}"), vec![])).collect(); + let many: Vec<(&str, Vec)> = many.iter().map(|(n, d)| (n.as_str(), d.clone())).collect(); + assert_eq!(read(&zip_of(&many), Limits::default()), Err(Error::Limit("package member count"))); + assert_eq!(read(&zip_of(&many[..4096]), Limits::default()), Err(Error::NotCdr)); + // A member named twice. + let twice = zip_of(&[("content/riffData.cdr", riff.clone()), ("content/riffData.cdr", riff.clone())]); + assert_eq!(read(&twice, Limits::default()), Err(Error::Damaged("package member named twice"))); + // A member whose bytes run into the next member's header. + let two = zip_of(&[("a", vec![1; 10]), ("content/riffData.cdr", riff.clone())]); + let mut overlap = two.clone(); + let at = directory(&two) + 20; + overlap[at..at + 4].copy_from_slice(&20u32.to_le_bytes()); + assert_eq!(read(&overlap, Limits::default()), Err(Error::Damaged("package members overlap"))); + // A central directory cut short, and an archive without its end record. + let mut short = good.clone(); + let n = short.len(); + let len_at = n - 22 + 12; + let len = u32::from_le_bytes(short[len_at..len_at + 4].try_into().unwrap()); + short[len_at..len_at + 4].copy_from_slice(&(len - 10).to_le_bytes()); + assert_eq!(read(&short, Limits::default()), Err(Error::Damaged("package directory"))); + assert_eq!(read(&good[..directory(&good) + 30], Limits::default()), Err(Error::Damaged("package directory"))); + // Encrypted members, ZIP64 fields and archives split across files. + let mut encrypted = good.clone(); + encrypted[directory(&good) + 8] |= 1; + assert_eq!(read(&encrypted, Limits::default()), Err(Error::Unsupported("encrypted packages"))); + let mut zip64 = good.clone(); + zip64[n - 22 + 10..n - 22 + 12].copy_from_slice(&[0xff, 0xff]); + assert_eq!(read(&zip64, Limits::default()), Err(Error::Unsupported("ZIP64 packages"))); + let mut split = good.clone(); + split[n - 22 + 4] = 1; + assert_eq!(read(&split, Limits::default()), Err(Error::Unsupported("packages split across files"))); +} + +#[test] +fn a_package_member_bomb_stops_at_its_stated_size_or_the_limit() { + let riff = synth::sample(1400, false); + let m = synth::Member { name: "content/riffData.cdr".into(), data: riff.clone(), deflate: true }; + let good = synth::zip(std::slice::from_ref(&m), b""); + assert!(read(&good, Limits::default()).is_ok()); + // A member that inflates past the size its entry states stops one byte past it. + let bomb = synth::zip(&[synth::Member { data: [riff.clone(), vec![0; 64 << 20]].concat(), ..m.clone() }], b""); + assert!(bomb.len() < 1 << 20); + let mut lying = bomb.clone(); + let at = directory(&bomb) + 24; + lying[at..at + 4].copy_from_slice(&(riff.len() as u32).to_le_bytes()); + assert_eq!(read(&lying, Limits::default()), Err(Error::Damaged("package member"))); + // One that states more than a member may hold, or than is left to inflate, is not inflated. + assert_eq!(read(&bomb, Limits { member: 1 << 20, ..Limits::default() }), Err(Error::Limit("package member size"))); + assert_eq!(read(&bomb, Limits { inflated: 1 << 20, ..Limits::default() }), Err(Error::Limit("inflated size"))); +} + +#[test] +fn stored_package_members_take_nothing_from_the_inflate_limit() { + // Nothing may be inflated, and the stored members of either package layout still read, as + // the same drawing does as a plain RIFF file. + let none = Limits { inflated: 0, ..Limits::default() }; + assert!(read(&synth::sample(1400, false), none).is_ok()); + for version in [1400, 1700] { + let d = read(&synth::sample_file(version, false), none).unwrap_or_else(|e| panic!("{version}: {e}")); + assert!(d.warnings.iter().all(|w| *w == Warning::UnsupportedObjects), "{version}: {:?}", d.warnings); + check_shapes(&d, version); + } + // Deflated members do take from it. + assert_eq!(read(&synth::sample_file(1400, true), none), Err(Error::Limit("inflated size"))); +} + +#[test] +fn redirect_records_that_lead_nowhere_count_toward_the_chunk_limit() { + // 3,000 redirects to a stream the package lacks: each lost record is counted. + let root: Vec = (0..3000).flat_map(|_| redirect(b"mcfg", 7, 4, 0)).collect(); + let file = raw_package(&root, b"", b"data1.dat"); + assert_eq!(read(&file, Limits { chunks: 2_000, ..Limits::default() }), Err(Error::Limit("chunk count"))); + let d = read(&file, Limits { chunks: 4_000, ..Limits::default() }).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); +} + +#[test] +fn rectangles_from_version_15_give_radii_as_shares_of_half_the_shorter_side() { + let v = V(1500); + let mut c = synth::V(1500).rect(100.0, 50.0, 0.0); + // The four shares: 0.2, 0.4, 0, and 3, which the shorter side holds to 50 pt. + for (k, share) in [0.2f64, 0.4, 0.0, 3.0].iter().enumerate() { + let at = 40 + 24 * k; + c[at..at + 8].copy_from_slice(&share.to_le_bytes()); + } + let file = + synth::riff(1500, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c.clone())], None)])])]); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Geometry::Rect { w, h, radii } = s[0].geometry else { panic!("{:?}", s[0].geometry) }; + assert!((w - 100.0).abs() < 1e-6 && (h - 50.0).abs() < 1e-6); + for (got, want) in radii.iter().zip([5.0, 10.0, 0.0, 50.0]) { + assert!((got - want).abs() < 1e-6, "{radii:?}"); + } + // With the scale-with flag set the radii are inches, held to the shorter side as well. + c[32] = 1; + let file = synth::riff(1500, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c)], None)])])]); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Geometry::Rect { radii, .. } = s[0].geometry else { panic!("{:?}", s[0].geometry) }; + for (got, want) in radii.iter().zip([14.4, 28.8, 0.0, 50.0]) { + assert!((got - want).abs() < 1e-6, "{radii:?}"); + } +} + +#[test] +fn paths_of_version_16_read_their_points() { + let v = V(1700); + let mut c = vec![0; 4]; + c.extend(2u16.to_le_bytes()); + c.extend(1u16.to_le_bytes()); + c.extend([0; 16]); + c.extend(&v.points(&[(0.0, 0.0, 0x08), (50.0, 0.0, 0x40), (50.0, 20.0, 0x48)])[4..]); + let objects = |version: u16| { + let v = V(version); + synth::riff( + version, + &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 0x25, &[(30, c.clone())], None)])])], + ) + }; + let d = read(&objects(1700), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Geometry::Path(p) = &s[0].geometry else { panic!("{:?}", s[0].geometry) }; + assert_eq!(p.subpaths[0].segments.len(), 2); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + // Before 16 the type is not a path. + let d = read(&objects(1500), Limits::default()).unwrap(); + assert!(d.pages[0].layers[0].objects.is_empty() && d.warnings.contains(&Warning::UnsupportedObjects)); +} + +#[test] +fn a_template_takes_its_version_from_the_vrsn_chunk() { + let mut file = synth::sample(2100, false); + file[8..12].copy_from_slice(b"CDTQ"); + assert!(vectorcraft_cdr::is_cdr(&file)); + let d = read(&file, Limits::default()).unwrap(); + assert_eq!(d.version, 2100); + check_shapes(&d, 2100); + let mut bare = synth::riff(2100, &[]); + bare[8..12].copy_from_slice(b"CDTQ"); + assert_eq!(read(&bare, Limits::default()), Err(Error::NotCdr)); + // A template of a version after 27 is refused by its version, and one before 3 as a RIFF + // file of those versions. + for (version, refused) in [(2800u16, Error::Version(2800)), (200, Error::Unsupported("RIFF files of versions before 3"))] { + let mut t = synth::riff(2100, &[chunk(b"vrsn", version.to_le_bytes().to_vec())]); + t[8..12].copy_from_slice(b"CDTQ"); + assert_eq!(read(&t, Limits::default()), Err(refused)); + } +} + +#[test] +fn master_page_layers_take_their_kind_by_byte_0_from_version_14() { + // Flags that mark the master page's guides and desktop layers in versions 7 to 13 mark + // drawing layers from 14. + for version in [1300, 1700] { + let v = V(version); + let rect = || synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0))], None); + let master = + synth::page(true, vec![synth::layer(v, [2, 1, 1, 0x98], "G", vec![rect()]), synth::layer(v, [0, 1, 1, 0x98], "D", vec![rect()])]); + let own = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect()])]); + let body = [chunk(b"vrsn", version.to_le_bytes().to_vec()), master, own]; + let file = if version < 1400 { synth::riff(version, &body) } else { synth::package16(version, &body, true, &[]) }; + let d = read(&file, Limits::default()).unwrap(); + let kinds: Vec<_> = d.master.iter().map(|l| l.kind).collect(); + let want = if version < 1400 { vec![LayerKind::Guides, LayerKind::Desktop] } else { vec![LayerKind::Drawing, LayerKind::Drawing] }; + assert_eq!(kinds, want, "{version}"); + } +} + +#[test] +fn a_lower_case_form_type_names_the_same_versions() { + let mut file = synth::sample(600, false); + file[8..12].copy_from_slice(b"cdr6"); + // The `vrsn` chunk agrees; without it the form type alone decides. + assert_eq!(read(&file, Limits::default()).unwrap().version, 600); + assert!(vectorcraft_cdr::is_cdr(&file)); + file[8..12].copy_from_slice(b"cdrX"); + assert_eq!(read(&file, Limits::default()), Err(Error::NotCdr)); +} + +#[test] +fn rectangles_keep_four_corner_radii_from_version_9() { + let v = V(900); + let c = [v.coord(100.0), v.coord(50.0), v.coord(1.0), v.coord(2.0), v.coord(3.0), v.coord(4.0)].concat(); + let file = synth::riff(900, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c)], None)])])]); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Geometry::Rect { radii, .. } = s[0].geometry else { panic!("{:?}", s[0].geometry) }; + for (got, want) in radii.iter().zip([1.0, 2.0, 3.0, 4.0]) { + assert!((got - want).abs() < 0.01, "{radii:?}"); + } + // Before version 9 one radius rounds every corner. + let v = V(800); + let c = [v.coord(100.0), v.coord(50.0), v.coord(6.0)].concat(); + let file = synth::riff(800, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c)], None)])])]); + let s = read(&file, Limits::default()).unwrap(); + let s = shapes(&s.pages[0].layers[0].objects); + assert!(matches!(s[0].geometry, Geometry::Rect { radii, .. } if radii.iter().all(|r| (r - 6.0).abs() < 0.01))); +} + +#[test] +fn version_7_guidelines_count_toward_the_object_limit() { + let v = V(700); + let mut guid = 1000u32.to_le_bytes().to_vec(); + guid.extend(1000u32.to_le_bytes()); + for i in 0..1000 { + guid.extend([0; 12]); + guid.extend(90_000_000i32.to_le_bytes()); + guid.extend([v.coord(f64::from(i)), v.coord(0.0), v.coord(f64::from(i)), v.coord(1.0), v.coord(f64::from(i)), v.coord(0.0)].concat()); + } + let file = synth::riff(700, &[chunk(b"vrsn", 700u16.to_le_bytes().to_vec()), list(b"doc ", vec![chunk(b"guid", guid)])]); + let d = read(&file, Limits::default()).unwrap(); + assert_eq!(d.guides.len(), 1000); + let d = read(&file, Limits { objects: 10, ..Limits::default() }).unwrap(); + assert_eq!(d.guides.len(), 10); + assert!(d.warnings.contains(&Warning::TooDeep)); +} + +/// Guidelines on any layer of the master page show on every page, not only those of its guides +/// layer: one on a drawing layer that also holds art, and one alone on the desktop layer. +#[test] +fn master_guidelines_on_any_layer_show_on_every_page() { + let v = V(1100); + let guide = |x: f64| { + let mut g = vec![0; 12]; + g.extend(90_000_000i32.to_le_bytes()); + g.extend([v.coord(x), v.coord(0.0)].concat()); + synth::object(v, 0x16, &[(16000, g)], None) + }; + let rect = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let master = synth::page( + true, + vec![synth::layer(v, [0, 0, 1, 0x98], "Art", vec![guide(10.0), rect]), synth::layer(v, [0x08, 0, 1, 0x98], "Desktop", vec![guide(20.0)])], + ); + let file = synth::riff(1100, &[master, synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "Art", vec![])])]); + let d = read(&file, Limits::default()).unwrap(); + let mut xs: Vec = d.guides.iter().map(|g| g.at.x).collect(); + xs.sort_by(f64::total_cmp); + assert_eq!(xs.len(), 2, "{:?}", d.guides); + assert!((xs[0] - 10.0).abs() < 0.01 && (xs[1] - 20.0).abs() < 0.01, "{xs:?}"); + assert_eq!(d.master.len(), 1); + assert_eq!(d.master[0].objects.len(), 1); +} + +/// An object with more arguments than the limit keeps the ones read paired with their own types: +/// the types table runs from the stored count, not from the limit. +#[test] +fn arguments_past_the_limit_leave_the_first_ones_paired_with_their_types() { + let v = V(1100); + let mut args = vec![(30, [v.coord(40.0), v.coord(20.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())]; + args.extend((0..69).map(|i| (500 + i, vec![0; 4]))); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &args, None)])])]); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert!( + matches!(s.first().map(|s| &s.geometry), Some(Geometry::Rect { w, h, .. }) if (w - 40.0).abs() < 0.01 && (h - 20.0).abs() < 0.01), + "{s:?}" + ); + assert!(d.warnings.contains(&Warning::Damaged)); +} + +/// Groups count toward the object limit; a group past it leaves its objects ungrouped. +#[test] +fn groups_count_toward_the_object_limit() { + fn count(objects: &[Object]) -> usize { + objects.iter().map(|o| 1 + if let Object::Group(kids) = o { count(kids) } else { 0 }).sum() + } + let v = V(1100); + let rect = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let nested = list(b"grp ", vec![list(b"grp ", vec![rect])]); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![nested])])]); + let d = read(&file, Limits { objects: 2, ..Limits::default() }).unwrap(); + let objects = &d.pages[0].layers[0].objects; + assert_eq!(count(objects), 2, "{objects:?}"); + assert!(matches!(objects.as_slice(), [Object::Group(kids)] if matches!(kids.as_slice(), [Object::Shape(_)])), "{objects:?}"); + assert!(d.warnings.contains(&Warning::TooDeep)); +} + +/// A rectangle, ellipse, curve or polygon stored without its coordinates is left out as damage. +#[test] +fn shapes_without_their_coordinates_are_damage() { + let v = V(1100); + for kind in [1, 2, 3, 0x14] { + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, kind, &[], None)])])]); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.pages[0].layers[0].objects.is_empty(), "{kind}"); + assert!(d.warnings.contains(&Warning::Damaged), "{kind}: {:?}", d.warnings); + } +} + +/// An object list without its `loda`, a fill or outline record that can't be read, and a `guid` +/// chunk that counts more guidelines than it holds are each damage. +#[test] +fn unreadable_records_and_lists_are_damage() { + let v = V(1300); + let rect = |args: Vec<(u32, Vec)>| { + let mut args = args; + args.push((30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())); + synth::object(v, 1, &args, None) + }; + let on_page = |objects: Vec, styles: Vec| { + let mut kids = vec![chunk(b"vrsn", 1300u16.to_le_bytes().to_vec())]; + kids.extend(styles); + kids.push(synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)])); + read(&synth::riff(1300, &kids), Limits::default()).unwrap() + }; + let d = on_page(vec![list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 0x08])])], vec![]); + assert!(d.warnings.contains(&Warning::Damaged), "no loda: {:?}", d.warnings); + // A fill record of only its id. + let d = on_page(vec![rect(vec![(20, 4u32.to_le_bytes().to_vec())])], vec![list(b"filt", vec![chunk(b"fild", 4u32.to_le_bytes().to_vec())])]); + assert_eq!(shapes(&d.pages[0].layers[0].objects)[0].fill, None); + assert!(d.warnings.contains(&Warning::Damaged), "fill: {:?}", d.warnings); + // A tagged outline whose first records are none of record 1. + let mut outl = 9u32.to_le_bytes().to_vec(); + for _ in 0..16 { + outl.extend(5u32.to_le_bytes()); + outl.extend(0u32.to_le_bytes()); + } + let d = on_page(vec![rect(vec![(10, 9u32.to_le_bytes().to_vec())])], vec![list(b"otlt", vec![chunk(b"outl", outl)])]); + assert!(shapes(&d.pages[0].layers[0].objects)[0].outline.is_none()); + assert!(d.warnings.contains(&Warning::Damaged), "outline: {:?}", d.warnings); + // Version 7: a `guid` chunk counting three guidelines and holding one. + let mut guid = 3u32.to_le_bytes().to_vec(); + guid.extend(3u32.to_le_bytes()); + guid.extend([0; 40]); + let d = read(&synth::riff(700, &[chunk(b"vrsn", 700u16.to_le_bytes().to_vec()), list(b"doc ", vec![chunk(b"guid", guid)])]), Limits::default()) + .unwrap(); + assert_eq!(d.guides.len(), 1); + assert!(d.warnings.contains(&Warning::Damaged), "guid: {:?}", d.warnings); +} + +/// Pages keep their layers in a `gobj` list, and layers and objects their `loda` (and objects +/// their transform) in a `lgob` list. The layout with those chunks directly in the page, layer and +/// object lists reads the same. +#[test] +fn layers_and_objects_read_from_their_gobj_and_lgob_lists() { + let v = V(1000); + let c = [v.coord(10.0), v.coord(20.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat(); + let m = [1.0, 0.0, 0.0, 1.0, 5.0, 6.0]; + let nested = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c.clone())], Some(m))])]); + let plain_object = list(b"obj ", vec![chunk(b"loda", v.loda(1, &[(30, c)])), list(b"trfl", vec![chunk(b"trfd", v.trfd(&[m]))])]); + let plain_layer = list(b"layr", vec![chunk(b"flgs", vec![0, 0, 0, 0x98]), chunk(b"loda", v.loda(0, &[(1000, b"L\0".to_vec())])), plain_object]); + let plain = list(b"page", vec![chunk(b"flgs", vec![0, 0, 0, 0x90]), plain_layer]); + for page in [nested, plain] { + let d = read(&synth::riff(1000, &[page]), Limits::default()).unwrap(); + let layer = &d.pages[0].layers[0]; + assert_eq!(layer.name, "L"); + let s = shapes(&layer.objects); + assert_eq!(s.len(), 1, "{:?}", layer.objects); + assert!(matches!(s[0].geometry, Geometry::Rect { w, .. } if (w - 10.0).abs() < 0.01)); + assert!((s[0].matrix.0[4] - 5.0).abs() < 0.01 && (s[0].matrix.0[5] - 6.0).abs() < 0.01, "{:?}", s[0].matrix); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + } +} + +/// From version 7 a `LIST stlt` holds the style tables, which don't parse as chunks: it is not +/// damage. +#[test] +fn a_style_table_list_is_not_read_as_chunks() { + let v = V(1000); + let stlt = chunk(b"LIST", [b"stlt".to_vec(), 3u32.to_le_bytes().to_vec(), vec![0xff; 30]].concat()); + let d = read(&synth::riff(1000, &[list(b"doc ", vec![stlt, synth::mcfg(v, 100.0, 50.0)])]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert!(d.page_size.is_some_and(|(w, h)| (w - 100.0).abs() < 0.01 && (h - 50.0).abs() < 0.01)); +} + +#[test] +fn linked_groups_are_left_out_with_a_warning() { + let v = V(1100); + let rect = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![list(b"lnkg", vec![rect])])])]); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.pages[0].layers[0].objects.is_empty()); + assert!(d.warnings.contains(&Warning::UnsupportedObjects)); +} + +#[test] +fn a_file_cut_short_keeps_what_it_holds() { + let full = synth::sample(900, false); + let cut = &full[..full.len() - 40]; + let d = read(cut, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged)); +} + +#[test] +fn a_riff_length_shorter_than_the_form_type_is_damage() { + for declared in 0u32..4 { + let mut file = synth::sample(900, false); + file[4..8].copy_from_slice(&declared.to_le_bytes()); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{declared}"); + check_shapes(&d, 900); + } +} + +#[test] +fn a_zip_bomb_stops_at_the_inflate_limit() { + let v = V(1100); + let big = chunk(b"junk", vec![0; 4 << 20]); + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), synth::cmpr(&[big, synth::mcfg(v, 10.0, 10.0)])]); + assert!(file.len() < 64 << 10); + let limits = Limits { inflated: 1 << 20, ..Limits::default() }; + assert_eq!(read(&file, limits), Err(Error::Limit("inflated size"))); +} + +#[test] +fn a_million_empty_chunks_stop_at_the_chunk_limit() { + let kids: Vec<_> = (0..5000).map(|_| chunk(b"junk", vec![])).collect(); + let file = synth::riff(1100, &[list(b"doc ", kids)]); + let limits = Limits { chunks: 1000, ..Limits::default() }; + assert_eq!(read(&file, limits), Err(Error::Limit("chunk count"))); + assert!(read(&file, Limits::default()).is_ok()); +} + +#[test] +fn deep_nesting_is_left_out_with_a_warning() { + let v = V(1100); + let mut inner = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + for _ in 0..300 { + inner = list(b"grp ", vec![inner]); + } + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![inner])])]); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::TooDeep)); +} + +#[test] +fn a_size_pool_index_out_of_range_is_damage() { + // A compressed stream whose one chunk names pool entry 7 of a pool of one. + let mut cmpr = synth::cmpr(&[chunk(b"mcfg", vec![0; 8])]); + if let synth::Node::Chunk(_, body) = &mut cmpr { + // Rebuild the stream with a bad index: the pool keeps its one size. + let mut stream = b"mcfg".to_vec(); + stream.extend(7u32.to_le_bytes()); + stream.extend([0; 8]); + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut e, &stream).unwrap(); + let z = e.finish().unwrap(); + let pool_block = body[4 + 16 + u32::from_le_bytes(body[4..8].try_into().unwrap()) as usize..].to_vec(); + let mut b = b"cmpr".to_vec(); + b.extend(((z.len() + 8) as u32).to_le_bytes()); + b.extend((stream.len() as u32).to_le_bytes()); + b.extend(body[12..20].to_vec()); + b.extend(b"CPng\x01\x00\x04\x00"); + b.extend(z); + b.extend(pool_block); + *body = b; + } + let d = read(&synth::riff(1100, &[cmpr]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); +} + +#[test] +fn backward_and_huge_loda_offsets_do_not_panic() { + let v = V(1100); + let mut loda = v.loda(3, &[(30, v.points(&[(0.0, 0.0, 0), (1.0, 1.0, 0x40)]))]); + // The offsets table now points before the header and far past the end. + let at = u32::from_le_bytes(loda[8..12].try_into().unwrap()) as usize; + loda[at..at + 4].copy_from_slice(&40u32.to_le_bytes()); + loda[at + 4..at + 8].copy_from_slice(&2u32.to_le_bytes()); + let obj = list(b"obj ", vec![chunk(b"loda", loda)]); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![obj])])]); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged)); +} + +#[test] +fn outlines_flagged_none_and_dashes_read() { + let v = V(1300); + let black = synth::color(2, [0, 0, 0, 100]); + let dashed = v.outline(9, synth::Pen { line_type: 4, width: 1.0, cap: 2, join: 2 }, &black, &[3, 1]); + let style = vec![(10, 9u32.to_le_bytes().to_vec()), (30, v.points(&[(0.0, 0.0, 0), (10.0, 0.0, 0x40)]))]; + let file = synth::riff( + 1300, + &[ + chunk(b"vrsn", 1300u16.to_le_bytes().to_vec()), + list(b"otlt", vec![chunk(b"outl", dashed)]), + synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 3, &style, None)])]), + ], + ); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let o = s[0].outline.as_ref().unwrap(); + assert_eq!(o.dashes, vec![3.0, 1.0]); + assert_eq!((o.cap, o.join), (Cap::Square, vectorcraft_cdr::model::Join::Bevel)); +} + +#[test] +fn library_colors_from_version_13_keep_their_names_and_tints() { + // A model 21 color (blue, green, red, tint) shown at 50 %, and its library name. + let shown = synth::color(21, [255, 191, 128, 50]); + let mut props = vec![1]; + props.extend(12u32.to_le_bytes()); + props.extend(shown); + props.push(8); + let name: Vec = "Sky Blue".encode_utf16().flat_map(|u| u.to_le_bytes()).collect(); + props.extend((16 + 4 + name.len() as u32).to_le_bytes()); + props.extend([0; 16]); + props.extend(8u32.to_le_bytes()); + props.extend(name); + props.extend([0, 0, 0, 0, 0]); + let mut solid = 1300u32.to_le_bytes().to_vec(); + solid.extend((props.len() as u32).to_le_bytes()); + solid.extend(props); + let mut body = 1u16.to_le_bytes().to_vec(); + body.extend(solid); + let mut fill = 4u32.to_le_bytes().to_vec(); + // A record of a later layout first, which the reader steps over. + fill.extend(2400u32.to_le_bytes()); + fill.extend(16u32.to_le_bytes()); + fill.extend([0; 16]); + fill.extend(1300u32.to_le_bytes()); + fill.extend((body.len() as u32).to_le_bytes()); + fill.extend(body); + // The same records in a plain file of version 13 and the packages of later versions. + for version in [1300, 1400, 1700, 2700] { + let v = V(version); + let style = vec![(20, 4u32.to_le_bytes().to_vec()), (30, v.rect(1.0, 1.0, 0.0))]; + let body = [ + chunk(b"vrsn", version.to_le_bytes().to_vec()), + list(b"filt", vec![chunk(b"fild", fill.clone())]), + synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &style, None)])]), + ]; + let file = match version { + ..1400 => synth::riff(version, &body), + 1400..1600 => synth::package14(synth::riff(version, &body), true), + _ => synth::package16(version, &body, true, &[]), + }; + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Some(Color::Spot { name, tint, look: Some(look) }) = &s[0].fill else { panic!("{version}: {:?}", s[0].fill) }; + assert_eq!((name.as_str(), *tint), ("Sky Blue", 0.5)); + // 128/255 shown at half strength comes from about 1/255 at full strength. + assert!(look[0] < 0.01 && (look[2] - 1.0).abs() < 1e-6, "{version}: {look:?}"); + } +} + +/// One rectangle of version `v` that uses fill `fill` and outline `outline` (0: none). +fn styled_rect(v: V, fill: u32, outline: u32) -> synth::Node { + let mut args = vec![(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())]; + if fill != 0 { + args.push((20, fill.to_le_bytes().to_vec())); + } + if outline != 0 { + args.push((10, outline.to_le_bytes().to_vec())); + } + synth::object(v, 1, &args, None) +} + +/// A drawing of version `v` with `styles` in its `doc` list and `objects` on one page. +fn styled_drawing(v: V, styles: Vec, objects: Vec) -> Vec { + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)]); + synth::riff(v.0, &[chunk(b"vrsn", v.0.to_le_bytes().to_vec()), list(b"doc ", styles), page]) +} + +/// An outline's dashes count toward the read's dashes for every shape that uses it: one outline +/// of 65,535 dashes on 260 shapes would copy 17 million dashes, past the default limit. +#[test] +fn a_shared_dashed_outline_counts_its_dashes_for_every_shape() { + let v = V(1300); + let pen = synth::Pen { line_type: 4, width: 1.0, cap: 0, join: 0 }; + let outl = |dashes: &[u16]| list(b"otlt", vec![chunk(b"outl", v.outline(9, pen, &synth::color(2, [0, 0, 0, 100]), dashes))]); + let file = styled_drawing(v, vec![outl(&[2, 1].repeat(10))], (0..20).map(|_| styled_rect(v, 0, 9)).collect()); + let d = read(&file, Limits { dashes: 100, ..Limits::default() }).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 20); + let dashed = s.iter().filter(|s| s.outline.as_ref().is_some_and(|o| o.dashes.len() == 20)).count(); + assert_eq!(dashed, 5, "100 dashes hold five outlines of 20"); + assert!(s.iter().all(|s| s.outline.as_ref().is_some_and(|o| o.dashes.is_empty() || o.dashes.len() == 20))); + assert!(d.warnings.contains(&Warning::TooDeep), "{:?}", d.warnings); + // An outline with more dashes than the limit is solid, not cut short. + let file = styled_drawing(v, vec![outl(&[2, 1])], vec![styled_rect(v, 0, 9)]); + let d = read(&file, Limits { dashes: 1, ..Limits::default() }).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s[0].outline.as_ref().is_some_and(|o| o.dashes.is_empty()), "{:?}", s[0].outline); + assert_eq!(d.warnings, vec![Warning::TooDeep]); + // At the default limit. + let file = styled_drawing(v, vec![outl(&[1; 65_535])], (0..260).map(|_| styled_rect(v, 0, 9)).collect()); + assert!(file.len() < 256 << 10); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let total: usize = s.iter().filter_map(|s| s.outline.as_ref()).map(|o| o.dashes.len()).sum(); + assert!(total <= Limits::default().dashes, "{total}"); + assert!(d.warnings.contains(&Warning::TooDeep), "{:?}", d.warnings); +} + +/// A library color's name is copied for every shape that uses it: a long one keeps its first 256 +/// units and a hash of the whole name. +#[test] +fn a_library_color_keeps_the_first_256_units_of_its_name() { + let v = V(1300); + let mut props = vec![1]; + props.extend(12u32.to_le_bytes()); + props.extend(synth::color(21, [255, 191, 128, 100])); + props.push(8); + let name: Vec = "N".repeat(10_000).encode_utf16().flat_map(|u| u.to_le_bytes()).collect(); + props.extend((16 + 4 + name.len() as u32).to_le_bytes()); + props.extend([0; 16]); + props.extend(10_000u32.to_le_bytes()); + props.extend(name); + props.extend([0, 0, 0, 0, 0]); + let mut body = 1u16.to_le_bytes().to_vec(); + body.extend(1300u32.to_le_bytes()); + body.extend((props.len() as u32).to_le_bytes()); + body.extend(props); + let mut fill = 4u32.to_le_bytes().to_vec(); + fill.extend(1300u32.to_le_bytes()); + fill.extend((body.len() as u32).to_le_bytes()); + fill.extend(body); + let d = read(&styled_drawing(v, vec![list(b"filt", vec![chunk(b"fild", fill)])], vec![styled_rect(v, 4, 0)]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Some(Color::Spot { name, .. }) = &s[0].fill else { panic!("{:?}", s[0].fill) }; + assert_eq!(name.chars().count(), 256 + 17, "{name}"); + assert!(name.starts_with(&"N".repeat(256)), "{name}"); + assert!(d.warnings.contains(&Warning::TooDeep), "{:?}", d.warnings); +} + +/// A transform or a uniform fill's color that is there but can't be read is damage: the shape +/// stays, without its transform or its fill, and the warnings say so. +#[test] +fn unreadable_transforms_and_fill_colors_are_damage() { + let v = V(1100); + let rect = [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat(); + let obj = list(b"obj ", vec![chunk(b"loda", v.loda(1, &[(30, rect)])), list(b"trfl", vec![chunk(b"trfd", vec![1, 2])])]); + let d = read(&styled_drawing(v, vec![], vec![obj]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!((s.len(), s[0].matrix), (1, vectorcraft_cdr::model::Matrix::IDENTITY)); + assert!(d.warnings.contains(&Warning::Damaged), "trfd: {:?}", d.warnings); + // A uniform fill cut off in its color record, before version 13 and from it. + for v in [V(1100), V(1300)] { + let mut fill = v.fill(4, &synth::color(2, [0, 100, 0, 0])); + fill.truncate(fill.len() - 10); + let d = read(&styled_drawing(v, vec![list(b"filt", vec![chunk(b"fild", fill)])], vec![styled_rect(v, 4, 0)]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].fill, None, "{}", v.0); + assert!(d.warnings.contains(&Warning::Damaged), "fill {}: {:?}", v.0, d.warnings); + } +} + +/// The inflate limit may be as large as `usize` holds. +#[test] +fn the_largest_inflate_limit_reads_compressed_lists() { + let d = read(&synth::sample(1100, true), Limits { inflated: usize::MAX, ..Limits::default() }).unwrap(); + check_shapes(&d, 1100); +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] + + #[test] + fn never_panics_on_garbage(bytes in prop::collection::vec(any::(), 0..2048)) { + let mut b = b"RIFF".to_vec(); + b.extend(bytes); + let _ = read(&b, Limits::default()); + } + + #[test] + fn never_panics_on_mutated_samples(version in prop::sample::select(vec![300u16, 400, 500, 700, 900, 1100, 1300]), compress: bool, edits in prop::collection::vec((any::(), any::()), 1..24)) { + let mut b = synth::sample(version, compress && version >= 700); + let n = b.len(); + for (at, v) in edits { + b[at % n] = v; + } + let _ = read(&b, Limits::default()); + } + + #[test] + fn never_panics_on_garbage_after_a_wl_header(marker in prop::sample::select(vec![b'd', b'e', b'm']), bytes in prop::collection::vec(any::(), 0..2048)) { + // Offsets that fit the file, so the garbage is walked as records. + let mut b = vec![b'W', b'L', marker, 0]; + b.extend(28u32.to_le_bytes()); + b.extend(28u32.to_le_bytes()); + b.extend((28 + bytes.len() as u32).to_le_bytes()); + b.extend([0; 12]); + b.extend(bytes); + prop_assert!(vectorcraft_cdr::is_cdr(&b)); + let _ = read(&b, Limits::default()); + } + + #[test] + fn never_panics_on_mutated_wl_files(marker in prop::sample::select(vec![b'd', b'e', b'm']), cut in any::(), edits in prop::collection::vec((any::(), any::()), 1..24)) { + let mut b = synth::wl_sample(marker); + let n = b.len(); + for (at, v) in edits { + b[at % n] = v; + } + let _ = read(&b, Limits::default()); + let _ = read(&b[..cut % (n + 1)], Limits::default()); + } + + #[test] + fn never_panics_on_mutated_packages(version in prop::sample::select(vec![1400u16, 1500, 1700, 2700]), edits in prop::collection::vec((any::(), any::(), any::()), 1..24)) { + // The members are edited before they are zipped, so that the edits reach the chunks and + // redirect records rather than stop at the CRC-32. + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(version)); + let mut members = if version < 1600 { + vec![synth::Member { name: "content/riffData.cdr".into(), data: synth::sample(version, false), deflate: false }] + } else { + synth::package16_members(version, &body, false, &[]) + }; + for (m, at, v) in edits { + let k = m % members.len(); + let data = &mut members[k].data; + if !data.is_empty() { + let n = data.len(); + data[at % n] = v; + } + } + let _ = read(&synth::zip(&members, b""), Limits::default()); + } +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 0fccbcdecb..52bdbdb18b 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -39,6 +39,7 @@ vectorcraft-eps = { workspace = true } vectorcraft-metafile = { workspace = true } vectorcraft-plugins = { workspace = true } vectorcraft-affinity = { workspace = true } +vectorcraft-cdr = { workspace = true } vectorcraft-scriptcheck = { workspace = true } vectorcraft-js = { workspace = true } # The commands' parameter schemas (schemas.rs). @@ -79,6 +80,7 @@ rayon = { version = "1.12", optional = true } [dev-dependencies] vectorcraft-affinity = { workspace = true, features = ["synth"] } +vectorcraft-cdr = { workspace = true, features = ["synth"] } crc32fast = { workspace = true } vectorcraft-testkit = { workspace = true } proptest = { workspace = true } diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 61eac58f37..c8ddc12c8e 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -17,6 +17,7 @@ //! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`. //! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`. //! - `metafile`: EMF and WMF export, open and place. +//! - `cdr`: `.cdr` drawings of versions 1 to 27 and `.cdt` templates, open and place. //! - `hpgl`: HP-GL export options and plots. //! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no //! built-in format reads). @@ -28,6 +29,7 @@ mod action_batch; mod affinity; mod batch; +mod cdr; pub mod dxf; pub mod dxfimport; mod encode; @@ -162,6 +164,8 @@ mod tests_affinity; #[cfg(test)] mod tests_artboard_fill; #[cfg(test)] +mod tests_cdr; +#[cfg(test)] mod tests_pdf; #[cfg(test)] mod tests_pdfcolor; diff --git a/crates/engine/src/cmd/fileio/cdr.rs b/crates/engine/src/cmd/fileio/cdr.rs new file mode 100644 index 0000000000..f483f2f0a6 --- /dev/null +++ b/crates/engine/src/cmd/fileio/cdr.rs @@ -0,0 +1,321 @@ +//! `.cdr` drawings of versions 1 to 27 (`.cdr`, and `.cdt` templates): the pages, layers, +//! guidelines, groups, curves, rectangles, ellipses, arcs and polygons with uniform fills and +//! outlines that `vectorcraft-cdr` reads, mapped to editable VectorCraft art. Pages become +//! artboards side by side; layers of the same name on different pages become one layer where the +//! pages stack them in the same order. What the +//! reader leaves out is listed in the warnings, one line for each kind ([`note`]). + +use std::collections::HashMap; +use std::sync::Arc; + +use kurbo::{Affine, Rect}; +use vectorcraft_cdr::model::{self as cd, LayerKind}; +use vectorcraft_cdr::{Limits, Warning}; +use vectorcraft_doc::{Artboard, ColorMode, Document, Guide, LayerColor, Node, NodeKind}; + +use super::load::err; +use crate::Result; + +mod shapes; + +const UNSUPPORTED_OBJECTS: &str = "CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out"; +const UNSUPPORTED_FILLS: &str = "CDR fountain, pattern, texture and PostScript fills were left out"; +const UNKNOWN_COLORS: &str = "colors in CDR color models VectorCraft doesn't read were opened as black"; +const SPOT_LOOKS: &str = "CDR library colors that the drawing stores only by number were opened as black spot colors"; +const ARROWHEADS: &str = "CDR outline arrowheads were left out"; +const ENVELOPES: &str = "CDR envelopes were not applied, and the shapes under them keep their outlines"; +const TOO_DEEP: &str = "parts of the drawing nested too deeply, or past the import limits, were left out"; +const DAMAGED: &str = "damaged parts of the drawing were left out"; +const PAGES_CUT: &str = "CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard"; + +/// What reading a drawing left out or changed, for each kind the reader reports. +fn note(w: Warning) -> &'static str { + match w { + Warning::UnsupportedObjects => UNSUPPORTED_OBJECTS, + Warning::UnsupportedFills => UNSUPPORTED_FILLS, + Warning::UnknownColors => UNKNOWN_COLORS, + Warning::SpotLooks => SPOT_LOOKS, + Warning::Arrowheads => ARROWHEADS, + Warning::Envelopes => ENVELOPES, + Warning::TooDeep => TOO_DEEP, + Warning::Damaged => DAMAGED, + } +} + +/// The page size used when neither the page nor the document settings give one: US Letter, +/// VectorCraft's own choice. +const FALLBACK_PAGE: (f64, f64) = (612.0, 792.0); +/// The layer that holds guidelines at angles other than horizontal and vertical, as guide paths. +const GUIDES_LAYER: &str = "Guides"; +/// The most pages read, as artboards: the most a new document may have. +const MAX_PAGES: usize = crate::cmd::newdoc::MAX_ARTBOARDS as usize; +/// The longest page side, in points: the longest artboard side a new document may have. +const MAX_PAGE_SIDE: f64 = 16383.0 * 10.0; +/// The gap between pages laid side by side, in points. +const PAGE_GAP: f64 = 36.0; +/// The most objects, subpaths and path segments copied from master layers onto pages, all pages +/// together: the `.af` importer's budget for its master pages (`affinity/master_copies.rs`). +const MAX_MASTER_COPIES: usize = 1 << 23; +/// The most guides and guide paths made, the master page's copied onto every page included. +const MAX_GUIDES: usize = 100_000; +/// The most layers made from the master page's and the pages' layers: VectorCraft's own limit. +const MAX_LAYERS: usize = 10_000; + +/// Is `bytes` a `.cdr` drawing this importer reads? +pub(super) fn is_cdr(bytes: &[u8]) -> bool { + vectorcraft_cdr::is_cdr(bytes) +} + +pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec)> { + let d = vectorcraft_cdr::read(bytes, Limits::default()).map_err(|e| match e { + vectorcraft_cdr::Error::Version(v) => { + let version = v / 100; + err(format!("CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27")) + } + why => err(format!("this CDR drawing can't be read ({why})")), + })?; + let mut b = shapes::Builder::new(); + let mut doc = b.document(&d); + let mut warnings: Vec = Vec::new(); + for w in d.warnings.iter().chain(&b.notes) { + if !warnings.iter().any(|x| x == note(*w)) { + warnings.push(note(*w).to_string()); + } + } + if b.pages_cut { + warnings.push(PAGES_CUT.to_string()); + } + doc.limit_depth_noting(&mut warnings); + Ok((doc, warnings)) +} + +/// Where each page lies in the document: its artboard, and the map from its own space (points +/// from its centre, y up) into the document. +struct Placed { + rect: Rect, + to_doc: Affine, +} + +/// Pages laid out by [`place_pages`]. +struct Layout { + placed: Vec, + /// Pages past [`MAX_PAGES`] or past the document's range were left out. + left_out: bool, + /// A page side longer than [`MAX_PAGE_SIDE`] was cut to it. + cut: bool, +} + +/// The pages' artboards side by side, each side held to 1 to [`MAX_PAGE_SIDE`] points. +fn place_pages(d: &cd::Drawing) -> Layout { + let mut x = 0.0; + let size = |p: &cd::Page| p.size.or(d.page_size).unwrap_or(FALLBACK_PAGE); + let sizes: Vec<(f64, f64)> = + if d.pages.is_empty() { vec![d.page_size.unwrap_or(FALLBACK_PAGE)] } else { d.pages.iter().take(MAX_PAGES).map(size).collect() }; + let mut placed = Vec::with_capacity(sizes.len()); + let mut cut = false; + for (w, h) in sizes { + let long = w > MAX_PAGE_SIDE || h > MAX_PAGE_SIDE; + let (w, h) = (w.clamp(1.0, MAX_PAGE_SIDE), h.clamp(1.0, MAX_PAGE_SIDE)); + if x + w > crate::MAX_COORD { + break; + } + cut |= long; + let rect = Rect::new(x, 0.0, x + w, h); + placed.push(Placed { rect, to_doc: Affine::translate((x + w / 2.0, h / 2.0)) * Affine::FLIP_Y }); + x += w + PAGE_GAP; + } + let left_out = placed.len() < d.pages.len(); + Layout { placed, left_out, cut } +} + +impl shapes::Builder { + fn document(&mut self, d: &cd::Drawing) -> Document { + self.learn_spots(d); + let Layout { placed, left_out, cut } = place_pages(d); + if left_out { + self.notes.push(Warning::TooDeep); + } + self.pages_cut = cut; + let (w, h) = placed.first().map_or(FALLBACK_PAGE, |p| (p.rect.width(), p.rect.height())); + let mut doc = Document::new(w, h); + doc.artboards = placed + .iter() + .enumerate() + .map(|(i, p)| Artboard { + id: i as u32 + 1, + name: format!("Page {}", i + 1), + rect: p.rect, + locked: false, + show_center_mark: false, + show_cross_hairs: false, + show_video_safe_areas: false, + video_ruler_pixel_aspect_ratio: 1.0, + color: None, + guide_label: None, + }) + .collect(); + self.doc = doc; + self.name_spots(); + // Bottom to top: the master page's layers, then the pages' in the order first seen. + let mut layers: Vec<(String, Vec>)> = Vec::new(); + // A layer is known by its name and how many layers of that name the page has below it, so + // two layers of one name on a page stay two layers. Each key keeps every layer made for + // it, bottom to top. + let mut by_name: HashMap<(String, usize), Vec> = HashMap::new(); + self.master_layers(d, &placed, &mut layers); + // The pages' layers go above the master page's. + let pages_from = layers.len(); + for (i, (page, p)) in d.pages.iter().zip(&placed).enumerate() { + let artboard = Some(i as u32 + 1); + let mut seen: HashMap<&str, usize> = HashMap::new(); + // The layer this page's last layer went to: the next one goes above it. + let mut below: Option = None; + // The file lists layers front to back. + for l in page.layers.iter().rev() { + self.guides(&l.guides, p, artboard); + if l.kind != LayerKind::Drawing && l.kind != LayerKind::Desktop { + continue; + } + let art = self.objects(&l.objects, p.to_doc); + let n = seen.entry(l.name.as_str()).or_insert(0); + let key = (l.name.clone(), *n); + *n += 1; + // A layer an earlier page stacked below this page's last one would put this page's + // art in the wrong order, so the page gets a new layer of that name instead, just + // above its last one. Of the layers of that name above the last one, the lowest + // takes the art. + match by_name.get(&key).and_then(|is| is.iter().copied().find(|&i| below.is_none_or(|b| i > b))) { + Some(i) => { + if let Some((_, kids)) = layers.get_mut(i) { + kids.extend(art); + } + below = Some(i); + } + None if layers.len() >= MAX_LAYERS => self.notes.push(Warning::TooDeep), + None => { + let at = below.map_or(pages_from, |b| b + 1); + if at < layers.len() { + for i in by_name.values_mut().flatten().filter(|i| **i >= at) { + *i += 1; + } + } + let is = by_name.entry(key).or_default(); + is.insert(is.partition_point(|&i| i < at), at); + layers.insert(at, (l.name.clone(), art)); + below = Some(at); + } + } + } + } + // Guidelines every page shows, on each page's artboard. + for (i, p) in placed.iter().enumerate() { + self.guides(&d.guides, p, Some(i as u32 + 1)); + } + if !self.guide_paths.is_empty() { + let paths = std::mem::take(&mut self.guide_paths); + // At the layer limit the guide paths go on the top layer instead of a layer of their own. + let full = layers.len() >= MAX_LAYERS; + match layers.last_mut() { + Some((_, kids)) if full => kids.extend(paths), + _ => layers.push((GUIDES_LAYER.to_string(), paths)), + } + } + let mut doc = std::mem::replace(&mut self.doc, Document::new(1.0, 1.0)); + doc.layers = layers.into_iter().enumerate().map(|(i, (name, kids))| layer(&mut doc, &name, i, kids)).collect(); + if doc.layers.is_empty() { + let l = layer(&mut doc, "Layer 1", 0, Vec::new()); + doc.layers.push(l); + } + // Ruler guides go at the top of the top layer, in the order they were read. + let guides: Vec> = std::mem::take(&mut self.guide_list) + .into_iter() + .map(|g| Arc::new(Node::new(doc.alloc_id(), NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard }))) + .collect(); + if let Some(kids) = doc.layers.last_mut().and_then(|l| Arc::make_mut(l).children_mut()) { + kids.extend(guides); + } + self.finish_swatches(&mut doc); + if self.cmyk > self.rgb { + doc.color_mode = ColorMode::Cmyk; + } + doc + } + + /// The master page's layers: the desktop's objects once, on the first page's space; other + /// layers' objects on every page, as many copies as [`MAX_MASTER_COPIES`] allows. + fn master_layers(&mut self, d: &cd::Drawing, placed: &[Placed], layers: &mut Vec<(String, Vec>)>) { + for l in d.master.iter().rev() { + if layers.len() >= MAX_LAYERS { + self.notes.push(Warning::TooDeep); + break; + } + let frames: Vec<&Placed> = if l.kind == LayerKind::Desktop { placed.iter().take(1).collect() } else { placed.iter().collect() }; + let mut art = Vec::new(); + let count = copy_cost(&l.objects); + for p in frames { + if count > self.copies_left { + self.notes.push(Warning::TooDeep); + break; + } + self.copies_left -= count; + art.extend(self.objects(&l.objects, p.to_doc)); + } + let name = if l.name.is_empty() { "Master".to_string() } else { l.name.clone() }; + layers.push((name, art)); + } + } + + /// `guides` of a page placed by `p`: horizontal and vertical ones as guides of the page's + /// artboard, others as guide paths. + fn guides(&mut self, guides: &[cd::Guideline], p: &Placed, artboard: Option) { + for g in guides { + if self.guide_list.len() + self.guide_paths.len() >= MAX_GUIDES { + self.notes.push(Warning::TooDeep); + return; + } + let at = p.to_doc * kurbo::Point::new(g.at.x, g.at.y); + let turn = g.angle.rem_euclid(180.0); + if !(at.x.is_finite() && at.y.is_finite() && at.x.abs() <= crate::MAX_COORD && at.y.abs() <= crate::MAX_COORD) { + self.notes.push(Warning::TooDeep); + continue; + } + if turn.abs() < 1e-9 { + self.guide_list.push(Guide { artboard, ..Guide::new(false, at.y) }); + } else if (turn - 90.0).abs() < 1e-9 { + self.guide_list.push(Guide { artboard, ..Guide::new(true, at.x) }); + } else { + self.angled_guide(at, g.angle, p.rect); + } + } + } +} + +/// What one copy of `objects` takes: each object, each subpath and segment of its path, and each +/// dash of its outline, since every copy builds its own path and dash pattern. +fn copy_cost(objects: &[cd::Object]) -> usize { + let mut n: usize = 0; + let mut stack: Vec<&cd::Object> = objects.iter().collect(); + while let Some(o) = stack.pop() { + n = n.saturating_add(1); + match o { + cd::Object::Group(kids) => stack.extend(kids), + cd::Object::Shape(s) => { + if let cd::Geometry::Path(p) = &s.geometry { + n = p.subpaths.iter().fold(n, |n, sp| n.saturating_add(1 + sp.segments.len())); + } + n = n.saturating_add(s.outline.as_ref().map_or(0, |o| o.dashes.len())); + } + } + } + n +} + +/// A layer of the document named `name` holding `kids` (bottom to top). +fn layer(doc: &mut Document, name: &str, i: usize, kids: Vec>) -> Arc { + let name = if name.is_empty() { format!("Layer {}", i + 1) } else { name.to_string() }; + let mut n = Node::layer(doc.alloc_id(), &name, LayerColor::Preset((i % 9) as u8)); + if let Some(c) = n.children_mut() { + *c = kids; + } + Arc::new(n) +} diff --git a/crates/engine/src/cmd/fileio/cdr/shapes.rs b/crates/engine/src/cmd/fileio/cdr/shapes.rs new file mode 100644 index 0000000000..7bd04c6a70 --- /dev/null +++ b/crates/engine/src/cmd/fileio/cdr/shapes.rs @@ -0,0 +1,482 @@ +//! A drawing's objects as VectorCraft art: paths, live rectangles and ellipses, groups, solid +//! fills and strokes, and the spot colors they use as swatches. + +use std::collections::HashMap; +use std::sync::Arc; + +use kurbo::{Affine, BezPath, Point, Rect}; +use vectorcraft_cdr::Warning; +use vectorcraft_cdr::model::{self as cd, Geometry}; +use vectorcraft_color::swatch::REGISTRATION; +use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_doc::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, StrokeLayer}; +use vectorcraft_doc::geom::{FillRule, PathData}; +use vectorcraft_doc::{Document, Guide, LiveShape, Node, NodeKind}; + +/// The most nested groups mapped; the reader holds nesting well below it. +const MAX_DEPTH: usize = 256; + +pub(super) struct Builder { + pub(super) doc: Document, + /// What mapping left out, as the reader's warning kinds. + pub(super) notes: Vec, + /// A page side was cut to the longest artboard side. + pub(super) pages_cut: bool, + /// What copies of master art onto the pages may still take ([`super::MAX_MASTER_COPIES`] at + /// the start). + pub(super) copies_left: usize, + /// Horizontal and vertical guidelines, as guides of the pages' artboards. + pub(super) guide_list: Vec, + /// Guidelines at other angles, as guide paths. + pub(super) guide_paths: Vec>, + /// Colors read in each model, which picks the document's color mode. + pub(super) cmyk: usize, + pub(super) rgb: usize, + /// The spot colors used, in the order first seen, with their full-strength color and the tint + /// of the use it was worked out from (`None`: the file stores no color for it). + spots: Vec<(String, Color, Option)>, + spot_index: HashMap, +} + +impl Builder { + pub(super) fn new() -> Self { + Builder { + doc: Document::new(1.0, 1.0), + notes: Vec::new(), + pages_cut: false, + copies_left: super::MAX_MASTER_COPIES, + guide_list: Vec::new(), + guide_paths: Vec::new(), + cmyk: 0, + rgb: 0, + spots: Vec::new(), + spot_index: HashMap::new(), + } + } + + /// Every spot color `d` uses, with its full-strength color taken from its use at the highest + /// tint: a use at a low tint keeps little of the color, and one at 0% keeps none. + pub(super) fn learn_spots(&mut self, d: &cd::Drawing) { + let layers = d.pages.iter().flat_map(|p| &p.layers).chain(&d.master); + let mut stack: Vec<&cd::Object> = layers.flat_map(|l| &l.objects).collect(); + while let Some(o) = stack.pop() { + match o { + cd::Object::Shape(s) => { + for c in s.fill.iter().chain(s.outline.iter().map(|o| &o.color)) { + self.learn_spot(c); + } + } + cd::Object::Group(kids) => stack.extend(kids), + } + } + } + + /// Note spot color `c`, keeping the full-strength color of its use at the highest tint. + fn learn_spot(&mut self, c: &cd::Color) -> Option { + let cd::Color::Spot { name, tint, look } = c else { return None }; + let seen = look.map(|_| *tint); + let base = look.map_or(Color::BLACK, |[r, g, b]| Color::rgb(r, g, b)); + let Some(&i) = self.spot_index.get(name) else { + self.spot_index.insert(name.clone(), self.spots.len()); + self.spots.push((name.clone(), base, seen)); + return Some(base); + }; + let slot = self.spots.get_mut(i)?; + if seen.is_some() && seen > slot.2 { + slot.1 = base; + slot.2 = seen; + } + Some(slot.1) + } + + fn note(&mut self, w: Warning) { + if !self.notes.contains(&w) { + self.notes.push(w); + } + } + + /// `objects` (front to back, as the file lists them) bottom to top, mapped by `to_doc`. + pub(super) fn objects(&mut self, objects: &[cd::Object], to_doc: Affine) -> Vec> { + self.objects_at(objects, to_doc, 0) + } + + fn objects_at(&mut self, objects: &[cd::Object], to_doc: Affine, depth: usize) -> Vec> { + if depth > MAX_DEPTH { + self.note(Warning::TooDeep); + return Vec::new(); + } + let mut out = Vec::with_capacity(objects.len()); + for o in objects.iter().rev() { + match o { + cd::Object::Shape(s) => out.extend(self.shape(s, to_doc)), + cd::Object::Group(kids) => { + let children = self.objects_at(kids, to_doc, depth + 1); + if !children.is_empty() { + out.push(Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: false }))); + } + } + } + } + out + } + + fn shape(&mut self, s: &cd::Shape, to_doc: Affine) -> Option> { + let m = to_doc * affine(&s.matrix); + let (path, live) = match &s.geometry { + Geometry::Path(p) => (PathData::from_bezpath(&(m * bez(p))), None), + Geometry::Rect { w, h, radii } => live_rect(*w, *h, *radii, m)?, + Geometry::Ellipse { w, h } => { + let (x0, y0) = (w.min(0.0), h.min(0.0)); + let live = LiveShape::Ellipse { w: w.abs(), h: h.abs(), pie: (0.0, 360.0), xf: m * Affine::translate((x0, y0)) }; + (live.to_path(), Some(live)) + } + }; + if path.is_empty() || !in_range(&path) { + self.note(Warning::TooDeep); + return None; + } + let mut items = Vec::new(); + if let Some(c) = &s.fill { + items.push(AppearanceItem::Fill(FillLayer::new(self.paint(c)))); + } + if let Some(o) = &s.outline { + items.push(AppearanceItem::Stroke(self.stroke(o))); + } + // A curve of several subpaths is filled with holes where they overlap: VectorCraft's own + // choice of rule for it. + let rule = FillRule::EvenOdd; + let mut n = Node::new(self.doc.alloc_id(), NodeKind::Path { path, rule, live: live.map(Box::new), clipping: false, guide: false }); + n.appearance = Appearance { items, ..Appearance::default() }.into(); + Some(Arc::new(n)) + } + + fn stroke(&mut self, o: &cd::Outline) -> StrokeLayer { + let width = if o.width.is_finite() { o.width.clamp(0.0, 1000.0) } else { 0.0 }; + let mut l = StrokeLayer::new(self.paint(&o.color), width); + l.cap = match o.cap { + cd::Cap::Butt => LineCap::Butt, + cd::Cap::Round => LineCap::Round, + cd::Cap::Square => LineCap::Square, + }; + l.join = match o.join { + cd::Join::Miter => LineJoin::Miter, + cd::Join::Round => LineJoin::Round, + cd::Join::Bevel => LineJoin::Bevel, + }; + // Dashes are stored in multiples of the outline's width. + if !o.dashes.is_empty() && width > 0.0 { + let pattern: Vec = o.dashes.iter().map(|d| d * width).collect(); + l.dash = Some(Dash { pattern, offset: 0.0, align_corners: false }); + } + l + } + + fn paint(&mut self, c: &cd::Color) -> Paint { + match c { + cd::Color::Rgb([r, g, b]) => { + self.rgb += 1; + Paint::solid(Color::rgb(*r, *g, *b)) + } + cd::Color::Cmyk([c, m, y, k]) => { + self.cmyk += 1; + Paint::solid(Color::cmyk(*c, *m, *y, *k)) + } + cd::Color::Gray(k) => Paint::solid(Color::Gray { k: *k }), + cd::Color::Registration => Paint::Solid { color: Color::cmyk(1.0, 1.0, 1.0, 1.0), swatch: Some(REGISTRATION.into()), tint: 1.0 }, + cd::Color::Spot { name, tint, .. } => { + let base = self.learn_spot(c).unwrap_or(Color::BLACK); + let tint = tint.clamp(0.0, 1.0); + let swatch = self.spot_index.get(name).and_then(|&i| self.spots.get(i)).map_or_else(|| name.clone(), |s| s.0.clone()); + Paint::Solid { color: base.tinted(tint), swatch: Some(swatch), tint } + } + } + } + + /// Gives each spot color a swatch name of its own in the new document: a name its swatches, + /// color groups or Registration already use becomes the first free "name 2", "name 3"…, so + /// the ink stays a spot color. The drawing's other spot names are kept as they are. Call it + /// once the document is made and before any paint. + pub(super) fn name_spots(&mut self) { + let mut free = self.doc.free_swatch_names(); + let clashes: Vec = self.spots.iter().map(|s| s.0 == REGISTRATION || self.doc.swatch_name_taken(&s.0)).collect(); + for (s, _) in self.spots.iter().zip(&clashes).filter(|(_, c)| !**c) { + free.take(&s.0); + } + for (s, _) in self.spots.iter_mut().zip(&clashes).filter(|(_, c)| **c) { + s.0 = free.take(&s.0); + } + } + + /// The spot colors the drawing used, as global spot swatches; a swatch of the same name the + /// document already has is kept as it is. + pub(super) fn finish_swatches(&mut self, doc: &mut Document) { + self.spot_index.clear(); + for (name, color, _) in std::mem::take(&mut self.spots) { + if !doc.swatches.iter().any(|s| s.name == name) { + doc.swatches.push(Swatch { name, paint: Paint::solid(color), global: true, spot: true }); + } + } + } + + /// A guideline through `at` (document space) at `angle` degrees counterclockwise, as a guide + /// path from edge to edge of the page `rect`, so it moves with the page's artboard. A + /// guideline that misses the page runs through `at` for the page's diagonal each way. + pub(super) fn angled_guide(&mut self, at: Point, angle: f64, rect: Rect) { + let (s, c) = angle.to_radians().sin_cos(); + // The document's y axis points down. + let dir = kurbo::Vec2::new(c, -s); + let (a, b) = match chord(at, dir, rect) { + Some((t0, t1)) => (at + dir * t0, at + dir * t1), + None => { + let d = dir * rect.width().hypot(rect.height()).max(1.0); + (at - d, at + d) + } + }; + let mut bp = BezPath::new(); + bp.move_to(a); + bp.line_to(b); + let path = PathData::from_bezpath(&bp); + if !in_range(&path) { + self.note(Warning::TooDeep); + return; + } + let n = Node::new(self.doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: true }); + self.guide_paths.push(Arc::new(n)); + } +} + +/// Where the line through `at` along the unit vector `dir` crosses `rect`: the distances along +/// it to the two edges it meets, the nearer first. None when it misses `rect` or only touches it +/// at a point. +fn chord(at: Point, dir: kurbo::Vec2, rect: Rect) -> Option<(f64, f64)> { + let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY); + for (p, d, min, max) in [(at.x, dir.x, rect.x0, rect.x1), (at.y, dir.y, rect.y0, rect.y1)] { + if d.abs() < 1e-12 { + if p < min || p > max { + return None; + } + } else { + let (t0, t1) = ((min - p) / d, (max - p) / d); + lo = lo.max(t0.min(t1)); + hi = hi.min(t0.max(t1)); + } + } + (lo.is_finite() && hi.is_finite() && hi - lo > 1e-9).then_some((lo, hi)) +} + +fn affine(m: &cd::Matrix) -> Affine { + Affine::new(m.0) +} + +fn bez(p: &cd::Path) -> BezPath { + let pt = |q: cd::Pt| Point::new(q.x, q.y); + let mut bp = BezPath::new(); + for s in &p.subpaths { + bp.move_to(pt(s.start)); + for seg in &s.segments { + match *seg { + cd::Segment::Line(e) => bp.line_to(pt(e)), + cd::Segment::Cubic(a, b, e) => bp.curve_to(pt(a), pt(b), pt(e)), + } + } + if s.closed { + bp.close_path(); + } + } + bp +} + +/// A rectangle from the origin to (`w`, `h`) with `radii` counterclockwise from its corner at +/// (`w`, 0), placed by `m`, as a live rectangle: each radius stays on the corner it belongs to, +/// whichever way `w` and `h` point. +fn live_rect(w: f64, h: f64, radii: [f64; 4], m: Affine) -> Option<(PathData, Option)> { + if !(w.is_finite() && h.is_finite()) { + return None; + } + let (x0, y1, ww, hh) = (w.min(0.0), h.max(0.0), w.abs(), h.abs()); + // The live shape's own space has its origin at the top-left and y pointing down. + let to_file = Affine::translate((x0, y1)) * Affine::FLIP_Y; + let corners = [(w, 0.0), (w, h), (0.0, h), (0.0, 0.0)]; + let mut live_radii = [0.0; 4]; + for ((px, py), r) in corners.into_iter().zip(radii) { + let (lx, ly) = (px - x0, y1 - py); + let right = lx > ww / 2.0; + let bottom = ly > hh / 2.0; + let i = match (right, bottom) { + (false, false) => 0, + (true, false) => 1, + (true, true) => 2, + (false, true) => 3, + }; + if let Some(slot) = live_radii.get_mut(i) { + *slot = if r.is_finite() { r.max(0.0) } else { 0.0 }; + } + } + let mut live = LiveShape::Rectangle { w: ww, h: hh, radii: live_radii, kinds: Default::default(), radii_relative: false, xf: m * to_file }; + live.fold_scale(); + Some((live.to_path(), Some(live))) +} + +/// Whether every control point of `path` is finite and within `MAX_COORD` of the origin. +fn in_range(path: &PathData) -> bool { + path.control_bounds().is_some_and(|r| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= crate::MAX_COORD)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A named spot color takes its full-strength color from its use at the highest tint, wherever + /// that use comes in the drawing: a use at 0% stores only white. + #[test] + fn a_spot_color_keeps_its_color_from_its_strongest_use() { + let red = [1.0, 0.0, 0.0]; + let shape = |tint: f32, look: [f32; 3]| { + cd::Object::Shape(Box::new(cd::Shape { + geometry: Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, + matrix: cd::Matrix::IDENTITY, + fill: Some(cd::Color::Spot { name: "Red ink".into(), tint, look: Some(look) }), + outline: None, + })) + }; + for objects in [vec![shape(0.0, [1.0; 3]), shape(1.0, red)], vec![shape(1.0, red), shape(0.0, [1.0; 3])]] { + let layer = cd::Layer { name: "L".into(), kind: cd::LayerKind::Drawing, objects, guides: vec![] }; + let d = cd::Drawing { + version: 1300, + page_size: None, + pages: vec![cd::Page { size: None, layers: vec![layer] }], + master: vec![], + guides: vec![], + warnings: vec![], + }; + let doc = Builder::new().document(&d); + let swatch = doc.swatches.iter().find(|s| s.name == "Red ink").unwrap(); + assert_eq!(swatch.paint, Paint::solid(Color::rgb(1.0, 0.0, 0.0))); + let layer = doc.layers.first().unwrap().children().unwrap(); + let full = layer.iter().find_map(|n| match n.appearance.items.first() { + Some(AppearanceItem::Fill(f)) => match &f.paint { + Paint::Solid { color, tint, .. } if *tint == 1.0 => Some(*color), + _ => None, + }, + _ => None, + }); + assert_eq!(full, Some(Color::rgb(1.0, 0.0, 0.0))); + } + } + + /// A spot color named like one of a new document's process swatches gets a numbered name that + /// no other spot color of the drawing uses, and its paint names that spot swatch. + #[test] + fn a_spot_color_named_like_a_default_swatch_stays_a_spot_color() { + let shape = |name: &str| { + cd::Object::Shape(Box::new(cd::Shape { + geometry: Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, + matrix: cd::Matrix::IDENTITY, + fill: Some(cd::Color::Spot { name: name.into(), tint: 1.0, look: Some([0.0; 3]) }), + outline: None, + })) + }; + let layer = cd::Layer { name: "L".into(), kind: cd::LayerKind::Drawing, objects: vec![shape("Black"), shape("Black 2")], guides: vec![] }; + let d = cd::Drawing { + version: 1300, + page_size: None, + pages: vec![cd::Page { size: None, layers: vec![layer] }], + master: vec![], + guides: vec![], + warnings: vec![], + }; + assert!(Document::new(612.0, 792.0).swatches.iter().any(|s| s.name == "Black" && !s.spot)); + let doc = Builder::new().document(&d); + let layer = doc.layers.first().unwrap().children().unwrap(); + let mut names: Vec = layer + .iter() + .filter_map(|n| match n.appearance.items.first() { + Some(AppearanceItem::Fill(f)) => match &f.paint { + Paint::Solid { swatch: Some(name), .. } => Some(name.clone()), + _ => None, + }, + _ => None, + }) + .collect(); + names.sort(); + assert_eq!(names, ["Black 2", "Black 3"]); + for name in &names { + let swatch = doc.swatches.iter().find(|s| &s.name == name).unwrap(); + assert!(swatch.spot && swatch.global, "{name}: {swatch:?}"); + } + } + + /// Copies of master art onto the pages take from the budget by their objects, subpaths and + /// segments: a curve of 300 segments costs 302 each time it is copied. + #[test] + fn master_copies_count_their_path_segments() { + let segments = (1..=300).map(|i| cd::Segment::Line(cd::Pt { x: f64::from(i), y: 0.0 })).collect(); + let curve = cd::Object::Shape(Box::new(cd::Shape { + geometry: Geometry::Path(cd::Path { subpaths: vec![cd::SubPath { start: cd::Pt { x: 0.0, y: 0.0 }, segments, closed: false }] }), + matrix: cd::Matrix::IDENTITY, + fill: None, + outline: None, + })); + let master = cd::Layer { name: "M".into(), kind: cd::LayerKind::Drawing, objects: vec![curve], guides: vec![] }; + let d = cd::Drawing { + version: 1300, + page_size: None, + pages: (0..10).map(|_| cd::Page { size: None, layers: vec![] }).collect(), + master: vec![master], + guides: vec![], + warnings: vec![], + }; + let mut b = Builder::new(); + b.copies_left = 1000; + let doc = b.document(&d); + let copies = doc.layers.first().and_then(|l| l.children()).map_or(0, |c| c.len()); + assert_eq!(copies, 3, "1,000 holds three copies of 302"); + assert!(b.notes.contains(&Warning::TooDeep)); + } + + /// Copies of master art take from the budget by the dashes of their outlines too: a rectangle + /// whose outline has 299 dashes costs 300 each time it is copied. + #[test] + fn master_copies_count_their_dashes() { + let outline = cd::Outline { width: 1.0, color: cd::Color::Gray(1.0), cap: cd::Cap::Butt, join: cd::Join::Miter, dashes: vec![1.0; 299] }; + let rect = cd::Object::Shape(Box::new(cd::Shape { + geometry: Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, + matrix: cd::Matrix::IDENTITY, + fill: None, + outline: Some(outline), + })); + let master = cd::Layer { name: "M".into(), kind: cd::LayerKind::Drawing, objects: vec![rect], guides: vec![] }; + let d = cd::Drawing { + version: 1300, + page_size: None, + pages: (0..10).map(|_| cd::Page { size: None, layers: vec![] }).collect(), + master: vec![master], + guides: vec![], + warnings: vec![], + }; + let mut b = Builder::new(); + b.copies_left = 1000; + let doc = b.document(&d); + let copies = doc.layers.first().and_then(|l| l.children()).map_or(0, |c| c.len()); + assert_eq!(copies, 3, "1,000 holds three copies of 300"); + assert!(b.notes.contains(&Warning::TooDeep)); + } + + /// A corner rounded in the file stays on the same corner of the page, however the rectangle's + /// size points. + #[test] + fn rectangle_radii_stay_on_their_corners() { + // Only the corner at (w, 0) rounded; the page flips y as the document does. + for (w, h) in [(100.0, 50.0), (-100.0, 50.0), (100.0, -50.0), (-100.0, -50.0)] { + let (path, _) = live_rect(w, h, [10.0, 0.0, 0.0, 0.0], Affine::FLIP_Y).unwrap(); + let rounded = Point::new(w, -0.0); + let bp = path.to_bezpath(); + // No anchor sits on the rounded corner itself; the other three corners are anchors. + let anchors: Vec = bp.elements().iter().filter_map(|e| e.end_point()).collect(); + assert!(!anchors.iter().any(|p| (*p - rounded).hypot() < 1e-6), "{w} {h}: {anchors:?}"); + for c in [Point::new(w, -h), Point::new(0.0, -h), Point::new(0.0, 0.0)] { + assert!(anchors.iter().any(|p| (*p - c).hypot() < 1e-6), "{w} {h}: {c:?} not in {anchors:?}"); + } + } + } +} diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index d5137c8b1a..4d583a8399 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -520,6 +520,11 @@ pub const FORMATS: &[Format] = &[ reader("heif", "HEIC/HEIF", &["heic", "heif"], "image/heic", true), // jxl-oxide reads a JPEG XL file's first frame, which is stored as PNG. Exports don't write it. reader("jxl", "JPEG XL", &["jxl"], "image/jxl", true), + // `.cdr` drawings of versions 1 to 27 (`WL` files, RIFF files from version 3, and the ZIP packages of 14 on), read by + // `vectorcraft-cdr`; a `.cdt` template opens as a new untitled document. Exports don't write + // them. + reader("cdr", "CDR Drawing", &["cdr"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type + reader("cdt", "CDR Template", &["cdt"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type ]; /// Every extension `document.open` reads (the "All readable files" filter of open dialogs). @@ -574,17 +579,19 @@ pub const OPEN_EXTS: &[&str] = &[ "af", "afdesign", "afpub", + "cdr", + "cdt", ]; /// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to /// raster editors, so Finder and file managers don't offer a vector app for them, and there is no -/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF or JPEG XL type, nor one for the `.pns`, `.dib` and `.rle` names of +/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL or `.cdr` type, nor one for the `.pns`, `.dib` and `.rle` names of /// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS /// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it. /// The packaging declares no type for HP-GL plot files either. pub const UNASSOCIATED_EXTS: &[&str] = &[ "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc", - "heic", "heif", "jxl", "plt", "hpgl", "hgl", "hpg", + "heic", "heif", "jxl", "cdr", "cdt", "plt", "hpgl", "hgl", "hpg", ]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares @@ -668,6 +675,8 @@ pub const PLACE_EXTS: &[&str] = &[ "af", "afdesign", "afpub", + "cdr", + "cdt", "txt", "rtf", "docx", diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index ec1d7e36ba..4407c010ba 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -91,6 +91,10 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { if vectorcraft_affinity::is_affinity(bytes) { return format("affinity"); } + if super::cdr::is_cdr(bytes) { + // A template keeps its meaning from the extension. + return by_name.filter(|f| f.id == "cdt").or_else(|| format("cdr")); + } if vectorcraft_format::sniff(bytes) { // A template keeps its meaning from the extension, like .ait. return by_name.filter(|f| f.id == "template").or_else(|| format("vectorcraft")); @@ -508,6 +512,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result preview_only = i.preview_only; (i.doc, i.warnings, false) } + "cdr" | "cdt" => { + let (doc, warnings) = super::cdr::import(bytes)?; + (doc, warnings, false) + } // A PSD or PSB file's layers become layers (`layers`, default on); without layers, or with // `layers: false`, its merged image opens. Layers that can't be read leave the merged image. "psd" | "psb" if opts.layers => { @@ -682,9 +690,9 @@ fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option], out: &mut Vec) { + for n in nodes { + match &n.kind { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => walk(children, out), + NodeKind::RulerGuide { .. } => {} + _ => out.push((**n).clone()), + } + } +} + +fn paths(doc: &vectorcraft_doc::Document) -> Vec { + let mut out = Vec::new(); + walk(&doc.layers, &mut out); + out +} + +#[test] +fn every_version_opens_as_editable_art() { + // Versions 14 on are ZIP packages. + for version in [500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 2000, 2700] { + let mut s = Session::new(); + let r = open_bytes(&mut s, "drawing.cdr", &synth::sample_file(version, version >= 700), None).unwrap(); + assert_eq!(r["format"], "cdr", "{version}"); + let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect(); + assert!(w.iter().any(|w| w.contains("text, bitmaps")), "{version}: {w:?}"); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.artboards.len(), 1); + assert_eq!((doc.artboards[0].rect.width().round(), doc.artboards[0].rect.height().round()), (612.0, 792.0)); + // The page's layer "Art", above the master page's desktop layer. + let names: Vec = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names.last().map(String::as_str), Some("Art"), "{version}: {names:?}"); + let p = paths(doc); + // Five shapes on the page and one on the desktop. + assert_eq!(p.len(), 6, "{version}"); + let rect = p.iter().find( + |n| matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Rectangle { w, .. } if (w - 100.0).abs() < 0.1)), + ); + let rect = rect.unwrap_or_else(|| panic!("{version}: no live rectangle")); + let NodeKind::Path { live: Some(live), .. } = &rect.kind else { unreachable_in_test() }; + let LiveShape::Rectangle { radii, .. } = **live else { unreachable_in_test() }; + assert!(radii.iter().all(|r| (r - 5.0).abs() < 0.1), "{version}: {radii:?}"); + assert!(p.iter().any(|n| matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Ellipse { .. })))); + // The rectangle is filled red and stroked 2 pt with round caps. + let a = &rect.appearance; + assert_eq!(a.items.len(), 2, "{version}"); + // The master page's vertical guideline at 36 pt right of the page centre, a ruler guide + // on the top layer. + if version >= 600 { + let guides = doc.ruler_guides(); + let top = doc.layers.last().map(|l| l.id); + assert!( + guides.iter().any(|g| g.vertical && (g.pos - (306.0 + 36.0)).abs() < 0.05 && g.artboard == Some(1) && g.layer == top), + "{version}: {guides:?}" + ); + } + } +} + +fn unreachable_in_test() -> ! { + panic!("the match above already checked the shape") +} + +/// The live rectangle of `doc` that is 100 pt wide, with its node. +fn sample_rect(doc: &vectorcraft_doc::Document) -> Node { + paths(doc) + .into_iter() + .find(|n| matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Rectangle { w, .. } if (w - 100.0).abs() < 0.1))) + .unwrap_or_else(|| panic!("no live rectangle")) +} + +#[test] +fn versions_3_and_4_open_and_place_as_editable_art() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::appearance::{AppearanceItem, LineCap, LineJoin}; + for version in [300, 400] { + let bytes = synth::sample(version, false); + let mut s = Session::new(); + // By its name, and by its content under another name. + for name in ["drawing.cdr", "renamed.bin"] { + let r = open_bytes(&mut s, name, &bytes, None).unwrap(); + assert_eq!(r["format"], "cdr", "{version} {name}"); + let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect(); + assert!(w.iter().any(|w| w.contains("text, bitmaps")) && !w.iter().any(|w| w.contains("damaged")), "{version}: {w:?}"); + } + let doc = &s.doc().unwrap().doc; + assert_eq!((doc.artboards[0].rect.width().round(), doc.artboards[0].rect.height().round()), (612.0, 792.0), "{version}"); + let names: Vec = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names.last().map(String::as_str), Some("Art"), "{version}: {names:?}"); + assert_eq!(paths(doc).len(), 6, "{version}"); + let rect = sample_rect(doc); + let NodeKind::Path { live: Some(live), path, .. } = &rect.kind else { unreachable_in_test() }; + let LiveShape::Rectangle { radii, .. } = **live else { unreachable_in_test() }; + assert!(radii.iter().all(|r| (r - 5.0).abs() < 0.1), "{version}: {radii:?}"); + // 100 pt left of and above the page centre, y pointing down in the document. + let b = path.bounds().unwrap(); + assert!((b.x0 - 206.0).abs() < 0.2 && (b.y1 - 296.0).abs() < 0.2, "{version}: {b:?}"); + let [AppearanceItem::Fill(fill), AppearanceItem::Stroke(stroke)] = rect.appearance.items.as_slice() else { + panic!("{version}: {:?}", rect.appearance.items) + }; + assert_eq!(fill.paint, Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), "{version}"); + assert!((stroke.width - 2.0).abs() < 0.05, "{version}: {}", stroke.width); + assert_eq!((stroke.cap, stroke.join), (LineCap::Round, LineJoin::Round), "{version}"); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + s.execute("file.place", &json!({"name":"art.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap(); + assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty()), "{version}"); + } +} + +#[test] +fn versions_1_and_2_open_and_place_as_editable_art() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::appearance::AppearanceItem; + for marker in *b"em" { + let bytes = synth::wl_sample(marker); + let mut s = Session::new(); + for name in ["drawing.cdr", "renamed.bin"] { + let r = open_bytes(&mut s, name, &bytes, None).unwrap(); + assert_eq!(r["format"], "cdr", "{name}"); + let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect(); + assert!(w.len() == 1 && w[0].contains("text, bitmaps"), "{w:?}"); + } + assert_eq!(detect("drawing.cdt", &bytes).map(|f| f.id), Some("cdt")); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.artboards.len(), 1); + assert_eq!((doc.artboards[0].rect.width().round(), doc.artboards[0].rect.height().round()), (612.0, 792.0)); + assert_eq!(doc.layers.len(), 1); + // Bottom first in the document: the curve, the ellipse, then the rectangle in front. + let p = paths(doc); + assert_eq!(p.len(), 3); + assert!(matches!(&p[1].kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Ellipse { .. }))); + let rect = sample_rect(doc); + assert_eq!(rect.id, p[2].id); + let NodeKind::Path { path, .. } = &rect.kind else { unreachable_in_test() }; + let b = path.bounds().unwrap(); + assert!((b.x0 - 206.0).abs() < 0.2 && (b.y1 - 296.0).abs() < 0.2 && (b.height() - 50.0).abs() < 0.2, "{b:?}"); + let [AppearanceItem::Fill(fill), AppearanceItem::Stroke(stroke)] = rect.appearance.items.as_slice() else { + panic!("{:?}", rect.appearance.items) + }; + assert_eq!(fill.paint, Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0))); + assert_eq!(stroke.paint, Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + assert!((stroke.width - 2.0).abs() < 0.05, "{}", stroke.width); + // The curve is drawn at twice its size by its matrix: 100 pt wide. + let NodeKind::Path { path, .. } = &p[0].kind else { panic!("{:?}", p[0].kind) }; + assert!((path.bounds().unwrap().width() - 100.0).abs() < 0.2); + assert_eq!(doc.color_mode, vectorcraft_doc::ColorMode::Cmyk); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + s.execute("file.place", &json!({"name":"art.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap(); + assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty())); + } + // The two letters alone are not taken for a drawing. + assert_eq!(detect("notes.bin", b"WLAN settings, exported as plain text for the help desk").map(|f| f.id), None); +} + +#[test] +fn objects_keep_the_file_order_front_to_back() { + let v = V(1100); + let rect = + |w: f64| synth::object(v, 1, &[(30, [v.coord(w), v.coord(10.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + // The first object listed is the front-most. + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(30.0), rect(20.0)])]); + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), page]); + let (doc, _) = super::cdr::import(&file).unwrap(); + let p = paths(&doc); + let widths: Vec = p + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Path { path, .. } => path.bounds(), + _ => None, + }) + .map(|b| b.width().round()) + .collect(); + assert_eq!(widths, vec![20.0, 30.0], "bottom first"); +} + +#[test] +fn spot_colors_become_spot_swatches_and_cmyk_drawings_open_in_cmyk() { + let v = V(1100); + let spot = synth::color(25, [7, 0, 40, 0]); + let cmyk = synth::color(2, [0, 100, 0, 0]); + let doc = list(b"doc ", vec![list(b"filt", vec![chunk(b"fild", v.fill(1, &spot)), chunk(b"fild", v.fill(2, &cmyk))])]); + let obj = |fill: u32| { + synth::object( + v, + 1, + &[ + (20, fill.to_le_bytes().to_vec()), + (30, [v.coord(10.0), v.coord(10.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat()), + ], + None, + ) + }; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![obj(1), obj(2), obj(2)])]); + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page]); + let (doc, warnings) = super::cdr::import(&file).unwrap(); + let s = doc.swatches.iter().find(|s| s.name == "Spot 0:7").unwrap(); + assert!(s.spot && s.global); + assert!(warnings.iter().any(|w| w.contains("library colors")), "{warnings:?}"); + let filled_with_spot = paths(&doc).iter().any(|n| { + n.appearance.items.iter().any(|i| matches!(i, vectorcraft_doc::appearance::AppearanceItem::Fill(f) if matches!(&f.paint, vectorcraft_color::Paint::Solid { swatch: Some(name), tint, .. } if name == "Spot 0:7" && (*tint - 0.4).abs() < 1e-6))) + }); + assert!(filled_with_spot); + assert_eq!(doc.color_mode, vectorcraft_doc::ColorMode::Cmyk); +} + +#[test] +fn detection_by_content_place_and_template() { + let bytes = synth::sample(1100, true); + let mut s = Session::new(); + // A renamed drawing is found by its content. + assert_eq!(open_bytes(&mut s, "renamed.bin", &bytes, None).unwrap()["format"], "cdr"); + assert_eq!(detect("drawing.cdt", &bytes).map(|f| f.id), Some("cdt")); + assert_eq!(detect("drawing.png", &bytes).map(|f| f.id), Some("cdr")); + // So is a package of version 14 or later, and other ZIP archives are not taken for one. + for version in [1400, 2700] { + let package = synth::sample_file(version, true); + assert_eq!(open_bytes(&mut s, "renamed.zip", &package, None).unwrap()["format"], "cdr", "{version}"); + assert_eq!(detect("drawing.cdt", &package).map(|f| f.id), Some("cdt")); + } + let other = synth::zip(&[synth::Member { name: "content/other.dat".into(), data: vec![1, 2, 3], deflate: false }], b""); + assert_eq!(detect("archive.zip", &other).map(|f| f.id), None); + let r = open_bytes(&mut s, "letter.cdt", &bytes, Some("/t/letter.cdt".into())).unwrap(); + assert_eq!(r["format"], "cdt"); + assert!(s.doc().unwrap().path.is_none(), "a template opens untitled"); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + s.execute("file.place", &json!({"name":"art.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap(); + assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty())); + // Packages place too. + for version in [1400, 2700] { + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let package = synth::sample_file(version, true); + s.execute("file.place", &json!({"name":"art.cdr", "dataBase64":vectorcraft_format::base64_encode(&package)})).unwrap(); + assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty()), "{version}"); + } + for ext in ["cdr", "cdt"] { + let f = format(ext).unwrap(); + assert!(f.read && !f.write); + assert!(OPEN_EXTS.contains(&ext) && PLACE_EXTS.contains(&ext) && UNASSOCIATED_EXTS.contains(&ext), "{ext}"); + assert!(!SAVE_FORMATS.contains(&ext)); + } +} + +#[test] +fn layers_of_one_name_on_a_page_stay_apart_and_pages_share_them() { + let v = V(1100); + let rect = || synth::object(v, 1, &[(30, [v.coord(5.0), v.coord(5.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let layer = |name: &str| synth::layer(v, [0, 0, 0, 0x98], name, vec![rect()]); + // Front to back: A, B, A on each of two pages. + let page = || synth::page(false, vec![layer("A"), layer("B"), layer("A")]); + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), page(), page()]); + let (doc, _) = super::cdr::import(&file).unwrap(); + let names: Vec = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, ["A", "B", "A"]); + assert!(doc.layers.iter().all(|l| l.children().unwrap().len() == 2), "one object from each page"); +} + +/// Pages that stack layers of the same names in another order keep their own order: the later +/// page gets a new layer rather than art under a layer it stacks above. A layer a later page adds +/// below the shared ones goes below them. +#[test] +fn each_page_keeps_its_own_layer_order() { + let v = V(1100); + let rect = || synth::object(v, 1, &[(30, [v.coord(5.0), v.coord(5.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let page = |names: &[&str]| synth::page(false, names.iter().map(|n| synth::layer(v, [0, 0, 0, 0x98], n, vec![rect()])).collect()); + // Front to back on each page. + for (second, want, counts) in [(&["A", "B"][..], vec!["A", "B", "A"], vec![1, 2, 1]), (&["B", "A", "C"][..], vec!["C", "A", "B"], vec![1, 2, 2])] + { + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), page(&["B", "A"]), page(second)]); + let (doc, _) = super::cdr::import(&file).unwrap(); + let names: Vec = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, want, "bottom to top, second page {second:?}"); + let got: Vec = doc.layers.iter().map(|l| l.children().unwrap().len()).collect(); + assert_eq!(got, counts, "second page {second:?}"); + } +} + +/// Pages that alternate between two orders of the same layers reuse the layers made for each +/// order instead of adding layers page after page. +#[test] +fn pages_in_alternating_layer_orders_reuse_their_layers() { + let v = V(1100); + let rect = || synth::object(v, 1, &[(30, [v.coord(5.0), v.coord(5.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let page = |names: &[&str]| synth::page(false, names.iter().map(|n| synth::layer(v, [0, 0, 0, 0x98], n, vec![rect()])).collect()); + // Front to back on each page. + let mut kids = vec![chunk(b"vrsn", 1100u16.to_le_bytes().to_vec())]; + kids.extend((0..6).map(|i| if i % 2 == 0 { page(&["B", "A"]) } else { page(&["A", "B"]) })); + let (doc, _) = super::cdr::import(&synth::riff(1100, &kids)).unwrap(); + let names: Vec = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, ["A", "B", "A"], "bottom to top"); + let got: Vec = doc.layers.iter().map(|l| l.children().unwrap().len()).collect(); + assert_eq!(got, [3, 6, 3]); +} + +#[test] +fn pages_and_the_guides_copied_onto_them_are_bounded() { + let v = V(1100); + let guide = |x: f64| { + let mut g = vec![0; 12]; + g.extend(90_000_000i32.to_le_bytes()); + g.extend([v.coord(x), v.coord(0.0), v.coord(x), v.coord(10.0), v.coord(x), v.coord(0.0)].concat()); + synth::object(v, 0x16, &[(16000, g)], None) + }; + let guides: Vec<_> = (0..200).map(|i| guide(f64::from(i))).collect(); + let mut kids = vec![chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), synth::page(true, vec![synth::layer(v, [0x0a, 0, 1, 0x98], "G", guides)])]; + kids.extend((0..1100).map(|_| synth::page(false, vec![]))); + let (doc, warnings) = super::cdr::import(&synth::riff(1100, &kids)).unwrap(); + assert_eq!(doc.artboards.len(), 1000); + let guides = doc.ruler_guides().len(); + assert!(guides <= 100_000, "{guides}"); + assert!(warnings.iter().any(|w| w.contains("past the import limits")), "{warnings:?}"); +} + +/// Layers are held to 10,000, the master page's and the pages' together; at the limit, guide +/// paths of angled guidelines go on the top layer. +#[test] +fn layers_are_bounded() { + let v = V(1100); + let rect = || synth::object(v, 1, &[(30, [v.coord(5.0), v.coord(5.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let mut angled = vec![0; 12]; + angled.extend(45_000_000i32.to_le_bytes()); + angled.extend([v.coord(0.0), v.coord(0.0)].concat()); + let angled = synth::object(v, 0x16, &[(16000, angled)], None); + let page_layers = + (0..10_050).map(|i| synth::layer(v, [0, 0, 0, 0x98], &format!("L{i}"), if i == 0 { vec![angled.clone()] } else { vec![] })).collect(); + let master_layers = (0..10_050).map(|i| synth::layer(v, [0, 0, 1, 0x98], &format!("M{i}"), vec![rect()])).collect(); + for (page, guide_paths) in [(synth::page(false, page_layers), 1), (synth::page(true, master_layers), 0)] { + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), page, synth::page(false, vec![])]); + let (doc, warnings) = super::cdr::import(&file).unwrap(); + assert_eq!(doc.layers.len(), 10_000); + assert!(warnings.iter().any(|w| w.contains("past the import limits")), "{warnings:?}"); + let guides = paths(&doc).iter().filter(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })).count(); + assert_eq!(guides, guide_paths); + } +} + +/// A guide path of an angled guideline runs from edge to edge of its page, so it moves with that +/// page's artboard and not with the page beside it. +#[test] +fn angled_guides_move_with_their_page() { + let v = V(1100); + let angled = |deg: i32, x: f64, y: f64| { + let mut g = vec![0; 12]; + g.extend((deg * 1_000_000).to_le_bytes()); + g.extend([v.coord(x), v.coord(y)].concat()); + synth::object(v, 0x16, &[(16000, g)], None) + }; + let page = |g| synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "G", vec![g])]); + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), page(angled(45, 0.0, 0.0)), page(angled(30, 50.0, -40.0))]); + let (doc, _) = super::cdr::import(&file).unwrap(); + assert_eq!(doc.artboards.len(), 2); + let guide = |id: &vectorcraft_doc::NodeId| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })); + let moving: Vec> = (0..2).map(|i| doc.art_moving_with(i, false).into_iter().filter(guide).collect()).collect(); + assert_eq!(moving[0].len(), 1, "{moving:?}"); + assert_eq!(moving[1].len(), 1, "{moving:?}"); + assert_ne!(moving[0], moving[1]); +} + +/// A page longer than the longest artboard opens at that length, and the warnings say so. +#[test] +fn pages_past_the_longest_artboard_are_cut_with_a_warning() { + let v = V(1100); + for (w, cut) in [(200_000.0, true), (100_000.0, false)] { + let doc = list(b"doc ", vec![synth::mcfg(v, w, 792.0)]); + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, synth::page(false, vec![])]); + let (doc, warnings) = super::cdr::import(&file).unwrap(); + assert_eq!(doc.artboards[0].rect.width().round(), if cut { 163_830.0 } else { w }, "{w}"); + assert_eq!(warnings.iter().any(|x| x.contains("longer than 163,830 pt")), cut, "{w}: {warnings:?}"); + } +} + +#[test] +fn fills_and_outlines_keep_their_colors_widths_caps_joins_and_dashes() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::appearance::{AppearanceItem, LineCap, LineJoin}; + let v = V(1300); + let red = synth::color(5, [0, 0, 255, 0]); + let black = synth::color(2, [0, 0, 0, 100]); + let pen = synth::Pen { line_type: 0, width: 2.0, cap: 1, join: 2 }; + let args = vec![ + (20, 1u32.to_le_bytes().to_vec()), + (10, 2u32.to_le_bytes().to_vec()), + (30, v.points(&[(0.0, 0.0, 0x08), (10.0, 0.0, 0x40), (10.0, 10.0, 0x48)])), + ]; + let styles = list( + b"doc ", + vec![list(b"filt", vec![chunk(b"fild", v.fill(1, &red))]), list(b"otlt", vec![chunk(b"outl", v.outline(2, pen, &black, &[3, 1]))])], + ); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 3, &args, None)])]); + let (doc, _) = super::cdr::import(&synth::riff(1300, &[chunk(b"vrsn", 1300u16.to_le_bytes().to_vec()), styles, page])).unwrap(); + let p = paths(&doc); + let [AppearanceItem::Fill(fill), AppearanceItem::Stroke(stroke)] = p[0].appearance.items.as_slice() else { + panic!("{:?}", p[0].appearance.items) + }; + assert_eq!(fill.paint, Paint::solid(Color::rgb(1.0, 0.0, 0.0))); + assert_eq!(stroke.paint, Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + assert!((stroke.width - 2.0).abs() < 0.01, "{}", stroke.width); + assert_eq!((stroke.cap, stroke.join), (LineCap::Round, LineJoin::Bevel)); + // Dashes are stored in multiples of the width. + let dash = stroke.dash.as_ref().unwrap(); + assert!(dash.pattern.len() == 2 && (dash.pattern[0] - 6.0).abs() < 0.01 && (dash.pattern[1] - 2.0).abs() < 0.01, "{:?}", dash.pattern); +} + +#[test] +fn other_versions_and_damaged_drawings_say_why() { + let mut s = Session::new(); + // A RIFF file that names version 2: files of versions 1 and 2 are not RIFF files. + let e = open_bytes(&mut s, "old.cdr", &synth::riff(200, &[]), None).unwrap_err().to_string(); + assert!(e.contains("can't be read (RIFF files of versions before 3 are not read)"), "{e}"); + let e = open_bytes(&mut s, "new.cdr", &synth::riff(2800, &[]), None).unwrap_err().to_string(); + assert!(e.contains("CDR 28 drawings can't be opened: VectorCraft reads versions 1 to 27"), "{e}"); + // A file that starts like one of version 1 or 2 but whose offsets don't fit it. + let e = open_bytes(&mut s, "odd.cdr", b"WLe\0 and no more", None).unwrap_err().to_string(); + assert!(e.contains("can't be read (not a CDR drawing)"), "{e}"); + // A package cut short, and one whose drawing is encrypted (flag bit 0 of its directory entry). + let package = synth::sample_file(1400, false); + let e = open_bytes(&mut s, "cut.cdr", &package[..package.len() / 2], None).unwrap_err().to_string(); + assert!(e.contains("can't be read (damaged package directory)"), "{e}"); + let mut encrypted = package.clone(); + let dir = package.windows(4).position(|w| w == b"PK\x01\x02").unwrap(); + encrypted[dir + 8] |= 1; + let e = open_bytes(&mut s, "locked.cdr", &encrypted, None).unwrap_err().to_string(); + assert!(e.contains("can't be read (encrypted packages are not read)"), "{e}"); + let mut big = synth::riff(1100, &[]); + big[4..8].copy_from_slice(&u32::MAX.to_le_bytes()); + // A declared size past the end keeps what the file holds. + assert!(open_bytes(&mut s, "cut.cdr", &big, None).is_ok()); +} diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index ac98db8e9c..fdc2be6692 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -6,8 +6,9 @@ //! of every kind with random contents) opened, placed or pasted, nor EPS and PostScript files //! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of //! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor Affinity documents -//! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor the -//! font files a folder search reads (damaged fonts, collections whose headers give any count of +//! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor +//! `.cdr` drawings (mutated and cut short, plain, compressed and packaged, opened and placed), +//! nor the font files a folder search reads (damaged fonts, collections whose headers give any count of //! faces), nor scripts written for the reference app checked without running them (garbage, //! generated script text and mutated scripts). //! @@ -268,6 +269,124 @@ proptest! { } } +// ---------- .cdr drawings ---------- + +proptest! { + #![proptest_config(config())] + + #[test] + fn cdr_mutated_drawings_render_and_export( + version in prop::sample::select(vec![300u16, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300]), + compress: bool, + cut in 12usize..8192, + edits in prop::collection::vec((0usize..8192, any::()), 0..24), + ) { + let mut bytes = vectorcraft_cdr::synth::sample(version, compress && version >= 700); + let n = bytes.len(); + for (at, b) in edits { bytes[at % n] = b; } + bytes.truncate(cut); + survive("CDR drawing", || vectorcraft_engine::cmd::fileio::load("x.cdr", &bytes).ok().map(|l| l.doc))?; + } + + #[test] + fn cdr_mutated_packages_render_and_export( + version in prop::sample::select(vec![1400u16, 1500, 1600, 2000, 2700]), + cut in prop::option::of(22usize..16384), + edits in prop::collection::vec((any::(), 0usize..8192, any::()), 0..24), + ) { + // The members are edited before they are zipped, so that the edits reach the drawing + // rather than stop at the CRC-32; the archive may then be cut short. + let mut members = if version < 1600 { + vec![vectorcraft_cdr::synth::Member { name: "content/riffData.cdr".into(), data: vectorcraft_cdr::synth::sample(version, true), deflate: false }] + } else { + let mut body = vec![vectorcraft_cdr::synth::chunk(b"vrsn", version.to_le_bytes().to_vec())]; + body.extend(vectorcraft_cdr::synth::sample_content(version)); + vectorcraft_cdr::synth::package16_members(version, &body, false, &[]) + }; + for (m, at, b) in edits { + let k = m % members.len(); + let data = &mut members[k].data; + if !data.is_empty() { + let n = data.len(); + data[at % n] = b; + } + } + let mut bytes = vectorcraft_cdr::synth::zip(&members, b""); + if let Some(cut) = cut { + bytes.truncate(cut); + } + survive("CDR package", || vectorcraft_engine::cmd::fileio::load("x.cdr", &bytes).ok().map(|l| l.doc))?; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let p = json!({"name":"x.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "CDR package placement panicked: {:?}", r.err()); + } + + #[test] + fn cdr_garbage_opens_and_places_without_panicking(tail in prop::collection::vec(any::(), 0..2048)) { + let mut bytes = b"RIFF".to_vec(); + bytes.extend(((4 + tail.len()) as u32).to_le_bytes()); + bytes.extend(b"CDRB"); + bytes.extend(tail); + survive("CDR garbage", || vectorcraft_engine::cmd::fileio::load("x.cdr", &bytes).ok().map(|l| l.doc))?; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let p = json!({"name":"x.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "CDR placement panicked: {:?}", r.err()); + } + + // Drawings of versions 1 and 2 are not RIFF files: a header of offsets, then records. + #[test] + fn cdr_mutated_wl_drawings_render_and_export( + marker in prop::sample::select(vec![b'd', b'e', b'm']), + cut in prop::option::of(0usize..1024), + edits in prop::collection::vec((0usize..8192, any::()), 0..24), + ) { + let mut bytes = vectorcraft_cdr::synth::wl_sample(marker); + let n = bytes.len(); + for (at, b) in edits { bytes[at % n] = b; } + if let Some(cut) = cut { + bytes.truncate(cut); + } + survive("CDR drawing of version 1 or 2", || vectorcraft_engine::cmd::fileio::load("x.cdr", &bytes).ok().map(|l| l.doc))?; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let p = json!({"name":"x.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "placing a CDR drawing of version 1 or 2 panicked: {:?}", r.err()); + } + + #[test] + fn cdr_garbage_after_a_wl_header_opens_and_places_without_panicking( + marker in prop::sample::select(vec![b'd', b'e', b'm']), + tail in prop::collection::vec(any::(), 0..2048), + ) { + // Offsets that fit the file, so the garbage is walked as records. + let mut bytes = vec![b'W', b'L', marker, 0]; + bytes.extend(28u32.to_le_bytes()); + bytes.extend(28u32.to_le_bytes()); + bytes.extend((28 + tail.len() as u32).to_le_bytes()); + bytes.extend([0; 12]); + bytes.extend(tail); + survive("CDR garbage of version 1 or 2", || vectorcraft_engine::cmd::fileio::load("x.cdr", &bytes).ok().map(|l| l.doc))?; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let p = json!({"name":"x.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "placing CDR garbage of version 1 or 2 panicked: {:?}", r.err()); + } +} + // ---------- Affinity documents with every feature the reader maps ---------- #[path = "support/affinity_docs.rs"] diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 0b642a2007..65b8589783 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6690,6 +6690,17 @@ breakText Glyphs Glifs @msg the HEIC or HEIF file can't be read no es pot llegir el fitxer HEIC o HEIF @msg the HEIC or HEIF file holds a kind of image that can't be read el fitxer HEIC o HEIF conté un tipus d'imatge que no es pot llegir @msg HEIC and HEIF images can't be opened in this build les imatges HEIC i HEIF no es poden obrir en aquesta compilació +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 no es poden obrir dibuixos del CDR {version}: el VectorCraft llegeix les versions 1 a 27 +@msg this CDR drawing can't be read ({why}) no es pot llegir aquest dibuix del CDR ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out s’han omès els textos, els mapes de bits, les fusions, les siluetes, els traços de pinzell i altres objectes del CDR que el VectorCraft encara no llegeix +@msg CDR fountain, pattern, texture and PostScript fills were left out s’han omès els emplenaments degradats, de patró, de textura i PostScript del CDR +@msg colors in CDR color models VectorCraft doesn't read were opened as black els colors en models de color del CDR que el VectorCraft no llegeix s’han obert en negre +@msg CDR library colors that the drawing stores only by number were opened as black spot colors els colors de biblioteca del CDR que el dibuix desa només pel número s’han obert com a colors directes negres +@msg CDR outline arrowheads were left out s’han omès les puntes de fletxa dels contorns del CDR +@msg CDR envelopes were not applied, and the shapes under them keep their outlines no s’han aplicat les envoltants del CDR, i les formes que hi ha a sota conserven els seus contorns +@msg parts of the drawing nested too deeply, or past the import limits, were left out s’han omès les parts del dibuix imbricades massa a fons o fora dels límits d’importació +@msg damaged parts of the drawing were left out s’han omès les parts danyades del dibuix +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard les pàgines del CDR de més de 163.830 pt s’han obert amb aquesta longitud, i el dibuix a prop de les vores queda fora del tauler @msg You must choose a side pattern. Heu de triar un patró lateral. @msg invalid pattern tile choice opció de mosaic de patró no vàlida @msg no pattern named `{choice}` no hi ha cap patró anomenat `{choice}` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b9599f2f6d..1d019853a5 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5320,6 +5320,17 @@ imageTrace Outline Obrys @msg the HEIC or HEIF file can't be read soubor HEIC nebo HEIF nelze přečíst @msg the HEIC or HEIF file holds a kind of image that can't be read soubor HEIC nebo HEIF obsahuje druh obrázku, který nelze přečíst @msg HEIC and HEIF images can't be opened in this build obrázky HEIC a HEIF nelze v tomto sestavení otevřít +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 výkresy CDR {version} nelze otevřít: VectorCraft čte verze 1 až 27 +@msg this CDR drawing can't be read ({why}) tento výkres CDR nelze přečíst ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out texty, bitmapy, prolnutí, kontury, tahy štětcem a další objekty CDR, které VectorCraft zatím nečte, byly vynechány +@msg CDR fountain, pattern, texture and PostScript fills were left out přechodové, vzorkové, texturové a PostScriptové výplně CDR byly vynechány +@msg colors in CDR color models VectorCraft doesn't read were opened as black barvy v barevných modelech CDR, které VectorCraft nečte, byly otevřeny jako černé +@msg CDR library colors that the drawing stores only by number were opened as black spot colors knihovní barvy CDR, které výkres ukládá jen číslem, byly otevřeny jako černé přímé barvy +@msg CDR outline arrowheads were left out šipky na obrysových čarách CDR byly vynechány +@msg CDR envelopes were not applied, and the shapes under them keep their outlines obálky CDR nebyly použity a tvary pod nimi si ponechávají své obrysy +@msg parts of the drawing nested too deeply, or past the import limits, were left out části výkresu vnořené příliš hluboko nebo za hranicemi importu byly vynechány +@msg damaged parts of the drawing were left out poškozené části výkresu byly vynechány +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard stránky CDR delší než 163 830 pt byly otevřeny v této délce a kresba u jejich okrajů leží mimo pracovní plochu @msg the PSD image is too large to read ({_1} × {_2} pixels) obraz PSD je příliš velký na přečtení ({_1} × {_2} obrazových bodů) @msg zipped 1-bit PSD image data with prediction can't be read zazipovaná 1bitová obrazová data PSD s predikcí nelze přečíst @msg the PSD file's layer data uses an unknown compression ({m}) data vrstev souboru PSD používají neznámou kompresi ({m}) diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 17392851a3..1d4dc2af43 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5071,6 +5071,17 @@ theme Appearance Erscheinungsbild @msg the HEIC or HEIF file can't be read die HEIC- oder HEIF-Datei kann nicht gelesen werden @msg the HEIC or HEIF file holds a kind of image that can't be read die HEIC- oder HEIF-Datei enthält eine Bildart, die nicht gelesen werden kann @msg HEIC and HEIF images can't be opened in this build HEIC- und HEIF-Bilder können in diesem Build nicht geöffnet werden +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 Zeichnungen aus CDR {version} können nicht geöffnet werden: VectorCraft liest die Versionen 1 bis 27 +@msg this CDR drawing can't be read ({why}) diese CDR-Zeichnung kann nicht gelesen werden ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out Texte, Bitmaps, Überblendungen, Konturen, Pinselstriche und andere CDR-Objekte, die VectorCraft noch nicht liest, wurden ausgelassen +@msg CDR fountain, pattern, texture and PostScript fills were left out CDR-Verlaufs-, Muster-, Textur- und PostScript-Füllungen wurden ausgelassen +@msg colors in CDR color models VectorCraft doesn't read were opened as black Farben in CDR-Farbmodellen, die VectorCraft nicht liest, wurden als Schwarz geöffnet +@msg CDR library colors that the drawing stores only by number were opened as black spot colors CDR-Bibliotheksfarben, die die Zeichnung nur als Nummer speichert, wurden als schwarze Volltonfarben geöffnet +@msg CDR outline arrowheads were left out Pfeilspitzen an CDR-Umrisslinien wurden ausgelassen +@msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR-Hüllen wurden nicht angewendet, und die Formen darunter behalten ihre Umrisse +@msg parts of the drawing nested too deeply, or past the import limits, were left out Teile der Zeichnung, die zu tief verschachtelt sind oder die Importgrenzen überschreiten, wurden ausgelassen +@msg damaged parts of the drawing were left out beschädigte Teile der Zeichnung wurden ausgelassen +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard CDR-Seiten, die länger als 163.830 pt sind, wurden in dieser Länge geöffnet, und Grafik nahe ihren Rändern liegt außerhalb der Zeichenfläche @msg the PSD image is too large to read ({_1} × {_2} pixels) das PSD-Bild ist zu groß zum Lesen ({_1} × {_2} Pixel) @msg zipped 1-bit PSD image data with prediction can't be read ZIP-komprimierte 1-Bit-PSD-Bilddaten mit Vorhersage können nicht gelesen werden @msg the PSD file's layer data uses an unknown compression ({m}) die Ebenendaten der PSD-Datei verwenden eine unbekannte Komprimierung ({m}) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 48099c9440..4aeee667dc 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4999,6 +4999,17 @@ digits Malayalam Μαλαγιάλαμ @msg the HEIC or HEIF file can't be read δεν είναι δυνατή η ανάγνωση του αρχείου HEIC ή HEIF @msg the HEIC or HEIF file holds a kind of image that can't be read το αρχείο HEIC ή HEIF περιέχει είδος εικόνας που δεν είναι δυνατό να διαβαστεί @msg HEIC and HEIF images can't be opened in this build οι εικόνες HEIC και HEIF δεν μπορούν να ανοίξουν σε αυτή την έκδοση +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 δεν είναι δυνατό το άνοιγμα σχεδίων του CDR {version}: το VectorCraft διαβάζει τις εκδόσεις 1 έως 27 +@msg this CDR drawing can't be read ({why}) δεν είναι δυνατή η ανάγνωση αυτού του σχεδίου CDR ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out παραλείφθηκαν κείμενα, bitmap, αναμείξεις, ομόκεντρα περιγράμματα, πινελιές και άλλα αντικείμενα του CDR που το VectorCraft δεν διαβάζει ακόμη +@msg CDR fountain, pattern, texture and PostScript fills were left out παραλείφθηκαν τα διαβαθμισμένα γεμίσματα και τα γεμίσματα μοτίβου, υφής και PostScript του CDR +@msg colors in CDR color models VectorCraft doesn't read were opened as black τα χρώματα σε χρωματικά μοντέλα του CDR που δεν διαβάζει το VectorCraft ανοίχτηκαν ως μαύρα +@msg CDR library colors that the drawing stores only by number were opened as black spot colors τα χρώματα βιβλιοθήκης του CDR που το σχέδιο αποθηκεύει μόνο με αριθμό ανοίχτηκαν ως μαύρα πλακάτα χρώματα +@msg CDR outline arrowheads were left out παραλείφθηκαν οι αιχμές βελών των γραμμών περιγράμματος του CDR +@msg CDR envelopes were not applied, and the shapes under them keep their outlines δεν εφαρμόστηκαν τα περιβλήματα του CDR, και τα σχήματα κάτω από αυτά διατηρούν τα περιγράμματά τους +@msg parts of the drawing nested too deeply, or past the import limits, were left out παραλείφθηκαν τμήματα του σχεδίου με υπερβολικά βαθιά ένθεση ή πέρα από τα όρια εισαγωγής +@msg damaged parts of the drawing were left out παραλείφθηκαν κατεστραμμένα τμήματα του σχεδίου +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard οι σελίδες του CDR με μήκος πάνω από 163.830 pt ανοίχτηκαν σε αυτό το μήκος και το γραφικό κοντά στα άκρα τους βρίσκεται έξω από τον πίνακα σχεδίασης @msg the PSD image is too large to read ({_1} × {_2} pixels) η εικόνα PSD είναι πολύ μεγάλη για ανάγνωση ({_1} × {_2} εικονοστοιχεία) @msg zipped 1-bit PSD image data with prediction can't be read τα συμπιεσμένα δεδομένα εικόνας PSD 1 bit με πρόβλεψη δεν διαβάζονται @msg the PSD file's layer data uses an unknown compression ({m}) τα δεδομένα επιπέδων του αρχείου PSD χρησιμοποιούν άγνωστη συμπίεση ({m}) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 8bc2616f25..cd88d4b938 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5038,6 +5038,17 @@ axis Both Ambos @msg the HEIC or HEIF file can't be read no se puede leer el archivo HEIC o HEIF @msg the HEIC or HEIF file holds a kind of image that can't be read el archivo HEIC o HEIF contiene un tipo de imagen que no se puede leer @msg HEIC and HEIF images can't be opened in this build las imágenes HEIC y HEIF no se pueden abrir en esta compilación +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 no se pueden abrir dibujos de CDR {version}: VectorCraft lee las versiones 1 a 27 +@msg this CDR drawing can't be read ({why}) no se puede leer este dibujo de CDR ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out se omitieron textos, mapas de bits, mezclas, siluetas, trazos de pincel y otros objetos de CDR que VectorCraft aún no lee +@msg CDR fountain, pattern, texture and PostScript fills were left out se omitieron los rellenos degradados, de patrón, de textura y PostScript de CDR +@msg colors in CDR color models VectorCraft doesn't read were opened as black los colores en modelos de color de CDR que VectorCraft no lee se abrieron en negro +@msg CDR library colors that the drawing stores only by number were opened as black spot colors los colores de biblioteca de CDR que el dibujo guarda solo por número se abrieron como tintas planas negras +@msg CDR outline arrowheads were left out se omitieron las puntas de flecha de los contornos de CDR +@msg CDR envelopes were not applied, and the shapes under them keep their outlines no se aplicaron las envolventes de CDR, y las formas que contienen conservan sus contornos +@msg parts of the drawing nested too deeply, or past the import limits, were left out se omitieron partes del dibujo anidadas a demasiada profundidad o fuera de los límites de importación +@msg damaged parts of the drawing were left out se omitieron partes dañadas del dibujo +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard las páginas de CDR de más de 163.830 pt se abrieron con esa longitud, y el arte cerca de sus bordes queda fuera de la mesa de trabajo @msg the PSD image is too large to read ({_1} × {_2} pixels) la imagen PSD es demasiado grande para leerla ({_1} × {_2} píxeles) @msg zipped 1-bit PSD image data with prediction can't be read no se pueden leer datos de imagen PSD de 1 bit comprimidos en ZIP con predicción @msg the PSD file's layer data uses an unknown compression ({m}) los datos de capa del archivo PSD usan una compresión desconocida ({m}) diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d9bf3e80da..a398d0e4f6 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5222,6 +5222,17 @@ imageTrace Outline Ääriviiva @msg the HEIC or HEIF file can't be read tätä HEIC- tai HEIF-tiedostoa ei voi lukea @msg the HEIC or HEIF file holds a kind of image that can't be read tässä HEIC- tai HEIF-tiedostossa on kuvatyyppi, jota ei voi lukea @msg HEIC and HEIF images can't be opened in this build HEIC- ja HEIF-kuvia ei voi avata tässä versiossa +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 CDR {version} -piirroksia ei voi avata: VectorCraft lukee versioita 1–27 +@msg this CDR drawing can't be read ({why}) tätä CDR-piirrosta ei voi lukea ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out CDR-tekstit, bittikartat, sulautukset, kontuurit, siveltimenvedot ja muut objektit, joita VectorCraft ei vielä lue, jätettiin pois +@msg CDR fountain, pattern, texture and PostScript fills were left out CDR-liukuväri-, kuvio-, pintakuvio- ja PostScript-täytöt jätettiin pois +@msg colors in CDR color models VectorCraft doesn't read were opened as black värit CDR-värimalleissa, joita VectorCraft ei lue, avattiin mustina +@msg CDR library colors that the drawing stores only by number were opened as black spot colors CDR-kirjastovärit, jotka piirros tallentaa vain numerona, avattiin mustina spottiväreinä +@msg CDR outline arrowheads were left out CDR-ääriviivojen nuolenkärjet jätettiin pois +@msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR-verhokäyriä ei käytetty, ja niiden alla olevat muodot säilyttävät ääriviivansa +@msg parts of the drawing nested too deeply, or past the import limits, were left out liian syvälle sisäkkäiset tai tuontirajojen ylittävät piirroksen osat jätettiin pois +@msg damaged parts of the drawing were left out piirroksen vahingoittuneet osat jätettiin pois +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard yli 163 830 pt pitkät CDR-sivut avattiin tämän pituisina, ja niiden reunojen lähellä oleva grafiikka on piirtoalustan ulkopuolella @msg the PSD image is too large to read ({_1} × {_2} pixels) tämä PSD-kuva on liian suuri luettavaksi ({_1} × {_2} pikseliä) @msg zipped 1-bit PSD image data with prediction can't be read ennustusta käyttävää zip-pakattua 1-bittistä PSD-kuvadataa ei voi lukea @msg the PSD file's layer data uses an unknown compression ({m}) tämän PSD-tiedoston tasodata käyttää tuntematonta pakkausta ({m}) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 93f330de11..4bc1284566 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5045,6 +5045,17 @@ axis Both Les deux @msg the HEIC or HEIF file can't be read le fichier HEIC ou HEIF ne peut pas être lu @msg the HEIC or HEIF file holds a kind of image that can't be read le fichier HEIC ou HEIF contient un type d'image qui ne peut pas être lu @msg HEIC and HEIF images can't be opened in this build les images HEIC et HEIF ne peuvent pas être ouvertes dans cette version +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 impossible d’ouvrir les dessins de CDR {version} : VectorCraft lit les versions 1 à 27 +@msg this CDR drawing can't be read ({why}) impossible de lire ce dessin CDR ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out les textes, bitmaps, dégradés de formes, contours progressifs, traits de pinceau et autres objets CDR que VectorCraft ne lit pas encore ont été ignorés +@msg CDR fountain, pattern, texture and PostScript fills were left out les remplissages dégradés, à motif, de texture et PostScript de CDR ont été ignorés +@msg colors in CDR color models VectorCraft doesn't read were opened as black les couleurs des modèles colorimétriques CDR que VectorCraft ne lit pas ont été ouvertes en noir +@msg CDR library colors that the drawing stores only by number were opened as black spot colors les couleurs de bibliothèque CDR que le dessin enregistre uniquement par numéro ont été ouvertes comme tons directs noirs +@msg CDR outline arrowheads were left out les pointes de flèche des contours CDR ont été ignorées +@msg CDR envelopes were not applied, and the shapes under them keep their outlines les enveloppes CDR n’ont pas été appliquées, et les formes qu’elles contiennent gardent leurs contours +@msg parts of the drawing nested too deeply, or past the import limits, were left out les parties du dessin trop profondément imbriquées ou au-delà des limites d’importation ont été ignorées +@msg damaged parts of the drawing were left out les parties endommagées du dessin ont été ignorées +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard les pages CDR de plus de 163 830 pt ont été ouvertes à cette longueur, et l’illustration proche de leurs bords se trouve hors du plan de travail @msg the PSD image is too large to read ({_1} × {_2} pixels) l'image PSD est trop grande pour être lue ({_1} × {_2} pixels) @msg zipped 1-bit PSD image data with prediction can't be read les données d'image PSD 1 bit compressées en ZIP avec prédiction ne peuvent pas être lues @msg the PSD file's layer data uses an unknown compression ({m}) les données de calque du fichier PSD utilisent une compression inconnue ({m}) diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index d2fc0dc733..5d75e54e6e 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7734,6 +7734,17 @@ antiAlias Sharp शार्प @msg the job would print more than {_1} pages नौकरी {_1} पृष्ठों से अधिक प्रिंट करेगी @msg the job would print more than {MAX_PAGES} pages इस जॉब में {MAX_PAGES} से अधिक पेज प्रिंट होंगे @msg the JPEG 2000 file can't be read JPEG 2000 फ़ाइल पढ़ा नहीं जा सकता +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 CDR {version} की ड्रॉइंग नहीं खोली जा सकतीं: VectorCraft संस्करण 1 से 27 तक पढ़ता है +@msg this CDR drawing can't be read ({why}) इस CDR ड्रॉइंग को पढ़ा नहीं जा सकता ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out CDR के टेक्स्ट, बिटमैप, ब्लेंड, कंटूर, ब्रश स्ट्रोक और अन्य ऑब्जेक्ट, जिन्हें VectorCraft अभी नहीं पढ़ता, छोड़ दिए गए +@msg CDR fountain, pattern, texture and PostScript fills were left out CDR के फ़ाउंटेन, पैटर्न, टेक्सचर और PostScript फ़िल छोड़ दिए गए +@msg colors in CDR color models VectorCraft doesn't read were opened as black जिन CDR रंग मॉडलों को VectorCraft नहीं पढ़ता, उनके रंग काले के रूप में खोले गए +@msg CDR library colors that the drawing stores only by number were opened as black spot colors CDR लाइब्रेरी के जिन रंगों को ड्रॉइंग केवल संख्या से सहेजती है, वे काले स्पॉट रंगों के रूप में खोले गए +@msg CDR outline arrowheads were left out CDR आउटलाइन के तीर-शीर्ष छोड़ दिए गए +@msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR एनवेलप लागू नहीं किए गए, और उनके नीचे की आकृतियाँ अपनी आउटलाइन बनाए रखती हैं +@msg parts of the drawing nested too deeply, or past the import limits, were left out ड्रॉइंग के बहुत गहराई तक नेस्ट किए गए या आयात सीमाओं से परे के हिस्से छोड़ दिए गए +@msg damaged parts of the drawing were left out ड्रॉइंग के क्षतिग्रस्त हिस्से छोड़ दिए गए +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163,830 pt से लंबे CDR पेज उसी लंबाई पर खोले गए, और उनके किनारों के पास का आर्ट आर्टबोर्ड के बाहर है @msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000 फ़ाइल में एक unसमर्थित रंग स्थान या JPX सामग्री है @msg The last start of VectorCraft ended on {name} before its window appeared, so it started on {summary}. To try that graphics processor again, change Preferences › Performance › Graphics Processor or start with WGPU_BACKEND set वेक्टर क्रेफ्ट की अंतिम शुरुआत अपनी विंडो दिखाई देने से पहले {name} पर समाप्त हुई, इसलिए यह {summary} पर शुरू हुआ। उस ग्राफिक्स प्रोसेसर को फिर से आज़माने के लिए, वरीयताओं को बदलें › प्रदर्शन › ग्राफिक्स प्रोसेसर या WGPU_BACKEND सेट के साथ शुरू होता है। @msg The last start of VectorCraft ended while it listed the graphics processors, so it started on {summary} with OpenGL alone. To try the other graphics backends again, change Preferences › Performance › Graphics Processor or start with WGPU_BACKEND set जब यह ग्राफिक्स प्रोसेसर को सूचीबद्ध करता है, तो यह केवल ओपनजीएल के साथ {summary} पर शुरू हुआ। फिर से अन्य ग्राफिक्स बैकेंड की कोशिश करने के लिए, वरीयताओं को बदलें › प्रदर्शन › ग्राफिक्स प्रोसेसर या WGPU_BACKEND सेट के साथ शुरू होता है। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index eadf8f2058..3dd4738d20 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5555,6 +5555,17 @@ imageTrace Outline Körvonal @msg the HEIC or HEIF file can't be read a HEIC- vagy HEIF-fájl nem olvasható @msg the HEIC or HEIF file holds a kind of image that can't be read a HEIC- vagy HEIF-fájl olyan képtípust tartalmaz, amely nem olvasható @msg HEIC and HEIF images can't be opened in this build a HEIC- és HEIF-képek ebben a buildben nem nyithatók meg +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 a CDR {version} rajzai nem nyithatók meg; a VectorCraft ezeket a verziókat olvassa: 1–27 +@msg this CDR drawing can't be read ({why}) ez a CDR-rajz nem olvasható ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out kimaradtak a CDR szövegei, bitképei, összemosásai, kontúrjai, ecsetvonásai és egyéb objektumai, amelyeket a VectorCraft még nem olvas +@msg CDR fountain, pattern, texture and PostScript fills were left out kimaradtak a CDR színátmenetes, mintázatos, textúrás és PostScript-kitöltései +@msg colors in CDR color models VectorCraft doesn't read were opened as black a CDR olyan színmodelljeiben megadott színek, amelyeket a VectorCraft nem olvas, feketeként nyíltak meg +@msg CDR library colors that the drawing stores only by number were opened as black spot colors a CDR könyvtári színei, amelyeket a rajz csak számként tárol, fekete direktszínként nyíltak meg +@msg CDR outline arrowheads were left out kimaradtak a CDR körvonalainak nyílhegyei +@msg CDR envelopes were not applied, and the shapes under them keep their outlines a CDR burkolók nem lettek alkalmazva, és az alattuk lévő alakzatok megtartják a körvonalukat +@msg parts of the drawing nested too deeply, or past the import limits, were left out kimaradtak a rajz túl mélyen egymásba ágyazott vagy az importálási korlátokon túli részei +@msg damaged parts of the drawing were left out kimaradtak a rajz sérült részei +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard a 163 830 pt-nál hosszabb CDR-oldalak ekkora hosszal nyíltak meg, és a szélük közelében lévő grafika a rajztáblán kívül esik @msg the PSD image is too large to read ({_1} × {_2} pixels) a PSD-kép túl nagy a beolvasáshoz ({_1} × {_2} pixel) @msg the Save PDF dialog didn't open a PDF mentése párbeszédablak nem nyílt meg @msg the scale is not a usable number a méretarány nem használható szám diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ee47282a98..9e95d70bb9 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5089,6 +5089,17 @@ axis Both Entrambi @msg the HEIC or HEIF file can't be read impossibile leggere il file HEIC o HEIF @msg the HEIC or HEIF file holds a kind of image that can't be read il file HEIC o HEIF contiene un tipo di immagine che non può essere letto @msg HEIC and HEIF images can't be opened in this build le immagini HEIC e HEIF non possono essere aperte in questa build +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 impossibile aprire i disegni di CDR {version}: VectorCraft legge le versioni da 1 a 27 +@msg this CDR drawing can't be read ({why}) impossibile leggere questo disegno di CDR ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out testi, bitmap, fusioni, contorni progressivi, tratti di pennello e altri oggetti di CDR che VectorCraft non legge ancora sono stati omessi +@msg CDR fountain, pattern, texture and PostScript fills were left out i riempimenti sfumati, a motivo, a texture e PostScript di CDR sono stati omessi +@msg colors in CDR color models VectorCraft doesn't read were opened as black i colori in modelli di colore di CDR che VectorCraft non legge sono stati aperti in nero +@msg CDR library colors that the drawing stores only by number were opened as black spot colors i colori di libreria di CDR che il disegno salva solo per numero sono stati aperti come colori spot neri +@msg CDR outline arrowheads were left out le punte di freccia dei contorni di CDR sono state omesse +@msg CDR envelopes were not applied, and the shapes under them keep their outlines gli inviluppi di CDR non sono stati applicati, e le forme al loro interno mantengono i propri contorni +@msg parts of the drawing nested too deeply, or past the import limits, were left out le parti del disegno annidate troppo in profondità o oltre i limiti di importazione sono state omesse +@msg damaged parts of the drawing were left out le parti danneggiate del disegno sono state omesse +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard le pagine di CDR più lunghe di 163.830 pt sono state aperte con quella lunghezza, e la grafica vicina ai loro bordi si trova fuori dalla tavola da disegno @msg the PSD image is too large to read ({_1} × {_2} pixels) l'immagine PSD è troppo grande per essere letta ({_1} × {_2} pixel) @msg zipped 1-bit PSD image data with prediction can't be read i dati immagine PSD a 1 bit compressi ZIP con previsione non possono essere letti @msg the PSD file's layer data uses an unknown compression ({m}) i dati dei livelli del file PSD usano una compressione sconosciuta ({m}) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4d73b8aedc..b47b1239a7 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5130,6 +5130,17 @@ swatch Bright Violet ビビッドバイオレット @msg the HEIC or HEIF file can't be read HEIC または HEIF ファイルを読み込めません @msg the HEIC or HEIF file holds a kind of image that can't be read HEIC または HEIF ファイルには読み込めない種類の画像が含まれています @msg HEIC and HEIF images can't be opened in this build このビルドでは HEIC と HEIF の画像を開けません +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 CDR {version} の図面は開けません: VectorCraft で読み込めるのはバージョン 1 から 27 までです +@msg this CDR drawing can't be read ({why}) この CDR 図面は読み込めません ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out VectorCraft でまだ読み込めない CDR のテキスト、ビットマップ、ブレンド、コンター、ブラシストローク、その他のオブジェクトは除外されました +@msg CDR fountain, pattern, texture and PostScript fills were left out CDR のグラデーション、パターン、テクスチャ、PostScript の塗りは除外されました +@msg colors in CDR color models VectorCraft doesn't read were opened as black VectorCraft で読み込めない CDR のカラーモデルの色は黒として開きました +@msg CDR library colors that the drawing stores only by number were opened as black spot colors 図面が番号だけで保存している CDR のライブラリカラーは黒の特色として開きました +@msg CDR outline arrowheads were left out CDR のアウトラインの矢印は除外されました +@msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR のエンベロープは適用されず、その下のシェイプは元のアウトラインのままです +@msg parts of the drawing nested too deeply, or past the import limits, were left out 入れ子が深すぎる図面の部分や読み込みの上限を超えた部分は除外されました +@msg damaged parts of the drawing were left out 図面の破損した部分は除外されました +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163,830 pt より長い CDR のページはその長さで開いたため、端の近くのアートはアートボードの外にあります @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 画像が大きすぎて読み込めません({_1} × {_2} ピクセル) @msg zipped 1-bit PSD image data with prediction can't be read 予測付き ZIP 圧縮の 1 bit PSD 画像データは読み込めません @msg the PSD file's layer data uses an unknown compression ({m}) PSD ファイルのレイヤーデータの圧縮方式が不明です({m}) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 7ac6cef429..8d44662dcc 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4737,6 +4737,17 @@ font-technology Variable ცვლადი @msg the HEIC or HEIF file can't be read HEIC ან HEIF ფაილის წაკითხვა შეუძლებელია @msg the HEIC or HEIF file holds a kind of image that can't be read HEIC ან HEIF ფაილი შეიცავს გამოსახულების ტიპს, რომლის წაკითხვაც შეუძლებელია @msg HEIC and HEIF images can't be opened in this build ამ ვერსიაში HEIC და HEIF გამოსახულებების გახსნა შეუძლებელია +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 CDR {version}-ის ნახაზების გახსნა შეუძლებელია: VectorCraft კითხულობს ვერსიებს 1-დან 27-მდე +@msg this CDR drawing can't be read ({why}) ამ CDR ნახაზის წაკითხვა შეუძლებელია ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out CDR-ის ტექსტები, ბიტმაპები, გადასვლები, კონტურები, ფუნჯის შტრიხები და სხვა ობიექტები, რომლებსაც VectorCraft ჯერ ვერ კითხულობს, გამოტოვებულია +@msg CDR fountain, pattern, texture and PostScript fills were left out CDR-ის გრადიენტული, ნიმუშის, ტექსტურის და PostScript შევსებები გამოტოვებულია +@msg colors in CDR color models VectorCraft doesn't read were opened as black CDR-ის იმ ფერის მოდელების ფერები, რომლებსაც VectorCraft ვერ კითხულობს, შავად გაიხსნა +@msg CDR library colors that the drawing stores only by number were opened as black spot colors CDR-ის ბიბლიოთეკის ფერები, რომლებსაც ნახაზი მხოლოდ ნომრით ინახავს, შავ სპოტ-ფერებად გაიხსნა +@msg CDR outline arrowheads were left out CDR-ის მოხაზულობების ისრისპირები გამოტოვებულია +@msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR-ის კონვერტები არ იქნა გამოყენებული, და მათ ქვეშ მყოფი ფორმები ინარჩუნებენ თავიანთ მოხაზულობას +@msg parts of the drawing nested too deeply, or past the import limits, were left out ნახაზის ზედმეტად ღრმად ჩადგმული ან იმპორტის ლიმიტებს მიღმა არსებული ნაწილები გამოტოვებულია +@msg damaged parts of the drawing were left out ნახაზის დაზიანებული ნაწილები გამოტოვებულია +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163 830 pt-ზე გრძელი CDR-ის გვერდები ამ სიგრძით გაიხსნა და მათ კიდეებთან ახლოს მყოფი გრაფიკა სამუშაო დაფის გარეთაა @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD გამოსახულება ზედმეტად დიდია წასაკითხად ({_1} × {_2} პიქსელი) @msg zipped 1-bit PSD image data with prediction can't be read zip-ით შეკუმშული 1-ბიტიანი PSD გამოსახულების მონაცემების წაკითხვა პროგნოზირებით ვერ ხერხდება @msg the PSD file's layer data uses an unknown compression ({m}) PSD ფაილის შრეების მონაცემები უცნობ შეკუმშვას იყენებს ({m}) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index fff1a1a14a..ada1ecc10e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5057,6 +5057,17 @@ theme Appearance 외관 @msg the HEIC or HEIF file can't be read HEIC 또는 HEIF 파일을 읽을 수 없습니다 @msg the HEIC or HEIF file holds a kind of image that can't be read HEIC 또는 HEIF 파일에 읽을 수 없는 종류의 이미지가 있습니다 @msg HEIC and HEIF images can't be opened in this build 이 빌드에서는 HEIC 및 HEIF 이미지를 열 수 없습니다 +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 CDR {version} 도면을 열 수 없습니다: VectorCraft는 버전 1~27을 읽습니다 +@msg this CDR drawing can't be read ({why}) 이 CDR 도면을 읽을 수 없습니다 ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out VectorCraft가 아직 읽지 못하는 CDR 텍스트, 비트맵, 블렌드, 윤곽 효과, 브러시 획 및 기타 개체는 제외했습니다 +@msg CDR fountain, pattern, texture and PostScript fills were left out CDR 그라디언트, 패턴, 텍스처 및 PostScript 칠은 제외했습니다 +@msg colors in CDR color models VectorCraft doesn't read were opened as black VectorCraft가 읽지 못하는 CDR 색상 모델의 색상은 검정으로 열었습니다 +@msg CDR library colors that the drawing stores only by number were opened as black spot colors 도면이 번호로만 저장한 CDR 라이브러리 색상은 검정 별색으로 열었습니다 +@msg CDR outline arrowheads were left out CDR 외곽선의 화살촉은 제외했습니다 +@msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR 엔벨로프는 적용하지 않았으며, 그 아래의 도형은 원래 외곽선을 유지합니다 +@msg parts of the drawing nested too deeply, or past the import limits, were left out 너무 깊이 중첩되었거나 가져오기 한도를 넘은 도면 부분은 제외했습니다 +@msg damaged parts of the drawing were left out 도면의 손상된 부분은 제외했습니다 +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163,830pt보다 긴 CDR 페이지는 그 길이로 열었으며, 가장자리 근처의 아트는 아트보드 밖에 있습니다 @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 이미지가 너무 커서 읽을 수 없습니다({_1} × {_2}픽셀) @msg zipped 1-bit PSD image data with prediction can't be read 예측이 적용된 ZIP 압축 1비트 PSD 이미지 데이터는 읽을 수 없습니다 @msg the PSD file's layer data uses an unknown compression ({m}) PSD 파일의 레이어 데이터가 알 수 없는 압축({m})을 사용합니다 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 40efff131c..b7f371ccc1 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5146,6 +5146,17 @@ imageTrace Outline Kontur @msg the HEIC or HEIF file can't be read nie można odczytać pliku HEIC lub HEIF @msg the HEIC or HEIF file holds a kind of image that can't be read plik HEIC lub HEIF zawiera rodzaj obrazu, którego nie można odczytać @msg HEIC and HEIF images can't be opened in this build obrazów HEIC i HEIF nie można otworzyć w tej wersji +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 nie można otworzyć rysunków CDR {version}: VectorCraft odczytuje wersje od 1 do 27 +@msg this CDR drawing can't be read ({why}) nie można odczytać tego rysunku CDR ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out pominięto teksty, mapy bitowe, przejścia, efekty konturu, pociągnięcia pędzla i inne obiekty CDR, których VectorCraft jeszcze nie odczytuje +@msg CDR fountain, pattern, texture and PostScript fills were left out pominięto wypełnienia tonalne, deseniowe, teksturowe i PostScript CDR +@msg colors in CDR color models VectorCraft doesn't read were opened as black kolory w modelach kolorów CDR, których VectorCraft nie odczytuje, otwarto jako czarne +@msg CDR library colors that the drawing stores only by number were opened as black spot colors kolory z bibliotek CDR, które rysunek zapisuje tylko jako numer, otwarto jako czarne kolory dodatkowe +@msg CDR outline arrowheads were left out pominięto groty strzałek na obrysach CDR +@msg CDR envelopes were not applied, and the shapes under them keep their outlines obwiednie CDR nie zostały zastosowane, a kształty pod nimi zachowują swoje obrysy +@msg parts of the drawing nested too deeply, or past the import limits, were left out pominięto części rysunku zagnieżdżone zbyt głęboko lub wykraczające poza limity importu +@msg damaged parts of the drawing were left out pominięto uszkodzone części rysunku +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard strony CDR dłuższe niż 163 830 pt otwarto z tą długością, a grafika przy ich krawędziach leży poza obszarem kompozycji @msg the PSD image is too large to read ({_1} × {_2} pixels) obraz PSD jest zbyt duży, aby go odczytać ({_1} × {_2} pikseli) @msg zipped 1-bit PSD image data with prediction can't be read nie można odczytać spakowanych 1-bitowych danych obrazu PSD z predykcją @msg the PSD file's layer data uses an unknown compression ({m}) dane warstw pliku PSD używają nieznanej kompresji ({m}) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index f7bda91264..a292009e30 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4541,6 +4541,17 @@ axis Both Ambos @msg the HEIC or HEIF file can't be read não é possível ler o arquivo HEIC ou HEIF @msg the HEIC or HEIF file holds a kind of image that can't be read o arquivo HEIC ou HEIF contém um tipo de imagem que não pode ser lido @msg HEIC and HEIF images can't be opened in this build imagens HEIC e HEIF não podem ser abertas nesta versão +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 não é possível abrir desenhos do CDR {version}: o VectorCraft lê as versões 1 a 27 +@msg this CDR drawing can't be read ({why}) não é possível ler este desenho do CDR ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out textos, bitmaps, mesclagens, efeitos de contorno, traços de pincel e outros objetos do CDR que o VectorCraft ainda não lê foram omitidos +@msg CDR fountain, pattern, texture and PostScript fills were left out os preenchimentos gradientes, de padrão, de textura e PostScript do CDR foram omitidos +@msg colors in CDR color models VectorCraft doesn't read were opened as black cores em modelos de cor do CDR que o VectorCraft não lê foram abertas em preto +@msg CDR library colors that the drawing stores only by number were opened as black spot colors cores de biblioteca do CDR que o desenho guarda apenas pelo número foram abertas como cores spot pretas +@msg CDR outline arrowheads were left out as pontas de seta das linhas de contorno do CDR foram omitidas +@msg CDR envelopes were not applied, and the shapes under them keep their outlines os envelopes do CDR não foram aplicados, e as formas sob eles mantêm seus contornos +@msg parts of the drawing nested too deeply, or past the import limits, were left out partes do desenho aninhadas profundamente demais ou além dos limites de importação foram omitidas +@msg damaged parts of the drawing were left out partes danificadas do desenho foram omitidas +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard páginas do CDR com mais de 163.830 pt foram abertas com esse comprimento, e a arte perto das bordas fica fora da prancheta @msg the PSD image is too large to read ({_1} × {_2} pixels) a imagem PSD é grande demais para ser lida ({_1} × {_2} pixels) @msg zipped 1-bit PSD image data with prediction can't be read dados de imagem PSD de 1 bit compactados em zip com previsão não podem ser lidos @msg the PSD file's layer data uses an unknown compression ({m}) os dados de camada do arquivo PSD usam uma compactação desconhecida ({m}) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 92a9e3c965..dff5b64e39 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5077,6 +5077,17 @@ axis Both Оба @msg the HEIC or HEIF file can't be read не удается прочитать файл HEIC или HEIF @msg the HEIC or HEIF file holds a kind of image that can't be read файл HEIC или HEIF содержит изображение такого типа, которое не удается прочитать @msg HEIC and HEIF images can't be opened in this build изображения HEIC и HEIF нельзя открыть в этой сборке +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 не удается открыть рисунки CDR {version}: VectorCraft читает версии с 1 по 27 +@msg this CDR drawing can't be read ({why}) не удается прочитать этот рисунок CDR ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out текст, растровые изображения, перетекания, контуры, мазки кисти и другие объекты CDR, которые VectorCraft пока не читает, были пропущены +@msg CDR fountain, pattern, texture and PostScript fills were left out градиентные, узорные, текстурные и PostScript-заливки CDR были пропущены +@msg colors in CDR color models VectorCraft doesn't read were opened as black цвета в цветовых моделях CDR, которые VectorCraft не читает, открыты как черные +@msg CDR library colors that the drawing stores only by number were opened as black spot colors библиотечные цвета CDR, которые рисунок хранит только по номеру, открыты как черные плашечные цвета +@msg CDR outline arrowheads were left out наконечники стрелок абрисов CDR были пропущены +@msg CDR envelopes were not applied, and the shapes under them keep their outlines оболочки CDR не были применены, и фигуры под ними сохраняют свои контуры +@msg parts of the drawing nested too deeply, or past the import limits, were left out части рисунка со слишком глубокой вложенностью или за пределами ограничений импорта были пропущены +@msg damaged parts of the drawing were left out поврежденные части рисунка были пропущены +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard страницы CDR длиннее 163 830 pt открыты с этой длиной, и графика у их краев находится за пределами монтажной области @msg the PSD image is too large to read ({_1} × {_2} pixels) изображение PSD слишком велико для чтения ({_1} × {_2} пикс.) @msg zipped 1-bit PSD image data with prediction can't be read 1-битные данные изображения PSD со сжатием ZIP с предсказанием не читаются @msg the PSD file's layer data uses an unknown compression ({m}) данные слоёв файла PSD используют неизвестное сжатие ({m}) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index a2c032a5db..11d2989636 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4953,6 +4953,17 @@ axis Both Båda @msg the HEIC or HEIF file can't be read HEIC- eller HEIF-filen kan inte läsas @msg the HEIC or HEIF file holds a kind of image that can't be read HEIC- eller HEIF-filen innehåller en typ av bild som inte kan läsas @msg HEIC and HEIF images can't be opened in this build HEIC- och HEIF-bilder kan inte öppnas i den här versionen +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 teckningar från CDR {version} kan inte öppnas: VectorCraft läser version 1 till 27 +@msg this CDR drawing can't be read ({why}) den här CDR-teckningen kan inte läsas ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out text, bitmappar, övertoningar, konturer, penseldrag och andra CDR-objekt som VectorCraft ännu inte läser utelämnades +@msg CDR fountain, pattern, texture and PostScript fills were left out CDR-fyllningar med toning, mönster, struktur och PostScript utelämnades +@msg colors in CDR color models VectorCraft doesn't read were opened as black färger i CDR-färgmodeller som VectorCraft inte läser öppnades som svarta +@msg CDR library colors that the drawing stores only by number were opened as black spot colors CDR-biblioteksfärger som teckningen bara lagrar som nummer öppnades som svarta dekorfärger +@msg CDR outline arrowheads were left out pilspetsar på CDR-linjer utelämnades +@msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR-omslag tillämpades inte, och formerna under dem behåller sina konturer +@msg parts of the drawing nested too deeply, or past the import limits, were left out delar av teckningen som är för djupt nästlade eller ligger utanför importgränserna utelämnades +@msg damaged parts of the drawing were left out skadade delar av teckningen utelämnades +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard CDR-sidor längre än 163 830 pt öppnades med den längden, och grafik nära deras kanter ligger utanför ritytan @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD-bilden är för stor för att läsas ({_1} × {_2} pixlar) @msg zipped 1-bit PSD image data with prediction can't be read zippad 1-bitars PSD-bilddata med prediktion kan inte läsas @msg the PSD file's layer data uses an unknown compression ({m}) PSD-filens lagerdata använder en okänd komprimering ({m}) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index fbc6b9248f..e6d53b2ad3 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1762,6 +1762,29 @@ fn warped_type_note_is_translated() { } } +/// The notes a CDR import adds to its warnings are translated in every complete catalog. +/// They are constants, which the scan of message literals doesn't see. +#[test] +fn cdr_import_notes_are_translated() { + let notes = [ + "CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out", + "CDR fountain, pattern, texture and PostScript fills were left out", + "colors in CDR color models VectorCraft doesn't read were opened as black", + "CDR library colors that the drawing stores only by number were opened as black spot colors", + "CDR outline arrowheads were left out", + "CDR envelopes were not applied, and the shapes under them keep their outlines", + "parts of the drawing nested too deeply, or past the import limits, were left out", + "damaged parts of the drawing were left out", + "CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard", + ]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for note in notes { + assert_ne!(message(lang, note), note, "{code}: {note}"); + } + } +} + /// The Gamut Check status line names a count of 1 in the singular and other counts in the plural, /// and every complete catalog translates it, in the form its plural rule picks. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 2fea56d318..38fede40e3 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4783,6 +4783,17 @@ axis Both Her İkisi @msg the HEIC or HEIF file can't be read HEIC veya HEIF dosyası okunamıyor @msg the HEIC or HEIF file holds a kind of image that can't be read HEIC veya HEIF dosyası okunamayan türde bir görüntü içeriyor @msg HEIC and HEIF images can't be opened in this build HEIC ve HEIF görüntüleri bu derlemede açılamıyor +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 CDR {version} çizimleri açılamıyor: VectorCraft 1 ile 27 arasındaki sürümleri okur +@msg this CDR drawing can't be read ({why}) bu CDR çizimi okunamıyor ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out VectorCraft'ın henüz okumadığı CDR metinleri, bit eşlemleri, karışımları, konturları, fırça darbeleri ve diğer nesneleri dışarıda bırakıldı +@msg CDR fountain, pattern, texture and PostScript fills were left out CDR geçişli, desenli, dokulu ve PostScript dolguları dışarıda bırakıldı +@msg colors in CDR color models VectorCraft doesn't read were opened as black VectorCraft'ın okumadığı CDR renk modellerindeki renkler siyah olarak açıldı +@msg CDR library colors that the drawing stores only by number were opened as black spot colors çizimin yalnızca numarayla sakladığı CDR kitaplık renkleri siyah nokta renkleri olarak açıldı +@msg CDR outline arrowheads were left out CDR anahatlarının ok uçları dışarıda bırakıldı +@msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR zarfları uygulanmadı ve altlarındaki şekiller anahatlarını korur +@msg parts of the drawing nested too deeply, or past the import limits, were left out çizimin fazla derin iç içe geçmiş veya içe aktarma sınırlarının ötesindeki kısımları dışarıda bırakıldı +@msg damaged parts of the drawing were left out çizimin hasarlı kısımları dışarıda bırakıldı +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163.830 pt'den uzun CDR sayfaları bu uzunlukta açıldı ve kenarlarına yakın çizimler çalışma yüzeyinin dışında kalıyor @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD görüntüsü okunamayacak kadar büyük ({_1} × {_2} piksel) @msg zipped 1-bit PSD image data with prediction can't be read Tahmin içeren sıkıştırılmış 1 bit PSD görüntü verileri okunamıyor @msg the PSD file's layer data uses an unknown compression ({m}) PSD dosyasının katman verileri bilinmeyen bir sıkıştırma kullanıyor ({m}) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 4aac86567b..69ec093471 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5073,6 +5073,17 @@ axis Both Обидві @msg the HEIC or HEIF file can't be read не вдається прочитати файл HEIC або HEIF @msg the HEIC or HEIF file holds a kind of image that can't be read файл HEIC або HEIF містить зображення такого типу, яке не вдається прочитати @msg HEIC and HEIF images can't be opened in this build зображення HEIC і HEIF не можна відкрити в цій збірці +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 не вдається відкрити малюнки CDR {version}: VectorCraft читає версії з 1 по 27 +@msg this CDR drawing can't be read ({why}) не вдається прочитати цей малюнок CDR ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out текст, растрові зображення, перетікання, контури, мазки пензля та інші об’єкти CDR, які VectorCraft поки не читає, було пропущено +@msg CDR fountain, pattern, texture and PostScript fills were left out градієнтні, візерункові, текстурні та PostScript-заливки CDR було пропущено +@msg colors in CDR color models VectorCraft doesn't read were opened as black кольори в колірних моделях CDR, які VectorCraft не читає, відкрито як чорні +@msg CDR library colors that the drawing stores only by number were opened as black spot colors бібліотечні кольори CDR, які малюнок зберігає лише за номером, відкрито як чорні плашкові кольори +@msg CDR outline arrowheads were left out наконечники стрілок абрисів CDR було пропущено +@msg CDR envelopes were not applied, and the shapes under them keep their outlines оболонки CDR не було застосовано, і фігури під ними зберігають свої контури +@msg parts of the drawing nested too deeply, or past the import limits, were left out частини малюнка із надто глибоким вкладенням або поза межами обмежень імпорту було пропущено +@msg damaged parts of the drawing were left out пошкоджені частини малюнка було пропущено +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard сторінки CDR, довші за 163 830 pt, відкрито з цією довжиною, і графіка біля їхніх країв лежить поза монтажною областю @msg the PSD image is too large to read ({_1} × {_2} pixels) зображення PSD завелике для читання ({_1} × {_2} пікс.) @msg zipped 1-bit PSD image data with prediction can't be read 1-бітні дані зображення PSD зі стисненням ZIP із передбаченням не читаються @msg the PSD file's layer data uses an unknown compression ({m}) дані шарів файлу PSD використовують невідоме стиснення ({m}) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f40f0292a2..27f86d56c3 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5223,6 +5223,17 @@ theme Appearance Giao diện @msg the HEIC or HEIF file can't be read không thể đọc tệp HEIC hoặc HEIF @msg the HEIC or HEIF file holds a kind of image that can't be read tệp HEIC hoặc HEIF chứa loại ảnh không thể đọc được @msg HEIC and HEIF images can't be opened in this build không thể mở ảnh HEIC và HEIF trong bản dựng này +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 không thể mở bản vẽ CDR {version}: VectorCraft đọc các phiên bản từ 1 đến 27 +@msg this CDR drawing can't be read ({why}) không thể đọc bản vẽ CDR này ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out văn bản, ảnh bitmap, hòa trộn, đường đồng mức, nét cọ và các đối tượng CDR khác mà VectorCraft chưa đọc được đã bị bỏ qua +@msg CDR fountain, pattern, texture and PostScript fills were left out các kiểu tô chuyển sắc, mẫu, kết cấu và PostScript của CDR đã bị bỏ qua +@msg colors in CDR color models VectorCraft doesn't read were opened as black các màu trong mô hình màu CDR mà VectorCraft không đọc được đã được mở thành màu đen +@msg CDR library colors that the drawing stores only by number were opened as black spot colors các màu thư viện CDR mà bản vẽ chỉ lưu theo số đã được mở thành màu đặc biệt đen +@msg CDR outline arrowheads were left out các đầu mũi tên của đường viền CDR đã bị bỏ qua +@msg CDR envelopes were not applied, and the shapes under them keep their outlines các bao hình CDR không được áp dụng, và các hình bên dưới vẫn giữ đường viền của chúng +@msg parts of the drawing nested too deeply, or past the import limits, were left out các phần của bản vẽ lồng nhau quá sâu hoặc vượt quá giới hạn nhập đã bị bỏ qua +@msg damaged parts of the drawing were left out các phần bị hỏng của bản vẽ đã bị bỏ qua +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard các trang CDR dài hơn 163.830 pt đã được mở với độ dài đó, và hình vẽ gần mép trang nằm ngoài bảng vẽ @msg the PSD image is too large to read ({_1} × {_2} pixels) ảnh PSD quá lớn để đọc ({_1} × {_2} pixel) @msg the Save PDF dialog didn't open hộp thoại Lưu PDF không mở @msg the scale is not a usable number tỷ lệ không phải là số dùng được diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 6602ee3916..a1b8c3eddb 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4819,6 +4819,17 @@ imageTrace Outline 轮廓 @msg the HEIC or HEIF file can't be read 无法读取 HEIC 或 HEIF 文件 @msg the HEIC or HEIF file holds a kind of image that can't be read HEIC 或 HEIF 文件包含无法读取的图像类型 @msg HEIC and HEIF images can't be opened in this build 此版本无法打开 HEIC 和 HEIF 图像 +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 无法打开 CDR {version} 绘图:VectorCraft 读取的版本为 1 到 27 +@msg this CDR drawing can't be read ({why}) 无法读取此 CDR 绘图 ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out 已略去 VectorCraft 尚不能读取的 CDR 文本、位图、调和、轮廓图、画笔描边和其他对象 +@msg CDR fountain, pattern, texture and PostScript fills were left out 已略去 CDR 的渐变、图样、底纹和 PostScript 填充 +@msg colors in CDR color models VectorCraft doesn't read were opened as black VectorCraft 不能读取的 CDR 颜色模型中的颜色已作为黑色打开 +@msg CDR library colors that the drawing stores only by number were opened as black spot colors 绘图仅按编号存储的 CDR 库颜色已作为黑色专色打开 +@msg CDR outline arrowheads were left out 已略去 CDR 轮廓线的箭头 +@msg CDR envelopes were not applied, and the shapes under them keep their outlines 未应用 CDR 封套,其中的形状保留原有轮廓 +@msg parts of the drawing nested too deeply, or past the import limits, were left out 已略去绘图中嵌套过深或超出导入限制的部分 +@msg damaged parts of the drawing were left out 已略去绘图中损坏的部分 +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 长度超过 163,830 pt 的 CDR 页面已按该长度打开,其边缘附近的图稿位于画板之外 @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 图像过大,无法读取 ({_1} × {_2} 像素) @msg zipped 1-bit PSD image data with prediction can't be read 无法读取带预测的 ZIP 压缩 1 位 PSD 图像数据 @msg the PSD file's layer data uses an unknown compression ({m}) PSD 文件的图层数据使用了未知的压缩方式 ({m}) diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 545a75bcad..7aa2060bf9 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2598,6 +2598,17 @@ file-filter Templates 範本 @msg the HEIC or HEIF file can't be read 無法讀取 HEIC 或 HEIF 檔案 @msg the HEIC or HEIF file holds a kind of image that can't be read HEIC 或 HEIF 檔案包含無法讀取的影像類型 @msg HEIC and HEIF images can't be opened in this build 此版本無法開啟 HEIC 和 HEIF 影像 +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 無法開啟 CDR {version} 繪圖:VectorCraft 讀取的版本為 1 到 27 +@msg this CDR drawing can't be read ({why}) 無法讀取此 CDR 繪圖 ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out 已略過 VectorCraft 尚無法讀取的 CDR 文字、點陣圖、漸變、輪廓圖、筆刷筆觸和其他物件 +@msg CDR fountain, pattern, texture and PostScript fills were left out 已略過 CDR 的漸層、圖樣、材質和 PostScript 填色 +@msg colors in CDR color models VectorCraft doesn't read were opened as black VectorCraft 無法讀取的 CDR 色彩模式中的顏色已以黑色開啟 +@msg CDR library colors that the drawing stores only by number were opened as black spot colors 繪圖僅以編號儲存的 CDR 色彩庫顏色已以黑色特別色開啟 +@msg CDR outline arrowheads were left out 已略過 CDR 外框線的箭頭 +@msg CDR envelopes were not applied, and the shapes under them keep their outlines 未套用 CDR 封套,其中的形狀保留原有外框 +@msg parts of the drawing nested too deeply, or past the import limits, were left out 已略過繪圖中巢狀過深或超出讀入限制的部分 +@msg damaged parts of the drawing were left out 已略過繪圖中損壞的部分 +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 長度超過 163,830 pt 的 CDR 頁面已以該長度開啟,其邊緣附近的圖稿位於工作區域之外 @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 影像過大,無法讀取 ({_1} × {_2} 像素) @msg zipped 1-bit PSD image data with prediction can't be read 無法讀取使用預測的 ZIP 壓縮 1 位元 PSD 影像資料 @msg the PSD file's layer data uses an unknown compression ({m}) PSD 檔案的圖層資料使用了不明的壓縮方式 ({m}) diff --git a/docs/architecture.md b/docs/architecture.md index ad897cc820..16521e3e0c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -19,7 +19,7 @@ nothing below L6 depends on a UI toolkit (egui, eframe, winit, rfd). Table: `xta | Layer | Crates | Role | |---|---|---| -| L0 | `geom`, `color`; `affinity` (standalone, no workspace deps) | curves and transforms (on `kurbo`), colour models, ICC and conversions; the Affinity reader | +| L0 | `geom`, `color`; `affinity`, `cdr` (standalone, no workspace deps) | curves and transforms (on `kurbo`), colour models, ICC and conversions; the Affinity and `.cdr` readers | | L1 | `doc` | the document model: artboards, layers, objects, appearance, text, symbols; pure data + serde, structural sharing | | L2 | `pathops`, `brush`, `trace`, `text`, `effects`, `plugins`, `three-d` | booleans/Shape Builder/offset/outline; brushes; Image Trace; fonts, shaping (HarfRust, skrifa), bidi and layout; live effects and the pixel-filter pipeline; sandboxed WebAssembly plug-ins (wasmi); 3D surfaces of revolution, projection and shading (`three-d`, on `geom` only) | | L3 | `render`, `svg`, `pdf`, `format`, `eps`, `cad`, `metafile` | document to pixels (`vello_cpu`, multithreaded); SVG, PDF, native JSON, EPS/PostScript (with its own interpreter), DXF, EMF/WMF readers and writers | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 7a59146afa..b6bad704dc 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -19,9 +19,8 @@ Ordinary File > Save offers Save As when its own location refuses writes with a | | Illustrator | VectorCraft | Notes | |---|---:|---:|---| -| Formats opened or placed | ~30 | 30 | missing: FreeHand, CorelDRAW, DWG, PICT, PS | +| Formats opened or placed | ~30 | 31 | missing: FreeHand, DWG, PICT, PS | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, artboards) or as legacy version 7 (layers and groups, one artboard per file) | -| Formats opened or placed | ~30 | 29 | missing: FreeHand, CorelDRAW, DWG, HEIC/HEIF, PICT, PS | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, gradients, patterns, images, type, symbols, artboards, transparency, opacity masks, clipping) or as legacy version 7 (layers and groups, one artboard per file) | | Formats exported | ~16 | 18 | missing: DWG; extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | | **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting | @@ -308,7 +307,7 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | PICT | open, place (legacy) | no | no | rarely used | | Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` | | FreeHand `.fh*` | open (legacy) | no | no | | -| CorelDRAW `.cdr` | open | no | no | | +| `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies, and version 3 objects under an envelope are left out with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; record layouts and their sources in `crates/cdr/PROVENANCE.md`; synthetic test files only; tests in `crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` | | Text `.txt` | place, export | place (Text Import Options) | yes | | | RTF `.rtf` | place | place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only | | Word `.docx` | place | place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out | diff --git a/docs/mcp.md b/docs/mcp.md index 996908799f..beac1db458 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -553,7 +553,7 @@ applied colors still join the list while it is hidden. | `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. UI commands such as `view.*` and `window.*` are in `command_list` with `ui: true`; running them needs the desktop app (`--connect`). | | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | | `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. | -| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | +| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | | `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `_.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a `.ai` file reads `compress` but not `version`, `preview` or `precision`). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for a top-level `compress`, `version`, `preview` or `precision` and for each key in `options` that the format doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). | | `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning); `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | @@ -6837,6 +6837,30 @@ its pixels are decoded. `file.place {path}` links the file like any image. Vecto {"name":"run_command","arguments":{"command":"document.export","params":{"format":"psd","layers":false,"colorModel":"cmyk"}}} ``` +## CDR import + +`.cdr` drawings of versions 1 to 27 (and `.cdt` templates, which open as a new untitled document) open and +place as editable art, the ZIP packages that versions 14 and later save included. Each page becomes an artboard, side +by side. Layers of the same name on different pages become one layer when the pages stack them in the same order, and +the master page's guidelines become guides on every page. Groups stay groups. Curves, paths, arcs and polygons (stars +included) become paths, and rectangles and ellipses become live shapes; a rectangle keeps each corner's radius. Uniform +fills and outlines keep their colors, widths, caps, joins and dashes. A library color that the drawing stores with its +name and values (version 13 and later) becomes a spot swatch with its tint, and one stored only by its number opens as +a black spot color. Text, bitmaps, blends, contours, brush strokes, other objects the reader doesn't read yet, +fountain, pattern, texture and PostScript fills, and outline arrowheads are left out. The `warnings` of +`document.open` name each of these kinds the drawing had, and say when damaged parts or parts past the import limits +were left out. Drawings of versions after 27 are refused with a message, and so are packages that are +encrypted, ZIP64 archives or split across files. VectorCraft doesn't write `.cdr` files. + +No public specification covers versions 1 to 4, so the importer reads what published notes describe. A drawing of +version 1 or 2 opens as one page with one layer: its rectangles, whole ellipses and curves with their matrices, uniform +fills and outlines with their width and color. Its text, its arcs and pies, and its fills of other types are left out +with the same warnings, and its groups are not kept. A drawing of version 3 opens with its pages, layers and groups; +an envelope is not applied, so an object or a group under one keeps its outline, placed by its matrices, and the +`warnings` say so. A drawing of +version 4 opens as one of version 5 does. A file is taken for version 1 or 2 by its content only when the offsets in +its header fit the file. A RIFF file that names a version before 3 is refused with a message. + ## Printing `print.setup {settings?}` keeps print settings with the document (one undo step; without `settings` it answers the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2962c63b7e..2b32650bae 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -703,7 +703,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Artboard deletion keys:** Delete/Backspace delete selected boards in one Undo step, retaining the original first board in the current order when all are selected, as in the public [Delete artboards guide](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html). The last board and active drags stay protected; neither key clears selected artwork. Headless shortcut regressions in `tests/distortkeys.rs` cover reordered boards, artwork, saved state and Undo/Redo. - **Locked artboards:** a click in the Artboards panel's lock column locks or unlocks an artboard in one undo step (`artboard.setProps {index, locked}`), and the native format saves the lock. The Artboard tool doesn't move, copy, resize or delete a locked artboard, Rearrange and Fit to Artwork Bounds leave it as it is, and its name isn't edited on the canvas. The art on it (each object whose bounds overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, `select.set`, `select.all` and the tools pass over it, and commands that act on the selection leave it; art drawn or pasted onto it stays selected and editable until the selection leaves it out. Tests in `crates/doc/src/lib.rs`, `tests/panelcmds.rs`, `xform/artboard.rs`, `panels/artboards.rs` and `canvas.rs` cover them. Public references: [Lock artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/lock-artboards.html) and [Managing Artboards in Illustrator](https://creativepro.com/managing-artboards-in-illustrator/). - **Linux RPM packaging:** 64-bit runtime capabilities replace Fedora-specific required package names (#1275); glibc 2.35, libm and libgcc_s are declared alongside dynamically loaded xkbcommon and Vulkan/EGL. Generated x86_64/aarch64 metadata and isolated synthetic-provider resolution checked; real-distro install/start-up QA remains pending. -- **Linux file associations:** the desktop entry lists the MIME type of every format File › Open reads but PSD, PSB, `.ps` PostScript, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL and HP-GL, `.ai`, `.ait` and EPS included, and the MIME package declares the types shared-mime-info lacks (VectorCraft documents and templates, `.ait`, Affinity), so file managers list VectorCraft under Open With for them, as Finder does on macOS. `the_linux_desktop_entry_opens_every_readable_format` in `apps/vectorcraft/src/tests.rs` checks both files against `OPEN_EXTS`. On Debian 13, Ubuntu 24.04 and Fedora 42, `desktop-file-validate` accepts the desktop entry, `update-mime-database` accepts the MIME package, and `gio` registers the app for every one of these types. +- **Linux file associations:** the desktop entry lists the MIME type of every format File › Open reads but PSD, PSB, `.ps` PostScript, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, HP-GL and `.cdr`, `.ai`, `.ait` and EPS included, and the MIME package declares the types shared-mime-info lacks (VectorCraft documents and templates, `.ait`, Affinity), so file managers list VectorCraft under Open With for them, as Finder does on macOS. `the_linux_desktop_entry_opens_every_readable_format` in `apps/vectorcraft/src/tests.rs` checks both files against `OPEN_EXTS`. On Debian 13, Ubuntu 24.04 and Fedora 42, `desktop-file-validate` accepts the desktop entry, `update-mime-database` accepts the MIME package, and `gio` registers the app for every one of these types. - **Architecture:** 19+ crates with enforced layering (`cargo xtask layers`). Every action is a command (~400 engine + ~50 UI). Undo is unlimited via structural sharing. `command.batch` runs several commands as one transaction. - **Parameter schemas:** a command can carry a machine-readable parameter schema (the new `vectorcraft-apischema` crate): each parameter's type, range, unit, whether it is required, its default, whether null counts as left out, and the API levels it was added and deprecated at. `engine.commands` lists the schema in the shape of a JSON Schema 2020-12 object schema, a test keeps the command's `params` text equal to the text the schema writes, and a new call has the params checked against it before the command runs (batch steps before the first step), with an error naming the parameter and no change to the document; saved steps keep a key the schema does not name, and their values are checked. The View commands `view.capsLock`, `view.saved.new`, `view.saved.edit`, `view.saved.list`, `view.transparencyGrid` and `view.snapToGlyph.options` have schemas. The schemas belong to API level 1 (`vectorcraft_engine::schemas::API_VERSION`), and a test fails when a schema changes without a new level. Tests: `crates/apischema/src/tests.rs` (with `conformance.rs`, a separate check of the JSON form against the JSON Schema 2020-12 rules), `schemas::tests` and `cmd::views::tests::each_view_command_refuses_a_bad_value_naming_the_parameter` in `vectorcraft-engine`. @@ -1542,6 +1542,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). + - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents; the [supported file formats](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/supported-file-formats-in-illustrator.html) page lists `.cdr` versions 5 to 10. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width, caps, joins and dashes. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. EPS and PostScript `.ai` files are still embedded (`crates/engine/src/tests/placed_document.rs`). diff --git a/xtask/src/brands.rs b/xtask/src/brands.rs index 1d3b8f430c..a67b0c0945 100644 --- a/xtask/src/brands.rs +++ b/xtask/src/brands.rs @@ -20,6 +20,8 @@ use std::path::Path; const DENY: &[&str] = &[ "adobe", "illustrator", + "coreldraw", + "corel", "photoshop", "acrobat", "indesign", @@ -341,6 +343,9 @@ line Pantone"; } assert_eq!(terms_in("Adobe's app", DENY), ["adobe"]); assert_eq!(terms_in("an ILLUSTRATOR-style UI", DENY), ["illustrator"]); assert!(terms_in("illustrators illustration copyAicb aicbMode", DENY).is_empty()); + assert_eq!(terms_in("a CorelDRAW drawing", DENY), ["coreldraw"]); + assert_eq!(terms_in("application/vnd.corel-draw", DENY), ["corel"]); + assert!(terms_in("wCorel3Dict corels", DENY).is_empty()); } #[test] diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index 8a6f5f0256..5b31c3fb3c 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -65,6 +65,7 @@ pub const TABLE: &[(&str, Class)] = &[ ("scriptcheck", Class::Standalone), ("js", Class::Standalone), ("apischema", Class::Standalone), + ("cdr", Class::Standalone), ]; /// Explicit orderings *within* a layer (earlier may be used by later). From 0e146cc363bf649f3a0b9e57d491b9a293e2e880 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:24:17 -0800 Subject: [PATCH 02/34] Docs: keep main's other format summary rows Restores the second "Formats opened or placed" row as main has it; this pull request changes only the first row. --- docs/file-format-parity.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index b6bad704dc..524941fb65 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -21,6 +21,7 @@ Ordinary File > Save offers Save As when its own location refuses writes with a |---|---:|---:|---| | Formats opened or placed | ~30 | 31 | missing: FreeHand, DWG, PICT, PS | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, artboards) or as legacy version 7 (layers and groups, one artboard per file) | +| Formats opened or placed | ~30 | 29 | missing: FreeHand, CorelDRAW, DWG, HEIC/HEIF, PICT, PS | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, gradients, patterns, images, type, symbols, artboards, transparency, opacity masks, clipping) or as legacy version 7 (layers and groups, one artboard per file) | | Formats exported | ~16 | 18 | missing: DWG; extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | | **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting | From 6785e8df53c5c5694dc1c1f0e9ac797f43942f36 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:48:38 -0800 Subject: [PATCH 03/34] .cdr import: a page that shares no layer puts its layers on top A page whose bottom layer is new now goes below the lowest layer the rest of the page shares with earlier pages, and on top when it shares none, so the layers keep the order they were first seen in. --- crates/engine/src/cmd/fileio/cdr.rs | 26 +++++++++++++++++++++-- crates/engine/src/cmd/fileio/tests_cdr.rs | 9 +++++--- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/fileio/cdr.rs b/crates/engine/src/cmd/fileio/cdr.rs index f483f2f0a6..394220f194 100644 --- a/crates/engine/src/cmd/fileio/cdr.rs +++ b/crates/engine/src/cmd/fileio/cdr.rs @@ -171,7 +171,7 @@ impl shapes::Builder { // The layer this page's last layer went to: the next one goes above it. let mut below: Option = None; // The file lists layers front to back. - for l in page.layers.iter().rev() { + for (j, l) in page.layers.iter().rev().enumerate() { self.guides(&l.guides, p, artboard); if l.kind != LayerKind::Drawing && l.kind != LayerKind::Desktop { continue; @@ -193,7 +193,29 @@ impl shapes::Builder { } None if layers.len() >= MAX_LAYERS => self.notes.push(Warning::TooDeep), None => { - let at = below.map_or(pages_from, |b| b + 1); + // The page's bottom layer goes below the lowest layer that the rest of the + // page shares with earlier pages, so the page keeps its own order. When the + // page shares none, it goes on top, in the order the layers were first seen. + let at = match below { + Some(b) => b + 1, + None => { + let mut counts = seen.clone(); + page.layers + .iter() + .rev() + .skip(j + 1) + .filter(|l| l.kind == LayerKind::Drawing || l.kind == LayerKind::Desktop) + .filter_map(|l| { + let n = counts.entry(l.name.as_str()).or_insert(0); + let key = (l.name.clone(), *n); + *n += 1; + by_name.get(&key).and_then(|is| is.first().copied()) + }) + .min() + .unwrap_or(layers.len()) + .max(pages_from) + } + }; if at < layers.len() { for i in by_name.values_mut().flatten().filter(|i| **i >= at) { *i += 1; diff --git a/crates/engine/src/cmd/fileio/tests_cdr.rs b/crates/engine/src/cmd/fileio/tests_cdr.rs index 353c6ed9da..6cd91c3204 100644 --- a/crates/engine/src/cmd/fileio/tests_cdr.rs +++ b/crates/engine/src/cmd/fileio/tests_cdr.rs @@ -263,15 +263,18 @@ fn layers_of_one_name_on_a_page_stay_apart_and_pages_share_them() { /// Pages that stack layers of the same names in another order keep their own order: the later /// page gets a new layer rather than art under a layer it stacks above. A layer a later page adds -/// below the shared ones goes below them. +/// below the shared ones goes below them, and a page that shares no layer puts its layers on top. #[test] fn each_page_keeps_its_own_layer_order() { let v = V(1100); let rect = || synth::object(v, 1, &[(30, [v.coord(5.0), v.coord(5.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); let page = |names: &[&str]| synth::page(false, names.iter().map(|n| synth::layer(v, [0, 0, 0, 0x98], n, vec![rect()])).collect()); // Front to back on each page. - for (second, want, counts) in [(&["A", "B"][..], vec!["A", "B", "A"], vec![1, 2, 1]), (&["B", "A", "C"][..], vec!["C", "A", "B"], vec![1, 2, 2])] - { + for (second, want, counts) in [ + (&["A", "B"][..], vec!["A", "B", "A"], vec![1, 2, 1]), + (&["B", "A", "C"][..], vec!["C", "A", "B"], vec![1, 2, 2]), + (&["D", "C"][..], vec!["A", "B", "C", "D"], vec![1, 1, 1, 1]), + ] { let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), page(&["B", "A"]), page(second)]); let (doc, _) = super::cdr::import(&file).unwrap(); let names: Vec = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); From 4c8cfda86affac2755731f5233e9311227858581 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 11:38:11 -0800 Subject: [PATCH 04/34] .cdr import: read layouts as public sample files store them Version 2 files (markers m and l) start their settings after a 1-bit picture, so the page box is read two bytes after the settings offset in the header, and their drawn objects keep the fill at byte 105 and the shape at 136. Files with the marker l flag drawn objects 0xc0 and are now read; the marker d, which no sample shows, is refused. A record that does not start with 24, or a drawn object of an unknown type, ends the walk instead of reading the bytes after it as records. A rectangle's radius follows its height directly. A layer's kind comes from the object type in its own loda (11 grid, 12 guides, 17 desktop), so drawing layers flagged 0x10 or 0x08 are no longer dropped or taken for the desktop. Object type 0x25 is read as a path from version 10, and arrowhead ids are looked for from version 6. PROVENANCE.md now cites the Kaitai specification, the ZIP specification, the file utility's magic, PRONOM and the public sample files whose bytes each row was checked against. --- crates/cdr/PROVENANCE.md | 120 ++++++++-------- crates/cdr/README.md | 14 +- crates/cdr/src/build.rs | 22 ++- crates/cdr/src/layout.rs | 16 ++- crates/cdr/src/records.rs | 34 +++++ crates/cdr/src/synth.rs | 64 +++++++-- crates/cdr/src/wl.rs | 165 +++++++++++++++++----- crates/cdr/tests/read.rs | 58 +++++--- crates/engine/src/cmd/fileio/tests_cdr.rs | 2 +- crates/engine/tests/import_fuzz.rs | 4 +- docs/mcp.md | 9 +- docs/target-app-parity.md | 2 +- 12 files changed, 353 insertions(+), 157 deletions(-) diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 874f5bb4fc..c9a96f1206 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -7,13 +7,6 @@ Sources: - **K**: the Kaitai Struct specification `coreldraw_cdr.ksy` (MIT, notice in `LICENSE-kaitai.txt`), https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/coreldraw_cdr.ksy -- **T**: an open-source converter's CDR format notes (MIT OR Apache-2.0), rows its authors mark - confirmed, - https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/docs/cdr-format.md -- **C**: the published object model reference for the format's drawing program, - https://community.coreldraw.com/sdk/api/draw/17 -- **P**: a web editor's published CDR notes, - https://github.com/photopea/CDR-specification/blob/f91b3c7e8c812b28473f6399e95a624a72a3d6b8/README.md - **KR**: the README and the `bin/cdr-unpk` script of the Kaitai Struct specification (MIT), at the same commit as K, https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/README.md @@ -21,10 +14,6 @@ Sources: - **Z**: the PKWARE ZIP specification, APPNOTE.TXT version 6.3.10, https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT, and RFC 1951 (DEFLATE), https://www.rfc-editor.org/rfc/rfc1951 -- **TS**: the source of the reader that T's notes describe (MIT OR Apache-2.0), at the same commit - as T, read for where a field lies when the notes leave it open; no code is copied, - https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/crates/cdr/src/wl.rs - and https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/crates/cdr/src/parse.rs - **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 @@ -32,67 +21,72 @@ Sources: https://pronom.nationalarchives.gov.uk/fmt/467.xml, https://pronom.nationalarchives.gov.uk/fmt/466.xml and https://pronom.nationalarchives.gov.uk/fmt/465.xml +- **S**: own inspection of the bytes of public sample files, checked against the picture each file + carries of its drawing where it has one (versions 2 and 4 to 25; files of versions 1 and 3 carry + none). The files come from: + - **TP**: https://telparia.com/fileFormatSamples/image/cdr/, by file name + - **LT**: https://git.libreoffice.org/libcdr-test at commit + `dafe4fe53d685d89df20a5c0bb18f318ccefb4a8`, `testset//` + - **UC**: https://svn.code.sf.net/p/uniconvertor/code/formats/CDR/testing%20base/ at revision + 434, by file name + - **TDF**: attachments to The Document Foundation's bug tracker, + https://bugs.documentfoundation.org/attachment.cgi?id= + - **NR**: Natural Resources Canada's tactile maps, + https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/approach-approch/cdr/banff_ap_en.cdr and + https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/atlas-atlas/cdr/ab_en_br.cdr + - **DM**: the clip art of https://discmaster.textfiles.com/browse/31541, by file name -Status: `public-spec` (K, KR, C, Z, F or PR), `public-notes` (a confirmed row of T, a row of T's -table of the layouts its writer takes from sample files, TS, or P), `unconfirmed` (a row T marks as -assumed, or a point no source states; listed so it can be checked against a file). +Status: `public-spec` (K, KR, Z, F or PR), `sample` (S), `unconfirmed` (a point no source states +and no sample file shows; listed so it can be checked against a file, with what the reader does +when it is wrong). -No public specification covers versions 1 to 4, and the files of those versions that this reader -has read are the synthetic ones `src/synth.rs` builds from the rows below. T's authors took their -rows for versions 3 and 4 from four version 3 drawings, six version 4 drawings and a set of -version 3 clip art, and their rows for versions 1 and 2 from 18 files; none of those files is -public. - -T and P are themselves notes taken from files, not specifications. Drawings of versions 7 to 18, -20, 22, 24, 26 and 27 written by the converter that T's authors publish (release 0.44.0) read back -with the pages, layers, groups, shapes, colors, outline widths, caps, joins and dashes it wrote. -That converter also reads the synthetic packages of versions 14 to 18, 20, 22, 24, 26 and 27 that -`src/synth.rs` writes, with the page, its layer and the shapes on it. Those files are not -committed. +No public specification covers versions 1 to 4. Their rows rest on the sample files they name. +The test inputs are the synthetic files that `src/synth.rs` builds from the rows below; no sample +file is committed. | Id | What the code relies on | Source | Status | |---|---|---|---| -| R1 | `RIFF`, the body length, then the form type `CDR` or `cdr` and a version character: `1` to `9`, `A` (10) to `H` (17), `J` (18) on, `I` unused; `cdr8` is 8.01, `CDR ` is 3, `CDRX` is another format. Files of versions 23 to 27 carry `O` to `U`, which count differently from the version 24 update on (`CDRQ` with a `vrsn` of 2430, `CDRU` with 2700), so their `vrsn` chunk decides (R2) | K L68-L133; T L22 | public-spec (letters from version 23: public-notes) | +| R1 | `RIFF`, the body length, then the form type `CDR` or `cdr` and a version character: `1` to `9`, `A` (10) to `H` (17), `J` (18) on, `I` unused; `cdr8` is 8.01, `CDR ` is 3, `CDRX` is another format. Files of versions 23 to 25 carry `O` (23), `P` (24), `Q` (24.3, with a `vrsn` of 2430) and `R` (25), which count differently from the version 24 update on, so their `vrsn` chunk decides (R2) | K L68-L133; S: LT `testset/23` to `testset/25`, such as `circle_redfill_nooutline_cdr25.cdr` | public-spec (letters from version 23: sample; letters of versions 26 and 27: unconfirmed, and the `vrsn` chunk decides when the file has one) | | R2 | `vrsn`: the version as a u16, in hundreds | K L276-L278 | public-spec | -| R3 | `LIST cmpr`: two (compressed, uncompressed) u32 pairs, then two blocks of `CPng`, `01 00 04 00` and a zlib stream; the first inflates to the chunk stream, the second to a pool of u32 sizes that each chunk's size field indexes | K L193-L220, L2626-L2682; P "LIST cmpr"; T L30 | public-spec | +| R3 | `LIST cmpr`: two (compressed, uncompressed) u32 pairs, then two blocks of `CPng`, `01 00 04 00` and a zlib stream; the first inflates to the chunk stream, the second to a pool of u32 sizes that each chunk's size field indexes | K L193-L220, L2626-L2682 | public-spec | | R4 | A chunk is an id, a u32 size and the body, padded to an even length; a `LIST` body starts with its form type; from version 7 a `LIST stlt` holds the style tables, not chunks | K L68-L78, L135-L155, L307-L334 | public-spec | -| R5 | Coordinates: i16 in 1/1000 inch before version 6, else i32 in 1/254000 inch; header fields, counts and offsets are u16 before version 6, else u32 | K L58-L66, L2688-L2700; T L145 | public-spec | -| R6 | `loda` and `lobj`: length, argument count, offsets table, types table, object type; count + 1 offsets bound the arguments; the types table runs in reverse; object types (1 rectangle, 2 ellipse, 3 curve, 0x14 polygon) and argument types (10 outline, 20 fill, 30 coordinates, 1000 name, 11000 polygon, 19130 page size) | K L335-L450, L846-L893; T L145-L157 | public-spec | +| R5 | Coordinates: i16 in 1/1000 inch before version 6, else i32 in 1/254000 inch; header fields, counts and offsets are u16 before version 6, else u32 | K L58-L66, L2688-L2700 | public-spec | +| R6 | `loda` and `lobj`: length, argument count, offsets table, types table, object type; count + 1 offsets bound the arguments; the types table runs in reverse; object types (1 rectangle, 2 ellipse, 3 curve, 0x14 polygon) and argument types (10 outline, 20 fill, 30 coordinates, 1000 name, 11000 polygon, 19130 page size) | K L335-L450, L846-L893 | public-spec | | R7 | Angles: i16 tenths of a degree before version 6, else i32 millionths of a degree | K L2835-L2855 | public-spec | -| R8 | `trfd`: length, count, offsets table; each entry has 8 bytes first from version 13, a u16 type, and type 8 is a matrix after 6 bytes (from version 6) of six f64 `a c tx b d ty`, `tx` and `ty` in coordinate units; the matrices of one record apply in file order | K L895-L953, L2808-L2834; T L201-L204 | public-spec | +| R8 | `trfd`: length, count, offsets table; each entry has 8 bytes first from version 13, a u16 type, and type 8 is a matrix after 6 bytes (from version 6) of six f64 `a c tx b d ty`, `tx` and `ty` in coordinate units; the matrices of one record apply in file order | K L895-L953, L2808-L2834 | public-spec | | R9 | Name argument (1000): Windows-1252 up to a NUL before version 12, UTF-16LE from it | K L601-L630 | public-spec | -| R10 | `mcfg`: 12 bytes (13 on), 4 (9 to 12), 28 (6) or none, then the page width and height as coordinates | K L1670-L1765; P "mcfg" | public-spec | -| R11 | `fild` (`fill` before 7): id; from 13 a record tagged 1300 with its length, which records tagged 2400 or more may precede; the fill type u16 (0 none, 1 uniform, others not read); uniform: 2 bytes then a color before 13, from 13 a record tagged 1300 holding a property list (u8 type, u32 length, body; 0 ends it; 1 a color, 8 a palette id and a UTF-16 name, 3 a UTF-16 name) | K L1025-L1302; T L217-L220 | public-spec (2400 records: public-notes) | -| R12 | `outl`: id; from 13 records (u32 id, u32 length, body) up to id 1, whose body follows; line type, caps and join u16; 2 bytes (6 to 12); width; stretch u16; 2 bytes (6 on); nib angle; 52 bytes (6 to 12) or 46 (13 on); the color; 16 bytes (10 before 6); the dash count u16 and the dashes, in multiples of the width; the arrowhead ids 22 bytes after the first dash in 7 and 11 to 12, 20 bytes from 13. Caps 0 butt, 1 round, 2 square; joins 0 miter, 1 round, 2 bevel | K L954-L1024; T L242-L243; C `cdrOutlineLineCaps`, `cdrOutlineLineJoin` | public-spec (arrowhead places: public-notes) | -| R13 | Bit 0 of the outline's line type: no outline | T L246 | unconfirmed | -| R14 | A color record from version 5: model u16, palette u16, 4 bytes, four value bytes. Models: 2 CMYK in percent, 3 and 17 CMYK 0 to 255, 4 CMY 0 to 255, 5 blue, green, red, 9 gray 0 to 255, 20 registration, 21 blue, green, red and a tint in percent already applied; 1, 14 and 25 a library color's number (u16) and tint in percent (u16) | K L2856-L2965; T L256-L257 | public-spec (library values: public-notes) | -| R15 | Rectangle coordinates: width, height and one radius, three more radii from version 9, running counterclockwise from the corner at (width, 0) | K L674-L700; T L172-L173 | public-spec | -| R16 | Point list: u32 count (before version 6 as R39 gives it), the points, then one type byte each, the count held to what fits; type bits 7 and 6 move, line, curve end, control point; bit 3 closes the subpath | K L782-L787, L840-L845, L2701-L2807; T L170-L171, L180 | public-spec | -| R17 | Ellipse coordinates: width, height, start and end angles, pie flag (u16 before 6, else u32); the radii are half the width and height; the angles turn from the ellipse's own axes, which a negative width or height points the other way | K L754-L781; T L179 | public-spec (axis direction of a negative size: public-notes) | -| R18 | Polygon argument (11000): 4 bytes before 13, the side count u32, the next point u32 (the u32 after it when it is 0 or 1, else 4 bytes), 4 more from 13, rx and ry f64, the centre; the base curve is one side on a circle of 1000 mm from the top vertex to the vertex it runs to clockwise, copied once for each side | K L631-L655; T L182-L183 | public-spec (base curve: public-notes) | -| R19 | `flgs`: byte 3 the record type, byte 2 marks the master page; a layer's byte 0 is 0, 8 desktop, 0x0a guides, 0x1a grid; in versions 7 to 13 the master page flags its guides [2, 1, 1], desktop [0, 1, 1] and grid [0x12, 0, 1]; from 14 it flags them [0x0a, 0, 1], [8, 0, 1] and [0x1a or 0x5a, 1, 1], by byte 0 as other layers | K L1602-L1639; T L132-L133 | public-spec (master page flags: public-notes for versions 7 to 21, unconfirmed for 22 to 27) | +| R10 | `mcfg`: 12 bytes (13 on), 4 (9 to 12), 28 (6) or none, then the page width and height as coordinates | K L1670-L1765 | public-spec | +| R11 | `fild` (`fill` before 7): id; from 13 a record tagged 1300 with its length, which records tagged 2400 or more may precede; the fill type u16 (0 none, 1 uniform, others not read); uniform: 2 bytes then a color before 13, from 13 a record tagged 1300 holding a property list (u8 type, u32 length, body; 0 ends it; 1 a color, 8 a palette id and a UTF-16 name, 3 a UTF-16 name) | K L1025-L1302; S: LT `testset/15` to `testset/25` `circle_redfill_nooutline_cdr.cdr`, whose fill records hold a record tagged 2400 before the one tagged 1300 | public-spec (2400 records: sample) | +| R12 | `outl`: id; from 13 records (u32 id, u32 length, body) up to id 1, whose body follows; line type, caps and join u16; 2 bytes (6 to 12); width; stretch u16; 2 bytes (6 on); nib angle; 52 bytes (6 to 12) or 46 (13 on); the color; 16 bytes (10 before 6); the dash count u16 and the dashes, in multiples of the width; the arrowhead ids 22 bytes after the first dash in versions 6 to 12, 20 bytes from 13. Caps 0 butt, 1 round, 2 square; joins 0 miter, 1 round, 2 bevel | K L954-L1024; S: caps and joins in UC `outl_line_caps_cdr7.cdr` and `outl_corner_cdr7.cdr`; arrowhead ids, matched against the drawing's `arrw` records, in TP `web_cd.cdr` (6), UC `rogan_logo_cdr7.cdr`, `rogan_logo_cdr8.cdr` and `rogan_logo_cdr11.cdr`, NR `ab_en_br.cdr` (9) and `banff_ap_en.cdr` (10), TDF 76820 (12) and 140638 (13) | public-spec (caps, joins and arrowhead places: sample; arrowheads before version 6: no sample names one, and the reader does not look for them) | +| R13 | Bit 0 of the outline's line type: no outline | S: LT `square_blackfill_nooutline_cdr.cdr` and the other `nooutline` files of `testset/15` to `testset/25`, whose outline records all have line type 1 and whose pictures show no outline | sample | +| R14 | A color record from version 5: model u16, palette u16, 4 bytes, four value bytes. Models: 2 CMYK in percent, 3 and 17 CMYK 0 to 255, 4 CMY 0 to 255, 5 blue, green, red, 9 gray 0 to 255, 20 registration, 21 blue, green, red and a tint in percent already applied; 1, 14 and 25 a library color's number (u16) and tint in percent (u16) | K L2856-L2965; S: model 25 in LT `testset/12/square_pantoneblackfill_nooutline.cdr` (number 14, tint 100), model 1 in UC `rogan_logo_cdr11.cdr` (number 4, tint 50) | public-spec (library values of models 1 and 25: sample; model 14: unconfirmed, and its color opens as a spot color without a look) | +| R15 | Rectangle coordinates: width, height and one radius, three more radii from version 9, running counterclockwise from the corner at (width, 0) | K L674-L700 | public-spec | +| R16 | Point list: u32 count (before version 6 as R39 gives it), the points, then one type byte each, the count held to what fits; type bits 7 and 6 move, line, curve end, control point; bit 3 closes the subpath | K L782-L787, L840-L845, L2701-L2807 | public-spec | +| R17 | Ellipse coordinates: width, height, start and end angles, pie flag (u16 before 6, else u32); the radii are half the width and height; the angles turn from the ellipse's own axes, which a negative width or height points the other way | K L754-L781; S: the pies of negative height in the ellipse-sector drawings of versions 12 and 13 in UC | public-spec (axis direction of a negative size: sample) | +| R18 | Polygon argument (11000): 4 bytes before 13, the side count u32, the next point u32 (the u32 after it when it is 0 or 1, else 4 bytes), 4 more from 13, rx and ry f64, the centre; the base curve is one side on a circle of 1000 mm from the top vertex to the vertex it runs to clockwise, copied once for each side | K L631-L655; S: the polygons and stars of UC `shapes_cdr10.cdr` | public-spec (base curve: sample) | +| R19 | `flgs`: byte 3 the record type, byte 2 marks the master page. A layer's own `loda` names what it is by its object type: 11 a grid, 12 guides, 17 the desktop, any other a drawing layer (version 3 one less, R32). Only a layer without a `loda` is taken by its byte 0: 0 drawing, 8 desktop, 0x0a guides, a set bit 0x10 grid, and in versions 7 to 13 [2, 1, 1] guides and [0, 1, 1] desktop | K L1602-L1639 (record types); S: in every sample file of versions 3 to 25 the layer's object type agrees with its name; byte 0 does not: TDF 114901 (version 8) flags its master page's guides [2, 1, 1], desktop [0, 1, 1], grid [0x12, 0, 1] and drawing layer [8, 1, 0], and NR `ab_en_br.cdr` (version 9) flags drawing layers 0x10 and its guides 0x1a | public-spec (layer types: sample; byte 0 of a layer without a `loda`: unconfirmed, as no sample has such a layer, and a wrong guess drops or shows that layer's objects) | | R20 | Fill and outline arguments (20, 10): a u32 record id | K L452-L460, L548-L556 | public-spec | | R21 | Page size argument (19130): width and height | K L666-L672 | public-spec | -| R22 | `LIST page` holds `LIST layr` lists, in versions 7 to 13 inside a `LIST gobj`; a layer holds `LIST obj ` and `LIST grp `; a page, layer or object keeps its own `loda` (and an object its `trfd`, in a `trfl` list) among its chunks or in a `LIST lgob` | K L1602-L1639 (record types); T L120, L129, L359, L362 | public-notes | -| R23 | Guideline (object type 0x16), argument 16000: 12 bytes, the angle in millionths of a degree, then points from the page centre; version 7 keeps them in a `guid` chunk: a u32 count, the count again, 40-byte records laid out the same way | T L159-L160 | public-notes | +| R22 | `LIST page` holds `LIST layr` lists, directly or in a list it holds (a `LIST gobj` in the samples); a layer holds `LIST obj ` and `LIST grp `; a page, layer or object keeps its own `loda` (and an object its `trfd`, in a `trfl` list) among its chunks or in a `LIST lgob` | K L1602-L1639 (record types); S: the chunk trees of every sample file of versions 3 to 25 | sample | +| R23 | Guideline (object type 0x16), argument 16000: 12 bytes, the angle in millionths of a degree, then points from the page centre; version 7 keeps them in a `guid` chunk: a u32 count, the count again, 40-byte records laid out the same way | S: argument 16000 in NR `ab_en_br.cdr` (9) and TDF 194220 (13); the `guid` chunk of TDF 123971 (7). Pictures do not show guidelines | sample | | R24 | ZIP: the end of central directory record (signature `PK\5\6`, 22 bytes and a comment of up to 65,535 bytes) gives the member count and where the central directory lies; each central directory entry (46 bytes, then name, extra field and comment) gives the flags, method, CRC-32, sizes and its local header; a local header is 30 bytes, then its name and extra field, then the member's bytes. Flag bit 0 marks an encrypted member; method 0 is stored and 8 deflated; 0xFFFF and 0xFFFFFFFF mark ZIP64 fields, and a ZIP64 locator (`PK\6\7`, 20 bytes) precedes the end record of a ZIP64 archive; disk numbers other than 0 mark an archive split across files | Z 4.3.7, 4.3.12, 4.3.15, 4.3.16, 4.4.1.4, 4.4.4, 4.4.5, 4.4.7, 4.4.8, 4.4.13 | public-spec | -| R25 | Versions 14 and 15 save a ZIP package whose member `content/riffData.cdr` is the RIFF file | KR README L33, `cdr-unpk` L30; T L29, L355 | public-spec | -| R26 | From version 16 the package's member `content/root.dat` is the RIFF file; `content/dataFileList.dat` names the data streams, one per line, members of `content/data/`; a redirect's stream number counts lines from 0 | KR README L34, L40, `cdr-unpk` L34-L66; K L173-L180; T L37, L355 | public-spec | -| R27 | In a package of version 16 on, a chunk outside a compressed list whose size is 16 (in `root.dat` or in a redirected list's body) is a redirect record: stream u32, length u32, offset u32 and a reserved u32; its body is `length` bytes at `offset` of the stream; stream `0xFFFFFFFF` holds the body (at most 8 bytes) in the record after the length; a redirected list's body starts with its form type | K L144-L193; T L38-L40 | public-spec | -| R28 | Templates have the form type `CDT` and a letter of their own, `CDTQ` in version 21 with a `vrsn` of 2100; the `vrsn` chunk names the version. The reader takes any letter `A` to `Z` there | T L26 | public-notes (letters other than `Q`: unconfirmed) | -| R29 | Rectangle coordinates from version 15: width and height as f64 coordinate units, scale x and y (f64, repeating the transform's scale), the scale-with flag (u8) and 7 bytes, then the four radii as f64, 16 bytes apart (a corner type byte and 15 bytes after the first), in the order of R15. With the flag clear each radius is a share of half the shorter side; with it set the radii are multiplied by 254000 coordinate units, which makes them inches | K L674-L752; T L173-L177 | public-spec (radius share with the flag clear, scale not applied: public-notes) | -| R30 | Object type 0x25 (version 16 on) is a path: 4 bytes, two u16 counts that add up to the point count, 16 bytes, then the points and their type bytes as in R16 | K L788-L799, L892; T L157, L181 | public-spec (from version 16: public-notes) | -| R31 | Version 3 is a RIFF file with the form type `CDR ` (a space) and a `vrsn` of 300; version 4 has the form type `CDR4` and a `vrsn` chunk. Both use the 16-bit fields of R5 and R7. Their pages, layers, groups and objects are read by the rules of R19 and R22 | K L117-L134; T L44; PR fmt/465; F `riff` L786 | public-spec (pages and layers as R19 and R22: unconfirmed) | -| R32 | Version 3 counts its object types from 0: rectangle 0, ellipse 1, curve 2, text 3, bitmap 4; later versions use these plus one | T L53; TS `parse.rs` | public-notes | -| R33 | Version 3 keeps an object's transforms in argument 100 of its `lobj`: a u16, the entry count (u16), then 10-byte entries of a type (u16) and, at byte 6, where the entry's data starts, counted from the start of the argument. Type 0x8c is a matrix as R37, and the matrices apply in file order. Type 0x14 is an envelope, which this reader does not apply: the shape keeps its outline, placed by the matrices alone, and the drawing's warnings name the envelopes. A group's own `lobj` holds an argument 100 that places all of the group's objects after their own transforms | T L54-L56, L60; K L851; TS `parse.rs` | public-notes | -| R34 | Version 3 fill, argument 20: a type byte (0 none, 1 uniform, 2 and 4 fountain, 6 texture, 7 and 10 pattern); a uniform fill's color follows as R36 | K L452-L547; T L62 | public-spec | -| R35 | Version 3 outline, argument 10: a flags byte with bit 0 set when the object is outlined, the width (coordinate), the stretch (u16), the nib angle, the color as R36, 7 bytes, the dash count (u8) and 10 bytes that hold the dashes as one byte each, the join (u16 at byte 30) and the caps (u16 at byte 32) numbered as R12, then the two arrowhead ids (u32). Dashes are read in multiples of the width as R12 | K L548-L592; T L64 | public-spec (flag bit: public-notes; dash unit, and the join, which T puts in the byte at 33: unconfirmed) | -| R36 | A color before version 5: in versions 1 to 3 a model byte and four value bytes, in version 4 a model u16, four u16 values and 2 bytes. Model 1 is cyan, magenta, yellow and black in percent. Model 0 is an ink number (u16) and a tint in percent (u16): ink 0 is black at the tint, ink 1 is white, and other numbers are inks of a numbered library that the file does not store. Other models are read as R14 | K L2882-L2908; T L65-L66, L89; TS `parse.rs`, `wl.rs` | public-notes (models other than 0 and 1: unconfirmed, K and T differ on model 1) | -| R37 | A matrix of versions 3 and 4: six i32 `a c tx b d ty`, the four factors in 16.16 fixed point and `tx` and `ty` in coordinate units. A version 4 `trfd` entry of type 8 holds one where R8 has six f64 | T L55, L61; TS `parse.rs` | public-notes | -| R38 | `mcfg` of version 3: 2 bytes, then the page's two corners as four coordinates; the page size is the distance between them | K L1676-L1678, L1745-L1756; T L71 | public-spec | -| R39 | A point list before version 6 starts with a u16 count and another u16 (1 in some curves of versions 3 and 4), where K reads the two as one u32 | T L67 | public-notes | -| R40 | Versions 1 and 2 are not RIFF files. A file starts with `WL`, a marker byte, a zero byte and five u32: the start of the settings (28), the start and the end of the object records, the start of the trailer and that value minus two. F and PR give the marker `e` for version 1.0 and `m` for 2.0; T's authors also saw `d`. The reader takes these three markers and reads the three alike | T L82; F `images` L4159-L4172; PR fmt/467, fmt/466 | public-notes (which version `d` marks: unconfirmed) | -| R41 | The page's box in a file of version 1 or 2: four i16 at byte 30 (left, top, right, bottom) in 1/1000 inch around the page's centre, y pointing up | T L75-L78, L83; TS `wl.rs` | public-notes | -| R42 | The records of a file of version 1 or 2 run from the front of the stacking order to the back. A group or layer record is 28 bytes, and the low byte of its flags at byte 26 is not 0x40. A drawn object has 0x40 there and a u16 body size at byte 28; it is the body size plus 32 bytes long, and at least 118 | T L85, L86, L93; TS `wl.rs` | public-notes | -| R43 | A drawn object of version 1 or 2: a point (two i16) at byte 32; six i32 in 16.16 fixed point at 36, `a b tx c d ty`, with x' = a x + b y + tx + the point's x and y' = c x + d y + ty + the point's y; the object type at 60 (0 rectangle, 1 ellipse, 2 curve, 3 text); a byte at 67 that is not 0 when the object is outlined, the outline's width (u16) at 68 and its color at 74; the fill type at 94 (0 none, 1 uniform) and its color at 95; the shape from byte 114. Colors are as R36 | T L87-L89; TS `wl.rs` | public-notes | -| R44 | Shapes of version 1 or 2, from byte 114 of the object: a rectangle's width and height (i16), then after 2 bytes a corner radius; an ellipse's width and height, then two angles; a curve's point list as R39 and R16 | T L90, L91; TS `wl.rs` | public-notes (radius: unconfirmed; how the angles make an arc: unconfirmed, so an ellipse whose angles differ is left out) | +| R25 | Versions 14 and 15 save a ZIP package whose member `content/riffData.cdr` is the RIFF file | KR README L33, `cdr-unpk` L30 | public-spec | +| R26 | From version 16 the package's member `content/root.dat` is the RIFF file; `content/dataFileList.dat` names the data streams, one per line, members of `content/data/`; a redirect's stream number counts lines from 0 | KR README L34, L40, `cdr-unpk` L34-L66; K L173-L180 | public-spec | +| R27 | In a package of version 16 on, a chunk outside a compressed list whose size is 16 (in `root.dat` or in a redirected list's body) is a redirect record: stream u32, length u32, offset u32 and a reserved u32; its body is `length` bytes at `offset` of the stream; stream `0xFFFFFFFF` holds the body (at most 8 bytes) in the record after the length; a redirected list's body starts with its form type | K L144-L193 | public-spec | +| R28 | Templates have the form type `CDT` and a letter of their own; the `vrsn` chunk names the version. The reader takes any letter `A` to `Z` there | none: no sample template | unconfirmed (a template is read as a drawing of the version its `vrsn` chunk names, and one without that chunk is refused) | +| R29 | Rectangle coordinates from version 15: width and height as f64 coordinate units, scale x and y (f64, repeating the transform's scale), the scale-with flag (u8) and 7 bytes, then the four radii as f64, 16 bytes apart (a corner type byte and 15 bytes after the first), in the order of R15. With the flag clear each radius is a share of half the shorter side; with it set the radii are multiplied by 254000 coordinate units, which makes them inches | K L674-L752; S: LT `square_blackfill_nooutline_roundedcorners_cdr.cdr` of `testset/15` to `testset/25` (flag clear, a share of 0.25) | public-spec (radius share with the flag clear: sample; that the scale is not applied: unconfirmed, as every sample has a scale of 1, and a wrong guess changes only the corners' size) | +| R30 | Object type 0x25 (version 10 on) is a path: 4 bytes, two u16 counts that add up to the point count, 16 bytes, then the points and their type bytes as in R16 | K L788-L799, L892; S: TDF 78250 (version 15) and UC `shapes_cdr10.cdr`, `shapes_cdr11.cdr`, `shapes_cdr12.cdr` and `shapes_x3.cdr` (versions 10 to 13), whose type bytes start where the counts put them; no sample before version 10 holds the type | public-spec (from version 10: sample) | +| R31 | Version 3 is a RIFF file with the form type `CDR ` (a space) and a `vrsn` of 300; version 4 has the form type `CDR4` and a `vrsn` chunk. Both use the 16-bit fields of R5 and R7. Their pages, layers, groups and objects are read by the rules of R19 and R22 | K L117-L134; PR fmt/465; F `riff` L786; S: TP `FOX.CDR` and `DALI.CDR` (3), DM `lion1.cdr` and `tiger.cdr` (4) | public-spec (pages and layers as R19 and R22: sample) | +| R32 | Version 3 counts its object types from 0: rectangle 0, ellipse 1, curve 2, text 3, bitmap 4; later versions use these plus one | S: the rectangles, curves and text of TP `ARMYSTF1.CDR`, `DALI.CDR` and `FOX.CDR`, which come out whole | sample (ellipse 1 and bitmap 4: unconfirmed, as no sample holds them; a bitmap is left out with a warning) | +| R33 | Version 3 keeps an object's transforms in argument 100 of its `lobj`: a u16, the entry count (u16), then 10-byte entries of a type (u16) and, at byte 6, where the entry's data starts, counted from the start of the argument. Type 0x8c is a matrix as R37, and the matrices apply in file order. Type 0x14 is an envelope, which this reader does not apply: the shape keeps its outline, placed by the matrices alone, and the drawing's warnings name the envelopes. A group's own `lobj` holds an argument 100 that places all of the group's objects after their own transforms | K L851; S: the matrices of every version 3 file in TP, whose drawings come out whole | sample (envelope type 0x14: unconfirmed, as no sample holds one; it is not applied, with a warning) | +| R34 | Version 3 fill, argument 20: a type byte (0 none, 1 uniform, 2 and 4 fountain, 6 texture, 7 and 10 pattern); a uniform fill's color follows as R36 | K L452-L547 | public-spec | +| R35 | Version 3 outline, argument 10: a flags byte with bit 0 set when the object is outlined, the width (coordinate), the stretch (u16), the nib angle, the color as R36, 7 bytes, the dash count (u8) and 10 bytes that hold the dashes as one byte each, the join (u16 at byte 30) and the caps (u16 at byte 32) numbered as R12, then the two arrowhead ids (u32). Dashes are read in multiples of the width as R12 | K L548-L592; S: the outlines of the version 3 files in TP | public-spec (flag bit: sample; dash unit, and the join, where bytes 32 and 33 of some samples hold 2 and 2: unconfirmed, and a wrong guess changes only how corners, ends and dashes are drawn) | +| R36 | A color before version 5: in versions 1 to 3 a model byte and four value bytes, in version 4 a model u16, four u16 values and 2 bytes. Model 1 is cyan, magenta, yellow and black in percent. Model 0 is an ink number (u16) and a tint in percent (u16): ink 0 is black at the tint, ink 1 is white, and other numbers are inks of a numbered library that the file does not store. Other models are read as R14 | K L2882-L2908; S: model 1 in TP `ARMYSTF1.CDR` (3) and DM `lion1.cdr` (4), model 0 in TP `ARROW5.CDR` (3) and `WI.CDR` (1) | sample (ink 1, and models other than 0 and 1: unconfirmed; an ink of another number opens as a spot color without a look) | +| R37 | A matrix of versions 3 and 4: six i32 `a c tx b d ty`, the four factors in 16.16 fixed point and `tx` and `ty` in coordinate units. A version 4 `trfd` entry of type 8 holds one where R8 has six f64 | S: TP `FOX.CDR` and `DALI.CDR` (3), DM `lion1.cdr` and `tiger.cdr` (4) | sample | +| R38 | `mcfg` of version 3: 2 bytes, then the page's two corners as four coordinates; the page size is the distance between them | K L1676-L1678, L1745-L1756 | public-spec | +| R39 | A point list before version 6 starts with a u16 count and another u16 (1 in some curves of versions 1, 2 and 4, 0 in the others), where K reads the two as one u32 | S: TP `DALI.CDR` (3), DM `headup.cdr` and `lion1.cdr` (4), TP `WI.CDR` (1), `FLAG.CDR` and `MENU.CDR` (2) | sample | +| R40 | Versions 1 and 2 are not RIFF files. A file starts with `WL`, a marker byte, a zero byte and five u32: the start of the settings, the start and the end of the object records, the start of the trailer and that value minus two. Version 1 has the marker `e` and its settings start at byte 28. Version 2 has the marker `m` or `l`, and its settings start after a 1-bit picture of the drawing, whose header starts where the u32 at byte 28 says. The reader takes these three markers | F `images` L4159-L4172; PR fmt/467, fmt/466; S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`), `MENU.CDR` and `DRINKS.CDR` (`l`) | public-spec (markers `e` and `m`: F and PR; the offsets and the marker `l`: sample) | +| R41 | The page's box in a file of version 1 or 2: four i16 two bytes after the start of the settings (left, top, right, bottom) in 1/1000 inch around the page's centre, y pointing up | S: TP `WI.CDR`, `FLAG.CDR` and `MENU.CDR` | sample | +| R42 | The records of a file of version 1 or 2 run from the front of the stacking order to the back. Every record starts with the u32 24. A group or layer record is 28 bytes, and bit 0x40 of its flags byte at 26 is clear. A drawn object has that bit set (0x40 in files with the markers `e` and `m`, 0xc0 with `l`) and a u16 body size at byte 28; it is the body size plus 32 bytes long. A drawn object of another type than those of R43 gives its length otherwise, and the records after it are not read | S: TP `WI.CDR`, `FLAG.CDR`, `MENU.CDR` and `DRINKS.CDR`; the order checked against the picture of `MENU.CDR` | sample | +| R43 | A drawn object of version 1 or 2: a point (two i16) at byte 32; six i32 in 16.16 fixed point at 36, `a b tx c d ty`, with x' = a x + b y + tx + the point's x and y' = c x + d y + ty + the point's y; the object type at 60 (0 rectangle, 1 ellipse, 2 curve, 3 text); a byte at 67 that is not 0 when the object is outlined, the outline's width (u16) at 68 and its color at 74; the fill type (0 none, 1 uniform) and its color after it, at 94 and 95 with the marker `e` and at 105 and 106 with `l` and `m`; the shape from byte 114 with `e` and 136 with `l` and `m`. Colors are as R36 | S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`) and `MENU.CDR` (`l`), checked against the pictures of `FLAG.CDR` and `MENU.CDR` | sample | +| R44 | Shapes of version 1 or 2: a rectangle's width and height (i16), then a corner radius; an ellipse's width and height, then two angles; a curve's point list as R39 and R16 | S: rectangles in TP `FLAG.CDR`, ellipses and curves in TP `WI.CDR`, curves in TP `MENU.CDR` | sample (the radius of files with the marker `e`, which no sample shows, and how the angles make an arc: unconfirmed; a radius is kept only when it is at most half the shorter side, and an ellipse whose angles differ is left out with a warning) | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index 56ded19cfb..d5cf86ef54 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -15,7 +15,7 @@ with each object's transform. It does not write `.cdr` files. | Layers (drawing, desktop, guides and grid layers), the master page's among them | layers by name and kind | | Guidelines (object type 0x16, and the version 7 `guid` chunk) | guidelines at their point and angle | | Groups (`LIST grp `) | groups | -| Curves (point lists of moves, lines and cubic curves) and paths (object type 0x25, version 16 on) | paths | +| Curves (point lists of moves, lines and cubic curves) and paths (object type 0x25, version 10 on) | paths | | Rectangles (one corner radius, four from version 9) | rectangles with each corner's radius | | Ellipses, arcs and pies | ellipses, and paths for arcs and pies | | Polygons and stars (a base side copied for each side) | paths | @@ -29,19 +29,19 @@ that are encrypted, ZIP64 archives or split across files. ## Versions 1 to 4 -No public specification covers these versions. The reader follows the published notes that -`PROVENANCE.md` cites (rows R31 to R44), and the files of these versions it has read are the -synthetic ones that `src/synth.rs` builds from those rows. +No public specification covers these versions. The reader follows the layouts of public sample +files that `PROVENANCE.md` lists (rows R31 to R44), and its tests read the synthetic files that +`src/synth.rs` builds from those rows. | Version | Read | Left out or refused | |---|---|---| -| 1 and 2 (`WL` files) | the page size; rectangles with one corner radius, whole ellipses and curves, each with its matrix; uniform fills and outlines with their width and color, in CMYK percent and the inks black and white. The objects come in on one page and one layer, front to back | text and objects of other types, and ellipses whose two angles differ (arcs and pies), with the unsupported-objects warning; fills of other types, with the unsupported-fills warning; inks of a numbered library, which read as spot colors without a look; groups and layers, whose records are passed over; dashes, caps, joins and arrowheads, which the notes do not place | +| 1 and 2 (`WL` files) | the page size; rectangles with one corner radius, whole ellipses and curves, each with its matrix; uniform fills and outlines with their width and color, in CMYK percent and the inks black and white. The objects come in on one page and one layer, front to back | text and objects of other types, and ellipses whose two angles differ (arcs and pies), with the unsupported-objects warning; fills of other types, with the unsupported-fills warning; inks of a numbered library, which read as spot colors without a look; groups and layers, whose records are passed over; dashes, caps, joins and arrowheads, which the reader does not look for; the records after a drawn object of another type, with the unsupported-objects warning | | 3 (RIFF, form type `CDR `) | the page size from the page's corners; pages, layers and groups; rectangles, ellipses, arcs and curves with the matrices of the object and of the groups around it; uniform fills; outlines with their width, color, caps, joins and dashes | text and bitmaps; envelopes, with the envelopes warning (the objects and groups under one keep their outlines and matrices); fountain, pattern and texture fills; arrowheads | | 4 (RIFF, form type `CDR4`) | as version 5, with the colors and the fixed-point transforms of version 4 | as version 5 | A file is taken for version 1 or 2 by its content only when, after `WL`, its marker byte is one of -`d`, `e` and `m`, the next byte is zero, and the record offsets of its header fit the file. The -reader reports version 2 for the marker `m` and version 1 for the other two. A RIFF file that names +`e`, `l` and `m`, the next byte is zero, and the offsets of its header fit the file. The reader +reports version 1 for the marker `e` and version 2 for the other two. A RIFF file that names a version before 3 is refused, and so is the version 4 template form type `CDST`, which reads as not a `.cdr` drawing. diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs index b4909aca29..b78474136b 100644 --- a/crates/cdr/src/build.rs +++ b/crates/cdr/src/build.rs @@ -193,8 +193,20 @@ fn flags(ix: &Index, list: &Chunk) -> Option<[u8; 4]> { ix.data(c).get(..4)?.try_into().ok() } -/// What a layer's flags make it (R19). Byte 0 holds the kind; versions 7 to 13 flag the master -/// page's desktop layer 0 with bytes 1 and 2 set, and its guides layer 2. +/// What a layer's object type makes it (R19): 11 a grid, 12 guides, 17 the desktop, any other a +/// drawing layer. Version 3 counts its types from 0, one less (R32). +fn layer_kind_of_type(kind: u32, types_from_zero: bool) -> LayerKind { + match kind.saturating_add(u32::from(types_from_zero)) { + 11 => LayerKind::Grid, + 12 => LayerKind::Guides, + 17 => LayerKind::Desktop, + _ => LayerKind::Drawing, + } +} + +/// What a layer's flags make it, for a layer without an object type of its own (R19). Byte 0 holds +/// the kind; versions 7 to 13 may flag the master page's desktop layer 0 with bytes 1 and 2 set, +/// and its guides layer 2. fn layer_kind(f: [u8; 4], version_below_14: bool) -> LayerKind { let [b0, b1, b2, _] = f; if b0 & 0x10 != 0 { @@ -283,8 +295,12 @@ impl<'a, 'b> Ctx<'a, 'b> { fn layer(&mut self, list: &Chunk) -> Layer { let ix = self.ix; - let kind = flags(ix, list).map_or(LayerKind::Drawing, |f| layer_kind(f, self.p.old_master_flags)); let loda = own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)); + // The layer's own object type says what it is; its flags, only when it has none (R19). + let kind = match &loda { + Some(l) => layer_kind_of_type(l.kind, self.p.types_from_zero), + None => flags(ix, list).map_or(LayerKind::Drawing, |f| layer_kind(f, self.p.old_master_flags)), + }; let name = loda.and_then(|l| l.arg(ARG_NAME).map(|b| records::name(b, &self.p, self.warn))).unwrap_or_default(); let mut guides = Vec::new(); let objects = self.objects(ix.children(list), &mut guides); diff --git a/crates/cdr/src/layout.rs b/crates/cdr/src/layout.rs index e4d4e3456d..46c28496cf 100644 --- a/crates/cdr/src/layout.rs +++ b/crates/cdr/src/layout.rs @@ -95,7 +95,7 @@ const fn profile(from: u16) -> Profile { outl_after_color: if short { 10 } else { 16 }, marker_after_dash: if from >= 1300 { Some(20) - } else if from == 700 || from >= 1100 { + } else if from >= 600 { Some(22) } else { None @@ -103,7 +103,7 @@ const fn profile(from: u16) -> Profile { four_radii: from >= 900, f64_rect: from >= 1500, old_master_flags: from < 1400, - paths: from >= 1600, + paths: from >= 1000, utf16_names: from >= 1200, } } @@ -120,6 +120,7 @@ const PROFILES: &[(u16, Profile)] = &[ (700, profile(700)), (800, profile(800)), (900, profile(900)), + (1000, profile(1000)), (1100, profile(1100)), (1200, profile(1200)), (1300, profile(1300)), @@ -166,12 +167,13 @@ mod tests { assert!(for_version(500).is_some_and(|p| !p.fixed_matrix && !p.types_from_zero && p.color == ColorLayout::Record12)); assert!(for_version(1300).is_some_and(|p| p.old_master_flags)); assert!(for_version(1400).is_some_and(|p| p.tagged && !p.f64_rect && !p.old_master_flags)); - assert!(for_version(1500).is_some_and(|p| p.tagged && p.f64_rect && p.mcfg_skip == 12 && !p.paths)); + assert!(for_version(1500).is_some_and(|p| p.tagged && p.f64_rect && p.mcfg_skip == 12 && p.paths)); assert!(for_version(2430).is_some_and(|p| p.f64_rect && p.paths && p.utf16_names)); - assert!(for_version(500).is_some_and(|p| p.short && p.mcfg_skip == 0)); - assert!(for_version(600).is_some_and(|p| !p.short && p.mcfg_skip == 28)); - assert!(for_version(801).is_some_and(|p| p.mcfg_skip == 0 && p.marker_after_dash.is_none())); - assert!(for_version(1000).is_some_and(|p| p.mcfg_skip == 4 && p.four_radii && !p.utf16_names)); + assert!(for_version(500).is_some_and(|p| p.short && p.mcfg_skip == 0 && p.marker_after_dash.is_none())); + assert!(for_version(600).is_some_and(|p| !p.short && p.mcfg_skip == 28 && p.marker_after_dash == Some(22))); + assert!(for_version(801).is_some_and(|p| p.mcfg_skip == 0 && p.marker_after_dash == Some(22))); + assert!(for_version(999).is_some_and(|p| !p.paths && p.marker_after_dash == Some(22))); + assert!(for_version(1000).is_some_and(|p| p.mcfg_skip == 4 && p.four_radii && !p.utf16_names && p.paths)); assert!(for_version(1300).is_some_and(|p| p.tagged && p.trfd_head == 8 && p.outl_after_angle == 46)); // The table is in order, so the search finds each range's own row. assert!(PROFILES.windows(2).all(|w| w[0].0 < w[1].0)); diff --git a/crates/cdr/src/records.rs b/crates/cdr/src/records.rs index 379b4f8340..dd3ac5e18a 100644 --- a/crates/cdr/src/records.rs +++ b/crates/cdr/src/records.rs @@ -414,6 +414,40 @@ fn windows_1252(c: u8) -> char { mod tests { use super::*; + /// An outline that names an arrowhead says so with a warning, in each version whose arrowhead + /// ids have a known place: 22 bytes after the first dash in versions 6 to 12, 20 from 13. + #[test] + fn arrowheads_are_named_from_version_6() { + let pen = crate::synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }; + let color = [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100]; + for (version, place) in [ + (500, None), + (600, Some(22)), + (700, Some(22)), + (800, Some(22)), + (900, Some(22)), + (1000, Some(22)), + (1100, Some(22)), + (1200, Some(22)), + (1300, Some(20)), + (1700, Some(20)), + ] { + let p = crate::layout::for_version(version).unwrap(); + let plain = crate::synth::V(version).outline(7, pen, &color, &[]); + // The record ends with 32 bytes after its dashes, and this one has none. + let first_dash = plain.len() - 32; + let mut w = vec![]; + assert!(outline(&plain, &p, &mut w).is_some_and(|(id, o)| id == 7 && o.is_some()), "{version}"); + assert!(w.is_empty(), "{version}: {w:?}"); + let Some(place) = place else { continue }; + let mut arrow = plain.clone(); + arrow[first_dash + place..first_dash + place + 4].copy_from_slice(&9u32.to_le_bytes()); + let mut w = vec![]; + assert!(outline(&arrow, &p, &mut w).is_some(), "{version}"); + assert_eq!(w, vec![Warning::Arrowheads], "{version}"); + } + } + #[test] fn single_byte_names_read_as_windows_1252() { let p = crate::layout::for_version(1100).unwrap(); diff --git a/crates/cdr/src/synth.rs b/crates/cdr/src/synth.rs index bc55b4245d..e78028b675 100644 --- a/crates/cdr/src/synth.rs +++ b/crates/cdr/src/synth.rs @@ -426,11 +426,25 @@ pub fn object(v: V, kind: u32, args: &[(u32, Vec)], matrix: Option<[f64; 6]> list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 0x08]), list(b"lgob", own)]) } -/// A layer list of `kind` flags named `name` holding `objects`, its `loda` in a `lgob` list (R22). +/// A layer list of `kind` flags named `name` holding `objects`, its `loda` in a `lgob` list (R22), +/// with the object type that layers of such flags have in sample files (R19). pub fn layer(v: V, flags: [u8; 4], name: &str, objects: Vec) -> Node { + let kind = match flags { + [b0, ..] if b0 & 0x10 != 0 => 11, + [b0, ..] if b0 & 0x0f == 0x0a || b0 & 0x0f == 0x02 => 12, + [0x08, ..] | [0, 1, 1, _] => 17, + _ => 0, + }; + // Version 3 counts its types from 0, one less (R32). + let kind = if v.0 < 400 && kind > 0 { kind - 1 } else { kind }; + layer_of_type(v, flags, kind, name, objects) +} + +/// A layer list as [`layer`] writes it, with the object type `kind` in its `loda`. +pub fn layer_of_type(v: V, flags: [u8; 4], kind: u32, name: &str, objects: Vec) -> Node { let name: Vec = if v.0 >= 1200 { name.encode_utf16().chain([0]).flat_map(|u| u.to_le_bytes()).collect() } else { name.bytes().chain([0]).collect() }; - let mut kids = vec![chunk(b"flgs", flags.to_vec()), list(b"lgob", vec![chunk(b"loda", v.loda(0, &[(1000, name)]))])]; + let mut kids = vec![chunk(b"flgs", flags.to_vec()), list(b"lgob", vec![chunk(b"loda", v.loda(kind, &[(1000, name)]))])]; kids.extend(objects); list(b"layr", kids) } @@ -730,19 +744,20 @@ pub enum WlShape { Text, } -/// A drawn object's record of a version 1 or 2 file (R42, R43, R44): `shape` placed by `matrix` +/// A drawn object's record of a version 1 file (R42, R43, R44): `shape` placed by `matrix` /// `[a, b, c, d, e, f]` with offsets in points, a uniform fill of `fill` and an outline of a width /// in points and a color. The record's point holds the matrix's x offset and its `ty` the y -/// offset. +/// offset. [`wl_file`] moves the fill and the shape to their places in a version 2 file. pub fn wl_object(shape: WlShape, matrix: [f64; 6], fill: Option<[u8; 5]>, outline: Option<(f64, [u8; 5])>) -> Vec { let v = V(300); let (kind, body): (u8, Vec) = match shape { - WlShape::Rect { w, h, radius } => (0, [v.coord(w), v.coord(h), vec![0; 2], v.coord(radius)].concat()), + WlShape::Rect { w, h, radius } => (0, [v.coord(w), v.coord(h), v.coord(radius), vec![0; 2]].concat()), WlShape::Ellipse { w, h, angles } => (1, [v.coord(w), v.coord(h), angles.0.to_le_bytes().to_vec(), angles.1.to_le_bytes().to_vec()].concat()), WlShape::Curve(points) => (2, v.points(&points)), WlShape::Text => (3, vec![0; 30]), }; let mut r = vec![0u8; (114 + body.len()).max(118)]; + r[..4].copy_from_slice(&WL_RECORD_START); r[26] = 0x40; r[27] = 0x20; let size = (r.len() - 32) as u16; @@ -768,27 +783,54 @@ pub fn wl_object(shape: WlShape, matrix: [f64; 6], fill: Option<[u8; 5]>, outlin r } +/// The u32 that starts every record of a version 1 or 2 file (R42). +const WL_RECORD_START: [u8; 4] = 24u32.to_le_bytes(); + /// A group or layer record of a version 1 or 2 file (R42): 28 bytes. pub fn wl_group() -> Vec { let mut r = vec![0u8; 28]; - r[27] = 1; + r[..4].copy_from_slice(&WL_RECORD_START); + r[26] = 1; + r[27] = 0x60; r } -/// A file of version 1 or 2 (R40, R41): the header with `marker` (`e` or `d`, or `m` for version -/// 2), a page of `page` points, the `records` and an empty font table. +/// A drawn object's record of a version 1 file laid out as in a version 2 file (R43): 11 more bytes +/// before the fill and 11 more before the shape. Group records stay as they are. +fn wl_v2_record(rec: &[u8]) -> Vec { + if rec.get(26).is_none_or(|flags| flags & 0x40 == 0) || rec.len() < 114 { + return rec.to_vec(); + } + let mut out = [&rec[..94], &[0; 11], &rec[94..114], &[0; 11], &rec[114..]].concat(); + let size = (out.len() - 32) as u16; + out[28..30].copy_from_slice(&size.to_le_bytes()); + out +} + +/// A file of version 1 or 2 (R40, R41): the header with `marker` (`e` for version 1, `l` or `m` +/// for version 2), a page of `page` points, the `records` and an empty font table. A version 1 +/// file's settings start after the header; a version 2 file's start further on, where a picture +/// lies in the files of that version, and its drawn objects are laid out as [`wl_v2_record`] says. pub fn wl_file(marker: u8, page: (f64, f64), records: &[Vec]) -> Vec { let v = V(300); + let settings = if marker == b'e' { 28u32 } else { 40 }; let start = 64u32; let mut out = vec![0u8; start as usize]; out[..4].copy_from_slice(&[b'W', b'L', marker, 0]); let (w, h) = page; - out[30..38].copy_from_slice(&[v.coord(-w / 2.0), v.coord(h / 2.0), v.coord(w / 2.0), v.coord(-h / 2.0)].concat()); - out.extend(records.iter().flatten()); + let page_box = settings as usize + 2; + out[page_box..page_box + 8].copy_from_slice(&[v.coord(-w / 2.0), v.coord(h / 2.0), v.coord(w / 2.0), v.coord(-h / 2.0)].concat()); + for r in records { + if marker == b'e' { + out.extend(r); + } else { + out.extend(wl_v2_record(r)); + } + } let end = out.len() as u32; out.extend([0; 2]); let trailer = out.len() as u32; - for (k, offset) in [28, start, end, trailer, trailer - 2].into_iter().enumerate() { + for (k, offset) in [settings, start, end, trailer, trailer - 2].into_iter().enumerate() { out[4 + 4 * k..8 + 4 * k].copy_from_slice(&offset.to_le_bytes()); } out diff --git a/crates/cdr/src/wl.rs b/crates/cdr/src/wl.rs index c407421c98..0a20c00893 100644 --- a/crates/cdr/src/wl.rs +++ b/crates/cdr/src/wl.rs @@ -1,8 +1,8 @@ //! Drawings of versions 1 and 2: the file before RIFF, which starts with `WL` (R40 to R44). A -//! header of offsets, the page's box, then one flat list of records: 28 bytes for a group or a -//! layer, and a longer record for each drawn object, which holds its matrix, fill, outline and -//! shape. The reader maps the rectangles, ellipses and curves onto one page with one layer and -//! keeps no groups. +//! header of offsets, the settings with the page's box, then one flat list of records: 28 bytes +//! for a group or a layer, and a longer record for each drawn object, which holds its matrix, fill, +//! outline and shape. The reader maps the rectangles, ellipses and curves onto one page with one +//! layer and keeps no groups. use crate::bytes::{Rd, u32_at}; use crate::geometry; @@ -15,38 +15,56 @@ use crate::{Error, Warning}; /// The header: the signature, a marker byte, a zero and five u32 offsets (R40). const HEADER: usize = 28; -/// The marker bytes seen after `WL` (R40). `m` marks version 2. -const MARKERS: [u8; 3] = *b"dem"; -/// Where the page's box lies (R41). -const PAGE_BOX: usize = 30; +/// The marker bytes read after `WL` (R40): `e` for version 1, `l` and `m` for version 2. +const MARKERS: [u8; 3] = *b"elm"; +/// Where the page's box lies after the start of the settings (R41). +const PAGE_BOX: usize = 2; /// The bytes of a group or layer record (R42). const GROUP: usize = 28; -/// The low flag byte, at byte 26, of a drawn object (R42). +/// The u32 that starts every record (R42). +const RECORD_START: u32 = 24; +/// The flag bit, in byte 26, of a drawn object (R42). const DRAWN: u8 = 0x40; -/// The bytes after a drawn object's body size, and the least a drawn object takes with them (R42). +/// The bytes after a drawn object's body size (R42). const AFTER_BODY: usize = 32; -const LEAST: usize = 118; /// Where a drawn object's fields lie (R43, R44). const POINT: usize = 32; const KIND: usize = 60; const OUTLINED: usize = 67; const OUTLINE_WIDTH: usize = 68; const OUTLINE_COLOR: usize = 74; -const FILL_KIND: usize = 94; -const FILL_COLOR: usize = 95; -const SHAPE: usize = 114; + +/// Where a drawn object's fill and shape lie, which differs between the markers (R43, R44). +#[derive(Clone, Copy)] +struct Fields { + fill_kind: usize, + shape: usize, +} + +impl Fields { + fn of(marker: u8) -> Self { + if marker == b'e' { Fields { fill_kind: 94, shape: 114 } } else { Fields { fill_kind: 105, shape: 136 } } + } + + /// The least a drawn object takes: its fixed fields and the 4 bytes of a shape's size. + fn least(self) -> usize { + self.shape + 4 + } +} /// Object types (R43). const RECTANGLE: u8 = 0; const ELLIPSE: u8 = 1; const CURVE: u8 = 2; +const TEXT: u8 = 3; -/// Where the records start and end, when `b` has a `WL` header whose offsets fit the file. -fn header(b: &[u8]) -> Option<(usize, usize)> { +/// Where the settings start, and where the records start and end, when `b` has a `WL` header +/// whose offsets fit the file. +fn header(b: &[u8]) -> Option<(usize, usize, usize)> { if b.get(..2)? != b"WL" || !MARKERS.contains(b.get(2)?) || *b.get(3)? != 0 { return None; } - let (start, end) = (u32_at(b, 8)? as usize, u32_at(b, 12)? as usize); - (start >= HEADER && start <= end && end <= b.len()).then_some((start, end)) + let (settings, start, end) = (u32_at(b, 4)? as usize, u32_at(b, 8)? as usize, u32_at(b, 12)? as usize); + (settings >= HEADER && settings <= start && start <= end && end <= b.len()).then_some((settings, start, end)) } /// Does `b` start like a drawing of version 1 or 2? The two letters alone are not enough: the @@ -56,7 +74,9 @@ pub(crate) fn is_wl(b: &[u8]) -> bool { } pub(crate) fn drawing(b: &[u8], budget: &mut Budget) -> Result { - let (start, end) = header(b).ok_or(Error::NotCdr)?; + let (settings, start, end) = header(b).ok_or(Error::NotCdr)?; + let marker = b.get(2).copied().ok_or(Error::NotCdr)?; + let fields = Fields::of(marker); // Lengths are i16 in 1/1000 inch, as in version 3 (R5). let p = layout::for_version(layout::OLDEST_RIFF).ok_or(Error::NotCdr)?; let mut warn = Vec::new(); @@ -65,12 +85,23 @@ pub(crate) fn drawing(b: &[u8], budget: &mut Budget) -> Result { // Every step takes at least a group record's bytes, so the file's size bounds the steps. while end - at >= GROUP { budget.take_chunk()?; - if b.get(at + 26) != Some(&DRAWN) { + // A record that doesn't start as records do is past one whose length isn't known. + if u32_at(b, at) != Some(RECORD_START) { + break; + } + if b.get(at + 26).is_none_or(|flags| flags & DRAWN == 0) { at += GROUP; continue; } + // A drawn object of another type than rectangle, ellipse, curve and text doesn't say its + // length in the same way, so the records after it can't be found. + if b.get(at + KIND).is_none_or(|kind| *kind > TEXT) { + push(&mut warn, Warning::UnsupportedObjects); + at = end; + break; + } let len = Rd::at(b, at + 28).u16().map_or(0, |body| usize::from(body) + AFTER_BODY); - let Some(rec) = b.get(at..at + len).filter(|_| len >= LEAST && at + len <= end) else { + let Some(rec) = b.get(at..at + len).filter(|_| len >= fields.least() && at + len <= end) else { push(&mut warn, Warning::Damaged); at = end; break; @@ -81,20 +112,20 @@ pub(crate) fn drawing(b: &[u8], budget: &mut Budget) -> Result { at = end; break; } - objects.extend(object(rec, &p, budget, &mut warn)); + objects.extend(object(rec, fields, &p, budget, &mut warn)); } if at != end { push(&mut warn, Warning::Damaged); } - let version = if b.get(2) == Some(&b'm') { 200 } else { 100 }; + let version = if marker == b'e' { 100 } else { 200 }; let layer = Layer { name: String::new(), kind: LayerKind::Drawing, objects, guides: Vec::new() }; let pages = vec![Page { size: None, layers: vec![layer] }]; - Ok(Drawing { version, page_size: page_box(b, &p), pages, master: Vec::new(), guides: Vec::new(), warnings: warn }) + Ok(Drawing { version, page_size: page_box(b, settings, &p), pages, master: Vec::new(), guides: Vec::new(), warnings: warn }) } /// The page's size from its box (R41): left, top, right and bottom around the page's centre. -fn page_box(b: &[u8], p: &Profile) -> Option<(f64, f64)> { - let mut r = Rd::at(b, PAGE_BOX); +fn page_box(b: &[u8], settings: usize, p: &Profile) -> Option<(f64, f64)> { + let mut r = Rd::at(b, settings + PAGE_BOX); let (left, top, right, bottom) = (coord(&mut r, p)?, coord(&mut r, p)?, coord(&mut r, p)?, coord(&mut r, p)?); let (w, h) = ((right - left).abs(), (top - bottom).abs()); (w > 0.0 && h > 0.0).then_some((w, h)) @@ -102,8 +133,8 @@ fn page_box(b: &[u8], p: &Profile) -> Option<(f64, f64)> { /// One drawn object's record (R43, R44): a shape, or `None` with a warning for text, for an object /// of another type and for a shape that can't be read. -fn object(rec: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { - let read = shape(rec, p, budget, warn); +fn object(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let read = shape(rec, fields, p, budget, warn); if read.is_none() { push(warn, Warning::Damaged); } @@ -112,14 +143,14 @@ fn object(rec: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) /// The shape of a record. The outer `None` is a record that can't be read; the inner one an object /// the reader leaves out, with its warning. -fn shape(rec: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option> { +fn shape(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option> { let k = p.unit(); let mut r = Rd::at(rec, POINT); let (x, y) = (f64::from(r.i16()?), f64::from(r.i16()?)); // x' = a x + b y + tx + x of the point, y' = c x + d y + ty + y of the point. let (a, b, tx, c, d, ty) = (fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?); let matrix = Matrix([a, c, b, d, (tx + x) * k, (ty + y) * k]); - let body = rec.get(SHAPE..)?; + let body = rec.get(fields.shape..)?; let geometry = match *rec.get(KIND)? { RECTANGLE => rect(body, p)?, ELLIPSE => { @@ -140,9 +171,9 @@ fn shape(rec: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) } }; let color_at = |at: usize, warn: &mut Vec| Some(records::color5(rec.get(at..at + 5)?.try_into().ok()?, warn)); - let fill = match *rec.get(FILL_KIND)? { + let fill = match *rec.get(fields.fill_kind)? { 0 => None, - 1 => Some(color_at(FILL_COLOR, warn)?), + 1 => Some(color_at(fields.fill_kind + 1, warn)?), _ => { push(warn, Warning::UnsupportedFills); None @@ -157,12 +188,12 @@ fn shape(rec: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) Some(Some(Shape { geometry, matrix, fill, outline })) } -/// A rectangle (R44): its width and height, then after 2 bytes a corner radius, which is kept when -/// it is at most half the shorter side. +/// A rectangle (R44): its width and height, then a corner radius, which is kept when it is at most +/// half the shorter side. fn rect(body: &[u8], p: &Profile) -> Option { let mut r = Rd::new(body); let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?); - let radius = r.skip(2).and_then(|()| coord(&mut r, p)).filter(|v| *v > 0.0 && *v <= w.abs().min(h.abs()) / 2.0).unwrap_or(0.0); + let radius = coord(&mut r, p).filter(|v| *v > 0.0 && *v <= w.abs().min(h.abs()) / 2.0).unwrap_or(0.0); Some(Geometry::Rect { w, h, radii: [radius; 4] }) } @@ -193,18 +224,76 @@ mod tests { assert!(!is_wl(&with(8, 27))); assert!(!is_wl(&with(8, file.len() as u32))); assert!(!is_wl(&with(12, file.len() as u32 + 1))); + // Settings that start inside the header or after the records. + assert!(!is_wl(&with(4, 27))); + assert!(!is_wl(&with(4, 65))); let mut other = file.clone(); other[2] = b'x'; assert!(!is_wl(&other)); + // No sample shows the marker `d`, so it is not taken. + other[2] = b'd'; + assert!(!is_wl(&other)); + for marker in *b"lm" { + assert!(is_wl(&synth::wl_file(marker, (612.0, 792.0), &[synth::wl_group()]))); + } other[2] = b'e'; other[3] = 1; assert!(!is_wl(&other)); } + #[test] + fn a_version_2_file_keeps_its_page_box_fill_and_shape_where_that_version_puts_them() { + let (red, black) = ([1, 0, 100, 100, 0], [1, 0, 0, 0, 100]); + let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 9.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some(red), Some((2.0, black))); + for marker in *b"elm" { + let file = synth::wl_file(marker, (720.0, 504.0), std::slice::from_ref(&rect)); + // Version 2 files start their settings after a picture, not after the header. + assert_eq!(u32_at(&file, 4) == Some(28), marker == b'e'); + let d = read(&file).unwrap(); + let near = |a: f64, b: f64| (a - b).abs() < 0.02; + assert_eq!((d.version, d.warnings.clone()), (if marker == b'e' { 100 } else { 200 }, vec![])); + assert!(d.page_size.is_some_and(|(w, h)| near(w, 720.0) && near(h, 504.0)), "{:?}", d.page_size); + let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") }; + assert!( + matches!(s.geometry, Geometry::Rect { w, h, radii } if near(w, 72.0) && near(h, 36.0) && near(radii[0], 9.0)), + "{}", + marker as char + ); + assert_eq!(s.fill, Some(Color::Cmyk([0.0, 1.0, 1.0, 0.0])), "{}", marker as char); + assert!(s.outline.as_ref().is_some_and(|o| near(o.width, 2.0) && o.color == Color::Cmyk([0.0, 0.0, 0.0, 1.0])), "{}", marker as char); + } + } + + #[test] + fn a_drawn_object_is_marked_by_its_flag_bit() { + let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], None, None); + let mut file = synth::wl_file(b'l', (612.0, 792.0), &[rect]); + // Files with the marker `l` set another flag bit beside it. + file[64 + 26] = 0xc0; + let d = read(&file).unwrap(); + assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![])); + } + + #[test] + fn the_walk_stops_where_records_can_no_longer_be_found() { + let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + let rect = || synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, unit, None, None); + // An object of another type doesn't give its length in the same way. + let mut other = rect(); + other[KIND] = 0xff; + let d = read(&synth::wl_file(b'm', (612.0, 792.0), &[rect(), other, rect()])).unwrap(); + assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![Warning::UnsupportedObjects])); + // A record that doesn't start as records do. + let mut lost = rect(); + lost[0] = 0x84; + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect(), lost, rect()])).unwrap(); + assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![Warning::Damaged])); + } + #[test] fn a_rectangle_keeps_a_radius_of_at_most_half_its_shorter_side() { let p = layout::for_version(300).unwrap(); - let body = |radius: i16| [1000i16, 500, 0, radius].iter().flat_map(|v| v.to_le_bytes()).collect::>(); + let body = |radius: i16| [1000i16, 500, radius].iter().flat_map(|v| v.to_le_bytes()).collect::>(); let radius_of = |b: &[u8]| match rect(b, &p) { Some(Geometry::Rect { w, h, radii }) if (w - 72.0).abs() < 1e-9 && (h - 36.0).abs() < 1e-9 => radii[0], other => panic!("{other:?}"), @@ -223,7 +312,7 @@ mod tests { let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([1, 0, 0, 0, 100]), None); let mut short = rect.clone(); // A body size that leaves less than the fixed fields. - short[28..30].copy_from_slice(&((LEAST - AFTER_BODY - 1) as u16).to_le_bytes()); + short[28..30].copy_from_slice(&((Fields::of(b'e').least() - AFTER_BODY - 1) as u16).to_le_bytes()); let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect.clone(), short, rect])).unwrap(); assert_eq!(d.pages[0].layers[0].objects.len(), 1); assert_eq!(d.warnings, vec![Warning::Damaged]); @@ -237,7 +326,7 @@ mod tests { let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") }; assert_eq!(s.fill, Some(Color::Spot { name: "Spot 0:9".into(), tint: 0.5, look: None })); assert_eq!((d.version, d.warnings), (200, vec![Warning::SpotLooks])); - textured[FILL_KIND] = 5; + textured[Fields::of(b'e').fill_kind] = 5; let d = read(&synth::wl_file(b'm', (612.0, 792.0), &[textured])).unwrap(); let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") }; assert_eq!((s.fill.clone(), d.warnings), (None, vec![Warning::UnsupportedFills])); diff --git a/crates/cdr/tests/read.rs b/crates/cdr/tests/read.rs index 88c015bd89..49d447c170 100644 --- a/crates/cdr/tests/read.rs +++ b/crates/cdr/tests/read.rs @@ -336,7 +336,7 @@ fn wl_objects(d: &vectorcraft_cdr::Drawing) -> &[Object] { #[test] fn versions_1_and_2_read_their_sample() { - for (marker, version) in [(b'e', 100), (b'd', 100), (b'm', 200)] { + for (marker, version) in [(b'e', 100), (b'l', 200), (b'm', 200)] { let file = synth::wl_sample(marker); assert!(file.starts_with(b"WL") && vectorcraft_cdr::is_cdr(&file)); let d = read(&file, Limits::default()).unwrap(); @@ -855,7 +855,7 @@ fn rectangles_from_version_15_give_radii_as_shares_of_half_the_shorter_side() { } #[test] -fn paths_of_version_16_read_their_points() { +fn paths_from_version_10_read_their_points() { let v = V(1700); let mut c = vec![0; 4]; c.extend(2u16.to_le_bytes()); @@ -869,13 +869,15 @@ fn paths_of_version_16_read_their_points() { &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 0x25, &[(30, c.clone())], None)])])], ) }; - let d = read(&objects(1700), Limits::default()).unwrap(); - let s = shapes(&d.pages[0].layers[0].objects); - let Geometry::Path(p) = &s[0].geometry else { panic!("{:?}", s[0].geometry) }; - assert_eq!(p.subpaths[0].segments.len(), 2); - assert!(d.warnings.is_empty(), "{:?}", d.warnings); - // Before 16 the type is not a path. - let d = read(&objects(1500), Limits::default()).unwrap(); + for version in [1000, 1300, 1500, 1700] { + let d = read(&objects(version), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Geometry::Path(p) = &s[0].geometry else { panic!("{version}: {:?}", s[0].geometry) }; + assert_eq!(p.subpaths[0].segments.len(), 2); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + } + // No sample before version 10 holds the type, so it is not read as a path there. + let d = read(&objects(900), Limits::default()).unwrap(); assert!(d.pages[0].layers[0].objects.is_empty() && d.warnings.contains(&Warning::UnsupportedObjects)); } @@ -900,21 +902,37 @@ fn a_template_takes_its_version_from_the_vrsn_chunk() { } #[test] -fn master_page_layers_take_their_kind_by_byte_0_from_version_14() { - // Flags that mark the master page's guides and desktop layers in versions 7 to 13 mark - // drawing layers from 14. - for version in [1300, 1700] { +fn layers_take_their_kind_from_their_object_type() { + for version in [300, 800, 1300, 1700] { let v = V(version); let rect = || synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0))], None); - let master = - synth::page(true, vec![synth::layer(v, [2, 1, 1, 0x98], "G", vec![rect()]), synth::layer(v, [0, 1, 1, 0x98], "D", vec![rect()])]); - let own = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect()])]); + // Version 3 counts its types from 0 (R32). + let ty = |t: u32| if version < 400 { t - 1 } else { t }; + // Master page layers flagged in the older way, with the types of guides and desktop layers, + // and a drawing layer whose flags would make it a desktop layer. + let master = synth::page( + true, + vec![ + synth::layer_of_type(v, [2, 1, 1, 0x98], ty(12), "G", vec![rect()]), + synth::layer_of_type(v, [0, 1, 1, 0x98], ty(17), "D", vec![rect()]), + synth::layer_of_type(v, [8, 1, 0, 0x98], 0, "M", vec![rect()]), + ], + ); + // A drawing layer with flag bit 0x10 set, and a grid layer. + let own = synth::page( + false, + vec![ + synth::layer_of_type(v, [0x10, 0, 0, 0x98], 0, "L", vec![rect()]), + synth::layer_of_type(v, [0x1a, 0, 1, 0x98], ty(11), "Grid", vec![rect()]), + ], + ); let body = [chunk(b"vrsn", version.to_le_bytes().to_vec()), master, own]; let file = if version < 1400 { synth::riff(version, &body) } else { synth::package16(version, &body, true, &[]) }; let d = read(&file, Limits::default()).unwrap(); let kinds: Vec<_> = d.master.iter().map(|l| l.kind).collect(); - let want = if version < 1400 { vec![LayerKind::Guides, LayerKind::Desktop] } else { vec![LayerKind::Drawing, LayerKind::Drawing] }; - assert_eq!(kinds, want, "{version}"); + assert_eq!(kinds, [LayerKind::Guides, LayerKind::Desktop, LayerKind::Drawing], "{version}"); + let kinds: Vec<_> = d.pages[0].layers.iter().map(|l| (l.kind, l.objects.len())).collect(); + assert_eq!(kinds, [(LayerKind::Drawing, 1), (LayerKind::Grid, 1)], "{version}"); } } @@ -1416,7 +1434,7 @@ proptest! { } #[test] - fn never_panics_on_garbage_after_a_wl_header(marker in prop::sample::select(vec![b'd', b'e', b'm']), bytes in prop::collection::vec(any::(), 0..2048)) { + fn never_panics_on_garbage_after_a_wl_header(marker in prop::sample::select(vec![b'e', b'l', b'm']), bytes in prop::collection::vec(any::(), 0..2048)) { // Offsets that fit the file, so the garbage is walked as records. let mut b = vec![b'W', b'L', marker, 0]; b.extend(28u32.to_le_bytes()); @@ -1429,7 +1447,7 @@ proptest! { } #[test] - fn never_panics_on_mutated_wl_files(marker in prop::sample::select(vec![b'd', b'e', b'm']), cut in any::(), edits in prop::collection::vec((any::(), any::()), 1..24)) { + fn never_panics_on_mutated_wl_files(marker in prop::sample::select(vec![b'e', b'l', b'm']), cut in any::(), edits in prop::collection::vec((any::(), any::()), 1..24)) { let mut b = synth::wl_sample(marker); let n = b.len(); for (at, v) in edits { diff --git a/crates/engine/src/cmd/fileio/tests_cdr.rs b/crates/engine/src/cmd/fileio/tests_cdr.rs index 6cd91c3204..9b3d3cdb77 100644 --- a/crates/engine/src/cmd/fileio/tests_cdr.rs +++ b/crates/engine/src/cmd/fileio/tests_cdr.rs @@ -118,7 +118,7 @@ fn versions_3_and_4_open_and_place_as_editable_art() { fn versions_1_and_2_open_and_place_as_editable_art() { use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::appearance::AppearanceItem; - for marker in *b"em" { + for marker in *b"elm" { let bytes = synth::wl_sample(marker); let mut s = Session::new(); for name in ["drawing.cdr", "renamed.bin"] { diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index fdc2be6692..d538db4b1d 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -344,7 +344,7 @@ proptest! { // Drawings of versions 1 and 2 are not RIFF files: a header of offsets, then records. #[test] fn cdr_mutated_wl_drawings_render_and_export( - marker in prop::sample::select(vec![b'd', b'e', b'm']), + marker in prop::sample::select(vec![b'e', b'l', b'm']), cut in prop::option::of(0usize..1024), edits in prop::collection::vec((0usize..8192, any::()), 0..24), ) { @@ -366,7 +366,7 @@ proptest! { #[test] fn cdr_garbage_after_a_wl_header_opens_and_places_without_panicking( - marker in prop::sample::select(vec![b'd', b'e', b'm']), + marker in prop::sample::select(vec![b'e', b'l', b'm']), tail in prop::collection::vec(any::(), 0..2048), ) { // Offsets that fit the file, so the garbage is walked as records. diff --git a/docs/mcp.md b/docs/mcp.md index beac1db458..beac6b4b61 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6852,10 +6852,11 @@ fountain, pattern, texture and PostScript fills, and outline arrowheads are left were left out. Drawings of versions after 27 are refused with a message, and so are packages that are encrypted, ZIP64 archives or split across files. VectorCraft doesn't write `.cdr` files. -No public specification covers versions 1 to 4, so the importer reads what published notes describe. A drawing of -version 1 or 2 opens as one page with one layer: its rectangles, whole ellipses and curves with their matrices, uniform -fills and outlines with their width and color. Its text, its arcs and pies, and its fills of other types are left out -with the same warnings, and its groups are not kept. A drawing of version 3 opens with its pages, layers and groups; +No public specification covers versions 1 to 4, so the importer reads the layouts found in public sample files. A +drawing of version 1 or 2 opens as one page with one layer: its rectangles, whole ellipses and curves with their +matrices, uniform fills and outlines with their width and color. Its text, its arcs and pies, and its fills of other +types are left out with the same warnings, and its groups are not kept. An object of another type ends the read of +its records, with the warning for unsupported objects. A drawing of version 3 opens with its pages, layers and groups; an envelope is not applied, so an object or a group under one keeps its outline, placed by its matrices, and the `warnings` say so. A drawing of version 4 opens as one of version 5 does. A file is taken for version 1 or 2 by its content only when the offsets in diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2b32650bae..ae116dd6db 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1542,7 +1542,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents; the [supported file formats](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/supported-file-formats-in-illustrator.html) page lists `.cdr` versions 5 to 10. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width, caps, joins and dashes. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). + - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width, caps, joins and dashes. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. EPS and PostScript `.ai` files are still embedded (`crates/engine/src/tests/placed_document.rs`). From 2cd5ad52d1a08e5f889a45566a033374e2e16445 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 12:01:08 -0800 Subject: [PATCH 05/34] .cdr import: objects without their own fill or outline take their style's From version 7 a drawing keeps its styles in LIST stlt, and an object names its style in argument 200. An object without a fill (20) or outline (10) argument of its own now takes the fill and outline its style gives, through the style's parents where the style leaves one to them. Before, such objects came in without a fill or outline. The table is read only when it parses to the end of its list; a table that does not is damage when an object needs a style from it. Its entries and styles count toward the chunk limit. PROVENANCE.md row R45 gives the layout and the sample files it was checked against. --- crates/cdr/PROVENANCE.md | 1 + crates/cdr/README.md | 1 + crates/cdr/src/build.rs | 55 ++++++++- crates/cdr/src/lib.rs | 1 + crates/cdr/src/limits.rs | 9 +- crates/cdr/src/riff.rs | 2 +- crates/cdr/src/styles.rs | 241 ++++++++++++++++++++++++++++++++++++++ crates/cdr/src/synth.rs | 101 ++++++++++++++++ crates/cdr/tests/read.rs | 70 +++++++++++ docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 11 files changed, 475 insertions(+), 11 deletions(-) create mode 100644 crates/cdr/src/styles.rs diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index c9a96f1206..6d050ce00d 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -90,3 +90,4 @@ file is committed. | R42 | The records of a file of version 1 or 2 run from the front of the stacking order to the back. Every record starts with the u32 24. A group or layer record is 28 bytes, and bit 0x40 of its flags byte at 26 is clear. A drawn object has that bit set (0x40 in files with the markers `e` and `m`, 0xc0 with `l`) and a u16 body size at byte 28; it is the body size plus 32 bytes long. A drawn object of another type than those of R43 gives its length otherwise, and the records after it are not read | S: TP `WI.CDR`, `FLAG.CDR`, `MENU.CDR` and `DRINKS.CDR`; the order checked against the picture of `MENU.CDR` | sample | | R43 | A drawn object of version 1 or 2: a point (two i16) at byte 32; six i32 in 16.16 fixed point at 36, `a b tx c d ty`, with x' = a x + b y + tx + the point's x and y' = c x + d y + ty + the point's y; the object type at 60 (0 rectangle, 1 ellipse, 2 curve, 3 text); a byte at 67 that is not 0 when the object is outlined, the outline's width (u16) at 68 and its color at 74; the fill type (0 none, 1 uniform) and its color after it, at 94 and 95 with the marker `e` and at 105 and 106 with `l` and `m`; the shape from byte 114 with `e` and 136 with `l` and `m`. Colors are as R36 | S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`) and `MENU.CDR` (`l`), checked against the pictures of `FLAG.CDR` and `MENU.CDR` | sample | | R44 | Shapes of version 1 or 2: a rectangle's width and height (i16), then a corner radius; an ellipse's width and height, then two angles; a curve's point list as R39 and R16 | S: rectangles in TP `FLAG.CDR`, ellipses and curves in TP `WI.CDR`, curves in TP `MENU.CDR` | sample (the radius of files with the marker `e`, which no sample shows, and how the angles make an arc: unconfirmed; a radius is kept only when it is at most half the shorter side, and an ellipse whose angles differ is left out with a warning) | +| R45 | `LIST stlt` from version 7: a u32 style count, and when it is not 0: the fill table (a u32 count, entries of a table id, 4 bytes and a `fild` id, 12 bytes each, 60 from version 13), the outline table (12-byte entries laid out the same way, naming `outl` ids), the text tables (fonts of 44 bytes, 60 from version 10; alignments of 12; spacings of 52; tables of 152 and 784; bullets whose length a u32 inside them sets; indents of 28; hyphenation of 32, 36 from 13; drop caps of 28; from 8.01 a table of 12), then the styles: kind (u32), id, parent id, 8 bytes, name length and name (bytes before 12, UTF-16 units from it), the fill and outline table ids, then 16 bytes (20 from 8.01) for kinds above 1 and 20 more for kinds above 2. An object names its style in argument 200 (u32). An object without argument 20 or 10 takes the fill or outline of its style; a style whose table id is 0 takes its parent's | K L593-L600, L852, L1926-L2198; S: UC `corel_rounded_rect_cdr7.cdr`, whose rectangles carry argument 200 and neither 10 nor 20, and name the style whose outline is a black hairline and whose fill is none, as the file's picture shows; the table parses exactly to the end of the list in each of the 498 sample files of versions 7 to 15 that has one, and every object with argument 200 in them names a style whose table ids are in the tables | public-spec (what the table ids name, and that an object takes its style's fill and outline: sample; a style taking its parent's entry: unconfirmed, as only text styles in the samples leave theirs to the parent, and a wrong guess draws a shape without that fill or outline) | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index d5cf86ef54..d1a7c8fc21 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -21,6 +21,7 @@ with each object's transform. It does not write `.cdr` files. | Polygons and stars (a base side copied for each side) | paths | | Uniform fills: CMYK, CMY, RGB, gray, registration, library colors | colors, spot colors with their tints | | Outlines: width, caps, joins, dashes, the no-outline flag | outlines | +| Styles (`LIST stlt`, versions 7 to 15) that objects name | the fill and outline of an object that has none of its own | Text, bitmaps, linked groups (blends, contours, brush strokes), B-spline curves, fountain, pattern, texture and PostScript fills and outline arrowheads are not read; the drawing's diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs index b78474136b..0eb6bf29df 100644 --- a/crates/cdr/src/build.rs +++ b/crates/cdr/src/build.rs @@ -11,6 +11,7 @@ use crate::limits::Budget; use crate::model::{Color, Drawing, Geometry, Guideline, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape}; use crate::records::{self, Loda}; use crate::riff::{Chunk, Index, push}; +use crate::styles::Styles; use crate::{Error, Warning}; /// Object types (R6). @@ -25,6 +26,7 @@ const ARG_OUTLINE: u32 = 10; const ARG_FILL: u32 = 20; const ARG_COORDS: u32 = 30; const ARG_TRANSFORMS: u32 = 100; +const ARG_STYLE: u32 = 200; const ARG_NAME: u32 = 1000; const ARG_POLYGON: u32 = 11000; const ARG_GUIDE: u32 = 16000; @@ -44,6 +46,9 @@ struct Ctx<'a, 'b> { outline_chunks: HashMap, fills: HashMap>, outlines: HashMap>, + /// The styles objects name in argument 200 (R45): `Err` when the file's style table doesn't + /// parse. + styles: Result, } pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec) -> Result { @@ -62,8 +67,22 @@ pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec) let mut found = Found::default(); collect(ix, root, &mut found); let page_size = found.mcfg.and_then(|c| page_size(ix.data(c), &p)); - let mut cx = - Ctx { ix, p, budget, warn, fill_chunks: HashMap::new(), outline_chunks: HashMap::new(), fills: HashMap::new(), outlines: HashMap::new() }; + // Before version 7 a `LIST stlt` holds chunks, not the style table (R4). + let styles = match found.stlt { + Some(c) if version >= 700 => Styles::read(ix.data(c), version, budget)?.ok_or(()), + _ => Ok(Styles::default()), + }; + let mut cx = Ctx { + ix, + p, + budget, + warn, + fill_chunks: HashMap::new(), + outline_chunks: HashMap::new(), + fills: HashMap::new(), + outlines: HashMap::new(), + styles, + }; for c in &found.fills { if let Some(id) = Rd::new(ix.data(c)).u32() { cx.fill_chunks.entry(id).or_insert(ix.data(c)); @@ -118,11 +137,12 @@ struct Found<'i> { outlines: Vec<&'i Chunk>, mcfg: Option<&'i Chunk>, guid: Option<&'i Chunk>, + stlt: Option<&'i Chunk>, pages: Vec<&'i Chunk>, } -/// Every fill, outline and page in file order, and the first `mcfg` and `guid`; pages are not -/// looked into. +/// Every fill, outline and page in file order, and the first `mcfg`, `guid` and `LIST stlt`; +/// pages are not looked into. fn collect<'i>(ix: &'i Index, root: &'i Chunk, found: &mut Found<'i>) { let mut stack: Vec<&Chunk> = ix.children(root).iter().rev().collect(); while let Some(c) = stack.pop() { @@ -131,6 +151,7 @@ fn collect<'i>(ix: &'i Index, root: &'i Chunk, found: &mut Found<'i>) { b"outl" => found.outlines.push(c), b"mcfg" => found.mcfg = found.mcfg.or(Some(c)), b"guid" => found.guid = found.guid.or(Some(c)), + _ if c.is_list(b"stlt") => found.stlt = found.stlt.or(Some(c)), _ if c.is_list(b"page") => found.pages.push(c), _ => stack.extend(ix.children(c).iter().rev()), } @@ -414,11 +435,33 @@ impl<'a, 'b> Ctx<'a, 'b> { Matrix::IDENTITY }), }; - let fill = loda.arg(ARG_FILL).and_then(id_of).and_then(|id| self.fill(id)); - let outline = loda.arg(ARG_OUTLINE).and_then(id_of).and_then(|id| self.outline(id)); + // Without a fill or outline argument of its own, an object takes its style's (R45). + let style = loda.arg(ARG_STYLE).and_then(id_of); + let fill_id = match loda.arg(ARG_FILL) { + Some(b) => id_of(b), + None => style.and_then(|s| self.style_entry(s, Styles::fill)), + }; + let outline_id = match loda.arg(ARG_OUTLINE) { + Some(b) => id_of(b), + None => style.and_then(|s| self.style_entry(s, Styles::outline)), + }; + let fill = fill_id.and_then(|id| self.fill(id)); + let outline = outline_id.and_then(|id| self.outline(id)); Some(Object::Shape(Box::new(Shape { geometry, matrix, fill, outline }))) } + /// The fill or outline record that style `id` names; a style table that doesn't parse is + /// damage, and the object is drawn without it. + fn style_entry(&mut self, id: u32, entry: fn(&Styles, u32) -> Option) -> Option { + match &self.styles { + Ok(s) => entry(s, id), + Err(()) => { + push(self.warn, Warning::Damaged); + None + } + } + } + /// A version 3 object, whose transforms, fill and outline are arguments of its own record /// (R33, R34, R35). A fill or an outline that is there but can't be read is damage. fn inline_object(&mut self, loda: &Loda, outer: &Matrix) -> Option { diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs index 847288b878..6d642cc2b7 100644 --- a/crates/cdr/src/lib.rs +++ b/crates/cdr/src/lib.rs @@ -21,6 +21,7 @@ pub mod model; mod package; mod records; mod riff; +mod styles; #[cfg(any(test, feature = "synth"))] pub mod synth; mod wl; diff --git a/crates/cdr/src/limits.rs b/crates/cdr/src/limits.rs index 34db782b4c..b3aadc23df 100644 --- a/crates/cdr/src/limits.rs +++ b/crates/cdr/src/limits.rs @@ -15,7 +15,7 @@ pub struct Limits { pub members: usize, /// Nested lists below the file's own. Deeper content is left out with a warning. pub depth: usize, - /// Chunks in the index, nested ones included. + /// Chunks in the index, nested ones included, and the entries and styles of the style table. pub chunks: usize, /// Objects mapped (shapes, groups and guidelines). pub objects: usize, @@ -92,7 +92,12 @@ impl Budget { } pub(crate) fn take_chunk(&mut self) -> Result<(), Error> { - self.chunks += 1; + self.take_chunks(1) + } + + /// `n` more chunks or style table entries. + pub(crate) fn take_chunks(&mut self, n: usize) -> Result<(), Error> { + self.chunks = self.chunks.saturating_add(n); if self.chunks > self.limits.chunks { Err(Error::Limit("chunk count")) } else { Ok(()) } } diff --git a/crates/cdr/src/riff.rs b/crates/cdr/src/riff.rs index 0298125e18..fcec80692b 100644 --- a/crates/cdr/src/riff.rs +++ b/crates/cdr/src/riff.rs @@ -228,7 +228,7 @@ impl<'a> Index<'a> { continue; } }; - // A `LIST stlt` holds the style tables, not chunks (R4); the reader doesn't use them. + // A `LIST stlt` holds the style tables, not chunks (R4); its body is read whole (R45). if chunk.id == LIST && chunk.form != *b"stlt" { lists.push(self.chunks.len()); } diff --git a/crates/cdr/src/styles.rs b/crates/cdr/src/styles.rs new file mode 100644 index 0000000000..b3a83b6c92 --- /dev/null +++ b/crates/cdr/src/styles.rs @@ -0,0 +1,241 @@ +//! The style table in a `LIST stlt` of versions 7 to 15 (R45): the fill and outline records that a +//! style gives the objects that name it and have no fill or outline argument of their own. + +use std::collections::{HashMap, HashSet}; + +use crate::Error; +use crate::bytes::{Rd, u32_at}; +use crate::limits::Budget; + +/// One style: its parent, and the fill and outline table entries it names (0: none). +#[derive(Clone, Copy)] +struct Style { + parent: u32, + fill: u32, + outline: u32, +} + +/// The styles of a drawing: for each style id, the fill and outline records it gives, its +/// parents' included. +#[derive(Default)] +pub(crate) struct Styles { + fills: HashMap, + outlines: HashMap, +} + +impl Styles { + /// The style table in body `b` of a `LIST stlt` of `version` (R45), or `None` when it doesn't + /// parse to its end. Its fill and outline entries and its styles count toward the chunks a + /// read takes. + pub(crate) fn read(b: &[u8], version: u16, budget: &mut Budget) -> Result, Error> { + let mut limit = None; + let styles = parse(b, version, &mut |n| match budget.take_chunks(n) { + Ok(()) => true, + Err(e) => { + limit = Some(e); + false + } + }); + match limit { + Some(e) => Err(e), + None => Ok(styles), + } + } + + /// The fill record that style `id` gives. + pub(crate) fn fill(&self, id: u32) -> Option { + self.fills.get(&id).copied() + } + + /// The outline record that style `id` gives. + pub(crate) fn outline(&self, id: u32) -> Option { + self.outlines.get(&id).copied() + } +} + +/// The style table in `b`. `take` is asked for each count of entries or styles before they are +/// read; a `false` stops the read. +fn parse(b: &[u8], version: u16, take: &mut dyn FnMut(usize) -> bool) -> Option { + let mut r = Rd::new(b); + let count = r.u32()? as usize; + if count == 0 { + return (r.left() == 0).then(Styles::default); + } + // Fill entries carry 48 more bytes from version 13. + let fills = table(&mut r, if version >= 1300 { 60 } else { 12 }, take)?; + let outlines = table(&mut r, 12, take)?; + // The text style tables: fonts, alignments, spacings, two tables of fixed records, bullets, + // indents, hyphenation and drop caps, and from version 8.01 one more. + skip_table(&mut r, if version >= 1000 { 60 } else { 44 })?; + skip_table(&mut r, 12)?; + skip_table(&mut r, 52)?; + skip_table(&mut r, 152)?; + skip_table(&mut r, 784)?; + let bullets = r.u32()?; + for _ in 0..bullets { + bullet(&mut r, version)?; + } + skip_table(&mut r, 28)?; + skip_table(&mut r, if version >= 1300 { 36 } else { 32 })?; + skip_table(&mut r, 28)?; + if version >= 801 { + skip_table(&mut r, 12)?; + } + // Each style is at least 32 bytes. + if count > r.left() / 32 || !take(count) { + return None; + } + let mut styles = HashMap::new(); + for _ in 0..count { + let (id, s) = style(&mut r, version)?; + styles.entry(id).or_insert(s); + } + if r.left() != 0 { + return None; + } + Some(Styles { fills: resolve(&styles, &fills, |s| s.fill), outlines: resolve(&styles, &outlines, |s| s.outline) }) +} + +/// For each style, the record of `table` that its own entry names, or the nearest parent's where +/// its entry is 0. Each style is resolved once, so a chain of any length takes time in proportion +/// to the styles; a chain that comes back to a style on it, or reaches a style that isn't there, +/// gives no record. +fn resolve(styles: &HashMap, table: &HashMap, entry: impl Fn(&Style) -> u32) -> HashMap { + // `None`: resolved to no record. + let mut done: HashMap> = HashMap::new(); + let mut path = Vec::new(); + let mut on_path = HashSet::new(); + for &start in styles.keys() { + let mut id = start; + let found = loop { + if let Some(&known) = done.get(&id) { + break known; + } + let Some(s) = styles.get(&id) else { break None }; + // Back at a style on this path: a cycle. + if !on_path.insert(id) { + break None; + } + path.push(id); + match entry(s) { + 0 => id = s.parent, + e => break table.get(&e).copied(), + } + }; + on_path.clear(); + for id in path.drain(..) { + done.insert(id, found); + } + } + done.into_iter().filter_map(|(id, r)| Some((id, r?))).collect() +} + +/// A table of a u32 count and entries of `size` bytes, each a table id, 4 bytes and a record id. +fn table(r: &mut Rd, size: usize, take: &mut dyn FnMut(usize) -> bool) -> Option> { + let n = r.u32()? as usize; + if n > r.left() / size || !take(n) { + return None; + } + let mut out = HashMap::new(); + for _ in 0..n { + let e = r.bytes(size)?; + out.entry(u32_at(e, 0)?).or_insert(u32_at(e, 8)?); + } + Some(out) +} + +/// A table of a u32 count and entries of `size` bytes, passed over. +fn skip_table(r: &mut Rd, size: usize) -> Option<()> { + let n = r.u32()? as usize; + r.skip(n.checked_mul(size)?) +} + +/// A bullet record, passed over: its length depends on a u32 inside it. +fn bullet(r: &mut Rd, version: u16) -> Option<()> { + r.skip(40)?; + if version >= 1300 { + if version >= 1400 { + r.skip(4)?; + } + let more = r.u32()?; + return r.skip(if more != 0 { 68 } else { 12 }); + } + r.skip(if version >= 1000 { 28 } else { 20 })?; + let more = r.u32()?; + if more != 0 { + r.skip(8)?; + } + r.skip(8) +} + +/// A style record: its kind (u32), id, parent, 8 bytes, a name length and the name (bytes before +/// version 12, UTF-16 units from it), the fill and outline entries, then the entries of text +/// styles (kinds 2 and 3). +fn style(r: &mut Rd, version: u16) -> Option<(u32, Style)> { + let kind = r.u32()?; + let (id, parent) = (r.u32()?, r.u32()?); + r.skip(8)?; + let len = r.u32()? as usize; + r.skip(len.checked_mul(if version >= 1200 { 2 } else { 1 })?)?; + let (fill, outline) = (r.u32()?, r.u32()?); + if kind > 1 { + r.skip(if version >= 801 { 20 } else { 16 })?; + } + if kind > 2 { + r.skip(20)?; + } + Some((id, Style { parent, fill, outline })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Limits; + use crate::synth::{self, V}; + + fn read(b: &[u8], version: u16) -> Option { + Styles::read(b, version, &mut Budget::new(Limits::default())).unwrap() + } + + #[test] + fn styles_that_name_each_other_as_parents_end() { + let looped = [synth::Style { id: 0x10, parent: 0x11, fill: 0, outline: 0 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + let s = read(&synth::stlt_body(V(700), &[(0x100, 1)], &[], &looped, false), 700).unwrap(); + assert_eq!((s.fill(0x10), s.outline(0x11), s.fill(0x12)), (None, None, None)); + } + + #[test] + fn a_long_chain_of_parents_reaches_the_style_that_names_an_entry() { + let mut chain = vec![synth::Style { id: 1, parent: 0, fill: 0x100, outline: 0 }]; + chain.extend((2..=500).map(|id| synth::Style { id, parent: id - 1, fill: 0, outline: 0 })); + let s = read(&synth::stlt_body(V(1100), &[(0x100, 7)], &[], &chain, false), 1100).unwrap(); + assert_eq!((s.fill(500), s.fill(250), s.outline(500)), (Some(7), Some(7), None)); + } + + #[test] + fn an_entry_missing_from_its_table_names_no_record() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x101, outline: 0x200 }]; + let s = read(&synth::stlt_body(V(1300), &[(0x100, 1)], &[(0x200, 2)], &styles, false), 1300).unwrap(); + assert_eq!((s.fill(0x10), s.outline(0x10)), (None, Some(2))); + } + + #[test] + fn counts_past_the_body_do_not_parse() { + let mut b = synth::stlt_body(V(900), &[], &[], &[], false); + b[..4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(read(&b, 900).is_none()); + let empty = 0u32.to_le_bytes(); + assert!(read(&empty, 900).is_some()); + assert!(read(&[], 900).is_none()); + } + + #[test] + fn entries_and_styles_count_toward_the_chunk_limit() { + let styles: Vec<_> = (1..=10).map(|id| synth::Style { id, parent: 0, fill: 0x100, outline: 0 }).collect(); + let b = synth::stlt_body(V(1000), &[(0x100, 1)], &[], &styles, false); + let mut budget = Budget::new(Limits { chunks: 10, ..Limits::default() }); + assert_eq!(Styles::read(&b, 1000, &mut budget).err(), Some(Error::Limit("chunk count"))); + let mut budget = Budget::new(Limits { chunks: 11, ..Limits::default() }); + assert!(Styles::read(&b, 1000, &mut budget).is_ok_and(|s| s.is_some())); + } +} diff --git a/crates/cdr/src/synth.rs b/crates/cdr/src/synth.rs index e78028b675..71847dd984 100644 --- a/crates/cdr/src/synth.rs +++ b/crates/cdr/src/synth.rs @@ -479,6 +479,107 @@ pub fn mcfg(v: V, w: f64, h: f64) -> Node { chunk(b"mcfg", b) } +/// A style of a [`stlt_body`]: its id, its parent's id, and its fill and outline table entries. +#[derive(Clone, Copy, Debug)] +pub struct Style { + pub id: u32, + pub parent: u32, + pub fill: u32, + pub outline: u32, +} + +/// The body of a `LIST stlt` of `v` (R45): the style count, the fill table (`(entry, fild id)`) and +/// the outline table (`(entry, outl id)`), the text style tables (each with one record when +/// `text`), then `styles` as styles of kind 1, and when `text` a style of kind 2 and one of kind 3. +pub fn stlt_body(v: V, fills: &[(u32, u32)], outlines: &[(u32, u32)], styles: &[Style], text: bool) -> Vec { + let version = v.0; + let u32s = |vals: &[u32]| -> Vec { vals.iter().flat_map(|x| x.to_le_bytes()).collect() }; + let count = styles.len() + if text { 2 } else { 0 }; + let mut b = u32s(&[count as u32]); + // A table without styles holds nothing else. + if count == 0 { + return b; + } + for (table, size) in [(fills, if version >= 1300 { 60 } else { 12 }), (outlines, 12)] { + b.extend(u32s(&[table.len() as u32])); + for (entry, record) in table { + let mut e = u32s(&[*entry, 0, *record]); + e.resize(size, 0); + b.extend(e); + } + } + let n = u32::from(text); + let fixed = |size: usize| -> Vec { + let mut t = n.to_le_bytes().to_vec(); + t.extend(vec![0x5a; size * n as usize]); + t + }; + // Fonts, alignments, spacings and two tables of fixed records. + for size in [if version >= 1000 { 60 } else { 44 }, 12, 52, 152, 784] { + b.extend(fixed(size)); + } + // One bullet, whose u32 inside asks for the longer form. + b.extend(n.to_le_bytes()); + if text { + b.extend([0x5a; 40]); + if version >= 1300 { + if version >= 1400 { + b.extend([0x5a; 4]); + } + b.extend(u32s(&[1])); + b.extend([0x5a; 68]); + } else { + b.extend(vec![0x5a; if version >= 1000 { 28 } else { 20 }]); + b.extend(u32s(&[1])); + b.extend([0x5a; 16]); + } + } + // Indents, hyphenation, drop caps, and from version 8.01 one more table. + for size in [28, if version >= 1300 { 36 } else { 32 }, 28] { + b.extend(fixed(size)); + } + if version >= 801 { + b.extend(fixed(12)); + } + let text_styles = [(2, Style { id: 0x7f02, parent: 0, fill: 0, outline: 0 }), (3, Style { id: 0x7f03, parent: 0x7f02, fill: 0, outline: 0 })]; + let all = styles.iter().map(|s| (1u32, *s)).chain(text_styles.into_iter().filter(|_| text)); + for (kind, s) in all { + b.extend(u32s(&[kind, s.id, s.parent, 1, 1])); + if version >= 1200 { + b.extend(u32s(&[7])); + b.extend("Graphic".encode_utf16().flat_map(u16::to_le_bytes)); + } else { + b.extend(u32s(&[8])); + b.extend(b"Graphic\0"); + } + b.extend(u32s(&[s.fill, s.outline])); + if kind > 1 { + b.extend(vec![0; if version >= 801 { 20 } else { 16 }]); + } + if kind > 2 { + b.extend([0; 20]); + } + } + b +} + +/// A `LIST stlt` of [`stlt_body`]. +pub fn stlt(v: V, fills: &[(u32, u32)], outlines: &[(u32, u32)], styles: &[Style], text: bool) -> Node { + Node::Chunk(*b"LIST", [b"stlt".to_vec(), stlt_body(v, fills, outlines, styles, text)].concat()) +} + +/// A file of `version` holding `content` as the program of that version saves it: a RIFF file +/// before 14, then a package (R25, R26). +pub fn file_of(version: u16, content: Vec) -> Vec { + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + body.extend(content); + match version { + ..1400 => riff(version, &body), + 1400..1600 => package14(riff(version, &body), false), + _ => package16(version, &body, false, &[]), + } +} + /// The document list and pages of the [`sample`] of `version`. pub fn sample_content(version: u16) -> Vec { let v = V(version); diff --git a/crates/cdr/tests/read.rs b/crates/cdr/tests/read.rs index 49d447c170..1df3b800be 100644 --- a/crates/cdr/tests/read.rs +++ b/crates/cdr/tests/read.rs @@ -1133,6 +1133,76 @@ fn a_style_table_list_is_not_read_as_chunks() { assert!(d.page_size.is_some_and(|(w, h)| (w - 100.0).abs() < 0.01 && (h - 50.0).abs() < 0.01)); } +/// The objects of a styled drawing: a rectangle with only its style (argument 200), one whose +/// style leaves the fill and outline to its parent, and one with an outline argument of its own. +fn graphic_style_drawing(version: u16, table: synth::Node) -> Vec { + let v = V(version); + let black = synth::color(2, [0, 0, 0, 100]); + let doc = list( + b"doc ", + vec![ + synth::mcfg(v, 612.0, 792.0), + list(b"filt", vec![chunk(if version >= 700 { b"fild" } else { b"fill" }, v.fill(1, &synth::color(5, [0, 0, 255, 0])))]), + list( + b"otlt", + vec![ + chunk(b"outl", v.outline(2, synth::Pen { line_type: 0, width: 2.0, cap: 1, join: 1 }, &black, &[])), + chunk(b"outl", v.outline(3, synth::Pen { line_type: 1, width: 1.0, cap: 0, join: 0 }, &black, &[])), + ], + ), + table, + ], + ); + let rect = (30, v.rect(20.0, 10.0, 0.0)); + let styled = |style: u32, own: &[(u32, Vec)]| { + let mut args = vec![(200, style.to_le_bytes().to_vec())]; + args.extend(own.iter().cloned()); + args.push(rect.clone()); + synth::object(v, 1, &args, None) + }; + let objects = vec![styled(0x10, &[]), styled(0x11, &[]), styled(0x10, &[(10, 3u32.to_le_bytes().to_vec())])]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)]); + synth::file_of(version, vec![doc, page]) +} + +/// From version 7 an object without a fill or outline argument of its own takes its style's +/// (argument 200, `LIST stlt`), through the style's parent where the style names none; its own +/// argument wins over the style's. +#[test] +fn objects_without_their_own_fill_or_outline_take_their_styles() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + for version in [700, 800, 801, 900, 1000, 1100, 1200, 1300, 1400, 1500] { + for text in [false, true] { + let table = synth::stlt(V(version), &[(0x100, 1)], &[(0x200, 2)], &styles, text); + let d = read(&graphic_style_drawing(version, table), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 3, "{version}"); + for shape in &s[..2] { + assert_eq!(shape.fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{version} {text}"); + assert!(shape.outline.as_ref().is_some_and(|o| (o.width - 2.0).abs() < 0.05), "{version} {text}: {:?}", shape.outline); + } + assert_eq!(s[2].fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{version} {text}"); + assert!(s[2].outline.is_none(), "{version} {text}"); + assert!(d.warnings.is_empty(), "{version} {text}: {:?}", d.warnings); + } + } +} + +/// A style table that doesn't parse to its end is damage when an object needs a style from it; +/// the object is drawn with what it holds itself. +#[test] +fn a_style_table_that_does_not_parse_is_damage_when_an_object_needs_it() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + let mut body = synth::stlt_body(V(1000), &[(0x100, 1)], &[(0x200, 2)], &styles, true); + body.push(0); + let table = chunk(b"LIST", [b"stlt".to_vec(), body].concat()); + let d = read(&graphic_style_drawing(1000, table), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 3); + assert!(s[0].fill.is_none() && s[0].outline.is_none()); + assert_eq!(d.warnings, vec![Warning::Damaged]); +} + #[test] fn linked_groups_are_left_out_with_a_warning() { let v = V(1100); diff --git a/docs/mcp.md b/docs/mcp.md index beac6b4b61..cc10b8e828 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6844,7 +6844,8 @@ place as editable art, the ZIP packages that versions 14 and later save included by side. Layers of the same name on different pages become one layer when the pages stack them in the same order, and the master page's guidelines become guides on every page. Groups stay groups. Curves, paths, arcs and polygons (stars included) become paths, and rectangles and ellipses become live shapes; a rectangle keeps each corner's radius. Uniform -fills and outlines keep their colors, widths, caps, joins and dashes. A library color that the drawing stores with its +fills and outlines keep their colors, widths, caps, joins and dashes, and an object without a fill or outline of its own +takes its style's. A library color that the drawing stores with its name and values (version 13 and later) becomes a spot swatch with its tint, and one stored only by its number opens as a black spot color. Text, bitmaps, blends, contours, brush strokes, other objects the reader doesn't read yet, fountain, pattern, texture and PostScript fills, and outline arrowheads are left out. The `warnings` of diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ae116dd6db..82b20aed3d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1542,7 +1542,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width, caps, joins and dashes. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). + - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width, caps, joins and dashes, an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. EPS and PostScript `.ai` files are still embedded (`crates/engine/src/tests/placed_document.rs`). From 977b5773c3ae30a1d46fcc339cd8b081f78d0638 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 12:04:20 -0800 Subject: [PATCH 06/34] .cdr import: bit 0x10 of a layer's flags no longer makes it a grid A layer without a loda of its own is taken by the low four bits of its flags' byte 0: 0x0a guides, or a grid when bit 0x10 is also set, and 0x08 the desktop only when byte 2 is set. Sample files flag drawing layers 0x10, 0x18 and 0x58 with byte 2 clear, which the reader took for grid layers and left out, and 0x08 with byte 2 clear, which it took for the desktop. --- crates/cdr/PROVENANCE.md | 2 +- crates/cdr/src/build.rs | 34 +++++++++++++++++++++++----------- crates/cdr/src/synth.rs | 5 +++-- 3 files changed, 27 insertions(+), 14 deletions(-) diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 6d050ce00d..570171c7d4 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -64,7 +64,7 @@ file is committed. | R16 | Point list: u32 count (before version 6 as R39 gives it), the points, then one type byte each, the count held to what fits; type bits 7 and 6 move, line, curve end, control point; bit 3 closes the subpath | K L782-L787, L840-L845, L2701-L2807 | public-spec | | R17 | Ellipse coordinates: width, height, start and end angles, pie flag (u16 before 6, else u32); the radii are half the width and height; the angles turn from the ellipse's own axes, which a negative width or height points the other way | K L754-L781; S: the pies of negative height in the ellipse-sector drawings of versions 12 and 13 in UC | public-spec (axis direction of a negative size: sample) | | R18 | Polygon argument (11000): 4 bytes before 13, the side count u32, the next point u32 (the u32 after it when it is 0 or 1, else 4 bytes), 4 more from 13, rx and ry f64, the centre; the base curve is one side on a circle of 1000 mm from the top vertex to the vertex it runs to clockwise, copied once for each side | K L631-L655; S: the polygons and stars of UC `shapes_cdr10.cdr` | public-spec (base curve: sample) | -| R19 | `flgs`: byte 3 the record type, byte 2 marks the master page. A layer's own `loda` names what it is by its object type: 11 a grid, 12 guides, 17 the desktop, any other a drawing layer (version 3 one less, R32). Only a layer without a `loda` is taken by its byte 0: 0 drawing, 8 desktop, 0x0a guides, a set bit 0x10 grid, and in versions 7 to 13 [2, 1, 1] guides and [0, 1, 1] desktop | K L1602-L1639 (record types); S: in every sample file of versions 3 to 25 the layer's object type agrees with its name; byte 0 does not: TDF 114901 (version 8) flags its master page's guides [2, 1, 1], desktop [0, 1, 1], grid [0x12, 0, 1] and drawing layer [8, 1, 0], and NR `ab_en_br.cdr` (version 9) flags drawing layers 0x10 and its guides 0x1a | public-spec (layer types: sample; byte 0 of a layer without a `loda`: unconfirmed, as no sample has such a layer, and a wrong guess drops or shows that layer's objects) | +| R19 | `flgs`: byte 3 the record type, byte 2 marks the master page. A layer's own `loda` names what it is by its object type: 11 a grid, 12 guides, 17 the desktop, any other a drawing layer (version 3 one less, R32). Only a layer without a `loda` is taken by the low four bits of its byte 0: 0x0a guides, or a grid when bit 0x10 is also set; in versions 7 to 13 0x02 the same way; 0x08 the desktop when byte 2 is set and a drawing layer when it is clear; any other a drawing layer, except [0, 1, 1] in versions 7 to 13, the desktop | K L1602-L1639 (record types); S: in every sample file of versions 3 to 25 the layer's object type agrees with its name; byte 0 does not: TDF 114901 (version 8) flags its master page's guides [2, 1, 1], desktop [0, 1, 1], grid [0x12, 0, 1] and drawing layer [8, 1, 0], and NR `ab_en_br.cdr` (version 9) flags drawing layers 0x10 and its guides 0x1a; over the sample files of versions 3 to 25, drawing layers carry 0, 0x10, 0x40, or 0x08, 0x18 or 0x58 with byte 2 clear, desktop layers 0x08, 0x18 or 0x48 with byte 2 set, guides 0x0a, 0x4a, 0x02 or (in `ab_en_br.cdr`) 0x1a, and grids 0x1a, 0x5a or 0x12 | public-spec (layer types: sample; byte 0 of a layer without a `loda`: unconfirmed, as no sample has such a layer, and a wrong guess drops or shows that layer's objects) | | R20 | Fill and outline arguments (20, 10): a u32 record id | K L452-L460, L548-L556 | public-spec | | R21 | Page size argument (19130): width and height | K L666-L672 | public-spec | | R22 | `LIST page` holds `LIST layr` lists, directly or in a list it holds (a `LIST gobj` in the samples); a layer holds `LIST obj ` and `LIST grp `; a page, layer or object keeps its own `loda` (and an object its `trfd`, in a `trfl` list) among its chunks or in a `LIST lgob` | K L1602-L1639 (record types); S: the chunk trees of every sample file of versions 3 to 25 | sample | diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs index 0eb6bf29df..df1ddba71d 100644 --- a/crates/cdr/src/build.rs +++ b/crates/cdr/src/build.rs @@ -225,19 +225,22 @@ fn layer_kind_of_type(kind: u32, types_from_zero: bool) -> LayerKind { } } -/// What a layer's flags make it, for a layer without an object type of its own (R19). Byte 0 holds -/// the kind; versions 7 to 13 may flag the master page's desktop layer 0 with bytes 1 and 2 set, -/// and its guides layer 2. +/// What a layer's flags make it, for a layer without an object type of its own (R19). The low +/// four bits of byte 0 hold the kind: 0x0a guides, or a grid with bit 0x10 set (versions 7 to 13 +/// also flag them 0x02); 0x08 the desktop when byte 2 is set, a drawing layer when it is clear. +/// Versions 7 to 13 may flag the master page's desktop layer 0 with bytes 1 and 2 set. Bit 0x10 +/// alone does not make a grid. fn layer_kind(f: [u8; 4], version_below_14: bool) -> LayerKind { let [b0, b1, b2, _] = f; - if b0 & 0x10 != 0 { - LayerKind::Grid - } else if b0 & 0x1f == 0x0a || (version_below_14 && b0 & 0x1f == 0x02) { - LayerKind::Guides - } else if b0 == 0x08 || (version_below_14 && b0 == 0 && b1 == 1 && b2 == 1) { - LayerKind::Desktop - } else { - LayerKind::Drawing + let grid_bit = b0 & 0x10 != 0; + match b0 & 0x0f { + 0x0a if grid_bit => LayerKind::Grid, + 0x0a => LayerKind::Guides, + 0x02 if version_below_14 && grid_bit => LayerKind::Grid, + 0x02 if version_below_14 => LayerKind::Guides, + 0x08 if b2 != 0 => LayerKind::Desktop, + 0 if version_below_14 && b1 == 1 && b2 == 1 => LayerKind::Desktop, + _ => LayerKind::Drawing, } } @@ -592,5 +595,14 @@ mod tests { assert_eq!(layer_kind([0x5a, 1, 1, 0x98], false), LayerKind::Grid); assert_eq!(layer_kind([0x02, 1, 1, 0x98], false), LayerKind::Drawing); assert_eq!(layer_kind([0, 1, 1, 0x98], false), LayerKind::Drawing); + // Drawing layers flagged 0x10, 0x08, 0x18, 0x40 and 0x58 with byte 2 clear, as sample + // files flag them, and desktop and guides layers with bit 0x40 or 0x10 set. + for f in [[0x10, 0, 0, 0x98], [0x08, 1, 0, 0x98], [0x18, 1, 0, 0x98], [0x40, 0, 0, 0x98], [0x58, 1, 0, 0x98]] { + assert_eq!(layer_kind(f, true), LayerKind::Drawing, "{f:?}"); + assert_eq!(layer_kind(f, false), LayerKind::Drawing, "{f:?}"); + } + assert_eq!(layer_kind([0x18, 0, 1, 0x98], true), LayerKind::Desktop); + assert_eq!(layer_kind([0x48, 0, 1, 0x98], false), LayerKind::Desktop); + assert_eq!(layer_kind([0x4a, 1, 1, 0x98], true), LayerKind::Guides); } } diff --git a/crates/cdr/src/synth.rs b/crates/cdr/src/synth.rs index 71847dd984..f3bf25a6c7 100644 --- a/crates/cdr/src/synth.rs +++ b/crates/cdr/src/synth.rs @@ -430,9 +430,10 @@ pub fn object(v: V, kind: u32, args: &[(u32, Vec)], matrix: Option<[f64; 6]> /// with the object type that layers of such flags have in sample files (R19). pub fn layer(v: V, flags: [u8; 4], name: &str, objects: Vec) -> Node { let kind = match flags { - [b0, ..] if b0 & 0x10 != 0 => 11, + [b0, ..] if (b0 & 0x0f == 0x0a || b0 & 0x0f == 0x02) && b0 & 0x10 != 0 => 11, [b0, ..] if b0 & 0x0f == 0x0a || b0 & 0x0f == 0x02 => 12, - [0x08, ..] | [0, 1, 1, _] => 17, + [b0, _, b2, _] if b0 & 0x0f == 0x08 && b2 != 0 => 17, + [0, 1, 1, _] => 17, _ => 0, }; // Version 3 counts its types from 0, one less (R32). From 4507c470e31c5b87c949b7bbcae530d709802b83 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 12:26:53 -0800 Subject: [PATCH 07/34] .cdr import: clipping containers clip the objects they hold A container carries argument 8005, whose id names the LIST grp of the document's LIST clpt with the same id in its spnd chunk. The reader now gives the container with that group's objects, which keep their own transforms, and the importer makes a clipping group of them: the container's shape is the clipping path and keeps its fill and outline. Before, only the container came in, with no warning. A container whose group is missing is damage. A group already being read, or more than 64 clipped groups one inside another, is left out with the limit warning; the container stays as a plain shape either way. PROVENANCE.md row R46 gives the layout and the sample files it was checked against. --- crates/cdr/PROVENANCE.md | 1 + crates/cdr/README.md | 1 + crates/cdr/src/build.rs | 50 ++++++++++++++++-- crates/cdr/src/model.rs | 6 +++ crates/cdr/src/synth.rs | 19 +++++++ crates/cdr/tests/read.rs | 61 ++++++++++++++++++++++ crates/engine/src/cmd/fileio/cdr.rs | 19 +++++-- crates/engine/src/cmd/fileio/cdr/shapes.rs | 21 ++++++-- crates/engine/src/cmd/fileio/tests_cdr.rs | 29 ++++++++++ docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 11 files changed, 199 insertions(+), 13 deletions(-) diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 570171c7d4..83815aa5d9 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -91,3 +91,4 @@ file is committed. | R43 | A drawn object of version 1 or 2: a point (two i16) at byte 32; six i32 in 16.16 fixed point at 36, `a b tx c d ty`, with x' = a x + b y + tx + the point's x and y' = c x + d y + ty + the point's y; the object type at 60 (0 rectangle, 1 ellipse, 2 curve, 3 text); a byte at 67 that is not 0 when the object is outlined, the outline's width (u16) at 68 and its color at 74; the fill type (0 none, 1 uniform) and its color after it, at 94 and 95 with the marker `e` and at 105 and 106 with `l` and `m`; the shape from byte 114 with `e` and 136 with `l` and `m`. Colors are as R36 | S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`) and `MENU.CDR` (`l`), checked against the pictures of `FLAG.CDR` and `MENU.CDR` | sample | | R44 | Shapes of version 1 or 2: a rectangle's width and height (i16), then a corner radius; an ellipse's width and height, then two angles; a curve's point list as R39 and R16 | S: rectangles in TP `FLAG.CDR`, ellipses and curves in TP `WI.CDR`, curves in TP `MENU.CDR` | sample (the radius of files with the marker `e`, which no sample shows, and how the angles make an arc: unconfirmed; a radius is kept only when it is at most half the shorter side, and an ellipse whose angles differ is left out with a warning) | | R45 | `LIST stlt` from version 7: a u32 style count, and when it is not 0: the fill table (a u32 count, entries of a table id, 4 bytes and a `fild` id, 12 bytes each, 60 from version 13), the outline table (12-byte entries laid out the same way, naming `outl` ids), the text tables (fonts of 44 bytes, 60 from version 10; alignments of 12; spacings of 52; tables of 152 and 784; bullets whose length a u32 inside them sets; indents of 28; hyphenation of 32, 36 from 13; drop caps of 28; from 8.01 a table of 12), then the styles: kind (u32), id, parent id, 8 bytes, name length and name (bytes before 12, UTF-16 units from it), the fill and outline table ids, then 16 bytes (20 from 8.01) for kinds above 1 and 20 more for kinds above 2. An object names its style in argument 200 (u32). An object without argument 20 or 10 takes the fill or outline of its style; a style whose table id is 0 takes its parent's | K L593-L600, L852, L1926-L2198; S: UC `corel_rounded_rect_cdr7.cdr`, whose rectangles carry argument 200 and neither 10 nor 20, and name the style whose outline is a black hairline and whose fill is none, as the file's picture shows; the table parses exactly to the end of the list in each of the 498 sample files of versions 7 to 15 that has one, and every object with argument 200 in them names a style whose table ids are in the tables | public-spec (what the table ids name, and that an object takes its style's fill and outline: sample; a style taking its parent's entry: unconfirmed, as only text styles in the samples leave theirs to the parent, and a wrong guess draws a shape without that fill or outline) | +| R46 | A container (a PowerClip) carries argument 8005; its first u32 is the id that the `spnd` chunk (a u32) of one `LIST grp ` in the document's `LIST clpt` holds. That group's objects are the ones the container clips; they keep their own transforms, in page space like the container's | K L252, L860-L862, L1895-L1901 (the argument and the chunk); S: UC `corel_powerclip_cdr7.cdr` to `corel_powerclip_x3.cdr` (versions 7 to 13) and LT `powerclipsquare_blackfill_whiterectangleinside` of `testset/12` to `testset/25`, in each of which the id in argument 8005 matches one group's `spnd`; in `corel_powerclip_cdr7.cdr` the group's box, -1.96 to 1.97 inches across, overlaps the container's, -1.81 to 1.84 inches, and the file's picture shows the group cut to the container | public-spec (what the id names, and the space of the group's objects: sample) | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index d1a7c8fc21..f59719912e 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -15,6 +15,7 @@ with each object's transform. It does not write `.cdr` files. | Layers (drawing, desktop, guides and grid layers), the master page's among them | layers by name and kind | | Guidelines (object type 0x16, and the version 7 `guid` chunk) | guidelines at their point and angle | | Groups (`LIST grp `) | groups | +| PowerClip containers and the groups of `LIST clpt` they clip | the container with the objects it clips | | Curves (point lists of moves, lines and cubic curves) and paths (object type 0x25, version 10 on) | paths | | Rectangles (one corner radius, four from version 9) | rectangles with each corner's radius | | Ellipses, arcs and pies | ellipses, and paths for arcs and pies | diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs index df1ddba71d..5462eb0920 100644 --- a/crates/cdr/src/build.rs +++ b/crates/cdr/src/build.rs @@ -28,6 +28,7 @@ const ARG_COORDS: u32 = 30; const ARG_TRANSFORMS: u32 = 100; const ARG_STYLE: u32 = 200; const ARG_NAME: u32 = 1000; +const ARG_CONTAINER: u32 = 8005; const ARG_POLYGON: u32 = 11000; const ARG_GUIDE: u32 = 16000; const ARG_PAGE_SIZE: u32 = 19130; @@ -49,8 +50,15 @@ struct Ctx<'a, 'b> { /// The styles objects name in argument 200 (R45): `Err` when the file's style table doesn't /// parse. styles: Result, + /// The groups of `LIST clpt` that containers clip, by the id in their `spnd` chunk (R46). + clips: HashMap, + /// The clipped groups being read, innermost last. + open_clips: Vec, } +/// The most clipped groups read one inside another: VectorCraft's own limit. +const MAX_CLIP_DEPTH: usize = 64; + pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec) -> Result { let root = ix.root().ok_or(Error::NotCdr)?; let version = version(ix, root); @@ -82,7 +90,14 @@ pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec) fills: HashMap::new(), outlines: HashMap::new(), styles, + clips: HashMap::new(), + open_clips: Vec::new(), }; + for g in found.clpt.iter().flat_map(|c| ix.children(c)).filter(|g| g.is_list(b"grp ")) { + if let Some(id) = ix.children(g).iter().find(|c| &c.id == b"spnd").and_then(|c| Rd::new(ix.data(c)).u32()) { + cx.clips.entry(id).or_insert(g); + } + } for c in &found.fills { if let Some(id) = Rd::new(ix.data(c)).u32() { cx.fill_chunks.entry(id).or_insert(ix.data(c)); @@ -138,11 +153,12 @@ struct Found<'i> { mcfg: Option<&'i Chunk>, guid: Option<&'i Chunk>, stlt: Option<&'i Chunk>, + clpt: Vec<&'i Chunk>, pages: Vec<&'i Chunk>, } -/// Every fill, outline and page in file order, and the first `mcfg`, `guid` and `LIST stlt`; -/// pages are not looked into. +/// Every fill, outline, `LIST clpt` and page in file order, and the first `mcfg`, `guid` and +/// `LIST stlt`; pages are not looked into. fn collect<'i>(ix: &'i Index, root: &'i Chunk, found: &mut Found<'i>) { let mut stack: Vec<&Chunk> = ix.children(root).iter().rev().collect(); while let Some(c) = stack.pop() { @@ -152,6 +168,7 @@ fn collect<'i>(ix: &'i Index, root: &'i Chunk, found: &mut Found<'i>) { b"mcfg" => found.mcfg = found.mcfg.or(Some(c)), b"guid" => found.guid = found.guid.or(Some(c)), _ if c.is_list(b"stlt") => found.stlt = found.stlt.or(Some(c)), + _ if c.is_list(b"clpt") => found.clpt.push(c), _ if c.is_list(b"page") => found.pages.push(c), _ => stack.extend(ix.children(c).iter().rev()), } @@ -450,7 +467,34 @@ impl<'a, 'b> Ctx<'a, 'b> { }; let fill = fill_id.and_then(|id| self.fill(id)); let outline = outline_id.and_then(|id| self.outline(id)); - Some(Object::Shape(Box::new(Shape { geometry, matrix, fill, outline }))) + let shape = Box::new(Shape { geometry, matrix, fill, outline }); + // A container clips the group its argument 8005 names (R46). + Some(match loda.arg(ARG_CONTAINER).and_then(id_of) { + Some(id) => self.clip(shape, id, guides), + None => Object::Shape(shape), + }) + } + + /// `container` and the objects of the clipped group `id`, which keep their own transforms. + /// A group that isn't there is damage; one already being read, or past the depth limit, is + /// left out with the limit warning. Either way the container stays, as a plain shape. + fn clip(&mut self, container: Box, id: u32, guides: &mut Vec) -> Object { + let Some(&group) = self.clips.get(&id) else { + push(self.warn, Warning::Damaged); + return Object::Shape(container); + }; + if self.open_clips.contains(&id) || self.open_clips.len() >= MAX_CLIP_DEPTH { + push(self.warn, Warning::TooDeep); + return Object::Shape(container); + } + self.open_clips.push(id); + let ix = self.ix; + let objects = self.objects(ix.children(group), guides); + self.open_clips.pop(); + if objects.is_empty() { + return Object::Shape(container); + } + Object::Clip { container, objects } } /// The fill or outline record that style `id` names; a style table that doesn't parse is diff --git a/crates/cdr/src/model.rs b/crates/cdr/src/model.rs index f3553ce329..c901d65d91 100644 --- a/crates/cdr/src/model.rs +++ b/crates/cdr/src/model.rs @@ -119,6 +119,12 @@ pub struct Shape { pub enum Object { Shape(Box), Group(Vec), + /// A container and the objects it clips (a PowerClip): `objects` (front to back) show only + /// inside the container's shape, with its fill behind them and its outline over them. + Clip { + container: Box, + objects: Vec, + }, } /// A guideline through `at`, at `angle` degrees counterclockwise from horizontal. diff --git a/crates/cdr/src/synth.rs b/crates/cdr/src/synth.rs index f3bf25a6c7..21d3b1db72 100644 --- a/crates/cdr/src/synth.rs +++ b/crates/cdr/src/synth.rs @@ -569,6 +569,25 @@ pub fn stlt(v: V, fills: &[(u32, u32)], outlines: &[(u32, u32)], styles: &[Style Node::Chunk(*b"LIST", [b"stlt".to_vec(), stlt_body(v, fills, outlines, styles, text)].concat()) } +/// A `LIST clpt` of clipped groups (R46): each a `LIST grp ` with its `spnd` id, then its objects. +pub fn clpt(groups: Vec<(u32, Vec)>) -> Node { + let groups = groups + .into_iter() + .map(|(id, objects)| { + let mut kids = vec![chunk(b"spnd", id.to_le_bytes().to_vec())]; + kids.extend(objects); + list(b"grp ", kids) + }) + .collect(); + list(b"clpt", groups) +} + +/// The container argument (8005) naming clipped group `id` (R46), laid out as sample files lay it +/// out. +pub fn container(id: u32) -> (u32, Vec) { + (8005, [id, 1, 0, 1].iter().flat_map(|v| v.to_le_bytes()).collect()) +} + /// A file of `version` holding `content` as the program of that version saves it: a RIFF file /// before 14, then a package (R25, R26). pub fn file_of(version: u16, content: Vec) -> Vec { diff --git a/crates/cdr/tests/read.rs b/crates/cdr/tests/read.rs index 1df3b800be..815688fba6 100644 --- a/crates/cdr/tests/read.rs +++ b/crates/cdr/tests/read.rs @@ -14,6 +14,10 @@ fn shapes(objects: &[Object]) -> Vec<&vectorcraft_cdr::model::Shape> { match o { Object::Shape(s) => out.push(&**s), Object::Group(kids) => stack.extend(kids.iter().rev()), + Object::Clip { container, objects } => { + out.push(&**container); + stack.extend(objects.iter().rev()); + } } } out @@ -1203,6 +1207,63 @@ fn a_style_table_that_does_not_parse_is_damage_when_an_object_needs_it() { assert_eq!(d.warnings, vec![Warning::Damaged]); } +/// A drawing with fill 1 (red), whose `LIST clpt` holds `groups` and whose page holds `objects`. +fn clip_drawing(version: u16, groups: Vec<(u32, Vec)>, objects: Vec) -> Vec { + let v = V(version); + let doc = list( + b"doc ", + vec![ + synth::mcfg(v, 612.0, 792.0), + list(b"filt", vec![chunk(if version >= 700 { b"fild" } else { b"fill" }, v.fill(1, &synth::color(5, [0, 0, 255, 0])))]), + synth::clpt(groups), + ], + ); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)]); + synth::file_of(version, vec![doc, page]) +} + +fn clip_rect(v: V, w: f64, extra: &[(u32, Vec)], at: [f64; 2]) -> synth::Node { + let mut args = vec![(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(w, w, 0.0))]; + args.extend(extra.iter().cloned()); + synth::object(v, 1, &args, Some([1.0, 0.0, 0.0, 1.0, at[0], at[1]])) +} + +/// A container (argument 8005) clips the group of `LIST clpt` whose `spnd` id it names; the +/// group's objects keep their own transforms, front to back. +#[test] +fn a_container_clips_the_group_it_names() { + for version in [700, 900, 1200, 1300, 1500, 1600, 2000] { + let v = V(version); + let contents = vec![clip_rect(v, 10.0, &[], [5.0, 6.0]), clip_rect(v, 20.0, &[], [-50.0, 0.0])]; + let container = clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0]); + let d = read(&clip_drawing(version, vec![(0x77, contents)], vec![container]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let objects = &d.pages[0].layers[0].objects; + let [Object::Clip { container, objects: clipped }] = objects.as_slice() else { panic!("{version}: {objects:?}") }; + assert!(matches!(container.geometry, Geometry::Rect { w, .. } if (w - 40.0).abs() < 0.01), "{version}"); + let s = shapes(clipped); + assert_eq!(s.len(), 2, "{version}"); + assert!((s[0].matrix.0[4] - 5.0).abs() < 0.01 && (s[1].matrix.0[4] + 50.0).abs() < 0.01, "{version}: {:?}", s[0].matrix); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + } +} + +/// A container whose group isn't there is damage, and one whose group holds a container naming +/// it again is read once, with the limit warning; the containers stay as plain shapes. +#[test] +fn a_missing_or_repeating_clipped_group_keeps_the_container() { + let v = V(1100); + let missing = clip_rect(v, 40.0, &[synth::container(0x78)], [0.0, 0.0]); + let d = read(&clip_drawing(1100, vec![(0x77, vec![clip_rect(v, 10.0, &[], [0.0, 0.0])])], vec![missing]), Limits::default()).unwrap(); + assert!(matches!(d.pages[0].layers[0].objects.as_slice(), [Object::Shape(_)])); + assert_eq!(d.warnings, vec![Warning::Damaged]); + let inner = clip_rect(v, 10.0, &[synth::container(0x77)], [0.0, 0.0]); + let outer = clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0]); + let d = read(&clip_drawing(1100, vec![(0x77, vec![inner])], vec![outer]), Limits::default()).unwrap(); + let [Object::Clip { objects: clipped, .. }] = d.pages[0].layers[0].objects.as_slice() else { panic!("{:?}", d.pages[0].layers[0].objects) }; + assert!(matches!(clipped.as_slice(), [Object::Shape(_)]), "{clipped:?}"); + assert_eq!(d.warnings, vec![Warning::TooDeep]); +} + #[test] fn linked_groups_are_left_out_with_a_warning() { let v = V(1100); diff --git a/crates/engine/src/cmd/fileio/cdr.rs b/crates/engine/src/cmd/fileio/cdr.rs index 394220f194..1658dc5dba 100644 --- a/crates/engine/src/cmd/fileio/cdr.rs +++ b/crates/engine/src/cmd/fileio/cdr.rs @@ -321,17 +321,26 @@ fn copy_cost(objects: &[cd::Object]) -> usize { n = n.saturating_add(1); match o { cd::Object::Group(kids) => stack.extend(kids), - cd::Object::Shape(s) => { - if let cd::Geometry::Path(p) = &s.geometry { - n = p.subpaths.iter().fold(n, |n, sp| n.saturating_add(1 + sp.segments.len())); - } - n = n.saturating_add(s.outline.as_ref().map_or(0, |o| o.dashes.len())); + cd::Object::Shape(s) => n = n.saturating_add(shape_cost(s)), + cd::Object::Clip { container, objects } => { + n = n.saturating_add(shape_cost(container)); + stack.extend(objects); } } } n } +/// What one copy of shape `s` takes past the object itself: its path's subpaths and segments and +/// its outline's dashes. +fn shape_cost(s: &cd::Shape) -> usize { + let mut n: usize = 0; + if let cd::Geometry::Path(p) = &s.geometry { + n = p.subpaths.iter().fold(n, |n, sp| n.saturating_add(1 + sp.segments.len())); + } + n.saturating_add(s.outline.as_ref().map_or(0, |o| o.dashes.len())) +} + /// A layer of the document named `name` holding `kids` (bottom to top). fn layer(doc: &mut Document, name: &str, i: usize, kids: Vec>) -> Arc { let name = if name.is_empty() { format!("Layer {}", i + 1) } else { name.to_string() }; diff --git a/crates/engine/src/cmd/fileio/cdr/shapes.rs b/crates/engine/src/cmd/fileio/cdr/shapes.rs index 7bd04c6a70..71d8d78ad5 100644 --- a/crates/engine/src/cmd/fileio/cdr/shapes.rs +++ b/crates/engine/src/cmd/fileio/cdr/shapes.rs @@ -67,6 +67,12 @@ impl Builder { } } cd::Object::Group(kids) => stack.extend(kids), + cd::Object::Clip { container, objects } => { + for c in container.fill.iter().chain(container.outline.iter().map(|o| &o.color)) { + self.learn_spot(c); + } + stack.extend(objects); + } } } } @@ -108,19 +114,28 @@ impl Builder { let mut out = Vec::with_capacity(objects.len()); for o in objects.iter().rev() { match o { - cd::Object::Shape(s) => out.extend(self.shape(s, to_doc)), + cd::Object::Shape(s) => out.extend(self.shape(s, to_doc, false)), cd::Object::Group(kids) => { let children = self.objects_at(kids, to_doc, depth + 1); if !children.is_empty() { out.push(Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: false }))); } } + // A clipping group whose clipping path keeps the container's paint: its fill + // behind the clipped objects and its outline over them. + cd::Object::Clip { container, objects } => { + let Some(clip) = self.shape(container, to_doc, true) else { continue }; + let mut children = vec![clip]; + children.extend(self.objects_at(objects, to_doc, depth + 1)); + out.push(Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: true }))); + } } } out } - fn shape(&mut self, s: &cd::Shape, to_doc: Affine) -> Option> { + /// Shape `s` placed by `to_doc`; as a clipping path when `clipping`. + fn shape(&mut self, s: &cd::Shape, to_doc: Affine, clipping: bool) -> Option> { let m = to_doc * affine(&s.matrix); let (path, live) = match &s.geometry { Geometry::Path(p) => (PathData::from_bezpath(&(m * bez(p))), None), @@ -145,7 +160,7 @@ impl Builder { // A curve of several subpaths is filled with holes where they overlap: VectorCraft's own // choice of rule for it. let rule = FillRule::EvenOdd; - let mut n = Node::new(self.doc.alloc_id(), NodeKind::Path { path, rule, live: live.map(Box::new), clipping: false, guide: false }); + let mut n = Node::new(self.doc.alloc_id(), NodeKind::Path { path, rule, live: live.map(Box::new), clipping, guide: false }); n.appearance = Appearance { items, ..Appearance::default() }.into(); Some(Arc::new(n)) } diff --git a/crates/engine/src/cmd/fileio/tests_cdr.rs b/crates/engine/src/cmd/fileio/tests_cdr.rs index 9b3d3cdb77..3056933dbf 100644 --- a/crates/engine/src/cmd/fileio/tests_cdr.rs +++ b/crates/engine/src/cmd/fileio/tests_cdr.rs @@ -410,6 +410,35 @@ fn fills_and_outlines_keep_their_colors_widths_caps_joins_and_dashes() { assert!(dash.pattern.len() == 2 && (dash.pattern[0] - 6.0).abs() < 0.01 && (dash.pattern[1] - 2.0).abs() < 0.01, "{:?}", dash.pattern); } +/// A container and the group it clips open as a clipping group: the container's shape first, as +/// the clipping path keeping its fill, then the clipped shapes. +#[test] +fn containers_open_as_clipping_groups() { + let v = V(1100); + let rect = |w: f64, extra: Vec<(u32, Vec)>| { + let mut args = vec![(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(w, w, 0.0))]; + args.extend(extra); + synth::object(v, 1, &args, None) + }; + let doc = list( + b"doc ", + vec![ + list(b"filt", vec![chunk(b"fild", v.fill(1, &synth::color(5, [0, 0, 255, 0])))]), + synth::clpt(vec![(5, vec![rect(10.0, vec![]), rect(20.0, vec![])])]), + ], + ); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(40.0, vec![synth::container(5)])])]); + let (doc, warnings) = super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + let layer = doc.layers.last().and_then(|l| l.children()).unwrap(); + let [group] = layer.as_slice() else { panic!("{layer:?}") }; + let NodeKind::Group { children, clip: true } = &group.kind else { panic!("{:?}", group.kind) }; + assert_eq!(children.len(), 3); + assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. })); + assert_eq!(children[0].appearance.items.len(), 1, "the container keeps its fill"); + assert!(children[1..].iter().all(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. }))); +} + #[test] fn other_versions_and_damaged_drawings_say_why() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index cc10b8e828..f5d6fd92ad 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6842,7 +6842,8 @@ its pixels are decoded. `file.place {path}` links the file like any image. Vecto `.cdr` drawings of versions 1 to 27 (and `.cdt` templates, which open as a new untitled document) open and place as editable art, the ZIP packages that versions 14 and later save included. Each page becomes an artboard, side by side. Layers of the same name on different pages become one layer when the pages stack them in the same order, and -the master page's guidelines become guides on every page. Groups stay groups. Curves, paths, arcs and polygons (stars +the master page's guidelines become guides on every page. Groups stay groups, and a PowerClip becomes a clipping +group whose clipping path keeps the container's fill and outline. Curves, paths, arcs and polygons (stars included) become paths, and rectangles and ellipses become live shapes; a rectangle keeps each corner's radius. Uniform fills and outlines keep their colors, widths, caps, joins and dashes, and an object without a fill or outline of its own takes its style's. A library color that the drawing stores with its diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 82b20aed3d..2bd3c612d1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1542,7 +1542,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width, caps, joins and dashes, an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). + - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, PowerClips (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width, caps, joins and dashes, an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. EPS and PostScript `.ai` files are still embedded (`crates/engine/src/tests/placed_document.rs`). From 907ca62d62eb60fa64a0d0a29158e90a5ba772c8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 12:42:08 -0800 Subject: [PATCH 08/34] .cdr import: name lenses and object transparency in the warnings An object with a lens or a transparency carries argument 8000. The reader does not apply it, and the object comes in opaque; the warnings now say so instead of nothing. PROVENANCE.md row R47 lists the sample files that carry the argument. --- crates/cdr/PROVENANCE.md | 1 + crates/cdr/README.md | 3 ++- crates/cdr/src/build.rs | 5 +++++ crates/cdr/src/model.rs | 2 ++ crates/cdr/tests/read.rs | 16 ++++++++++++++++ crates/engine/src/cmd/fileio/cdr.rs | 2 ++ crates/engine/src/cmd/fileio/tests_cdr.rs | 11 +++++++++++ docs/mcp.md | 3 ++- docs/target-app-parity.md | 2 +- 9 files changed, 42 insertions(+), 3 deletions(-) diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 83815aa5d9..08c606077f 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -92,3 +92,4 @@ file is committed. | R44 | Shapes of version 1 or 2: a rectangle's width and height (i16), then a corner radius; an ellipse's width and height, then two angles; a curve's point list as R39 and R16 | S: rectangles in TP `FLAG.CDR`, ellipses and curves in TP `WI.CDR`, curves in TP `MENU.CDR` | sample (the radius of files with the marker `e`, which no sample shows, and how the angles make an arc: unconfirmed; a radius is kept only when it is at most half the shorter side, and an ellipse whose angles differ is left out with a warning) | | R45 | `LIST stlt` from version 7: a u32 style count, and when it is not 0: the fill table (a u32 count, entries of a table id, 4 bytes and a `fild` id, 12 bytes each, 60 from version 13), the outline table (12-byte entries laid out the same way, naming `outl` ids), the text tables (fonts of 44 bytes, 60 from version 10; alignments of 12; spacings of 52; tables of 152 and 784; bullets whose length a u32 inside them sets; indents of 28; hyphenation of 32, 36 from 13; drop caps of 28; from 8.01 a table of 12), then the styles: kind (u32), id, parent id, 8 bytes, name length and name (bytes before 12, UTF-16 units from it), the fill and outline table ids, then 16 bytes (20 from 8.01) for kinds above 1 and 20 more for kinds above 2. An object names its style in argument 200 (u32). An object without argument 20 or 10 takes the fill or outline of its style; a style whose table id is 0 takes its parent's | K L593-L600, L852, L1926-L2198; S: UC `corel_rounded_rect_cdr7.cdr`, whose rectangles carry argument 200 and neither 10 nor 20, and name the style whose outline is a black hairline and whose fill is none, as the file's picture shows; the table parses exactly to the end of the list in each of the 498 sample files of versions 7 to 15 that has one, and every object with argument 200 in them names a style whose table ids are in the tables | public-spec (what the table ids name, and that an object takes its style's fill and outline: sample; a style taking its parent's entry: unconfirmed, as only text styles in the samples leave theirs to the parent, and a wrong guess draws a shape without that fill or outline) | | R46 | A container (a PowerClip) carries argument 8005; its first u32 is the id that the `spnd` chunk (a u32) of one `LIST grp ` in the document's `LIST clpt` holds. That group's objects are the ones the container clips; they keep their own transforms, in page space like the container's | K L252, L860-L862, L1895-L1901 (the argument and the chunk); S: UC `corel_powerclip_cdr7.cdr` to `corel_powerclip_x3.cdr` (versions 7 to 13) and LT `powerclipsquare_blackfill_whiterectangleinside` of `testset/12` to `testset/25`, in each of which the id in argument 8005 matches one group's `spnd`; in `corel_powerclip_cdr7.cdr` the group's box, -1.96 to 1.97 inches across, overlaps the container's, -1.81 to 1.84 inches, and the file's picture shows the group cut to the container | public-spec (what the id names, and the space of the group's objects: sample) | +| R47 | Argument 8000 marks an object seen through: a lens or a transparency. The reader does not apply it, and names lenses in the warnings | K L859 (the argument); S: of the sample files of versions 7 to 25, the argument is on the see-through objects that the pictures of UC `corel_lens_test_cdr7.cdr` to `corel_lens_test_x3.cdr`, LT `square_blackfill_nooutline_transparency50percent` of `testset/12` to `testset/25` and TDF 80103 show, and otherwise only on text in UC `fancytext_cdr7.cdr` to `fancytext_x3.cdr` and on two objects of TDF 114901. The value K reads at byte 10 (14 from version 13) is not the transparency in these samples | public-spec (the argument: K; what it marks: sample; its layout: unconfirmed, and it is not read) | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index f59719912e..6946f5b11e 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -25,7 +25,8 @@ with each object's transform. It does not write `.cdr` files. | Styles (`LIST stlt`, versions 7 to 15) that objects name | the fill and outline of an object that has none of its own | Text, bitmaps, linked groups (blends, contours, brush strokes), B-spline curves, fountain, -pattern, texture and PostScript fills and outline arrowheads are not read; the drawing's +pattern, texture and PostScript fills, outline arrowheads, lenses and object transparency are not +read; the drawing's `warnings` name each kind it held. Drawings of versions after 27 are refused, and so are packages that are encrypted, ZIP64 archives or split across files. diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs index 5462eb0920..fe54429fea 100644 --- a/crates/cdr/src/build.rs +++ b/crates/cdr/src/build.rs @@ -28,6 +28,7 @@ const ARG_COORDS: u32 = 30; const ARG_TRANSFORMS: u32 = 100; const ARG_STYLE: u32 = 200; const ARG_NAME: u32 = 1000; +const ARG_LENS: u32 = 8000; const ARG_CONTAINER: u32 = 8005; const ARG_POLYGON: u32 = 11000; const ARG_GUIDE: u32 = 16000; @@ -447,6 +448,10 @@ impl<'a, 'b> Ctx<'a, 'b> { return self.inline_object(&loda, outer); } let geometry = self.geometry(&loda)?; + // A lens or transparency (R47) is not applied: the shape shows opaque. + if loda.arg(ARG_LENS).is_some() { + push(self.warn, Warning::Lenses); + } // A transform that is there but can't be read is damage; the shape stays where it is. let matrix = match own_chunk(ix, list, &[b"trfd"]) { None => Matrix::IDENTITY, diff --git a/crates/cdr/src/model.rs b/crates/cdr/src/model.rs index c901d65d91..8cc15d6271 100644 --- a/crates/cdr/src/model.rs +++ b/crates/cdr/src/model.rs @@ -175,6 +175,8 @@ pub enum Warning { Arrowheads, /// Envelopes, which are not applied: the shapes under them keep their outlines. Envelopes, + /// Lenses and object transparency, which are not applied: the objects show opaque. + Lenses, /// Content nested deeper, or past the counts, that a read takes. TooDeep, /// Chunks or records that end early or don't parse. diff --git a/crates/cdr/tests/read.rs b/crates/cdr/tests/read.rs index 815688fba6..3e39384dad 100644 --- a/crates/cdr/tests/read.rs +++ b/crates/cdr/tests/read.rs @@ -1264,6 +1264,22 @@ fn a_missing_or_repeating_clipped_group_keeps_the_container() { assert_eq!(d.warnings, vec![Warning::TooDeep]); } +/// An object with a lens or transparency (argument 8000) comes in opaque, with the lenses +/// warning; one without the argument gives no warning. +#[test] +fn lenses_and_transparency_are_named_in_the_warnings() { + for (version, lens) in [(1000, [1u8, 0, 0, 0].to_vec()), (1200, [5, 0, 0, 0].to_vec()), (1500, [0x14, 5, 0, 0, 0x75, 0, 0, 0, 5].to_vec())] { + let v = V(version); + let plain = clip_rect(v, 10.0, &[], [0.0, 0.0]); + let d = read(&clip_drawing(version, vec![], vec![plain]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + let see_through = clip_rect(v, 10.0, &[(8000, lens)], [0.0, 0.0]); + let d = read(&clip_drawing(version, vec![], vec![see_through]), Limits::default()).unwrap(); + assert_eq!(shapes(&d.pages[0].layers[0].objects).len(), 1, "{version}"); + assert_eq!(d.warnings, vec![Warning::Lenses], "{version}"); + } +} + #[test] fn linked_groups_are_left_out_with_a_warning() { let v = V(1100); diff --git a/crates/engine/src/cmd/fileio/cdr.rs b/crates/engine/src/cmd/fileio/cdr.rs index 1658dc5dba..700a5a8671 100644 --- a/crates/engine/src/cmd/fileio/cdr.rs +++ b/crates/engine/src/cmd/fileio/cdr.rs @@ -24,6 +24,7 @@ const UNKNOWN_COLORS: &str = "colors in CDR color models VectorCraft doesn't rea const SPOT_LOOKS: &str = "CDR library colors that the drawing stores only by number were opened as black spot colors"; const ARROWHEADS: &str = "CDR outline arrowheads were left out"; const ENVELOPES: &str = "CDR envelopes were not applied, and the shapes under them keep their outlines"; +const LENSES: &str = "CDR lenses and object transparency were not applied, and the objects they are on show opaque"; const TOO_DEEP: &str = "parts of the drawing nested too deeply, or past the import limits, were left out"; const DAMAGED: &str = "damaged parts of the drawing were left out"; const PAGES_CUT: &str = "CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard"; @@ -37,6 +38,7 @@ fn note(w: Warning) -> &'static str { Warning::SpotLooks => SPOT_LOOKS, Warning::Arrowheads => ARROWHEADS, Warning::Envelopes => ENVELOPES, + Warning::Lenses => LENSES, Warning::TooDeep => TOO_DEEP, Warning::Damaged => DAMAGED, } diff --git a/crates/engine/src/cmd/fileio/tests_cdr.rs b/crates/engine/src/cmd/fileio/tests_cdr.rs index 3056933dbf..e2980b525c 100644 --- a/crates/engine/src/cmd/fileio/tests_cdr.rs +++ b/crates/engine/src/cmd/fileio/tests_cdr.rs @@ -439,6 +439,17 @@ fn containers_open_as_clipping_groups() { assert!(children[1..].iter().all(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. }))); } +/// An object with a lens or transparency opens opaque, and the warnings say so. +#[test] +fn lenses_and_transparency_are_named_in_the_warnings() { + let v = V(1200); + let args = vec![(30, v.rect(10.0, 10.0, 0.0)), (8000, vec![5, 0, 0, 0])]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &args, None)])]); + let (doc, warnings) = super::cdr::import(&synth::riff(1200, &[chunk(b"vrsn", 1200u16.to_le_bytes().to_vec()), page])).unwrap(); + assert_eq!(paths(&doc).len(), 1); + assert_eq!(warnings, ["CDR lenses and object transparency were not applied, and the objects they are on show opaque"]); +} + #[test] fn other_versions_and_damaged_drawings_say_why() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index f5d6fd92ad..1d4a65c3f9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6849,7 +6849,8 @@ fills and outlines keep their colors, widths, caps, joins and dashes, and an obj takes its style's. A library color that the drawing stores with its name and values (version 13 and later) becomes a spot swatch with its tint, and one stored only by its number opens as a black spot color. Text, bitmaps, blends, contours, brush strokes, other objects the reader doesn't read yet, -fountain, pattern, texture and PostScript fills, and outline arrowheads are left out. The `warnings` of +fountain, pattern, texture and PostScript fills, and outline arrowheads are left out, and lenses and object +transparency are not applied. The `warnings` of `document.open` name each of these kinds the drawing had, and say when damaged parts or parts past the import limits were left out. Drawings of versions after 27 are refused with a message, and so are packages that are encrypted, ZIP64 archives or split across files. VectorCraft doesn't write `.cdr` files. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2bd3c612d1..09e349f523 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1542,7 +1542,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, PowerClips (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width, caps, joins and dashes, an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). + - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, PowerClips (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width, caps, joins and dashes, an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, object transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. EPS and PostScript `.ai` files are still embedded (`crates/engine/src/tests/placed_document.rs`). From f8ad4565d097e05144e1aed71ada2287d41f9baa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 12:52:38 -0800 Subject: [PATCH 09/34] .cdr import: an outline is dashed only when its line type says so Bit 0x04 of an outline's line type marks it dashed. Some drawings store dashes in outlines without that bit, and their own preview pictures show those outlines solid; the reader drew them dashed. Such outlines now come in solid. PROVENANCE.md row R48 gives the sample files. --- crates/cdr/PROVENANCE.md | 1 + crates/cdr/src/records.rs | 4 +++- crates/cdr/tests/read.rs | 19 +++++++++++++++++++ crates/engine/src/cmd/fileio/tests_cdr.rs | 3 ++- 4 files changed, 25 insertions(+), 2 deletions(-) diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 08c606077f..57c217d0e9 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -93,3 +93,4 @@ file is committed. | R45 | `LIST stlt` from version 7: a u32 style count, and when it is not 0: the fill table (a u32 count, entries of a table id, 4 bytes and a `fild` id, 12 bytes each, 60 from version 13), the outline table (12-byte entries laid out the same way, naming `outl` ids), the text tables (fonts of 44 bytes, 60 from version 10; alignments of 12; spacings of 52; tables of 152 and 784; bullets whose length a u32 inside them sets; indents of 28; hyphenation of 32, 36 from 13; drop caps of 28; from 8.01 a table of 12), then the styles: kind (u32), id, parent id, 8 bytes, name length and name (bytes before 12, UTF-16 units from it), the fill and outline table ids, then 16 bytes (20 from 8.01) for kinds above 1 and 20 more for kinds above 2. An object names its style in argument 200 (u32). An object without argument 20 or 10 takes the fill or outline of its style; a style whose table id is 0 takes its parent's | K L593-L600, L852, L1926-L2198; S: UC `corel_rounded_rect_cdr7.cdr`, whose rectangles carry argument 200 and neither 10 nor 20, and name the style whose outline is a black hairline and whose fill is none, as the file's picture shows; the table parses exactly to the end of the list in each of the 498 sample files of versions 7 to 15 that has one, and every object with argument 200 in them names a style whose table ids are in the tables | public-spec (what the table ids name, and that an object takes its style's fill and outline: sample; a style taking its parent's entry: unconfirmed, as only text styles in the samples leave theirs to the parent, and a wrong guess draws a shape without that fill or outline) | | R46 | A container (a PowerClip) carries argument 8005; its first u32 is the id that the `spnd` chunk (a u32) of one `LIST grp ` in the document's `LIST clpt` holds. That group's objects are the ones the container clips; they keep their own transforms, in page space like the container's | K L252, L860-L862, L1895-L1901 (the argument and the chunk); S: UC `corel_powerclip_cdr7.cdr` to `corel_powerclip_x3.cdr` (versions 7 to 13) and LT `powerclipsquare_blackfill_whiterectangleinside` of `testset/12` to `testset/25`, in each of which the id in argument 8005 matches one group's `spnd`; in `corel_powerclip_cdr7.cdr` the group's box, -1.96 to 1.97 inches across, overlaps the container's, -1.81 to 1.84 inches, and the file's picture shows the group cut to the container | public-spec (what the id names, and the space of the group's objects: sample) | | R47 | Argument 8000 marks an object seen through: a lens or a transparency. The reader does not apply it, and names lenses in the warnings | K L859 (the argument); S: of the sample files of versions 7 to 25, the argument is on the see-through objects that the pictures of UC `corel_lens_test_cdr7.cdr` to `corel_lens_test_x3.cdr`, LT `square_blackfill_nooutline_transparency50percent` of `testset/12` to `testset/25` and TDF 80103 show, and otherwise only on text in UC `fancytext_cdr7.cdr` to `fancytext_x3.cdr` and on two objects of TDF 114901. The value K reads at byte 10 (14 from version 13) is not the transparency in these samples | public-spec (the argument: K; what it marks: sample; its layout: unconfirmed, and it is not read) | +| R48 | Bit 2 (0x04) of the outline's line type marks the outline dashed; the dashes of an outline without it are not drawn | S: every outline of versions 6 to 25 in the sample files with that bit set stores dashes, such as the dashed lines of UC `corel_dashes_cdr7.cdr` to `corel_dashes_x3.cdr`; TDF 76771 (version 15) stores dashes 2 and 1 in an outline of line type 0x22, and the file's picture draws that outline solid | sample | diff --git a/crates/cdr/src/records.rs b/crates/cdr/src/records.rs index dd3ac5e18a..d1db4cdc6f 100644 --- a/crates/cdr/src/records.rs +++ b/crates/cdr/src/records.rs @@ -355,7 +355,9 @@ pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec) -> Option< 2 => Join::Bevel, _ => Join::Miter, }; - let dashes = if dashes.iter().any(|d| *d > 0.0) { dashes } else { Vec::new() }; + // Bit 2 of the line type marks the outline dashed; without it the dashes stored are not drawn + // (R48). + let dashes = if line_type & 4 != 0 && dashes.iter().any(|d| *d > 0.0) { dashes } else { Vec::new() }; Some((id, Some(Outline { width, color, cap, join, dashes }))) } diff --git a/crates/cdr/tests/read.rs b/crates/cdr/tests/read.rs index 3e39384dad..c114d6392d 100644 --- a/crates/cdr/tests/read.rs +++ b/crates/cdr/tests/read.rs @@ -1401,6 +1401,25 @@ fn outlines_flagged_none_and_dashes_read() { assert_eq!((o.cap, o.join), (Cap::Square, vectorcraft_cdr::model::Join::Bevel)); } +/// Dashes stored in an outline whose line type doesn't mark it dashed (bit 2) are not drawn: the +/// outline is solid. +#[test] +fn dashes_are_drawn_only_when_the_line_type_marks_them() { + let black = synth::color(2, [0, 0, 0, 100]); + for version in [700, 1200, 1500] { + for (line_type, dashed) in [(2, false), (0x22, false), (0x42, false), (4, true), (0x24, true), (0x44, true)] { + let v = V(version); + let outline = v.outline(9, synth::Pen { line_type, width: 1.0, cap: 0, join: 0 }, &black, &[2, 1]); + let style = vec![(10, 9u32.to_le_bytes().to_vec()), (30, v.points(&[(0.0, 0.0, 0), (10.0, 0.0, 0x40)]))]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 3, &style, None)])]); + let d = read(&synth::file_of(version, vec![list(b"otlt", vec![chunk(b"outl", outline)]), page]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let o = s[0].outline.as_ref().unwrap(); + assert_eq!(o.dashes.is_empty(), !dashed, "{version} {line_type:#x}: {:?}", o.dashes); + } + } +} + #[test] fn library_colors_from_version_13_keep_their_names_and_tints() { // A model 21 color (blue, green, red, tint) shown at 50 %, and its library name. diff --git a/crates/engine/src/cmd/fileio/tests_cdr.rs b/crates/engine/src/cmd/fileio/tests_cdr.rs index e2980b525c..11c544de2a 100644 --- a/crates/engine/src/cmd/fileio/tests_cdr.rs +++ b/crates/engine/src/cmd/fileio/tests_cdr.rs @@ -385,7 +385,8 @@ fn fills_and_outlines_keep_their_colors_widths_caps_joins_and_dashes() { let v = V(1300); let red = synth::color(5, [0, 0, 255, 0]); let black = synth::color(2, [0, 0, 0, 100]); - let pen = synth::Pen { line_type: 0, width: 2.0, cap: 1, join: 2 }; + // Line type 4: a dashed outline. + let pen = synth::Pen { line_type: 4, width: 2.0, cap: 1, join: 2 }; let args = vec![ (20, 1u32.to_le_bytes().to_vec()), (10, 2u32.to_le_bytes().to_vec()), From 712e567a954ea013ce6d0cacb580cac2de5f074a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 13:33:33 -0800 Subject: [PATCH 10/34] .cdr import: outlines behind the fill come in below the fill Bit 0x10 of an outline's line type puts the outline behind the fill, so that a filled shape shows only its outer half. The reader now reports it, and the importer paints such a stroke before the fill. A clipping container's outline behind its fill becomes a stroke of its own below the clipping group, the two grouped together, since a clipping path's stroke paints over the clipped objects. PROVENANCE.md row R49 gives the sample files. --- crates/cdr/PROVENANCE.md | 1 + crates/cdr/README.md | 2 +- crates/cdr/src/build.rs | 2 +- crates/cdr/src/inline.rs | 2 +- crates/cdr/src/model.rs | 2 + crates/cdr/src/records.rs | 4 +- crates/cdr/src/wl.rs | 2 +- crates/cdr/tests/read.rs | 17 ++++++ crates/engine/src/cmd/fileio/cdr.rs | 19 +++++-- crates/engine/src/cmd/fileio/cdr/shapes.rs | 36 ++++++++++-- crates/engine/src/cmd/fileio/tests_cdr.rs | 65 ++++++++++++++++++++++ docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 13 files changed, 142 insertions(+), 15 deletions(-) diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 57c217d0e9..c2f3d79ebd 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -94,3 +94,4 @@ file is committed. | R46 | A container (a PowerClip) carries argument 8005; its first u32 is the id that the `spnd` chunk (a u32) of one `LIST grp ` in the document's `LIST clpt` holds. That group's objects are the ones the container clips; they keep their own transforms, in page space like the container's | K L252, L860-L862, L1895-L1901 (the argument and the chunk); S: UC `corel_powerclip_cdr7.cdr` to `corel_powerclip_x3.cdr` (versions 7 to 13) and LT `powerclipsquare_blackfill_whiterectangleinside` of `testset/12` to `testset/25`, in each of which the id in argument 8005 matches one group's `spnd`; in `corel_powerclip_cdr7.cdr` the group's box, -1.96 to 1.97 inches across, overlaps the container's, -1.81 to 1.84 inches, and the file's picture shows the group cut to the container | public-spec (what the id names, and the space of the group's objects: sample) | | R47 | Argument 8000 marks an object seen through: a lens or a transparency. The reader does not apply it, and names lenses in the warnings | K L859 (the argument); S: of the sample files of versions 7 to 25, the argument is on the see-through objects that the pictures of UC `corel_lens_test_cdr7.cdr` to `corel_lens_test_x3.cdr`, LT `square_blackfill_nooutline_transparency50percent` of `testset/12` to `testset/25` and TDF 80103 show, and otherwise only on text in UC `fancytext_cdr7.cdr` to `fancytext_x3.cdr` and on two objects of TDF 114901. The value K reads at byte 10 (14 from version 13) is not the transparency in these samples | public-spec (the argument: K; what it marks: sample; its layout: unconfirmed, and it is not read) | | R48 | Bit 2 (0x04) of the outline's line type marks the outline dashed; the dashes of an outline without it are not drawn | S: every outline of versions 6 to 25 in the sample files with that bit set stores dashes, such as the dashed lines of UC `corel_dashes_cdr7.cdr` to `corel_dashes_x3.cdr`; TDF 76771 (version 15) stores dashes 2 and 1 in an outline of line type 0x22, and the file's picture draws that outline solid | sample | +| R49 | Bit 4 (0x10) of the outline's line type puts the outline behind the fill | S: UC `outl_behind_fill_cdr7.cdr` to `outl_behind_fill_x3.cdr`, whose outline of line type 0x12 the file's picture shows behind the fill, and whose other outlines (0x02) it shows over the fill | sample | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index 6946f5b11e..6444c7f927 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -21,7 +21,7 @@ with each object's transform. It does not write `.cdr` files. | Ellipses, arcs and pies | ellipses, and paths for arcs and pies | | Polygons and stars (a base side copied for each side) | paths | | Uniform fills: CMYK, CMY, RGB, gray, registration, library colors | colors, spot colors with their tints | -| Outlines: width, caps, joins, dashes, the no-outline flag | outlines | +| Outlines: width, caps, joins, dashes, the no-outline and behind-the-fill flags | outlines | | Styles (`LIST stlt`, versions 7 to 15) that objects name | the fill and outline of an object that has none of its own | Text, bitmaps, linked groups (blends, contours, brush strokes), B-spline curves, fountain, diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs index fe54429fea..9b6e21c8e8 100644 --- a/crates/cdr/src/build.rs +++ b/crates/cdr/src/build.rs @@ -616,7 +616,7 @@ impl<'a, 'b> Ctx<'a, 'b> { return Some(o.clone()); } push(self.warn, Warning::TooDeep); - Some(Outline { width: o.width, color: o.color.clone(), cap: o.cap, join: o.join, dashes: Vec::new() }) + Some(Outline { dashes: Vec::new(), ..o.clone() }) } } diff --git a/crates/cdr/src/inline.rs b/crates/cdr/src/inline.rs index 65b2fa0da9..dc44ae0b23 100644 --- a/crates/cdr/src/inline.rs +++ b/crates/cdr/src/inline.rs @@ -79,7 +79,7 @@ pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec) -> Option< let _stretch = r.u16()?; let _nib = angle(&mut r, p)?; let color = records::color(&mut r, p, warn)?; - let mut out = Outline { width, color, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new() }; + let mut out = Outline { width, color, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new(), behind_fill: false }; let Some(stored) = r.skip(7).and_then(|()| r.u8()).map(usize::from) else { return Some(Some(out)) }; let Some(area) = r.bytes(DASH_AREA) else { return Some(Some(out)) }; if stored > DASH_AREA { diff --git a/crates/cdr/src/model.rs b/crates/cdr/src/model.rs index 8cc15d6271..06c9ddcb85 100644 --- a/crates/cdr/src/model.rs +++ b/crates/cdr/src/model.rs @@ -105,6 +105,8 @@ pub struct Outline { pub join: Join, /// Dash and gap lengths, in outline widths; empty for a solid line. pub dashes: Vec, + /// Drawn behind the fill, so that a filled shape shows only the outer half of it. + pub behind_fill: bool, } #[derive(Clone, Debug, PartialEq)] diff --git a/crates/cdr/src/records.rs b/crates/cdr/src/records.rs index d1db4cdc6f..dac441940f 100644 --- a/crates/cdr/src/records.rs +++ b/crates/cdr/src/records.rs @@ -358,7 +358,9 @@ pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec) -> Option< // Bit 2 of the line type marks the outline dashed; without it the dashes stored are not drawn // (R48). let dashes = if line_type & 4 != 0 && dashes.iter().any(|d| *d > 0.0) { dashes } else { Vec::new() }; - Some((id, Some(Outline { width, color, cap, join, dashes }))) + // Bit 4 of the line type: behind the fill (R49). + let behind_fill = line_type & 0x10 != 0; + Some((id, Some(Outline { width, color, cap, join, dashes, behind_fill }))) } /// A name argument (R9): Windows-1252 up to a NUL before version 12, UTF-16LE from it. A name diff --git a/crates/cdr/src/wl.rs b/crates/cdr/src/wl.rs index 0a20c00893..cb0c345204 100644 --- a/crates/cdr/src/wl.rs +++ b/crates/cdr/src/wl.rs @@ -181,7 +181,7 @@ fn shape(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mu }; let outline = if *rec.get(OUTLINED)? != 0 { let width = f64::from(Rd::at(rec, OUTLINE_WIDTH).u16()?) * k; - Some(Outline { width, color: color_at(OUTLINE_COLOR, warn)?, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new() }) + Some(Outline { width, color: color_at(OUTLINE_COLOR, warn)?, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new(), behind_fill: false }) } else { None }; diff --git a/crates/cdr/tests/read.rs b/crates/cdr/tests/read.rs index c114d6392d..e909174e10 100644 --- a/crates/cdr/tests/read.rs +++ b/crates/cdr/tests/read.rs @@ -1420,6 +1420,23 @@ fn dashes_are_drawn_only_when_the_line_type_marks_them() { } } +/// Bit 4 of the line type puts the outline behind the fill. +#[test] +fn outlines_flagged_behind_the_fill_say_so() { + let black = synth::color(2, [0, 0, 0, 100]); + for version in [700, 1300, 1600] { + for (line_type, behind) in [(2, false), (0x22, false), (0x12, true), (0x14, true)] { + let v = V(version); + let outline = v.outline(9, synth::Pen { line_type, width: 4.0, cap: 0, join: 0 }, &black, &[]); + let style = vec![(10, 9u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &style, None)])]); + let d = read(&synth::file_of(version, vec![list(b"otlt", vec![chunk(b"outl", outline)]), page]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].outline.as_ref().map(|o| o.behind_fill), Some(behind), "{version} {line_type:#x}"); + } + } +} + #[test] fn library_colors_from_version_13_keep_their_names_and_tints() { // A model 21 color (blue, green, red, tint) shown at 50 %, and its library name. diff --git a/crates/engine/src/cmd/fileio/cdr.rs b/crates/engine/src/cmd/fileio/cdr.rs index 700a5a8671..bd8e6a6092 100644 --- a/crates/engine/src/cmd/fileio/cdr.rs +++ b/crates/engine/src/cmd/fileio/cdr.rs @@ -325,7 +325,14 @@ fn copy_cost(objects: &[cd::Object]) -> usize { cd::Object::Group(kids) => stack.extend(kids), cd::Object::Shape(s) => n = n.saturating_add(shape_cost(s)), cd::Object::Clip { container, objects } => { + // A container whose outline is behind its fill is built twice, as that outline + // and as the clipping path, inside a group of their own. n = n.saturating_add(shape_cost(container)); + // The second path, without the dashes, which only the outline shape has, and the + // group around the two. + if container.outline.as_ref().is_some_and(|o| o.behind_fill) { + n = n.saturating_add(2 + path_cost(container)); + } stack.extend(objects); } } @@ -336,11 +343,15 @@ fn copy_cost(objects: &[cd::Object]) -> usize { /// What one copy of shape `s` takes past the object itself: its path's subpaths and segments and /// its outline's dashes. fn shape_cost(s: &cd::Shape) -> usize { - let mut n: usize = 0; - if let cd::Geometry::Path(p) = &s.geometry { - n = p.subpaths.iter().fold(n, |n, sp| n.saturating_add(1 + sp.segments.len())); + path_cost(s).saturating_add(s.outline.as_ref().map_or(0, |o| o.dashes.len())) +} + +/// The subpaths and segments of shape `s`'s path. +fn path_cost(s: &cd::Shape) -> usize { + match &s.geometry { + cd::Geometry::Path(p) => p.subpaths.iter().fold(0usize, |n, sp| n.saturating_add(1 + sp.segments.len())), + _ => 0, } - n.saturating_add(s.outline.as_ref().map_or(0, |o| o.dashes.len())) } /// A layer of the document named `name` holding `kids` (bottom to top). diff --git a/crates/engine/src/cmd/fileio/cdr/shapes.rs b/crates/engine/src/cmd/fileio/cdr/shapes.rs index 71d8d78ad5..3b92ecf170 100644 --- a/crates/engine/src/cmd/fileio/cdr/shapes.rs +++ b/crates/engine/src/cmd/fileio/cdr/shapes.rs @@ -124,10 +124,27 @@ impl Builder { // A clipping group whose clipping path keeps the container's paint: its fill // behind the clipped objects and its outline over them. cd::Object::Clip { container, objects } => { - let Some(clip) = self.shape(container, to_doc, true) else { continue }; + // A clipping path's stroke paints over the clipped objects, so an outline + // behind the fill becomes a shape of its own below the clipping group, the + // two in a group of their own. + let behind = container.outline.as_ref().is_some_and(|o| o.behind_fill); + let (outline, clip) = if behind { + let outline = self.shape(&cd::Shape { fill: None, ..(**container).clone() }, to_doc, false); + (outline, self.shape(&cd::Shape { outline: None, ..(**container).clone() }, to_doc, true)) + } else { + (None, self.shape(container, to_doc, true)) + }; + let Some(clip) = clip else { continue }; let mut children = vec![clip]; children.extend(self.objects_at(objects, to_doc, depth + 1)); - out.push(Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: true }))); + let group = Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: true })); + match outline { + Some(outline) => { + let children = vec![outline, group]; + out.push(Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: false }))); + } + None => out.push(group), + } } } } @@ -150,11 +167,15 @@ impl Builder { self.note(Warning::TooDeep); return None; } + // In paint order: an outline behind the fill comes first. let mut items = Vec::new(); + if let Some(o) = s.outline.as_ref().filter(|o| o.behind_fill) { + items.push(AppearanceItem::Stroke(self.stroke(o))); + } if let Some(c) = &s.fill { items.push(AppearanceItem::Fill(FillLayer::new(self.paint(c)))); } - if let Some(o) = &s.outline { + if let Some(o) = s.outline.as_ref().filter(|o| !o.behind_fill) { items.push(AppearanceItem::Stroke(self.stroke(o))); } // A curve of several subpaths is filled with holes where they overlap: VectorCraft's own @@ -453,7 +474,14 @@ mod tests { /// whose outline has 299 dashes costs 300 each time it is copied. #[test] fn master_copies_count_their_dashes() { - let outline = cd::Outline { width: 1.0, color: cd::Color::Gray(1.0), cap: cd::Cap::Butt, join: cd::Join::Miter, dashes: vec![1.0; 299] }; + let outline = cd::Outline { + width: 1.0, + color: cd::Color::Gray(1.0), + cap: cd::Cap::Butt, + join: cd::Join::Miter, + dashes: vec![1.0; 299], + behind_fill: false, + }; let rect = cd::Object::Shape(Box::new(cd::Shape { geometry: Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, matrix: cd::Matrix::IDENTITY, diff --git a/crates/engine/src/cmd/fileio/tests_cdr.rs b/crates/engine/src/cmd/fileio/tests_cdr.rs index 11c544de2a..7cde7a2c92 100644 --- a/crates/engine/src/cmd/fileio/tests_cdr.rs +++ b/crates/engine/src/cmd/fileio/tests_cdr.rs @@ -411,6 +411,71 @@ fn fills_and_outlines_keep_their_colors_widths_caps_joins_and_dashes() { assert!(dash.pattern.len() == 2 && (dash.pattern[0] - 6.0).abs() < 0.01 && (dash.pattern[1] - 2.0).abs() < 0.01, "{:?}", dash.pattern); } +/// An outline behind the fill becomes a stroke painted before the fill. +#[test] +fn outlines_behind_the_fill_paint_first() { + use vectorcraft_doc::appearance::AppearanceItem; + let v = V(1100); + let black = synth::color(2, [0, 0, 0, 100]); + let doc = list( + b"doc ", + vec![ + list(b"filt", vec![chunk(b"fild", v.fill(1, &synth::color(5, [0, 0, 255, 0])))]), + list( + b"otlt", + vec![ + chunk(b"outl", v.outline(2, synth::Pen { line_type: 0x12, width: 4.0, cap: 0, join: 0 }, &black, &[])), + chunk(b"outl", v.outline(3, synth::Pen { line_type: 0x02, width: 4.0, cap: 0, join: 0 }, &black, &[])), + ], + ), + ], + ); + let rect = |outline: u32| { + let args = vec![(20, 1u32.to_le_bytes().to_vec()), (10, outline.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))]; + synth::object(v, 1, &args, None) + }; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(2), rect(3)])]); + let (doc, _) = super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap(); + let p = paths(&doc); + assert_eq!(p.len(), 2); + // The file lists objects front to back; the document stacks them bottom to top. + let (behind, over) = (&p[1].appearance.items, &p[0].appearance.items); + assert!(matches!(behind.as_slice(), [AppearanceItem::Stroke(_), AppearanceItem::Fill(_)]), "{behind:?}"); + assert!(matches!(over.as_slice(), [AppearanceItem::Fill(_), AppearanceItem::Stroke(_)]), "{over:?}"); +} + +/// A container whose outline is behind its fill opens as a group of that outline below a clipping +/// group whose clipping path keeps only the fill. +#[test] +fn a_container_outline_behind_the_fill_stays_below_its_contents() { + use vectorcraft_doc::appearance::AppearanceItem; + let v = V(1100); + let black = synth::color(2, [0, 0, 0, 100]); + let rect = |w: f64, extra: Vec<(u32, Vec)>| { + let mut args = vec![(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(w, w, 0.0))]; + args.extend(extra); + synth::object(v, 1, &args, None) + }; + let doc = list( + b"doc ", + vec![ + list(b"filt", vec![chunk(b"fild", v.fill(1, &synth::color(5, [0, 0, 255, 0])))]), + list(b"otlt", vec![chunk(b"outl", v.outline(2, synth::Pen { line_type: 0x12, width: 4.0, cap: 0, join: 0 }, &black, &[]))]), + synth::clpt(vec![(5, vec![rect(10.0, vec![])])]), + ], + ); + let container = rect(40.0, vec![synth::container(5), (10, 2u32.to_le_bytes().to_vec())]); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![container])]); + let (doc, _) = super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap(); + let layer = doc.layers.last().and_then(|l| l.children()).unwrap(); + let [both] = layer.as_slice() else { panic!("{layer:?}") }; + let NodeKind::Group { children: both, clip: false } = &both.kind else { panic!("{:?}", both.kind) }; + let [outline, group] = both.as_slice() else { panic!("{both:?}") }; + assert!(matches!(outline.appearance.items.as_slice(), [AppearanceItem::Stroke(_)]), "{:?}", outline.appearance.items); + let NodeKind::Group { children, clip: true } = &group.kind else { panic!("{:?}", group.kind) }; + assert!(matches!(children[0].appearance.items.as_slice(), [AppearanceItem::Fill(_)]), "{:?}", children[0].appearance.items); +} + /// A container and the group it clips open as a clipping group: the container's shape first, as /// the clipping path keeping its fill, then the clipped shapes. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 1d4a65c3f9..7729d978d9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6845,7 +6845,8 @@ by side. Layers of the same name on different pages become one layer when the pa the master page's guidelines become guides on every page. Groups stay groups, and a PowerClip becomes a clipping group whose clipping path keeps the container's fill and outline. Curves, paths, arcs and polygons (stars included) become paths, and rectangles and ellipses become live shapes; a rectangle keeps each corner's radius. Uniform -fills and outlines keep their colors, widths, caps, joins and dashes, and an object without a fill or outline of its own +fills and outlines keep their colors, widths, caps, joins and dashes, an outline behind the fill becomes a stroke below +the fill, and an object without a fill or outline of its own takes its style's. A library color that the drawing stores with its name and values (version 13 and later) becomes a spot swatch with its tint, and one stored only by its number opens as a black spot color. Text, bitmaps, blends, contours, brush strokes, other objects the reader doesn't read yet, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 09e349f523..abcb3a8c23 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1542,7 +1542,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, PowerClips (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width, caps, joins and dashes, an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, object transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). + - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, PowerClips (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width, caps, joins and dashes (behind the fill where the file says so), an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, object transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. EPS and PostScript `.ai` files are still embedded (`crates/engine/src/tests/placed_document.rs`). From 08155e34e3cc12e445adf4b85215e020949b8f82 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 13:37:48 -0800 Subject: [PATCH 11/34] .cdr import: a shape left out at the coordinate limit is not damage A curve or polygon whose points go past the coordinate limit was left out with both the limit warning and the damage warning, in RIFF files and in files of versions 1 and 2. It now gives the limit warning only. A polygon without its sides argument is still damage. --- crates/cdr/src/build.rs | 18 ++++++++++++------ crates/cdr/src/limits.rs | 15 +++++++++++++-- crates/cdr/src/wl.rs | 4 +++- crates/cdr/tests/read.rs | 30 +++++++++++++++++++++++++++++- 4 files changed, 57 insertions(+), 10 deletions(-) diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs index 9b6e21c8e8..a89342c1f3 100644 --- a/crates/cdr/src/build.rs +++ b/crates/cdr/src/build.rs @@ -552,22 +552,28 @@ impl<'a, 'b> Ctx<'a, 'b> { // Version 3 counts the first object types from 0, one below the later numbers (R32). let kind = if self.p.types_from_zero && loda.kind <= 4 { loda.kind + 1 } else { loda.kind }; // A shape without its coordinates, or a polygon without its sides, is damage like a shape - // whose coordinates can't be read. + // whose coordinates can't be read; one left out at the coordinate limit is not. + self.budget.coordinates_refused(); let g = match kind { RECTANGLE => coords.and_then(|c| geometry::rect(c, &self.p)), ELLIPSE => coords.and_then(|c| geometry::ellipse(c, &self.p)), CURVE => coords.and_then(|c| geometry::point_list(c, &self.p, self.budget, self.warn)).map(Geometry::Path), PATH if self.p.paths => coords.and_then(|c| geometry::path_record(c, &self.p, self.budget, self.warn)).map(Geometry::Path), - POLYGON => coords - .and_then(|c| geometry::point_list(c, &self.p, self.budget, self.warn)) - .zip(loda.arg(ARG_POLYGON)) - .and_then(|(base, sides)| geometry::polygon(&base, sides, &self.p, self.budget, self.warn)), + POLYGON => match loda.arg(ARG_POLYGON) { + Some(sides) => coords + .and_then(|c| geometry::point_list(c, &self.p, self.budget, self.warn)) + .and_then(|base| geometry::polygon(&base, sides, &self.p, self.budget, self.warn)), + None => { + push(self.warn, Warning::Damaged); + return None; + } + }, _ => { push(self.warn, Warning::UnsupportedObjects); return None; } }; - if g.is_none() { + if g.is_none() && !self.budget.coordinates_refused() { push(self.warn, Warning::Damaged); } g diff --git a/crates/cdr/src/limits.rs b/crates/cdr/src/limits.rs index b3aadc23df..d1b0ff7fae 100644 --- a/crates/cdr/src/limits.rs +++ b/crates/cdr/src/limits.rs @@ -74,11 +74,19 @@ pub(crate) struct Budget { objects: usize, coordinates: usize, dashes: usize, + /// A request for coordinates was refused since [`Budget::coordinates_refused`] last asked. + refused: bool, } impl Budget { pub(crate) fn new(limits: Limits) -> Self { - Budget { limits, inflated: 0, chunks: 0, objects: 0, coordinates: 0, dashes: 0 } + Budget { limits, inflated: 0, chunks: 0, objects: 0, coordinates: 0, dashes: 0, refused: false } + } + + /// Whether a request for coordinates was refused since the last call, which tells a shape + /// left out at the limit from one whose bytes don't parse. + pub(crate) fn coordinates_refused(&mut self) -> bool { + std::mem::take(&mut self.refused) } /// Bytes an inflate may still produce. @@ -117,7 +125,10 @@ impl Budget { self.coordinates = t; true } - None => false, + None => { + self.refused = true; + false + } } } diff --git a/crates/cdr/src/wl.rs b/crates/cdr/src/wl.rs index cb0c345204..ed6bae1ca2 100644 --- a/crates/cdr/src/wl.rs +++ b/crates/cdr/src/wl.rs @@ -134,8 +134,10 @@ fn page_box(b: &[u8], settings: usize, p: &Profile) -> Option<(f64, f64)> { /// One drawn object's record (R43, R44): a shape, or `None` with a warning for text, for an object /// of another type and for a shape that can't be read. fn object(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + // A curve left out at the coordinate limit is not damage. + budget.coordinates_refused(); let read = shape(rec, fields, p, budget, warn); - if read.is_none() { + if read.is_none() && !budget.coordinates_refused() { push(warn, Warning::Damaged); } read?.map(|s| Object::Shape(Box::new(s))) diff --git a/crates/cdr/tests/read.rs b/crates/cdr/tests/read.rs index e909174e10..9c201231eb 100644 --- a/crates/cdr/tests/read.rs +++ b/crates/cdr/tests/read.rs @@ -420,7 +420,7 @@ fn hostile_version_1_files_stop_within_their_bytes_and_limits() { curve[114..116].copy_from_slice(&3u16.to_le_bytes()); let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[curve]), Limits { coordinates: 2, ..Limits::default() }).unwrap(); assert_eq!(wl_objects(&d).len(), 0); - assert!(d.warnings.contains(&Warning::TooDeep)); + assert_eq!(d.warnings, vec![Warning::TooDeep]); // Objects past the object limit are left out, and records past the chunk limit stop the read. let many: Vec> = (0..10).map(|_| rect()).collect(); let d = read(&synth::wl_file(b'e', (612.0, 792.0), &many), Limits { objects: 4, ..Limits::default() }).unwrap(); @@ -1401,6 +1401,34 @@ fn outlines_flagged_none_and_dashes_read() { assert_eq!((o.cap, o.join), (Cap::Square, vectorcraft_cdr::model::Join::Bevel)); } +/// A curve or polygon left out at the coordinate limit gives the limit warning, not the damage +/// warning. +#[test] +fn shapes_past_the_coordinate_limit_are_not_damage() { + let v = V(1100); + let curve = synth::object(v, 3, &[(30, v.points(&[(0.0, 0.0, 0), (10.0, 0.0, 0x40), (10.0, 10.0, 0x40)]))], None); + let side = synth::POLYGON_SIDE; + let mut sides = vec![0; 4]; + sides.extend(5u32.to_le_bytes()); + sides.extend([0; 8]); + sides.extend(0.05f64.to_le_bytes()); + sides.extend(0.05f64.to_le_bytes()); + sides.extend([v.coord(0.0), v.coord(0.0)].concat()); + let base = v.points(&[(0.0, side, 0x0C), (side * 0.587, side * 0.809, 0x44)]); + let polygon = synth::object(v, 0x14, &[(30, base.clone()), (11000, sides)], None); + for (objects, limit) in [(vec![curve], 2), (vec![polygon], 4)] { + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)])]); + let d = read(&file, Limits { coordinates: limit, ..Limits::default() }).unwrap(); + assert!(d.pages[0].layers[0].objects.is_empty()); + assert_eq!(d.warnings, vec![Warning::TooDeep]); + } + // A polygon without its sides is damage, past the limit too. + let sideless = synth::object(v, 0x14, &[(30, base)], None); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![sideless])])]); + let d = read(&file, Limits { coordinates: 1, ..Limits::default() }).unwrap(); + assert_eq!(d.warnings, vec![Warning::Damaged]); +} + /// Dashes stored in an outline whose line type doesn't mark it dashed (bit 2) are not drawn: the /// outline is solid. #[test] From e71ab08233ce6977bb8bfafdc38a48afa8466638 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 13:40:48 -0800 Subject: [PATCH 12/34] .cdr import: bytes a failing compressed stream inflated count toward the limit A zlib stream that fails near its end has already inflated most of its bytes, which the reader discarded without counting them. Several such streams could each inflate up to the file's inflate limit. Those bytes now count toward it. --- crates/cdr/src/riff.rs | 4 ++++ crates/cdr/tests/read.rs | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/crates/cdr/src/riff.rs b/crates/cdr/src/riff.rs index fcec80692b..3417c61b4a 100644 --- a/crates/cdr/src/riff.rs +++ b/crates/cdr/src/riff.rs @@ -378,6 +378,10 @@ impl<'a> Index<'a> { let got = match reader.take((left as u64).saturating_add(1)).read_to_end(&mut self.inflated) { Ok(n) => n, Err(_) => { + // What a stream inflated before it failed counts toward the limit too, so that + // streams that fail late can't inflate past it again and again. + let produced = self.inflated.len().saturating_sub(at); + self.left.set(left.saturating_sub(produced)); self.inflated.truncate(at); return Err(Error::Damaged("compressed block")); } diff --git a/crates/cdr/tests/read.rs b/crates/cdr/tests/read.rs index 9c201231eb..1c07bedb46 100644 --- a/crates/cdr/tests/read.rs +++ b/crates/cdr/tests/read.rs @@ -1319,6 +1319,26 @@ fn a_zip_bomb_stops_at_the_inflate_limit() { assert_eq!(read(&file, limits), Err(Error::Limit("inflated size"))); } +/// What a compressed stream inflates before it fails counts toward the inflate limit, so that +/// streams failing at their checksum can't each inflate up to the limit. +#[test] +fn bytes_inflated_by_a_failing_stream_count_toward_the_limit() { + let failing = || { + let mut cmpr = synth::cmpr(&[chunk(b"junk", vec![0; 600 << 10])]); + if let synth::Node::Chunk(_, body) = &mut cmpr { + // The last byte of the first block's zlib stream is part of its checksum. + let first = u32::from_le_bytes(body[4..8].try_into().unwrap()) as usize; + body[4 + 16 + first - 1] ^= 0xff; + } + cmpr + }; + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), failing(), failing()]); + let one = + read(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), failing()]), Limits { inflated: 1 << 20, ..Limits::default() }); + assert!(one.is_ok_and(|d| d.warnings == vec![Warning::Damaged])); + assert_eq!(read(&file, Limits { inflated: 1 << 20, ..Limits::default() }), Err(Error::Limit("inflated size"))); +} + #[test] fn a_million_empty_chunks_stop_at_the_chunk_limit() { let kids: Vec<_> = (0..5000).map(|_| chunk(b"junk", vec![])).collect(); From 8fbb5aae5cabbeb6ea06d16f0a7a9fe5bca960ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 13:54:24 -0800 Subject: [PATCH 13/34] .cdr import: an outline of width 0 opens as a hairline A drawn outline of width 0 became a stroke of width 0, which the renderer does not draw. It now becomes a 0.25 pt stroke, the width PDF import gives a line width of 0. --- crates/engine/src/cmd/fileio/cdr/shapes.rs | 6 ++++- crates/engine/src/cmd/fileio/tests_cdr.rs | 30 ++++++++++++++++++++++ docs/mcp.md | 4 +-- docs/target-app-parity.md | 2 +- 4 files changed, 38 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/fileio/cdr/shapes.rs b/crates/engine/src/cmd/fileio/cdr/shapes.rs index 3b92ecf170..69e9cb1ea4 100644 --- a/crates/engine/src/cmd/fileio/cdr/shapes.rs +++ b/crates/engine/src/cmd/fileio/cdr/shapes.rs @@ -15,6 +15,9 @@ use vectorcraft_doc::{Document, Guide, LiveShape, Node, NodeKind}; /// The most nested groups mapped; the reader holds nesting well below it. const MAX_DEPTH: usize = 256; +/// The width, in points, of a stroke made from an outline of width 0: the width PDF import gives a +/// line width of 0 (`crates/pdf/src/import/state.rs`). +const HAIRLINE: f64 = 0.25; pub(super) struct Builder { pub(super) doc: Document, @@ -187,7 +190,8 @@ impl Builder { } fn stroke(&mut self, o: &cd::Outline) -> StrokeLayer { - let width = if o.width.is_finite() { o.width.clamp(0.0, 1000.0) } else { 0.0 }; + // A drawn outline of width 0 shows as a hairline, as a PDF line width of 0 does. + let width = if o.width.is_finite() && o.width > 0.0 { o.width.min(1000.0) } else { HAIRLINE }; let mut l = StrokeLayer::new(self.paint(&o.color), width); l.cap = match o.cap { cd::Cap::Butt => LineCap::Butt, diff --git a/crates/engine/src/cmd/fileio/tests_cdr.rs b/crates/engine/src/cmd/fileio/tests_cdr.rs index 7cde7a2c92..8dbf876b7d 100644 --- a/crates/engine/src/cmd/fileio/tests_cdr.rs +++ b/crates/engine/src/cmd/fileio/tests_cdr.rs @@ -411,6 +411,36 @@ fn fills_and_outlines_keep_their_colors_widths_caps_joins_and_dashes() { assert!(dash.pattern.len() == 2 && (dash.pattern[0] - 6.0).abs() < 0.01 && (dash.pattern[1] - 2.0).abs() < 0.01, "{:?}", dash.pattern); } +/// An outline of width 0 opens as a hairline stroke, which draws; a thin outline keeps its width. +#[test] +fn outlines_of_width_0_open_as_hairlines() { + use vectorcraft_doc::appearance::AppearanceItem; + let v = V(1100); + let black = synth::color(2, [0, 0, 0, 100]); + let doc = list( + b"doc ", + vec![list( + b"otlt", + vec![ + chunk(b"outl", v.outline(2, synth::Pen { line_type: 2, width: 0.0, cap: 0, join: 0 }, &black, &[])), + chunk(b"outl", v.outline(3, synth::Pen { line_type: 2, width: 0.1, cap: 0, join: 0 }, &black, &[])), + ], + )], + ); + let rect = |outline: u32| synth::object(v, 1, &[(10, outline.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(2), rect(3)])]); + let (doc, _) = super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap(); + let widths: Vec = paths(&doc) + .iter() + .map(|n| match n.appearance.items.as_slice() { + [AppearanceItem::Stroke(s)] => s.width, + other => panic!("{other:?}"), + }) + .collect(); + // Bottom to top: the file lists the 0.1 pt outline last. + assert!(widths.len() == 2 && (widths[0] - 0.1).abs() < 0.01 && (widths[1] - 0.25).abs() < 1e-9, "{widths:?}"); +} + /// An outline behind the fill becomes a stroke painted before the fill. #[test] fn outlines_behind_the_fill_paint_first() { diff --git a/docs/mcp.md b/docs/mcp.md index 7729d978d9..e13de2367c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6845,8 +6845,8 @@ by side. Layers of the same name on different pages become one layer when the pa the master page's guidelines become guides on every page. Groups stay groups, and a PowerClip becomes a clipping group whose clipping path keeps the container's fill and outline. Curves, paths, arcs and polygons (stars included) become paths, and rectangles and ellipses become live shapes; a rectangle keeps each corner's radius. Uniform -fills and outlines keep their colors, widths, caps, joins and dashes, an outline behind the fill becomes a stroke below -the fill, and an object without a fill or outline of its own +fills and outlines keep their colors, widths, caps, joins and dashes (an outline of width 0 becomes a 0.25 pt stroke), +an outline behind the fill becomes a stroke below the fill, and an object without a fill or outline of its own takes its style's. A library color that the drawing stores with its name and values (version 13 and later) becomes a spot swatch with its tint, and one stored only by its number opens as a black spot color. Text, bitmaps, blends, contours, brush strokes, other objects the reader doesn't read yet, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index abcb3a8c23..b9e066a72e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1542,7 +1542,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, PowerClips (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width, caps, joins and dashes (behind the fill where the file says so), an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, object transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). + - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, PowerClips (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill where the file says so), an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, object transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. EPS and PostScript `.ai` files are still embedded (`crates/engine/src/tests/placed_document.rs`). From 5da5317c6cb61147cab6a2dd1b0a883ba62a470f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 13:56:50 -0800 Subject: [PATCH 14/34] .cdr import: integration tests build as one test binary The crate's integration tests move to tests/it, one module per area, built as a single test binary as the other crates' are. The file format table now lists clipping containers, fills and outlines taken from the object's style, and the lenses warning. --- crates/cdr/PROVENANCE.md | 2 +- crates/cdr/README.md | 2 +- crates/cdr/tests/{ => it}/bench.rs | 3 +-- crates/cdr/tests/it/main.rs | 7 +++++++ crates/cdr/tests/{ => it}/provenance.rs | 1 - crates/cdr/tests/{ => it}/read.rs | 1 - docs/file-format-parity.md | 2 +- docs/target-app-parity.md | 2 +- 8 files changed, 12 insertions(+), 8 deletions(-) rename crates/cdr/tests/{ => it}/bench.rs (94%) create mode 100644 crates/cdr/tests/it/main.rs rename crates/cdr/tests/{ => it}/provenance.rs (96%) rename crates/cdr/tests/{ => it}/read.rs (99%) diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index c2f3d79ebd..11bae00fb3 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -1,7 +1,7 @@ # Where each layout comes from The reader relies on the record layouts below. Code cites a row by its id (`R1` ...), and -`tests/provenance.rs` fails when a cited id has no row here. +`tests/it/provenance.rs` fails when a cited id has no row here. Sources: diff --git a/crates/cdr/README.md b/crates/cdr/README.md index 6444c7f927..c30cb7d1b3 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -51,7 +51,7 @@ not a `.cdr` drawing. ## Provenance `PROVENANCE.md` lists every record layout the reader relies on, with its public source and status. -Code cites the rows by id (`R1` ...), and `tests/provenance.rs` fails when a cited id has no row. +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` (the `synth` feature); no third-party file is committed. diff --git a/crates/cdr/tests/bench.rs b/crates/cdr/tests/it/bench.rs similarity index 94% rename from crates/cdr/tests/bench.rs rename to crates/cdr/tests/it/bench.rs index dd23a0a76f..6ec024423a 100644 --- a/crates/cdr/tests/bench.rs +++ b/crates/cdr/tests/it/bench.rs @@ -1,6 +1,5 @@ -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] //! Read time of a large synthetic drawing. Run with -//! `cargo test --release -p vectorcraft-cdr --test bench -- --ignored --nocapture`. +//! `cargo test --release -p vectorcraft-cdr --test it bench -- --ignored --nocapture`. use vectorcraft_cdr::synth::{self, V, chunk, list}; use vectorcraft_cdr::{Limits, read}; diff --git a/crates/cdr/tests/it/main.rs b/crates/cdr/tests/it/main.rs new file mode 100644 index 0000000000..0c1aeef38e --- /dev/null +++ b/crates/cdr/tests/it/main.rs @@ -0,0 +1,7 @@ +//! Integration tests: one test binary for the crate, one module per area. +// Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod bench; +mod provenance; +mod read; diff --git a/crates/cdr/tests/provenance.rs b/crates/cdr/tests/it/provenance.rs similarity index 96% rename from crates/cdr/tests/provenance.rs rename to crates/cdr/tests/it/provenance.rs index 0a28df20f6..fffc006cb4 100644 --- a/crates/cdr/tests/provenance.rs +++ b/crates/cdr/tests/it/provenance.rs @@ -1,4 +1,3 @@ -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] //! Every layout id the code cites (`R1` ...) has a row in `PROVENANCE.md`. use std::collections::BTreeSet; diff --git a/crates/cdr/tests/read.rs b/crates/cdr/tests/it/read.rs similarity index 99% rename from crates/cdr/tests/read.rs rename to crates/cdr/tests/it/read.rs index 1c07bedb46..fd267c833d 100644 --- a/crates/cdr/tests/read.rs +++ b/crates/cdr/tests/it/read.rs @@ -1,4 +1,3 @@ -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] //! Reading synthetic drawings of every version the reader takes, plain and compressed, and //! hostile files. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 524941fb65..f12e8ad579 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -308,7 +308,7 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | PICT | open, place (legacy) | no | no | rarely used | | Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` | | FreeHand `.fh*` | open (legacy) | no | no | | -| `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies, and version 3 objects under an envelope are left out with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; record layouts and their sources in `crates/cdr/PROVENANCE.md`; synthetic test files only; tests in `crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` | +| `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, PowerClips, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses and object transparency are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies, and version 3 objects under an envelope are left out with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; record layouts and their sources in `crates/cdr/PROVENANCE.md`; synthetic test files only; tests in `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` | | Text `.txt` | place, export | place (Text Import Options) | yes | | | RTF `.rtf` | place | place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only | | Word `.docx` | place | place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b9e066a72e..7a6ad6368b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1542,7 +1542,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, PowerClips (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill where the file says so), an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, object transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). + - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, PowerClips (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill where the file says so), an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, object transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. EPS and PostScript `.ai` files are still embedded (`crates/engine/src/tests/placed_document.rs`). From f940e5e0f25697632fdf4262b8b8471314f658e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 14:03:22 -0800 Subject: [PATCH 15/34] .cdr import: fuzz mutated drawings with styles and clipping containers, and place them The importer's fuzz test of mutated RIFF drawings now also starts from a drawing with a style table, a clipping container, an outline behind the fill and a lens, and places each mutated drawing as well as opening it. --- crates/cdr/src/synth.rs | 49 ++++++++++++++++++++++++++++++ crates/cdr/tests/it/read.rs | 21 +++++++++++++ crates/engine/tests/import_fuzz.rs | 13 +++++++- 3 files changed, 82 insertions(+), 1 deletion(-) diff --git a/crates/cdr/src/synth.rs b/crates/cdr/src/synth.rs index 21d3b1db72..4f3ff0b05e 100644 --- a/crates/cdr/src/synth.rs +++ b/crates/cdr/src/synth.rs @@ -588,6 +588,55 @@ pub fn container(id: u32) -> (u32, Vec) { (8005, [id, 1, 0, 1].iter().flat_map(|v| v.to_le_bytes()).collect()) } +/// A RIFF drawing of `version` (7 to 13) with a style table, a PowerClip and a lens: a rectangle +/// that takes its fill and outline from its style, a container that clips two rectangles, one +/// with an outline behind the fill, and a rectangle with a lens; compressed when `compress`. +/// Before version 7, the [`sample`]. +pub fn feature_sample(version: u16, compress: bool) -> Vec { + if version < 700 { + return sample(version, false); + } + let v = V(version); + let black = color(2, [0, 0, 0, 100]); + let rect = |w: f64, extra: Vec<(u32, Vec)>, at: f64| { + let mut args = vec![(30, v.rect(w, w, 0.0))]; + args.extend(extra); + object(v, 1, &args, Some([1.0, 0.0, 0.0, 1.0, at, at])) + }; + let style = (200, 0x10u32.to_le_bytes().to_vec()); + let clipped = + vec![rect(30.0, vec![style.clone()], 10.0), rect(30.0, vec![(10, 3u32.to_le_bytes().to_vec()), (20, 1u32.to_le_bytes().to_vec())], -10.0)]; + let doc = list( + b"doc ", + vec![ + mcfg(v, 612.0, 792.0), + list(b"filt", vec![chunk(b"fild", v.fill(1, &color(5, [0, 0, 255, 0])))]), + list( + b"otlt", + vec![ + chunk(b"outl", v.outline(2, Pen { line_type: 4, width: 2.0, cap: 1, join: 1 }, &black, &[3, 1])), + chunk(b"outl", v.outline(3, Pen { line_type: 0x12, width: 4.0, cap: 0, join: 0 }, &black, &[])), + ], + ), + stlt(v, &[(0x100, 1)], &[(0x200, 2)], &[Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }], true), + clpt(vec![(7, clipped)]), + ], + ); + let objects = vec![ + rect(20.0, vec![style.clone()], 0.0), + rect(40.0, vec![style.clone(), container(7)], 50.0), + rect(20.0, vec![style, (8000, vec![1, 0, 0, 0])], -50.0), + ]; + let page = page(false, vec![layer(v, [0, 0, 0, 0x98], "Art", objects)]); + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + if compress { + body.push(cmpr(&[doc, page])); + } else { + body.extend([doc, page]); + } + riff(version, &body) +} + /// A file of `version` holding `content` as the program of that version saves it: a RIFF file /// before 14, then a package (R25, R26). pub fn file_of(version: u16, content: Vec) -> Vec { diff --git a/crates/cdr/tests/it/read.rs b/crates/cdr/tests/it/read.rs index fd267c833d..874932c8bf 100644 --- a/crates/cdr/tests/it/read.rs +++ b/crates/cdr/tests/it/read.rs @@ -1246,6 +1246,27 @@ fn a_container_clips_the_group_it_names() { } } +/// The feature sample, the seed of the importer's fuzz tests, reads its style table, PowerClip and +/// lens in every version from 7 to 13, plain and compressed. +#[test] +fn the_feature_sample_reads_its_styles_powerclip_and_lens() { + for version in [700, 800, 900, 1000, 1100, 1200, 1300] { + for compress in [false, true] { + let d = read(&synth::feature_sample(version, compress), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let objects = &d.pages[0].layers[0].objects; + let [Object::Shape(styled), Object::Clip { objects: clipped, .. }, Object::Shape(_)] = objects.as_slice() else { + panic!("{version}: {objects:?}") + }; + assert_eq!(styled.fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{version}"); + assert!(styled.outline.as_ref().is_some_and(|o| o.dashes == [3.0, 1.0]), "{version}"); + let s = shapes(clipped); + assert_eq!(s.len(), 2, "{version}"); + assert!(s[1].outline.as_ref().is_some_and(|o| o.behind_fill), "{version}"); + assert_eq!(d.warnings, vec![Warning::Lenses], "{version} {compress}"); + } + } +} + /// A container whose group isn't there is damage, and one whose group holds a container naming /// it again is read once, with the limit warning; the containers stay as plain shapes. #[test] diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index d538db4b1d..8f1d306b06 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -278,14 +278,25 @@ proptest! { fn cdr_mutated_drawings_render_and_export( version in prop::sample::select(vec![300u16, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300]), compress: bool, + features: bool, cut in 12usize..8192, edits in prop::collection::vec((0usize..8192, any::()), 0..24), ) { - let mut bytes = vectorcraft_cdr::synth::sample(version, compress && version >= 700); + // The feature sample adds a style table, a PowerClip and a lens to the shapes. + let compress = compress && version >= 700; + let mut bytes = + if features { vectorcraft_cdr::synth::feature_sample(version, compress) } else { vectorcraft_cdr::synth::sample(version, compress) }; let n = bytes.len(); for (at, b) in edits { bytes[at % n] = b; } bytes.truncate(cut); survive("CDR drawing", || vectorcraft_engine::cmd::fileio::load("x.cdr", &bytes).ok().map(|l| l.doc))?; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let p = json!({"name":"x.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "CDR drawing placement panicked: {:?}", r.err()); } #[test] From 75ac55b32aa475c0bfdb37ce6ba9e2ded33a45d7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 14:07:48 -0800 Subject: [PATCH 16/34] .cdr import: an ellipse of version 1 or 2 without its angles is damage A drawn ellipse whose record ends before its two angles came in as a whole ellipse with no warning; it is now left out as damage. The file format table now says that version 3 envelopes are not applied and the objects under them are kept, and gives one count of the formats opened. PROVENANCE.md, the crate README and docs/mcp.md now say which parts of versions 1 to 4 public specifications cover. --- crates/cdr/PROVENANCE.md | 4 +++- crates/cdr/README.md | 5 +++-- crates/cdr/src/wl.rs | 18 ++++++++++++++++-- docs/file-format-parity.md | 4 ++-- docs/mcp.md | 2 +- 5 files changed, 25 insertions(+), 8 deletions(-) diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 11bae00fb3..3940913f31 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -40,7 +40,9 @@ Status: `public-spec` (K, KR, Z, F or PR), `sample` (S), `unconfirmed` (a point and no sample file shows; listed so it can be checked against a file, with what the reader does when it is wrong). -No public specification covers versions 1 to 4. Their rows rest on the sample files they name. +Public specifications cover only parts of versions 1 to 4: the rows that cite K, F or PR, such as +the version 3 fill (R34) and page settings (R38). The other rows of those versions rest on the +sample files they name. The test inputs are the synthetic files that `src/synth.rs` builds from the rows below; no sample file is committed. diff --git a/crates/cdr/README.md b/crates/cdr/README.md index c30cb7d1b3..8a6b19d281 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -32,8 +32,9 @@ that are encrypted, ZIP64 archives or split across files. ## Versions 1 to 4 -No public specification covers these versions. The reader follows the layouts of public sample -files that `PROVENANCE.md` lists (rows R31 to R44), and its tests read the synthetic files that +Public specifications cover only parts of these versions, such as the version 3 fill and page +settings. For the rest, the reader follows the layouts of public sample files that +`PROVENANCE.md` lists (rows R31 to R44), and its tests read the synthetic files that `src/synth.rs` builds from those rows. | Version | Read | Left out or refused | diff --git a/crates/cdr/src/wl.rs b/crates/cdr/src/wl.rs index ed6bae1ca2..3ca20a1111 100644 --- a/crates/cdr/src/wl.rs +++ b/crates/cdr/src/wl.rs @@ -159,8 +159,9 @@ fn shape(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mu let mut s = Rd::new(body); let (w, h) = (coord(&mut s, p)?, coord(&mut s, p)?); // Two angles follow. No source confirms how they make an arc, so an ellipse whose - // angles differ is left out. - if matches!((s.i16(), s.i16()), (Some(from), Some(to)) if from != to) { + // angles differ is left out; one whose angles are missing is damage. + let (from, to) = (s.i16()?, s.i16()?); + if from != to { push(warn, Warning::UnsupportedObjects); return Some(None); } @@ -320,6 +321,19 @@ mod tests { assert_eq!(d.warnings, vec![Warning::Damaged]); } + #[test] + fn an_ellipse_without_its_angles_is_damage() { + let ellipse = + synth::wl_object(WlShape::Ellipse { w: 72.0, h: 36.0, angles: (0, 0) }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([1, 0, 0, 0, 100]), None); + let mut cut = ellipse.clone(); + // A body size that ends the record after the ellipse's width and height. + cut[28..30].copy_from_slice(&((Fields::of(b'e').least() - AFTER_BODY) as u16).to_le_bytes()); + cut.truncate(Fields::of(b'e').least()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[ellipse, cut])).unwrap(); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); + assert_eq!(d.warnings, vec![Warning::Damaged]); + } + #[test] fn fill_types_other_than_uniform_and_unknown_inks_are_named() { let mut textured = diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index f12e8ad579..7069934a73 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -21,7 +21,7 @@ Ordinary File > Save offers Save As when its own location refuses writes with a |---|---:|---:|---| | Formats opened or placed | ~30 | 31 | missing: FreeHand, DWG, PICT, PS | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, artboards) or as legacy version 7 (layers and groups, one artboard per file) | -| Formats opened or placed | ~30 | 29 | missing: FreeHand, CorelDRAW, DWG, HEIC/HEIF, PICT, PS | +| Formats opened or placed | ~30 | 30 | missing: FreeHand, DWG, HEIC/HEIF, PICT, PS | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, gradients, patterns, images, type, symbols, artboards, transparency, opacity masks, clipping) or as legacy version 7 (layers and groups, one artboard per file) | | Formats exported | ~16 | 18 | missing: DWG; extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | | **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting | @@ -308,7 +308,7 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | PICT | open, place (legacy) | no | no | rarely used | | Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` | | FreeHand `.fh*` | open (legacy) | no | no | | -| `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, PowerClips, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses and object transparency are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies, and version 3 objects under an envelope are left out with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; record layouts and their sources in `crates/cdr/PROVENANCE.md`; synthetic test files only; tests in `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` | +| `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, PowerClips, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses and object transparency are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies; version 3 envelopes are not applied, so the objects and groups under one keep their outlines and matrices, with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; record layouts and their sources in `crates/cdr/PROVENANCE.md`; synthetic test files only; tests in `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` | | Text `.txt` | place, export | place (Text Import Options) | yes | | | RTF `.rtf` | place | place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only | | Word `.docx` | place | place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out | diff --git a/docs/mcp.md b/docs/mcp.md index e13de2367c..1718e45a27 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6856,7 +6856,7 @@ transparency are not applied. The `warnings` of were left out. Drawings of versions after 27 are refused with a message, and so are packages that are encrypted, ZIP64 archives or split across files. VectorCraft doesn't write `.cdr` files. -No public specification covers versions 1 to 4, so the importer reads the layouts found in public sample files. A +Public specifications cover only parts of versions 1 to 4, so for the rest the importer reads the layouts found in public sample files. A drawing of version 1 or 2 opens as one page with one layer: its rectangles, whole ellipses and curves with their matrices, uniform fills and outlines with their width and color. Its text, its arcs and pies, and its fills of other types are left out with the same warnings, and its groups are not kept. An object of another type ends the read of From fdbdbe8696b693ce174a4bb65bcf91845105fcdb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 14:27:57 -0800 Subject: [PATCH 17/34] .cdr import: read the chunks of a style list before version 7 Before version 7 a LIST stlt holds chunks, not the style table, but the index left every such list unsplit, so fills and outlines kept there were not found. The index now splits it by the drawing's version, the one its first vrsn chunk names, once all of the file's own chunks are read. --- crates/cdr/src/build.rs | 22 ++++++------------- crates/cdr/src/riff.rs | 31 +++++++++++++++++++++++++-- crates/cdr/tests/it/read.rs | 42 +++++++++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 18 deletions(-) diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs index a89342c1f3..c2766cad76 100644 --- a/crates/cdr/src/build.rs +++ b/crates/cdr/src/build.rs @@ -62,7 +62,7 @@ const MAX_CLIP_DEPTH: usize = 64; pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec) -> Result { let root = ix.root().ok_or(Error::NotCdr)?; - let version = version(ix, root); + let version = ix.version(); // A template whose `vrsn` chunk doesn't name a version read (R28). if version == 0 { return Err(Error::NotCdr); @@ -133,20 +133,6 @@ pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec) Ok(Drawing { version, page_size, pages, master, guides, warnings: std::mem::take(cx.warn) }) } -/// The version: the `vrsn` chunk's when it names one from 3 to 27, else the form type's (R1, R2). -/// A template's form type names no version, so its `vrsn` chunk decides whatever it names (R28). -/// Letters count differently from the version 24 update on (R1), so when both name a version -/// after 27 the `vrsn` chunk's is the one refused. -fn version(ix: &Index, root: &Chunk) -> u16 { - let vrsn = ix.children(root).iter().find(|c| &c.id == b"vrsn").and_then(|c| Rd::new(ix.data(c)).u16()); - match vrsn { - Some(v) if (layout::OLDEST_RIFF..=layout::NEWEST).contains(&v) => v, - Some(v) if ix.form_version == 0 => v, - Some(v) if v > layout::NEWEST && ix.form_version > layout::NEWEST => v, - _ => ix.form_version, - } -} - #[derive(Default)] struct Found<'i> { fills: Vec<&'i Chunk>, @@ -168,7 +154,11 @@ fn collect<'i>(ix: &'i Index, root: &'i Chunk, found: &mut Found<'i>) { b"outl" => found.outlines.push(c), b"mcfg" => found.mcfg = found.mcfg.or(Some(c)), b"guid" => found.guid = found.guid.or(Some(c)), - _ if c.is_list(b"stlt") => found.stlt = found.stlt.or(Some(c)), + // Before version 7 the list holds chunks, which are looked through. + _ if c.is_list(b"stlt") => { + found.stlt = found.stlt.or(Some(c)); + stack.extend(ix.children(c).iter().rev()); + } _ if c.is_list(b"clpt") => found.clpt.push(c), _ if c.is_list(b"page") => found.pages.push(c), _ => stack.extend(ix.children(c).iter().rev()), diff --git a/crates/cdr/src/riff.rs b/crates/cdr/src/riff.rs index 3417c61b4a..584df2e264 100644 --- a/crates/cdr/src/riff.rs +++ b/crates/cdr/src/riff.rs @@ -7,6 +7,7 @@ use std::collections::BTreeMap; use std::io::Read as _; use crate::bytes::{Rd, u32_at}; +use crate::layout; use crate::limits::Budget; use crate::package::Streams; use crate::{Error, Warning}; @@ -58,6 +59,9 @@ pub(crate) struct Index<'a> { leaves: Cell>, /// Bytes that redirects to bytes another chunk already took may still read. shared_left: Cell, + /// The first `vrsn` chunk among the file's own chunks, once seen, and the version it names + /// (`None` when it can't be read) (R2). + vrsn: Option>, } /// A list still to be split into its children. @@ -139,6 +143,7 @@ impl<'a> Index<'a> { lists: Cell::default(), leaves: Cell::default(), shared_left: Cell::new(budget.limits.member), + vrsn: None, }; ix.chunks.push(Chunk { id: *b"RIFF", form, src: 0, start: 12, len: 0, first: 0, count: 0 }); let mut queue = vec![Pending { entry: 0, src: 0, start: 12, end, pool: None, depth: 0 }]; @@ -195,6 +200,19 @@ impl<'a> Index<'a> { self.chunks.first() } + /// The version: the `vrsn` chunk's when it names one from 3 to 27, else the form type's (R1, + /// R2). A template's form type names no version, so its `vrsn` chunk decides whatever it names + /// (R28). Letters count differently from the version 24 update on (R1), so when both name a + /// version after 27 the `vrsn` chunk's is the one refused. + pub(crate) fn version(&self) -> u16 { + match self.vrsn.flatten() { + Some(v) if (layout::OLDEST_RIFF..=layout::NEWEST).contains(&v) => v, + Some(v) if self.form_version == 0 => v, + Some(v) if v > layout::NEWEST && self.form_version > layout::NEWEST => v, + _ => self.form_version, + } + } + /// The warnings for data streams that were left out. pub(crate) fn stream_warnings(&self, warn: &mut Vec) { if let Some(s) = &self.streams { @@ -228,8 +246,11 @@ impl<'a> Index<'a> { continue; } }; - // A `LIST stlt` holds the style tables, not chunks (R4); its body is read whole (R45). - if chunk.id == LIST && chunk.form != *b"stlt" { + if p.entry == 0 && chunk.id == *b"vrsn" && self.vrsn.is_none() { + let at = chunk.start as usize; + self.vrsn = Some(self.span(chunk.src, at, at + chunk.len as usize).and_then(|b| Rd::new(b).u16())); + } + if chunk.id == LIST { lists.push(self.chunks.len()); } self.chunks.push(chunk); @@ -241,6 +262,12 @@ impl<'a> Index<'a> { } for i in lists { let Some(c) = self.chunks.get(i).copied() else { continue }; + // From version 7 a `LIST stlt` holds the style tables, not chunks (R4); its body is read + // whole (R45). Before version 7 it holds chunks. The file's own chunks, its `vrsn` + // among them, are all read before this. + if c.form == *b"stlt" && self.version() >= 700 { + continue; + } if p.depth + 1 > budget.limits.depth { push(warn, Warning::TooDeep); continue; diff --git a/crates/cdr/tests/it/read.rs b/crates/cdr/tests/it/read.rs index 874932c8bf..8ac2394400 100644 --- a/crates/cdr/tests/it/read.rs +++ b/crates/cdr/tests/it/read.rs @@ -1136,6 +1136,28 @@ fn a_style_table_list_is_not_read_as_chunks() { assert!(d.page_size.is_some_and(|(w, h)| (w - 100.0).abs() < 0.01 && (h - 50.0).abs() < 0.01)); } +/// Before version 7 a `LIST stlt` holds chunks (R4), which are read like the document's others. +#[test] +fn a_style_list_before_version_7_is_read_as_chunks() { + for version in [400, 500, 600] { + let v = V(version); + let red = if version < 500 { synth::color4(1, [0, 100, 100, 0]) } else { synth::color(5, [0, 0, 255, 0]) }; + let styles = list(b"stlt", vec![list(b"filt", vec![chunk(b"fill", v.fill(1, &red))])]); + let rect = synth::object(v, 1, &[(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect])]); + let content = vec![list(b"doc ", vec![styles]), page]; + let d = read(&synth::file_of(version, content.clone()), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s[0].fill.is_some(), "{version}"); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + // A template, whose form type names no version, by its `vrsn` chunk. + let mut template = synth::file_of(version, content); + template[8..12].copy_from_slice(b"CDTA"); + let d = read(&template, Limits::default()).unwrap(); + assert!(shapes(&d.pages[0].layers[0].objects)[0].fill.is_some(), "{version}"); + } +} + /// The objects of a styled drawing: a rectangle with only its style (argument 200), one whose /// style leaves the fill and outline to its parent, and one with an outline argument of its own. fn graphic_style_drawing(version: u16, table: synth::Node) -> Vec { @@ -1191,6 +1213,26 @@ fn objects_without_their_own_fill_or_outline_take_their_styles() { } } +/// A template whose style table comes before its `vrsn` chunk still reads the table by the +/// version that chunk names. +#[test] +fn a_style_table_before_the_version_chunk_reads_by_that_version() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + let table = synth::stlt(V(1000), &[(0x100, 1)], &[(0x200, 2)], &styles, true); + let mut file = graphic_style_drawing(1000, chunk(b"junk", vec![])); + // The drawing's chunks, the table put first, ahead of `vrsn`. + let body = file.split_off(12); + file.extend(synth::plain(&table)); + file.extend(body); + file[8..12].copy_from_slice(b"CDTA"); + let len = (file.len() - 8) as u32; + file[4..8].copy_from_slice(&len.to_le_bytes()); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].fill, Some(Color::Rgb([1.0, 0.0, 0.0]))); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); +} + /// A style table that doesn't parse to its end is damage when an object needs a style from it; /// the object is drawn with what it holds itself. #[test] From 206f36f1dfbf859b732d3440ff7b48320b379ba5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 14:42:54 -0800 Subject: [PATCH 18/34] .cdr import: describe clipping containers and their sources by what they hold The docs, comments and PROVENANCE.md rows R45 to R48 name clipping containers by what they do, and cite the sample files without a vendor prefix in their names. --- crates/cdr/PROVENANCE.md | 8 ++++---- crates/cdr/README.md | 2 +- crates/cdr/src/model.rs | 2 +- crates/cdr/src/synth.rs | 2 +- crates/cdr/tests/it/read.rs | 6 +++--- crates/engine/tests/import_fuzz.rs | 2 +- docs/file-format-parity.md | 2 +- docs/mcp.md | 4 ++-- docs/target-app-parity.md | 2 +- 9 files changed, 15 insertions(+), 15 deletions(-) diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 3940913f31..7c79cd3c8c 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -92,8 +92,8 @@ file is committed. | R42 | The records of a file of version 1 or 2 run from the front of the stacking order to the back. Every record starts with the u32 24. A group or layer record is 28 bytes, and bit 0x40 of its flags byte at 26 is clear. A drawn object has that bit set (0x40 in files with the markers `e` and `m`, 0xc0 with `l`) and a u16 body size at byte 28; it is the body size plus 32 bytes long. A drawn object of another type than those of R43 gives its length otherwise, and the records after it are not read | S: TP `WI.CDR`, `FLAG.CDR`, `MENU.CDR` and `DRINKS.CDR`; the order checked against the picture of `MENU.CDR` | sample | | R43 | A drawn object of version 1 or 2: a point (two i16) at byte 32; six i32 in 16.16 fixed point at 36, `a b tx c d ty`, with x' = a x + b y + tx + the point's x and y' = c x + d y + ty + the point's y; the object type at 60 (0 rectangle, 1 ellipse, 2 curve, 3 text); a byte at 67 that is not 0 when the object is outlined, the outline's width (u16) at 68 and its color at 74; the fill type (0 none, 1 uniform) and its color after it, at 94 and 95 with the marker `e` and at 105 and 106 with `l` and `m`; the shape from byte 114 with `e` and 136 with `l` and `m`. Colors are as R36 | S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`) and `MENU.CDR` (`l`), checked against the pictures of `FLAG.CDR` and `MENU.CDR` | sample | | R44 | Shapes of version 1 or 2: a rectangle's width and height (i16), then a corner radius; an ellipse's width and height, then two angles; a curve's point list as R39 and R16 | S: rectangles in TP `FLAG.CDR`, ellipses and curves in TP `WI.CDR`, curves in TP `MENU.CDR` | sample (the radius of files with the marker `e`, which no sample shows, and how the angles make an arc: unconfirmed; a radius is kept only when it is at most half the shorter side, and an ellipse whose angles differ is left out with a warning) | -| R45 | `LIST stlt` from version 7: a u32 style count, and when it is not 0: the fill table (a u32 count, entries of a table id, 4 bytes and a `fild` id, 12 bytes each, 60 from version 13), the outline table (12-byte entries laid out the same way, naming `outl` ids), the text tables (fonts of 44 bytes, 60 from version 10; alignments of 12; spacings of 52; tables of 152 and 784; bullets whose length a u32 inside them sets; indents of 28; hyphenation of 32, 36 from 13; drop caps of 28; from 8.01 a table of 12), then the styles: kind (u32), id, parent id, 8 bytes, name length and name (bytes before 12, UTF-16 units from it), the fill and outline table ids, then 16 bytes (20 from 8.01) for kinds above 1 and 20 more for kinds above 2. An object names its style in argument 200 (u32). An object without argument 20 or 10 takes the fill or outline of its style; a style whose table id is 0 takes its parent's | K L593-L600, L852, L1926-L2198; S: UC `corel_rounded_rect_cdr7.cdr`, whose rectangles carry argument 200 and neither 10 nor 20, and name the style whose outline is a black hairline and whose fill is none, as the file's picture shows; the table parses exactly to the end of the list in each of the 498 sample files of versions 7 to 15 that has one, and every object with argument 200 in them names a style whose table ids are in the tables | public-spec (what the table ids name, and that an object takes its style's fill and outline: sample; a style taking its parent's entry: unconfirmed, as only text styles in the samples leave theirs to the parent, and a wrong guess draws a shape without that fill or outline) | -| R46 | A container (a PowerClip) carries argument 8005; its first u32 is the id that the `spnd` chunk (a u32) of one `LIST grp ` in the document's `LIST clpt` holds. That group's objects are the ones the container clips; they keep their own transforms, in page space like the container's | K L252, L860-L862, L1895-L1901 (the argument and the chunk); S: UC `corel_powerclip_cdr7.cdr` to `corel_powerclip_x3.cdr` (versions 7 to 13) and LT `powerclipsquare_blackfill_whiterectangleinside` of `testset/12` to `testset/25`, in each of which the id in argument 8005 matches one group's `spnd`; in `corel_powerclip_cdr7.cdr` the group's box, -1.96 to 1.97 inches across, overlaps the container's, -1.81 to 1.84 inches, and the file's picture shows the group cut to the container | public-spec (what the id names, and the space of the group's objects: sample) | -| R47 | Argument 8000 marks an object seen through: a lens or a transparency. The reader does not apply it, and names lenses in the warnings | K L859 (the argument); S: of the sample files of versions 7 to 25, the argument is on the see-through objects that the pictures of UC `corel_lens_test_cdr7.cdr` to `corel_lens_test_x3.cdr`, LT `square_blackfill_nooutline_transparency50percent` of `testset/12` to `testset/25` and TDF 80103 show, and otherwise only on text in UC `fancytext_cdr7.cdr` to `fancytext_x3.cdr` and on two objects of TDF 114901. The value K reads at byte 10 (14 from version 13) is not the transparency in these samples | public-spec (the argument: K; what it marks: sample; its layout: unconfirmed, and it is not read) | -| R48 | Bit 2 (0x04) of the outline's line type marks the outline dashed; the dashes of an outline without it are not drawn | S: every outline of versions 6 to 25 in the sample files with that bit set stores dashes, such as the dashed lines of UC `corel_dashes_cdr7.cdr` to `corel_dashes_x3.cdr`; TDF 76771 (version 15) stores dashes 2 and 1 in an outline of line type 0x22, and the file's picture draws that outline solid | sample | +| R45 | `LIST stlt` from version 7: a u32 style count, and when it is not 0: the fill table (a u32 count, entries of a table id, 4 bytes and a `fild` id, 12 bytes each, 60 from version 13), the outline table (12-byte entries laid out the same way, naming `outl` ids), the text tables (fonts of 44 bytes, 60 from version 10; alignments of 12; spacings of 52; tables of 152 and 784; bullets whose length a u32 inside them sets; indents of 28; hyphenation of 32, 36 from 13; drop caps of 28; from 8.01 a table of 12), then the styles: kind (u32), id, parent id, 8 bytes, name length and name (bytes before 12, UTF-16 units from it), the fill and outline table ids, then 16 bytes (20 from 8.01) for kinds above 1 and 20 more for kinds above 2. An object names its style in argument 200 (u32). An object without argument 20 or 10 takes the fill or outline of its style; a style whose table id is 0 takes its parent's | K L593-L600, L852, L1926-L2198; S: UC `outl_width_cdr7.cdr`, one of whose lines carries argument 200 and neither 10 nor 20 and names the style whose outline is black and 0.003 inch wide and whose fill is none, as the file's picture shows; the table parses exactly to the end of the list in each of the 498 sample files of versions 7 to 15 that has one, and every object with argument 200 in them names a style whose table ids are in the tables | public-spec (what the table ids name, and that an object takes its style's fill and outline: sample; a style taking its parent's entry: unconfirmed, as only text styles in the samples leave theirs to the parent, and a wrong guess draws a shape without that fill or outline) | +| R46 | A clipping container carries argument 8005; its first u32 is the id that the `spnd` chunk (a u32) of one `LIST grp ` in the document's `LIST clpt` holds. That group's objects are the ones the container clips; they keep their own transforms, in page space like the container's | K L252, L860-L862, L1895-L1901 (the argument and the chunk); S: LT `powerclipsquare_blackfill_whiterectangleinside` of `testset/12` to `testset/25` and eight UC files of versions 7 to 13, in each of which the id in argument 8005 matches one group's `spnd`; in the UC file of version 7 the group's box, -1.96 to 1.97 inches across, overlaps the container's, -1.81 to 1.84 inches, and the file's picture shows the group cut to the container | public-spec (what the id names, and the space of the group's objects: sample) | +| R47 | Argument 8000 marks an object seen through: a lens or a transparency. The reader does not apply it, and names lenses in the warnings | K L859 (the argument); S: of the sample files of versions 7 to 25, the argument is on the see-through objects that the pictures of LT `square_blackfill_nooutline_transparency50percent` of `testset/12` to `testset/25`, TDF 80103 and eight UC lens test files of versions 7 to 13 show, and otherwise only on text in UC `fancytext_cdr7.cdr` to `fancytext_x3.cdr` and on two objects of TDF 114901. The value K reads at byte 10 (14 from version 13) is not the transparency in these samples | public-spec (the argument: K; what it marks: sample; its layout: unconfirmed, and it is not read) | +| R48 | Bit 2 (0x04) of the outline's line type marks the outline dashed; the dashes of an outline without it are not drawn | S: every outline of versions 6 to 25 in the sample files with that bit set (316 of them, in 29 files) stores dashes; TDF 76771 (version 15) stores dashes 2 and 1 in an outline of line type 0x22, and the file's picture draws that outline solid | sample | | R49 | Bit 4 (0x10) of the outline's line type puts the outline behind the fill | S: UC `outl_behind_fill_cdr7.cdr` to `outl_behind_fill_x3.cdr`, whose outline of line type 0x12 the file's picture shows behind the fill, and whose other outlines (0x02) it shows over the fill | sample | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index 8a6b19d281..266dd35638 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -15,7 +15,7 @@ with each object's transform. It does not write `.cdr` files. | Layers (drawing, desktop, guides and grid layers), the master page's among them | layers by name and kind | | Guidelines (object type 0x16, and the version 7 `guid` chunk) | guidelines at their point and angle | | Groups (`LIST grp `) | groups | -| PowerClip containers and the groups of `LIST clpt` they clip | the container with the objects it clips | +| Clipping containers and the groups of `LIST clpt` they clip | the container with the objects it clips | | Curves (point lists of moves, lines and cubic curves) and paths (object type 0x25, version 10 on) | paths | | Rectangles (one corner radius, four from version 9) | rectangles with each corner's radius | | Ellipses, arcs and pies | ellipses, and paths for arcs and pies | diff --git a/crates/cdr/src/model.rs b/crates/cdr/src/model.rs index 06c9ddcb85..cd3946ab7d 100644 --- a/crates/cdr/src/model.rs +++ b/crates/cdr/src/model.rs @@ -121,7 +121,7 @@ pub struct Shape { pub enum Object { Shape(Box), Group(Vec), - /// A container and the objects it clips (a PowerClip): `objects` (front to back) show only + /// A clipping container and the objects it clips: `objects` (front to back) show only /// inside the container's shape, with its fill behind them and its outline over them. Clip { container: Box, diff --git a/crates/cdr/src/synth.rs b/crates/cdr/src/synth.rs index 4f3ff0b05e..63f602b16c 100644 --- a/crates/cdr/src/synth.rs +++ b/crates/cdr/src/synth.rs @@ -588,7 +588,7 @@ pub fn container(id: u32) -> (u32, Vec) { (8005, [id, 1, 0, 1].iter().flat_map(|v| v.to_le_bytes()).collect()) } -/// A RIFF drawing of `version` (7 to 13) with a style table, a PowerClip and a lens: a rectangle +/// A RIFF drawing of `version` (7 to 13) with a style table, a clipping container and a lens: a rectangle /// that takes its fill and outline from its style, a container that clips two rectangles, one /// with an outline behind the fill, and a rectangle with a lens; compressed when `compress`. /// Before version 7, the [`sample`]. diff --git a/crates/cdr/tests/it/read.rs b/crates/cdr/tests/it/read.rs index 8ac2394400..1705e14439 100644 --- a/crates/cdr/tests/it/read.rs +++ b/crates/cdr/tests/it/read.rs @@ -1288,10 +1288,10 @@ fn a_container_clips_the_group_it_names() { } } -/// The feature sample, the seed of the importer's fuzz tests, reads its style table, PowerClip and -/// lens in every version from 7 to 13, plain and compressed. +/// The feature sample, the seed of the importer's fuzz tests, reads its style table, clipping +/// container and lens in every version from 7 to 13, plain and compressed. #[test] -fn the_feature_sample_reads_its_styles_powerclip_and_lens() { +fn the_feature_sample_reads_its_styles_container_and_lens() { for version in [700, 800, 900, 1000, 1100, 1200, 1300] { for compress in [false, true] { let d = read(&synth::feature_sample(version, compress), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 8f1d306b06..a26bfe3b09 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -282,7 +282,7 @@ proptest! { cut in 12usize..8192, edits in prop::collection::vec((0usize..8192, any::()), 0..24), ) { - // The feature sample adds a style table, a PowerClip and a lens to the shapes. + // The feature sample adds a style table, a clipping container and a lens to the shapes. let compress = compress && version >= 700; let mut bytes = if features { vectorcraft_cdr::synth::feature_sample(version, compress) } else { vectorcraft_cdr::synth::sample(version, compress) }; diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 7069934a73..5bbce826c2 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -308,7 +308,7 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | PICT | open, place (legacy) | no | no | rarely used | | Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` | | FreeHand `.fh*` | open (legacy) | no | no | | -| `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, PowerClips, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses and object transparency are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies; version 3 envelopes are not applied, so the objects and groups under one keep their outlines and matrices, with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; record layouts and their sources in `crates/cdr/PROVENANCE.md`; synthetic test files only; tests in `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` | +| `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, clipping containers, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses and object transparency are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies; version 3 envelopes are not applied, so the objects and groups under one keep their outlines and matrices, with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; record layouts and their sources in `crates/cdr/PROVENANCE.md`; synthetic test files only; tests in `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` | | Text `.txt` | place, export | place (Text Import Options) | yes | | | RTF `.rtf` | place | place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only | | Word `.docx` | place | place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out | diff --git a/docs/mcp.md b/docs/mcp.md index 1718e45a27..329f549ba1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6842,8 +6842,8 @@ its pixels are decoded. `file.place {path}` links the file like any image. Vecto `.cdr` drawings of versions 1 to 27 (and `.cdt` templates, which open as a new untitled document) open and place as editable art, the ZIP packages that versions 14 and later save included. Each page becomes an artboard, side by side. Layers of the same name on different pages become one layer when the pages stack them in the same order, and -the master page's guidelines become guides on every page. Groups stay groups, and a PowerClip becomes a clipping -group whose clipping path keeps the container's fill and outline. Curves, paths, arcs and polygons (stars +the master page's guidelines become guides on every page. Groups stay groups, and a container with the objects it clips +becomes a clipping group whose clipping path keeps the container's fill and outline. Curves, paths, arcs and polygons (stars included) become paths, and rectangles and ellipses become live shapes; a rectangle keeps each corner's radius. Uniform fills and outlines keep their colors, widths, caps, joins and dashes (an outline of width 0 becomes a 0.25 pt stroke), an outline behind the fill becomes a stroke below the fill, and an object without a fill or outline of its own diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7a6ad6368b..0b88575973 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1542,7 +1542,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, PowerClips (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill where the file says so), an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, object transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). + - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill where the file says so), an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, object transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. EPS and PostScript `.ai` files are still embedded (`crates/engine/src/tests/placed_document.rs`). From abbf611467411336766a190d3bacad098b2733e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 15:00:48 -0800 Subject: [PATCH 19/34] i18n: translate the CDR lenses warning Every complete catalog gets the warning a CDR import gives for lenses and object transparency, and the test of the CDR import notes checks it. --- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + 23 files changed, 23 insertions(+) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 65b8589783..efe0e83279 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6698,6 +6698,7 @@ breakText Glyphs Glifs @msg CDR library colors that the drawing stores only by number were opened as black spot colors els colors de biblioteca del CDR que el dibuix desa només pel número s’han obert com a colors directes negres @msg CDR outline arrowheads were left out s’han omès les puntes de fletxa dels contorns del CDR @msg CDR envelopes were not applied, and the shapes under them keep their outlines no s’han aplicat les envoltants del CDR, i les formes que hi ha a sota conserven els seus contorns +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque no s’han aplicat les lents ni la transparència dels objectes del CDR, i els objectes on són es mostren opacs @msg parts of the drawing nested too deeply, or past the import limits, were left out s’han omès les parts del dibuix imbricades massa a fons o fora dels límits d’importació @msg damaged parts of the drawing were left out s’han omès les parts danyades del dibuix @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard les pàgines del CDR de més de 163.830 pt s’han obert amb aquesta longitud, i el dibuix a prop de les vores queda fora del tauler diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 1d019853a5..2bee72600f 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5328,6 +5328,7 @@ imageTrace Outline Obrys @msg CDR library colors that the drawing stores only by number were opened as black spot colors knihovní barvy CDR, které výkres ukládá jen číslem, byly otevřeny jako černé přímé barvy @msg CDR outline arrowheads were left out šipky na obrysových čarách CDR byly vynechány @msg CDR envelopes were not applied, and the shapes under them keep their outlines obálky CDR nebyly použity a tvary pod nimi si ponechávají své obrysy +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque čočky a průhlednost objektů CDR nebyly použity a objekty, na kterých jsou, se zobrazují neprůhledně @msg parts of the drawing nested too deeply, or past the import limits, were left out části výkresu vnořené příliš hluboko nebo za hranicemi importu byly vynechány @msg damaged parts of the drawing were left out poškozené části výkresu byly vynechány @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard stránky CDR delší než 163 830 pt byly otevřeny v této délce a kresba u jejich okrajů leží mimo pracovní plochu diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 1d4dc2af43..a582b2a076 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5079,6 +5079,7 @@ theme Appearance Erscheinungsbild @msg CDR library colors that the drawing stores only by number were opened as black spot colors CDR-Bibliotheksfarben, die die Zeichnung nur als Nummer speichert, wurden als schwarze Volltonfarben geöffnet @msg CDR outline arrowheads were left out Pfeilspitzen an CDR-Umrisslinien wurden ausgelassen @msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR-Hüllen wurden nicht angewendet, und die Formen darunter behalten ihre Umrisse +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque CDR-Linsen und Objekttransparenz wurden nicht angewendet, und die Objekte, auf denen sie liegen, erscheinen deckend @msg parts of the drawing nested too deeply, or past the import limits, were left out Teile der Zeichnung, die zu tief verschachtelt sind oder die Importgrenzen überschreiten, wurden ausgelassen @msg damaged parts of the drawing were left out beschädigte Teile der Zeichnung wurden ausgelassen @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard CDR-Seiten, die länger als 163.830 pt sind, wurden in dieser Länge geöffnet, und Grafik nahe ihren Rändern liegt außerhalb der Zeichenfläche diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 4aeee667dc..c164b462e7 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5007,6 +5007,7 @@ digits Malayalam Μαλαγιάλαμ @msg CDR library colors that the drawing stores only by number were opened as black spot colors τα χρώματα βιβλιοθήκης του CDR που το σχέδιο αποθηκεύει μόνο με αριθμό ανοίχτηκαν ως μαύρα πλακάτα χρώματα @msg CDR outline arrowheads were left out παραλείφθηκαν οι αιχμές βελών των γραμμών περιγράμματος του CDR @msg CDR envelopes were not applied, and the shapes under them keep their outlines δεν εφαρμόστηκαν τα περιβλήματα του CDR, και τα σχήματα κάτω από αυτά διατηρούν τα περιγράμματά τους +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque δεν εφαρμόστηκαν οι φακοί και η διαφάνεια αντικειμένων του CDR, και τα αντικείμενα στα οποία βρίσκονται εμφανίζονται αδιαφανή @msg parts of the drawing nested too deeply, or past the import limits, were left out παραλείφθηκαν τμήματα του σχεδίου με υπερβολικά βαθιά ένθεση ή πέρα από τα όρια εισαγωγής @msg damaged parts of the drawing were left out παραλείφθηκαν κατεστραμμένα τμήματα του σχεδίου @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard οι σελίδες του CDR με μήκος πάνω από 163.830 pt ανοίχτηκαν σε αυτό το μήκος και το γραφικό κοντά στα άκρα τους βρίσκεται έξω από τον πίνακα σχεδίασης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index cd88d4b938..e3be641401 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5046,6 +5046,7 @@ axis Both Ambos @msg CDR library colors that the drawing stores only by number were opened as black spot colors los colores de biblioteca de CDR que el dibujo guarda solo por número se abrieron como tintas planas negras @msg CDR outline arrowheads were left out se omitieron las puntas de flecha de los contornos de CDR @msg CDR envelopes were not applied, and the shapes under them keep their outlines no se aplicaron las envolventes de CDR, y las formas que contienen conservan sus contornos +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque no se aplicaron las lentes ni la transparencia de objetos de CDR, y los objetos que las tienen se muestran opacos @msg parts of the drawing nested too deeply, or past the import limits, were left out se omitieron partes del dibujo anidadas a demasiada profundidad o fuera de los límites de importación @msg damaged parts of the drawing were left out se omitieron partes dañadas del dibujo @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard las páginas de CDR de más de 163.830 pt se abrieron con esa longitud, y el arte cerca de sus bordes queda fuera de la mesa de trabajo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a398d0e4f6..f5383fa59c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5230,6 +5230,7 @@ imageTrace Outline Ääriviiva @msg CDR library colors that the drawing stores only by number were opened as black spot colors CDR-kirjastovärit, jotka piirros tallentaa vain numerona, avattiin mustina spottiväreinä @msg CDR outline arrowheads were left out CDR-ääriviivojen nuolenkärjet jätettiin pois @msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR-verhokäyriä ei käytetty, ja niiden alla olevat muodot säilyttävät ääriviivansa +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque CDR-linssejä ja objektien läpinäkyvyyttä ei käytetty, ja objektit, joissa niitä on, näkyvät peittävinä @msg parts of the drawing nested too deeply, or past the import limits, were left out liian syvälle sisäkkäiset tai tuontirajojen ylittävät piirroksen osat jätettiin pois @msg damaged parts of the drawing were left out piirroksen vahingoittuneet osat jätettiin pois @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard yli 163 830 pt pitkät CDR-sivut avattiin tämän pituisina, ja niiden reunojen lähellä oleva grafiikka on piirtoalustan ulkopuolella diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4bc1284566..7a7c48d25e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5053,6 +5053,7 @@ axis Both Les deux @msg CDR library colors that the drawing stores only by number were opened as black spot colors les couleurs de bibliothèque CDR que le dessin enregistre uniquement par numéro ont été ouvertes comme tons directs noirs @msg CDR outline arrowheads were left out les pointes de flèche des contours CDR ont été ignorées @msg CDR envelopes were not applied, and the shapes under them keep their outlines les enveloppes CDR n’ont pas été appliquées, et les formes qu’elles contiennent gardent leurs contours +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque les lentilles et la transparence d’objet CDR n’ont pas été appliquées, et les objets qui les portent s’affichent opaques @msg parts of the drawing nested too deeply, or past the import limits, were left out les parties du dessin trop profondément imbriquées ou au-delà des limites d’importation ont été ignorées @msg damaged parts of the drawing were left out les parties endommagées du dessin ont été ignorées @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard les pages CDR de plus de 163 830 pt ont été ouvertes à cette longueur, et l’illustration proche de leurs bords se trouve hors du plan de travail diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 5d75e54e6e..6b82fca5e1 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7742,6 +7742,7 @@ antiAlias Sharp शार्प @msg CDR library colors that the drawing stores only by number were opened as black spot colors CDR लाइब्रेरी के जिन रंगों को ड्रॉइंग केवल संख्या से सहेजती है, वे काले स्पॉट रंगों के रूप में खोले गए @msg CDR outline arrowheads were left out CDR आउटलाइन के तीर-शीर्ष छोड़ दिए गए @msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR एनवेलप लागू नहीं किए गए, और उनके नीचे की आकृतियाँ अपनी आउटलाइन बनाए रखती हैं +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque CDR लेंस और ऑब्जेक्ट पारदर्शिता लागू नहीं की गई, और जिन ऑब्जेक्ट पर वे हैं वे अपारदर्शी दिखते हैं @msg parts of the drawing nested too deeply, or past the import limits, were left out ड्रॉइंग के बहुत गहराई तक नेस्ट किए गए या आयात सीमाओं से परे के हिस्से छोड़ दिए गए @msg damaged parts of the drawing were left out ड्रॉइंग के क्षतिग्रस्त हिस्से छोड़ दिए गए @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163,830 pt से लंबे CDR पेज उसी लंबाई पर खोले गए, और उनके किनारों के पास का आर्ट आर्टबोर्ड के बाहर है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 3dd4738d20..ecca299a07 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5563,6 +5563,7 @@ imageTrace Outline Körvonal @msg CDR library colors that the drawing stores only by number were opened as black spot colors a CDR könyvtári színei, amelyeket a rajz csak számként tárol, fekete direktszínként nyíltak meg @msg CDR outline arrowheads were left out kimaradtak a CDR körvonalainak nyílhegyei @msg CDR envelopes were not applied, and the shapes under them keep their outlines a CDR burkolók nem lettek alkalmazva, és az alattuk lévő alakzatok megtartják a körvonalukat +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque a CDR lencsék és objektumátlátszóság nem lettek alkalmazva, és az objektumok, amelyeken vannak, átlátszatlanul jelennek meg @msg parts of the drawing nested too deeply, or past the import limits, were left out kimaradtak a rajz túl mélyen egymásba ágyazott vagy az importálási korlátokon túli részei @msg damaged parts of the drawing were left out kimaradtak a rajz sérült részei @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard a 163 830 pt-nál hosszabb CDR-oldalak ekkora hosszal nyíltak meg, és a szélük közelében lévő grafika a rajztáblán kívül esik diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 9e95d70bb9..ff06ed4a50 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5097,6 +5097,7 @@ axis Both Entrambi @msg CDR library colors that the drawing stores only by number were opened as black spot colors i colori di libreria di CDR che il disegno salva solo per numero sono stati aperti come colori spot neri @msg CDR outline arrowheads were left out le punte di freccia dei contorni di CDR sono state omesse @msg CDR envelopes were not applied, and the shapes under them keep their outlines gli inviluppi di CDR non sono stati applicati, e le forme al loro interno mantengono i propri contorni +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque le lenti e la trasparenza degli oggetti di CDR non sono state applicate, e gli oggetti su cui si trovano appaiono opachi @msg parts of the drawing nested too deeply, or past the import limits, were left out le parti del disegno annidate troppo in profondità o oltre i limiti di importazione sono state omesse @msg damaged parts of the drawing were left out le parti danneggiate del disegno sono state omesse @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard le pagine di CDR più lunghe di 163.830 pt sono state aperte con quella lunghezza, e la grafica vicina ai loro bordi si trova fuori dalla tavola da disegno diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index b47b1239a7..0fef333284 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5138,6 +5138,7 @@ swatch Bright Violet ビビッドバイオレット @msg CDR library colors that the drawing stores only by number were opened as black spot colors 図面が番号だけで保存している CDR のライブラリカラーは黒の特色として開きました @msg CDR outline arrowheads were left out CDR のアウトラインの矢印は除外されました @msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR のエンベロープは適用されず、その下のシェイプは元のアウトラインのままです +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque CDR のレンズとオブジェクトの透明度は適用されず、それらがあるオブジェクトは不透明で表示されます @msg parts of the drawing nested too deeply, or past the import limits, were left out 入れ子が深すぎる図面の部分や読み込みの上限を超えた部分は除外されました @msg damaged parts of the drawing were left out 図面の破損した部分は除外されました @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163,830 pt より長い CDR のページはその長さで開いたため、端の近くのアートはアートボードの外にあります diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8d44662dcc..c82b437aba 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4745,6 +4745,7 @@ font-technology Variable ცვლადი @msg CDR library colors that the drawing stores only by number were opened as black spot colors CDR-ის ბიბლიოთეკის ფერები, რომლებსაც ნახაზი მხოლოდ ნომრით ინახავს, შავ სპოტ-ფერებად გაიხსნა @msg CDR outline arrowheads were left out CDR-ის მოხაზულობების ისრისპირები გამოტოვებულია @msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR-ის კონვერტები არ იქნა გამოყენებული, და მათ ქვეშ მყოფი ფორმები ინარჩუნებენ თავიანთ მოხაზულობას +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque CDR-ის ლინზები და ობიექტის გამჭვირვალობა არ იქნა გამოყენებული, და ობიექტები, რომლებზეც ისინია, გაუმჭვირვალედ ჩანს @msg parts of the drawing nested too deeply, or past the import limits, were left out ნახაზის ზედმეტად ღრმად ჩადგმული ან იმპორტის ლიმიტებს მიღმა არსებული ნაწილები გამოტოვებულია @msg damaged parts of the drawing were left out ნახაზის დაზიანებული ნაწილები გამოტოვებულია @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163 830 pt-ზე გრძელი CDR-ის გვერდები ამ სიგრძით გაიხსნა და მათ კიდეებთან ახლოს მყოფი გრაფიკა სამუშაო დაფის გარეთაა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index ada1ecc10e..1da37e894e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5065,6 +5065,7 @@ theme Appearance 외관 @msg CDR library colors that the drawing stores only by number were opened as black spot colors 도면이 번호로만 저장한 CDR 라이브러리 색상은 검정 별색으로 열었습니다 @msg CDR outline arrowheads were left out CDR 외곽선의 화살촉은 제외했습니다 @msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR 엔벨로프는 적용하지 않았으며, 그 아래의 도형은 원래 외곽선을 유지합니다 +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque CDR 렌즈와 개체 투명도는 적용하지 않았으며, 해당 개체는 불투명하게 표시됩니다 @msg parts of the drawing nested too deeply, or past the import limits, were left out 너무 깊이 중첩되었거나 가져오기 한도를 넘은 도면 부분은 제외했습니다 @msg damaged parts of the drawing were left out 도면의 손상된 부분은 제외했습니다 @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163,830pt보다 긴 CDR 페이지는 그 길이로 열었으며, 가장자리 근처의 아트는 아트보드 밖에 있습니다 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index b7f371ccc1..5f25ff15bc 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5154,6 +5154,7 @@ imageTrace Outline Kontur @msg CDR library colors that the drawing stores only by number were opened as black spot colors kolory z bibliotek CDR, które rysunek zapisuje tylko jako numer, otwarto jako czarne kolory dodatkowe @msg CDR outline arrowheads were left out pominięto groty strzałek na obrysach CDR @msg CDR envelopes were not applied, and the shapes under them keep their outlines obwiednie CDR nie zostały zastosowane, a kształty pod nimi zachowują swoje obrysy +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque soczewki i przezroczystość obiektów CDR nie zostały zastosowane, a obiekty, na których się znajdują, są wyświetlane jako nieprzezroczyste @msg parts of the drawing nested too deeply, or past the import limits, were left out pominięto części rysunku zagnieżdżone zbyt głęboko lub wykraczające poza limity importu @msg damaged parts of the drawing were left out pominięto uszkodzone części rysunku @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard strony CDR dłuższe niż 163 830 pt otwarto z tą długością, a grafika przy ich krawędziach leży poza obszarem kompozycji diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a292009e30..7197c3169c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4549,6 +4549,7 @@ axis Both Ambos @msg CDR library colors that the drawing stores only by number were opened as black spot colors cores de biblioteca do CDR que o desenho guarda apenas pelo número foram abertas como cores spot pretas @msg CDR outline arrowheads were left out as pontas de seta das linhas de contorno do CDR foram omitidas @msg CDR envelopes were not applied, and the shapes under them keep their outlines os envelopes do CDR não foram aplicados, e as formas sob eles mantêm seus contornos +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque as lentes e a transparência de objetos do CDR não foram aplicadas, e os objetos em que estão aparecem opacos @msg parts of the drawing nested too deeply, or past the import limits, were left out partes do desenho aninhadas profundamente demais ou além dos limites de importação foram omitidas @msg damaged parts of the drawing were left out partes danificadas do desenho foram omitidas @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard páginas do CDR com mais de 163.830 pt foram abertas com esse comprimento, e a arte perto das bordas fica fora da prancheta diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index dff5b64e39..46678a6700 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5085,6 +5085,7 @@ axis Both Оба @msg CDR library colors that the drawing stores only by number were opened as black spot colors библиотечные цвета CDR, которые рисунок хранит только по номеру, открыты как черные плашечные цвета @msg CDR outline arrowheads were left out наконечники стрелок абрисов CDR были пропущены @msg CDR envelopes were not applied, and the shapes under them keep their outlines оболочки CDR не были применены, и фигуры под ними сохраняют свои контуры +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque линзы и прозрачность объектов CDR не были применены, и объекты, к которым они относятся, отображаются непрозрачными @msg parts of the drawing nested too deeply, or past the import limits, were left out части рисунка со слишком глубокой вложенностью или за пределами ограничений импорта были пропущены @msg damaged parts of the drawing were left out поврежденные части рисунка были пропущены @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard страницы CDR длиннее 163 830 pt открыты с этой длиной, и графика у их краев находится за пределами монтажной области diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 11d2989636..a8866f610d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4961,6 +4961,7 @@ axis Both Båda @msg CDR library colors that the drawing stores only by number were opened as black spot colors CDR-biblioteksfärger som teckningen bara lagrar som nummer öppnades som svarta dekorfärger @msg CDR outline arrowheads were left out pilspetsar på CDR-linjer utelämnades @msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR-omslag tillämpades inte, och formerna under dem behåller sina konturer +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque CDR-linser och objekttransparens tillämpades inte, och objekten de ligger på visas ogenomskinliga @msg parts of the drawing nested too deeply, or past the import limits, were left out delar av teckningen som är för djupt nästlade eller ligger utanför importgränserna utelämnades @msg damaged parts of the drawing were left out skadade delar av teckningen utelämnades @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard CDR-sidor längre än 163 830 pt öppnades med den längden, och grafik nära deras kanter ligger utanför ritytan diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index e6d53b2ad3..132ca1c292 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1773,6 +1773,7 @@ fn cdr_import_notes_are_translated() { "CDR library colors that the drawing stores only by number were opened as black spot colors", "CDR outline arrowheads were left out", "CDR envelopes were not applied, and the shapes under them keep their outlines", + "CDR lenses and object transparency were not applied, and the objects they are on show opaque", "parts of the drawing nested too deeply, or past the import limits, were left out", "damaged parts of the drawing were left out", "CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard", diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 38fede40e3..7095792adc 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4791,6 +4791,7 @@ axis Both Her İkisi @msg CDR library colors that the drawing stores only by number were opened as black spot colors çizimin yalnızca numarayla sakladığı CDR kitaplık renkleri siyah nokta renkleri olarak açıldı @msg CDR outline arrowheads were left out CDR anahatlarının ok uçları dışarıda bırakıldı @msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR zarfları uygulanmadı ve altlarındaki şekiller anahatlarını korur +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque CDR mercekleri ve nesne saydamlığı uygulanmadı ve bulundukları nesneler opak görünür @msg parts of the drawing nested too deeply, or past the import limits, were left out çizimin fazla derin iç içe geçmiş veya içe aktarma sınırlarının ötesindeki kısımları dışarıda bırakıldı @msg damaged parts of the drawing were left out çizimin hasarlı kısımları dışarıda bırakıldı @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163.830 pt'den uzun CDR sayfaları bu uzunlukta açıldı ve kenarlarına yakın çizimler çalışma yüzeyinin dışında kalıyor diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 69ec093471..1bc0cc0149 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5081,6 +5081,7 @@ axis Both Обидві @msg CDR library colors that the drawing stores only by number were opened as black spot colors бібліотечні кольори CDR, які малюнок зберігає лише за номером, відкрито як чорні плашкові кольори @msg CDR outline arrowheads were left out наконечники стрілок абрисів CDR було пропущено @msg CDR envelopes were not applied, and the shapes under them keep their outlines оболонки CDR не було застосовано, і фігури під ними зберігають свої контури +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque лінзи та прозорість об’єктів CDR не було застосовано, і об’єкти, до яких вони належать, показано непрозорими @msg parts of the drawing nested too deeply, or past the import limits, were left out частини малюнка із надто глибоким вкладенням або поза межами обмежень імпорту було пропущено @msg damaged parts of the drawing were left out пошкоджені частини малюнка було пропущено @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard сторінки CDR, довші за 163 830 pt, відкрито з цією довжиною, і графіка біля їхніх країв лежить поза монтажною областю diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 27f86d56c3..9ce7d45c28 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5231,6 +5231,7 @@ theme Appearance Giao diện @msg CDR library colors that the drawing stores only by number were opened as black spot colors các màu thư viện CDR mà bản vẽ chỉ lưu theo số đã được mở thành màu đặc biệt đen @msg CDR outline arrowheads were left out các đầu mũi tên của đường viền CDR đã bị bỏ qua @msg CDR envelopes were not applied, and the shapes under them keep their outlines các bao hình CDR không được áp dụng, và các hình bên dưới vẫn giữ đường viền của chúng +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque thấu kính và độ trong suốt đối tượng CDR không được áp dụng, và các đối tượng có chúng hiển thị đục @msg parts of the drawing nested too deeply, or past the import limits, were left out các phần của bản vẽ lồng nhau quá sâu hoặc vượt quá giới hạn nhập đã bị bỏ qua @msg damaged parts of the drawing were left out các phần bị hỏng của bản vẽ đã bị bỏ qua @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard các trang CDR dài hơn 163.830 pt đã được mở với độ dài đó, và hình vẽ gần mép trang nằm ngoài bảng vẽ diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index a1b8c3eddb..7975c5b8de 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4827,6 +4827,7 @@ imageTrace Outline 轮廓 @msg CDR library colors that the drawing stores only by number were opened as black spot colors 绘图仅按编号存储的 CDR 库颜色已作为黑色专色打开 @msg CDR outline arrowheads were left out 已略去 CDR 轮廓线的箭头 @msg CDR envelopes were not applied, and the shapes under them keep their outlines 未应用 CDR 封套,其中的形状保留原有轮廓 +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque 未应用 CDR 透镜和对象透明度,相关对象显示为不透明 @msg parts of the drawing nested too deeply, or past the import limits, were left out 已略去绘图中嵌套过深或超出导入限制的部分 @msg damaged parts of the drawing were left out 已略去绘图中损坏的部分 @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 长度超过 163,830 pt 的 CDR 页面已按该长度打开,其边缘附近的图稿位于画板之外 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 7aa2060bf9..ccef3a457b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2606,6 +2606,7 @@ file-filter Templates 範本 @msg CDR library colors that the drawing stores only by number were opened as black spot colors 繪圖僅以編號儲存的 CDR 色彩庫顏色已以黑色特別色開啟 @msg CDR outline arrowheads were left out 已略過 CDR 外框線的箭頭 @msg CDR envelopes were not applied, and the shapes under them keep their outlines 未套用 CDR 封套,其中的形狀保留原有外框 +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque 未套用 CDR 透鏡和物件透明度,相關物件顯示為不透明 @msg parts of the drawing nested too deeply, or past the import limits, were left out 已略過繪圖中巢狀過深或超出讀入限制的部分 @msg damaged parts of the drawing were left out 已略過繪圖中損壞的部分 @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 長度超過 163,830 pt 的 CDR 頁面已以該長度開啟,其邊緣附近的圖稿位於工作區域之外 From c2789fff2ae23cb3c981d532b8e9424486563d2b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 18:30:51 -0800 Subject: [PATCH 20/34] CDR import: report id arguments cut short and resolve styles in linear time A container, fill, outline or style argument too short for the record id it names now adds the damage warning. Before, a container argument of fewer than four bytes imported the container alone and dropped the objects it clips without a warning. Resolving the style table's parent chains now removes each walk's styles from the visited set one by one instead of clearing the set, whose cost grew with its capacity after one long chain. --- crates/cdr/src/build.rs | 17 +++++++++++++---- crates/cdr/src/styles.rs | 29 +++++++++++++++++++++++------ crates/cdr/tests/it/read.rs | 21 +++++++++++++++++++++ 3 files changed, 57 insertions(+), 10 deletions(-) diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs index c2766cad76..df9f11d15d 100644 --- a/crates/cdr/src/build.rs +++ b/crates/cdr/src/build.rs @@ -451,20 +451,20 @@ impl<'a, 'b> Ctx<'a, 'b> { }), }; // Without a fill or outline argument of its own, an object takes its style's (R45). - let style = loda.arg(ARG_STYLE).and_then(id_of); + let style = loda.arg(ARG_STYLE).and_then(|b| self.id(b)); let fill_id = match loda.arg(ARG_FILL) { - Some(b) => id_of(b), + Some(b) => self.id(b), None => style.and_then(|s| self.style_entry(s, Styles::fill)), }; let outline_id = match loda.arg(ARG_OUTLINE) { - Some(b) => id_of(b), + Some(b) => self.id(b), None => style.and_then(|s| self.style_entry(s, Styles::outline)), }; let fill = fill_id.and_then(|id| self.fill(id)); let outline = outline_id.and_then(|id| self.outline(id)); let shape = Box::new(Shape { geometry, matrix, fill, outline }); // A container clips the group its argument 8005 names (R46). - Some(match loda.arg(ARG_CONTAINER).and_then(id_of) { + Some(match loda.arg(ARG_CONTAINER).and_then(|b| self.id(b)) { Some(id) => self.clip(shape, id, guides), None => Object::Shape(shape), }) @@ -492,6 +492,15 @@ impl<'a, 'b> Ctx<'a, 'b> { Object::Clip { container, objects } } + /// The record id that argument `b` names; an argument too short for one is damage. + fn id(&mut self, b: &[u8]) -> Option { + let id = id_of(b); + if id.is_none() { + push(self.warn, Warning::Damaged); + } + id + } + /// The fill or outline record that style `id` names; a style table that doesn't parse is /// damage, and the object is drawn without it. fn style_entry(&mut self, id: u32, entry: fn(&Styles, u32) -> Option) -> Option { diff --git a/crates/cdr/src/styles.rs b/crates/cdr/src/styles.rs index b3a83b6c92..e4022563c2 100644 --- a/crates/cdr/src/styles.rs +++ b/crates/cdr/src/styles.rs @@ -93,14 +93,16 @@ fn parse(b: &[u8], version: u16, take: &mut dyn FnMut(usize) -> bool) -> Option< if r.left() != 0 { return None; } - Some(Styles { fills: resolve(&styles, &fills, |s| s.fill), outlines: resolve(&styles, &outlines, |s| s.outline) }) + let mut work = 0; + Some(Styles { fills: resolve(&styles, &fills, |s| s.fill, &mut work), outlines: resolve(&styles, &outlines, |s| s.outline, &mut work) }) } /// For each style, the record of `table` that its own entry names, or the nearest parent's where -/// its entry is 0. Each style is resolved once, so a chain of any length takes time in proportion -/// to the styles; a chain that comes back to a style on it, or reaches a style that isn't there, -/// gives no record. -fn resolve(styles: &HashMap, table: &HashMap, entry: impl Fn(&Style) -> u32) -> HashMap { +/// its entry is 0. Each style is resolved once, and each path forgets only the styles on it, so a +/// chain of any length takes time in proportion to the styles; a chain that comes back to a style +/// on it, or reaches a style that isn't there, gives no record. `work` counts the styles visited +/// and forgotten. +fn resolve(styles: &HashMap, table: &HashMap, entry: impl Fn(&Style) -> u32, work: &mut usize) -> HashMap { // `None`: resolved to no record. let mut done: HashMap> = HashMap::new(); let mut path = Vec::new(); @@ -108,6 +110,7 @@ fn resolve(styles: &HashMap, table: &HashMap, entry: impl for &start in styles.keys() { let mut id = start; let found = loop { + *work += 1; if let Some(&known) = done.get(&id) { break known; } @@ -122,8 +125,9 @@ fn resolve(styles: &HashMap, table: &HashMap, entry: impl e => break table.get(&e).copied(), } }; - on_path.clear(); for id in path.drain(..) { + *work += 1; + on_path.remove(&id); done.insert(id, found); } } @@ -212,6 +216,19 @@ mod tests { assert_eq!((s.fill(500), s.fill(250), s.outline(500)), (Some(7), Some(7), None)); } + /// A loop of 2,000 styles, which every walk into it follows around, leaves the walks of 20,000 + /// other styles no more work than the styles they visit. + #[test] + fn one_long_walk_does_not_slow_the_walks_after_it() { + let mut styles: HashMap = (1..=2000).map(|id| (id, Style { parent: id % 2000 + 1, fill: 0, outline: 0 })).collect(); + styles.extend((10_001..=30_000).map(|id| (id, Style { parent: 0, fill: 0x100, outline: 0 }))); + let table = HashMap::from([(0x100, 7)]); + let mut work = 0; + let fills = resolve(&styles, &table, |s| s.fill, &mut work); + assert_eq!((fills.get(&1), fills.get(&10_001), fills.len()), (None, Some(&7), 20_000)); + assert!(work <= 4 * styles.len(), "{work}"); + } + #[test] fn an_entry_missing_from_its_table_names_no_record() { let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x101, outline: 0x200 }]; diff --git a/crates/cdr/tests/it/read.rs b/crates/cdr/tests/it/read.rs index 1705e14439..c7c5836073 100644 --- a/crates/cdr/tests/it/read.rs +++ b/crates/cdr/tests/it/read.rs @@ -1326,6 +1326,27 @@ fn a_missing_or_repeating_clipped_group_keeps_the_container() { assert_eq!(d.warnings, vec![Warning::TooDeep]); } +/// A container, fill, outline or style argument too short for the id it names is damage: the +/// shape comes in as a plain shape without that id. +#[test] +fn an_id_argument_cut_short_is_damage() { + for version in [700, 1100, 1600] { + let v = V(version); + let group = vec![(0x77, vec![clip_rect(v, 10.0, &[], [0.0, 0.0])])]; + let container = clip_rect(v, 40.0, &[(8005, vec![0x77, 0, 0])], [0.0, 0.0]); + let d = read(&clip_drawing(version, group, vec![container]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + assert!(matches!(d.pages[0].layers[0].objects.as_slice(), [Object::Shape(_)]), "{version}: {:?}", d.pages[0].layers[0].objects); + assert_eq!(d.warnings, vec![Warning::Damaged], "{version}"); + for kind in [20, 10, 200] { + let short = synth::object(v, 1, &[(kind, vec![1, 0]), (30, v.rect(10.0, 10.0, 0.0))], None); + let d = read(&clip_drawing(version, vec![], vec![short]), Limits::default()).unwrap_or_else(|e| panic!("{version} {kind}: {e}")); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s.len() == 1 && s[0].fill.is_none() && s[0].outline.is_none(), "{version} {kind}"); + assert_eq!(d.warnings, vec![Warning::Damaged], "{version} {kind}"); + } + } +} + /// An object with a lens or transparency (argument 8000) comes in opaque, with the lenses /// warning; one without the argument gives no warning. #[test] From daeb83d2ee243c0290e90c8bde5cef06bda09a03 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 19:04:31 -0800 Subject: [PATCH 21/34] CDR import: bound the walks of clipped groups and stop copying refused dashes Every chunk walked inside a clipped group now counts toward a new clipped_chunks limit (2,000,000), each time a container names the group, empty groups included. Containers that all name one group of empty groups took time in the product of the two counts; past the limit a container's group is left out, with its guidelines, and the container stays as a plain shape with the limit warning. An outline record refused at the dash limit drops its dashes from the cache, so later shapes that use it take it solid without copying the dash list. --- crates/cdr/src/build.rs | 66 ++++++++++++++++++++++++++++++++----- crates/cdr/src/limits.rs | 17 +++++++++- crates/cdr/tests/it/read.rs | 26 +++++++++++++++ 3 files changed, 100 insertions(+), 9 deletions(-) diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs index df9f11d15d..935021d29a 100644 --- a/crates/cdr/src/build.rs +++ b/crates/cdr/src/build.rs @@ -55,6 +55,8 @@ struct Ctx<'a, 'b> { clips: HashMap, /// The clipped groups being read, innermost last. open_clips: Vec, + /// Whether the walk of a clipped group stopped at the clipped chunk limit. + clip_cut: bool, } /// The most clipped groups read one inside another: VectorCraft's own limit. @@ -93,6 +95,7 @@ pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec) styles, clips: HashMap::new(), open_clips: Vec::new(), + clip_cut: false, }; for g in found.clpt.iter().flat_map(|c| ix.children(c)).filter(|g| g.is_list(b"grp ")) { if let Some(id) = ix.children(g).iter().find(|c| &c.id == b"spnd").and_then(|c| Rd::new(ix.data(c)).u32()) { @@ -366,6 +369,13 @@ impl<'a, 'b> Ctx<'a, 'b> { continue; }; top.next += 1; + // Every chunk of a clipped group counts, empty groups included, each time a container + // names the group; past the limit the group is left out. + if !self.open_clips.is_empty() && !self.budget.take_clipped_chunk() { + push(self.warn, Warning::TooDeep); + self.clip_cut = true; + return Vec::new(); + } if c.is_list(b"obj ") { if let Some(o) = self.object(c, guides, &outer) { top.objects.push(o); @@ -471,8 +481,9 @@ impl<'a, 'b> Ctx<'a, 'b> { } /// `container` and the objects of the clipped group `id`, which keep their own transforms. - /// A group that isn't there is damage; one already being read, or past the depth limit, is - /// left out with the limit warning. Either way the container stays, as a plain shape. + /// A group that isn't there is damage; one already being read, past the depth limit or past + /// the chunks clipped groups may walk is left out with the limit warning, the guidelines it + /// holds included. Either way the container stays, as a plain shape. fn clip(&mut self, container: Box, id: u32, guides: &mut Vec) -> Object { let Some(&group) = self.clips.get(&id) else { push(self.warn, Warning::Damaged); @@ -483,9 +494,13 @@ impl<'a, 'b> Ctx<'a, 'b> { return Object::Shape(container); } self.open_clips.push(id); - let ix = self.ix; + let (ix, mark) = (self.ix, guides.len()); let objects = self.objects(ix.children(group), guides); self.open_clips.pop(); + if std::mem::take(&mut self.clip_cut) { + guides.truncate(mark); + return Object::Shape(container); + } if objects.is_empty() { return Object::Shape(container); } @@ -616,12 +631,14 @@ impl<'a, 'b> Ctx<'a, 'b> { }); self.outlines.insert(id, read); } - let o = self.outlines.get(&id)?.as_ref()?; - if o.dashes.is_empty() || self.budget.take_dashes(o.dashes.len()) { - return Some(o.clone()); + let o = self.outlines.get_mut(&id)?.as_mut()?; + // The dashes left only shrink, so an outline refused once is refused for every later + // shape: its dashes are dropped from the cache, and later shapes take it solid. + if !o.dashes.is_empty() && !self.budget.take_dashes(o.dashes.len()) { + o.dashes = Vec::new(); + push(self.warn, Warning::TooDeep); } - push(self.warn, Warning::TooDeep); - Some(Outline { dashes: Vec::new(), ..o.clone() }) + Some(o.clone()) } } @@ -659,4 +676,37 @@ mod tests { assert_eq!(layer_kind([0x48, 0, 1, 0x98], false), LayerKind::Desktop); assert_eq!(layer_kind([0x4a, 1, 1, 0x98], true), LayerKind::Guides); } + + /// An outline record refused at the dash limit keeps no dashes in the cache, so the shapes + /// that use it later copy none. + #[test] + fn an_outline_past_the_dash_limit_keeps_no_dashes() { + let v = crate::synth::V(1100); + let pen = crate::synth::Pen { line_type: 4, width: 1.0, cap: 0, join: 0 }; + let record = v.outline(1, pen, &crate::synth::color(5, [0, 0, 0, 255]), &[3, 1, 3]); + let file = crate::synth::riff(1100, &[]); + let mut budget = Budget::new(crate::Limits { dashes: 4, ..crate::Limits::default() }); + let mut warn = Vec::new(); + let ix = crate::riff::Index::build(&file, None, &mut budget, &mut warn).unwrap(); + let mut cx = Ctx { + ix: &ix, + p: layout::for_version(1100).unwrap(), + budget: &mut budget, + warn: &mut warn, + fill_chunks: HashMap::new(), + outline_chunks: HashMap::from([(1, record.as_slice())]), + fills: HashMap::new(), + outlines: HashMap::new(), + styles: Ok(Styles::default()), + clips: HashMap::new(), + open_clips: Vec::new(), + clip_cut: false, + }; + assert_eq!(cx.outline(1).map(|o| o.dashes.len()), Some(3)); + for _ in 0..3 { + assert_eq!(cx.outline(1).map(|o| o.dashes.len()), Some(0)); + assert_eq!(cx.outlines.get(&1).and_then(|o| o.as_ref()).map(|o| o.dashes.len()), Some(0)); + } + assert_eq!(*cx.warn, vec![Warning::TooDeep]); + } } diff --git a/crates/cdr/src/limits.rs b/crates/cdr/src/limits.rs index d1b0ff7fae..b5f030b025 100644 --- a/crates/cdr/src/limits.rs +++ b/crates/cdr/src/limits.rs @@ -26,6 +26,9 @@ pub struct Limits { /// Dashes of all outlines together, an outline's counted again for every shape that uses it. /// Past them a shape's outline is solid, with a warning. pub dashes: usize, + /// Chunks walked inside clipped groups, all containers together, a group's counted again for + /// every container that names it. Past them a container's group is left out, with a warning. + pub clipped_chunks: usize, } #[cfg(not(target_arch = "wasm32"))] @@ -45,6 +48,7 @@ impl Default for Limits { coordinates: 16_000_000, arguments: 64, dashes: 16_000_000, + clipped_chunks: 2_000_000, } } @@ -61,6 +65,7 @@ impl Default for Limits { coordinates: 16_000_000, arguments: 64, dashes: 8_000_000, + clipped_chunks: 2_000_000, } } } @@ -74,13 +79,14 @@ pub(crate) struct Budget { objects: usize, coordinates: usize, dashes: usize, + clipped_chunks: usize, /// A request for coordinates was refused since [`Budget::coordinates_refused`] last asked. refused: bool, } impl Budget { pub(crate) fn new(limits: Limits) -> Self { - Budget { limits, inflated: 0, chunks: 0, objects: 0, coordinates: 0, dashes: 0, refused: false } + Budget { limits, inflated: 0, chunks: 0, objects: 0, coordinates: 0, dashes: 0, clipped_chunks: 0, refused: false } } /// Whether a request for coordinates was refused since the last call, which tells a shape @@ -147,4 +153,13 @@ impl Budget { None => false, } } + + /// One more chunk walked inside a clipped group, or `false` past the limit. + pub(crate) fn take_clipped_chunk(&mut self) -> bool { + if self.clipped_chunks >= self.limits.clipped_chunks { + return false; + } + self.clipped_chunks += 1; + true + } } diff --git a/crates/cdr/tests/it/read.rs b/crates/cdr/tests/it/read.rs index c7c5836073..226eb470c6 100644 --- a/crates/cdr/tests/it/read.rs +++ b/crates/cdr/tests/it/read.rs @@ -1326,6 +1326,32 @@ fn a_missing_or_repeating_clipped_group_keeps_the_container() { assert_eq!(d.warnings, vec![Warning::TooDeep]); } +/// Each chunk of a clipped group counts toward the clipped chunk limit every time a container +/// names the group, empty groups included; past it the containers stay as plain shapes, and a +/// group cut off at the limit leaves out its guidelines too. +#[test] +fn containers_naming_one_group_stop_at_the_clipped_chunk_limit() { + let v = V(1100); + // The group walks 53 chunks: its `spnd`, a guideline, 50 empty groups and a rectangle. + let mut guide = vec![0; 12]; + guide.extend(90_000_000i32.to_le_bytes()); + guide.extend([v.coord(36.0), v.coord(0.0)].concat()); + let mut contents = vec![synth::object(v, 0x16, &[(16000, guide)], None)]; + contents.extend((0..50).map(|_| list(b"grp ", vec![]))); + contents.push(clip_rect(v, 10.0, &[], [0.0, 0.0])); + let containers: Vec = (0..20).map(|_| clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0])).collect(); + let file = clip_drawing(1100, vec![(0x77, contents)], containers); + let count = |objects: &[Object]| objects.iter().filter(|o| matches!(o, Object::Clip { .. })).count(); + let d = read(&file, Limits::default()).unwrap(); + assert_eq!((count(&d.pages[0].layers[0].objects), d.pages[0].layers[0].guides.len()), (20, 20)); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + // The sixth container's walk stops after its guideline and 8 empty groups. + let d = read(&file, Limits { clipped_chunks: 53 * 5 + 10, ..Limits::default() }).unwrap(); + let layer = &d.pages[0].layers[0]; + assert_eq!((layer.objects.len(), count(&layer.objects), layer.guides.len()), (20, 5, 5)); + assert_eq!(d.warnings, vec![Warning::TooDeep]); +} + /// A container, fill, outline or style argument too short for the id it names is damage: the /// shape comes in as a plain shape without that id. #[test] From 7e89bf330d168f7cb00bac91efa1feca4305ec66 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 19:23:25 -0800 Subject: [PATCH 22/34] CDR import: keep the children read before a list is cut short A list whose length runs past the end of its parent, as in a file cut off inside its last page, now keeps the bytes it has, with the damage warning. Its complete children before the cut are read; other chunks that run past the end are still left out. --- crates/cdr/src/riff.rs | 27 ++++++++++++++++++++------- crates/cdr/tests/it/read.rs | 6 ++++++ 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/crates/cdr/src/riff.rs b/crates/cdr/src/riff.rs index 584df2e264..1e06b00c08 100644 --- a/crates/cdr/src/riff.rs +++ b/crates/cdr/src/riff.rs @@ -226,10 +226,13 @@ impl<'a> Index<'a> { let mut at = p.start; let mut lists = Vec::new(); while at < p.end { - let Some((read, next)) = self.read_chunk(p.src, at, p.end, p.pool) else { + let Some((read, next, cut)) = self.read_chunk(p.src, at, p.end, p.pool) else { push(warn, Warning::Damaged); break; }; + if cut { + push(warn, Warning::Damaged); + } at = next; // A redirect record whose body can't be found counts as well, so that lists redirected // to again and again can't repeat such records past the limit. @@ -288,8 +291,9 @@ impl<'a> Index<'a> { /// The chunk at `at` (before `end`) of source `src`, and where the next one starts. In a /// compressed stream the size field is an index into the size pool (R3); in a version 16+ - /// package a chunk of 16 bytes outside one is a redirect record (R27). - fn read_chunk(&self, src: u32, at: usize, end: usize, pool: Option<(usize, usize)>) -> Option<(Read, usize)> { + /// package a chunk of 16 bytes outside one is a redirect record (R27). The flag is set for a + /// list cut short at `end`. + fn read_chunk(&self, src: u32, at: usize, end: usize, pool: Option<(usize, usize)>) -> Option<(Read, usize, bool)> { let head = self.span(src, at, at.checked_add(8)?.min(end))?; let id: [u8; 4] = head.get(..4)?.try_into().ok()?; let raw = u32_at(head, 4)? as usize; @@ -302,17 +306,26 @@ impl<'a> Index<'a> { } }; let body = at + 8; - let body_end = body.checked_add(size).filter(|&e| e <= end)?; - let next = (body_end + (size & 1)).min(end); + // A list cut short by the end of its parent keeps the bytes it has, so the children + // before the cut are read; the caller warns that it is damaged. Other chunks are lost. + let (size, cut) = match body.checked_add(size) { + Some(e) if e <= end => (size, false), + _ if id == LIST => (end.checked_sub(body)?, true), + _ => return None, + }; + let next = (body + size + (size & 1)).min(end); + if cut { + return Some((self.chunk(id, src, body, size).map_or(Read::Lost, Read::Chunk), next, true)); + } if self.streams.is_some() && pool.is_none() && size == REDIRECT { let read = match self.redirect(id, src, body) { Some(read) => read, None if self.redirect_past_limit(src, body) => Read::PastLimit, None => Read::Lost, }; - return Some((read, next)); + return Some((read, next, false)); } - Some((Read::Chunk(self.chunk(id, src, body, size)?), next)) + Some((Read::Chunk(self.chunk(id, src, body, size)?), next, false)) } /// Chunk `id` whose body is `len` bytes at `body` of source `src`; a list's body starts with diff --git a/crates/cdr/tests/it/read.rs b/crates/cdr/tests/it/read.rs index 226eb470c6..1a5416d864 100644 --- a/crates/cdr/tests/it/read.rs +++ b/crates/cdr/tests/it/read.rs @@ -1405,6 +1405,12 @@ fn a_file_cut_short_keeps_what_it_holds() { let cut = &full[..full.len() - 40]; let d = read(cut, Limits::default()).unwrap(); assert!(d.warnings.contains(&Warning::Damaged)); + // The last page is cut inside its layer: the lists that hold the cut keep their whole + // children, so the rectangle, ellipse and curve before the cut are read. + assert_eq!(d.pages.len(), 1); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s.len() >= 3, "{}", s.len()); + assert!(matches!(s[0].geometry, Geometry::Rect { .. }) && matches!(s[1].geometry, Geometry::Ellipse { .. })); } #[test] From 93fde363153560e733366e7435e7ad4e08d3e9c6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 22:34:30 -0800 Subject: [PATCH 23/34] Docs: one formats row and one open_file row for PICT and CDR --- docs/file-format-parity.md | 3 +-- docs/mcp.md | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 686f55238e..28e129be4d 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -21,8 +21,7 @@ Ordinary File > Save offers Save As when its own location refuses writes with a | | Illustrator | VectorCraft | Notes | |---|---:|---:|---| -| Formats opened or placed | ~30 | 31 | missing: FreeHand, CorelDRAW, DWG, PS | -| Formats opened or placed | ~30 | 31 | missing: FreeHand, DWG, PICT, PS | +| Formats opened or placed | ~30 | 31 | missing: FreeHand, DWG, PS | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, gradients, patterns, images, type, symbols, artboards, transparency, opacity masks, clipping) or as legacy version 7 (layers and groups, one artboard per file) | | Formats exported | ~16 | 18 | missing: DWG; extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | | **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting | diff --git a/docs/mcp.md b/docs/mcp.md index 5cc21e758e..235baa8f2b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -631,8 +631,7 @@ sampler. | `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. UI commands such as `view.*` and `window.*` are in `command_list` with `ui: true`; running them needs the desktop app (`--connect`). | | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | | `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. | -| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | -| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | +| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | | `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `_.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a `.ai` file reads `compress` but not `version`, `preview` or `precision`). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for a top-level `compress`, `version`, `preview` or `precision` and for each key in `options` that the format doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). | | `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning); `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | From c920f2efd19aa244d839da92d893c1f03cd09c44 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 15:26:15 -0800 Subject: [PATCH 24/34] i18n: Dutch rows for the CDR import messages Dutch joined the complete-message languages on main, so the CDR reader's version and read errors and its ten import notes now need nl rows. They go after the HEIC rows, where the other catalogs keep them. --- crates/ui-egui/src/i18n/nl.tsv | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 6babee27ff..c0eeae799b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -242,6 +242,18 @@ @msg the HEIC or HEIF file can't be read het HEIC- of HEIF-bestand kan niet worden gelezen @msg the HEIC or HEIF file holds a kind of image that can't be read het HEIC- of HEIF-bestand bevat een soort afbeelding die niet kan worden gelezen @msg HEIC and HEIF images can't be opened in this build HEIC- en HEIF-afbeeldingen kunnen in deze build niet worden geopend +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 tekeningen uit CDR {version} kunnen niet worden geopend: VectorCraft leest versies 1 tot en met 27 +@msg this CDR drawing can't be read ({why}) deze CDR-tekening kan niet worden gelezen ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out CDR-tekst, bitmaps, vermengingen, omtrekken, penseelstreken en andere objecten die VectorCraft nog niet leest, zijn weggelaten +@msg CDR fountain, pattern, texture and PostScript fills were left out CDR-verloop-, patroon-, textuur- en PostScript-vullingen zijn weggelaten +@msg colors in CDR color models VectorCraft doesn't read were opened as black kleuren in CDR-kleurmodellen die VectorCraft niet leest, zijn als zwart geopend +@msg CDR library colors that the drawing stores only by number were opened as black spot colors CDR-bibliotheekkleuren die de tekening alleen als nummer opslaat, zijn als zwarte steunkleuren geopend +@msg CDR outline arrowheads were left out pijlpunten van CDR-contouren zijn weggelaten +@msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR-enveloppen zijn niet toegepast, en de vormen eronder behouden hun omtrek +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque CDR-lenzen en objecttransparantie zijn niet toegepast, en de objecten waarop ze liggen, worden dekkend weergegeven +@msg parts of the drawing nested too deeply, or past the import limits, were left out delen van de tekening die te diep genest zijn of buiten de importlimieten vallen, zijn weggelaten +@msg damaged parts of the drawing were left out beschadigde delen van de tekening zijn weggelaten +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard CDR-pagina’s langer dan 163.830 pt zijn op die lengte geopend, en illustraties bij de randen ervan liggen buiten het tekengebied @msg the JPEG XL file is cut short het JPEG XL-bestand is afgebroken @msg the JPEG XL container is too large to read de JPEG XL-container is te groot om te lezen @msg CMYK JPEG XL images can't be read CMYK-afbeeldingen in JPEG XL kunnen niet worden gelezen From 0adb013041ab747a56500c688bc87ccfea6bc6f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 20:35:11 -0800 Subject: [PATCH 25/34] CDR import: outlines set to scale with the object scale with its matrix Bit 5 of an outline's line type marks it to scale with the object. Such an outline's width and dashes are now multiplied by the square root of the area factor of the shape's matrix, instead of keeping their stored width (PROVENANCE.md R50). Other outlines keep their stored width. --- crates/cdr/PROVENANCE.md | 1 + crates/cdr/src/inline.rs | 2 +- crates/cdr/src/model.rs | 3 ++ crates/cdr/src/records.rs | 4 +- crates/cdr/src/wl.rs | 10 ++++- crates/cdr/tests/it/read.rs | 17 ++++++++ crates/engine/src/cmd/fileio/cdr/shapes.rs | 45 ++++++++++++++++++++-- docs/target-app-parity.md | 2 +- 8 files changed, 76 insertions(+), 8 deletions(-) diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 7c79cd3c8c..73642424cd 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -97,3 +97,4 @@ file is committed. | R47 | Argument 8000 marks an object seen through: a lens or a transparency. The reader does not apply it, and names lenses in the warnings | K L859 (the argument); S: of the sample files of versions 7 to 25, the argument is on the see-through objects that the pictures of LT `square_blackfill_nooutline_transparency50percent` of `testset/12` to `testset/25`, TDF 80103 and eight UC lens test files of versions 7 to 13 show, and otherwise only on text in UC `fancytext_cdr7.cdr` to `fancytext_x3.cdr` and on two objects of TDF 114901. The value K reads at byte 10 (14 from version 13) is not the transparency in these samples | public-spec (the argument: K; what it marks: sample; its layout: unconfirmed, and it is not read) | | R48 | Bit 2 (0x04) of the outline's line type marks the outline dashed; the dashes of an outline without it are not drawn | S: every outline of versions 6 to 25 in the sample files with that bit set (316 of them, in 29 files) stores dashes; TDF 76771 (version 15) stores dashes 2 and 1 in an outline of line type 0x22, and the file's picture draws that outline solid | sample | | R49 | Bit 4 (0x10) of the outline's line type puts the outline behind the fill | S: UC `outl_behind_fill_cdr7.cdr` to `outl_behind_fill_x3.cdr`, whose outline of line type 0x12 the file's picture shows behind the fill, and whose other outlines (0x02) it shows over the fill | sample | +| R50 | Bit 5 (0x20) of the outline's line type scales the outline's width and dashes with the shape's matrix. The engine multiplies them by the square root of the matrix's area factor (VectorCraft's own value for a matrix that scales x and y differently) | S: UC `outl_scale_with_cdr7.cdr` to `outl_scale_with_cdr12.cdr`, of whose outlines only one, 3.969 mm wide, has line type 0x22 and the others 0x02 or 0x01; TDF 76771 (version 15), whose outline of line type 0x22 is 10 mm wide on a shape that the matrix stretches and skews, and whose picture draws that outline several times wider and skewed | sample (the bit; the single width for a matrix that scales x and y differently: VectorCraft's own) | diff --git a/crates/cdr/src/inline.rs b/crates/cdr/src/inline.rs index dc44ae0b23..3d5214f136 100644 --- a/crates/cdr/src/inline.rs +++ b/crates/cdr/src/inline.rs @@ -79,7 +79,7 @@ pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec) -> Option< let _stretch = r.u16()?; let _nib = angle(&mut r, p)?; let color = records::color(&mut r, p, warn)?; - let mut out = Outline { width, color, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new(), behind_fill: false }; + let mut out = Outline { width, color, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new(), behind_fill: false, scale_with: false }; let Some(stored) = r.skip(7).and_then(|()| r.u8()).map(usize::from) else { return Some(Some(out)) }; let Some(area) = r.bytes(DASH_AREA) else { return Some(Some(out)) }; if stored > DASH_AREA { diff --git a/crates/cdr/src/model.rs b/crates/cdr/src/model.rs index cd3946ab7d..6e48fef497 100644 --- a/crates/cdr/src/model.rs +++ b/crates/cdr/src/model.rs @@ -107,6 +107,9 @@ pub struct Outline { pub dashes: Vec, /// Drawn behind the fill, so that a filled shape shows only the outer half of it. pub behind_fill: bool, + /// Scaled with the shape: the shape's matrix scales the width and dashes as it scales the + /// geometry. + pub scale_with: bool, } #[derive(Clone, Debug, PartialEq)] diff --git a/crates/cdr/src/records.rs b/crates/cdr/src/records.rs index dac441940f..0680583453 100644 --- a/crates/cdr/src/records.rs +++ b/crates/cdr/src/records.rs @@ -360,7 +360,9 @@ pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec) -> Option< let dashes = if line_type & 4 != 0 && dashes.iter().any(|d| *d > 0.0) { dashes } else { Vec::new() }; // Bit 4 of the line type: behind the fill (R49). let behind_fill = line_type & 0x10 != 0; - Some((id, Some(Outline { width, color, cap, join, dashes, behind_fill }))) + // Bit 5 of the line type: scaled with the shape (R50). + let scale_with = line_type & 0x20 != 0; + Some((id, Some(Outline { width, color, cap, join, dashes, behind_fill, scale_with }))) } /// A name argument (R9): Windows-1252 up to a NUL before version 12, UTF-16LE from it. A name diff --git a/crates/cdr/src/wl.rs b/crates/cdr/src/wl.rs index 3ca20a1111..3ec6f26c79 100644 --- a/crates/cdr/src/wl.rs +++ b/crates/cdr/src/wl.rs @@ -184,7 +184,15 @@ fn shape(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mu }; let outline = if *rec.get(OUTLINED)? != 0 { let width = f64::from(Rd::at(rec, OUTLINE_WIDTH).u16()?) * k; - Some(Outline { width, color: color_at(OUTLINE_COLOR, warn)?, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new(), behind_fill: false }) + Some(Outline { + width, + color: color_at(OUTLINE_COLOR, warn)?, + cap: Cap::Butt, + join: Join::Miter, + dashes: Vec::new(), + behind_fill: false, + scale_with: false, + }) } else { None }; diff --git a/crates/cdr/tests/it/read.rs b/crates/cdr/tests/it/read.rs index 1a5416d864..370db2f2fe 100644 --- a/crates/cdr/tests/it/read.rs +++ b/crates/cdr/tests/it/read.rs @@ -1600,6 +1600,23 @@ fn outlines_flagged_behind_the_fill_say_so() { } } +/// Bit 5 of the line type scales the outline with the shape. +#[test] +fn outlines_flagged_to_scale_with_the_shape_say_so() { + let black = synth::color(2, [0, 0, 0, 100]); + for version in [700, 1300, 1600] { + for (line_type, scale_with) in [(2, false), (0x22, true), (0x12, false), (0x26, true)] { + let v = V(version); + let outline = v.outline(9, synth::Pen { line_type, width: 4.0, cap: 0, join: 0 }, &black, &[]); + let style = vec![(10, 9u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &style, None)])]); + let d = read(&synth::file_of(version, vec![list(b"otlt", vec![chunk(b"outl", outline)]), page]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].outline.as_ref().map(|o| o.scale_with), Some(scale_with), "{version} {line_type:#x}"); + } + } +} + #[test] fn library_colors_from_version_13_keep_their_names_and_tints() { // A model 21 color (blue, green, red, tint) shown at 50 %, and its library name. diff --git a/crates/engine/src/cmd/fileio/cdr/shapes.rs b/crates/engine/src/cmd/fileio/cdr/shapes.rs index 69e9cb1ea4..070bcff762 100644 --- a/crates/engine/src/cmd/fileio/cdr/shapes.rs +++ b/crates/engine/src/cmd/fileio/cdr/shapes.rs @@ -173,13 +173,13 @@ impl Builder { // In paint order: an outline behind the fill comes first. let mut items = Vec::new(); if let Some(o) = s.outline.as_ref().filter(|o| o.behind_fill) { - items.push(AppearanceItem::Stroke(self.stroke(o))); + items.push(AppearanceItem::Stroke(self.stroke(o, &s.matrix))); } if let Some(c) = &s.fill { items.push(AppearanceItem::Fill(FillLayer::new(self.paint(c)))); } if let Some(o) = s.outline.as_ref().filter(|o| !o.behind_fill) { - items.push(AppearanceItem::Stroke(self.stroke(o))); + items.push(AppearanceItem::Stroke(self.stroke(o, &s.matrix))); } // A curve of several subpaths is filled with holes where they overlap: VectorCraft's own // choice of rule for it. @@ -189,9 +189,19 @@ impl Builder { Some(Arc::new(n)) } - fn stroke(&mut self, o: &cd::Outline) -> StrokeLayer { + /// The stroke of outline `o` on a shape placed by `matrix`. + fn stroke(&mut self, o: &cd::Outline, matrix: &cd::Matrix) -> StrokeLayer { + // The width of an outline scaled with the shape is multiplied by the square root of the + // matrix's area factor (R50). For a matrix that scales x and y differently, that width is + // VectorCraft's own value. + let width = if o.scale_with { + let [a, b, c, d, _, _] = matrix.0; + o.width * (a * d - b * c).abs().sqrt() + } else { + o.width + }; // A drawn outline of width 0 shows as a hairline, as a PDF line width of 0 does. - let width = if o.width.is_finite() && o.width > 0.0 { o.width.min(1000.0) } else { HAIRLINE }; + let width = if width.is_finite() && width > 0.0 { width.min(1000.0) } else { HAIRLINE }; let mut l = StrokeLayer::new(self.paint(&o.color), width); l.cap = match o.cap { cd::Cap::Butt => LineCap::Butt, @@ -485,6 +495,7 @@ mod tests { join: cd::Join::Miter, dashes: vec![1.0; 299], behind_fill: false, + scale_with: false, }; let rect = cd::Object::Shape(Box::new(cd::Shape { geometry: Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, @@ -509,6 +520,32 @@ mod tests { assert!(b.notes.contains(&Warning::TooDeep)); } + /// An outline scaled with the shape takes the square root of the matrix's area factor on its + /// width and dashes; another outline keeps its stored width under the same matrix. + #[test] + fn outlines_scaled_with_the_shape_scale_their_width_and_dashes() { + // A matrix that scales by 2 and 8 and skews: area factor 2 * 8 - 3 * 0 = 16, mean scale 4. + let matrix = cd::Matrix([2.0, 0.0, 3.0, 8.0, 5.0, 5.0]); + for (scale_with, width, dashes) in [(true, 6.0, [12.0, 6.0]), (false, 1.5, [3.0, 1.5])] { + let outline = cd::Outline { + width: 1.5, + color: cd::Color::Gray(1.0), + cap: cd::Cap::Butt, + join: cd::Join::Miter, + dashes: vec![2.0, 1.0], + behind_fill: false, + scale_with, + }; + let rect = cd::Shape { geometry: Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, matrix, fill: None, outline: Some(outline) }; + let mut b = Builder::new(); + let Some(node) = b.shape(&rect, Affine::IDENTITY, false) else { panic!("{scale_with}: no shape") }; + let [AppearanceItem::Stroke(s)] = node.appearance.items.as_slice() else { panic!("{scale_with}: {:?}", node.appearance.items) }; + assert!((s.width - width).abs() < 1e-9, "{scale_with}: {}", s.width); + let pattern = s.dash.as_ref().map(|d| d.pattern.clone()); + assert_eq!(pattern, Some(dashes.to_vec()), "{scale_with}"); + } + } + /// A corner rounded in the file stays on the same corner of the page, however the rectangle's /// size points. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 460c891980..486344b298 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1697,7 +1697,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill where the file says so), an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, object transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). + - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill, or scaled with the object's matrix, where the file says so), an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, object transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. EPS and PostScript `.ai` files are still embedded (`crates/engine/src/tests/placed_document.rs`). From ca804d921ebd635c08413fcdd17bf480970d80b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:31:24 -0800 Subject: [PATCH 26/34] CDR import: hidden and locked art, fill rule, outline spot colors and uniform transparency - Layers, groups and objects open hidden and locked from their flags (bit 0x01 of byte 1, bit 0x10 of byte 0). Layers of one name merged across pages are hidden or locked only when all of them are; otherwise their art is, object by object. A clipped group's flags reach its objects. Hidden guidelines go on a hidden "Hidden guides" layer, and the other guides on the top shown layer. - Byte 0 of argument 14001 other than 0 fills the shape with the nonzero rule; other shapes stay even-odd. - From version 13 an outline's property list record that names a library color gives the outline that spot color. - From version 13 a uniform transparency (a 117-byte record of version 1300 in argument 8000) becomes the object's opacity, read as the transparency in percent, and its merge mode the blend mode where one matches. Lenses, other records and other merge modes keep the warning. - A cdr8 file is the 8.01 variant whatever its vrsn chunk names. The argument 200 style id and the spnd id are u16 before version 6. A trfd entry ends at the next offset. A version 15 corner radius is held to half the shorter side. - PROVENANCE.md adds source KF, the MIT-licensed fork of the specification by Zach Wolfe, and rows R51 and R52; LICENSE-kaitai.txt and NOTICE credit it. --- NOTICE | 5 +- crates/cdr/LICENSE-kaitai.txt | 5 + crates/cdr/PROVENANCE.md | 19 +- crates/cdr/README.md | 12 +- crates/cdr/src/build.rs | 140 +++++++-- crates/cdr/src/geometry.rs | 6 +- crates/cdr/src/model.rs | 54 +++- crates/cdr/src/records.rs | 94 +++++- crates/cdr/src/riff.rs | 4 +- crates/cdr/src/synth.rs | 68 ++++- crates/cdr/src/wl.rs | 6 +- crates/cdr/tests/it/read.rs | 328 ++++++++++++++++++++- crates/engine/src/cmd/fileio/cdr.rs | 132 +++++++-- crates/engine/src/cmd/fileio/cdr/shapes.rs | 310 ++++++++++++++++--- crates/engine/src/cmd/fileio/tests_cdr.rs | 25 ++ docs/file-format-parity.md | 2 +- docs/mcp.md | 14 +- docs/target-app-parity.md | 2 +- 18 files changed, 1084 insertions(+), 142 deletions(-) diff --git a/NOTICE b/NOTICE index cd4004f0d3..ab345fd23f 100644 --- a/NOTICE +++ b/NOTICE @@ -36,8 +36,9 @@ WebAssembly plug-ins run in the wasmi interpreter (MIT OR Apache-2.0); its wasmp under the Apache License 2.0 with the LLVM exception. The .cdr reader (crates/cdr) reads the record layouts that the Kaitai Struct specification -coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy, MIT License) describes. No part -of the specification is copied into the crate; its license text is in crates/cdr/LICENSE-kaitai.txt. +coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy, MIT License) and its fork by Zach +Wolfe (https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, MIT License) describe. No part +of either specification is copied into the crate; the license text is in crates/cdr/LICENSE-kaitai.txt. Builds made with craft-fonts (the CRAFT_FONTS_DIR build option; all official releases) embed the fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (BIZ UDPGothic, diff --git a/crates/cdr/LICENSE-kaitai.txt b/crates/cdr/LICENSE-kaitai.txt index 948586e09a..296cf04d0e 100644 --- a/crates/cdr/LICENSE-kaitai.txt +++ b/crates/cdr/LICENSE-kaitai.txt @@ -5,6 +5,11 @@ specification `coreldraw_cdr.ksy` license below. No part of that specification is copied into this crate; `PROVENANCE.md` cites it by line. +Some layouts are also taken from the fork of that specification by Zach Wolfe +(https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, commit +2189b68f07e0cafe9afec3dcf699ebc0342144c7), which is published under the same +license and copyright notice. + MIT License Copyright (c) 2020 Kaitai team diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 73642424cd..330b567440 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -7,6 +7,9 @@ Sources: - **K**: the Kaitai Struct specification `coreldraw_cdr.ksy` (MIT, notice in `LICENSE-kaitai.txt`), https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/coreldraw_cdr.ksy +- **KF**: the fork of K by Zach Wolfe, `filestar/coreldraw_cdr.ksy`, branch `new_stuff`, under the same + MIT license and notice as K (`LICENSE-kaitai.txt`), + https://github.com/filestar/coreldraw_cdr.ksy/blob/2189b68f07e0cafe9afec3dcf699ebc0342144c7/coreldraw_cdr.ksy - **KR**: the README and the `bin/cdr-unpk` script of the Kaitai Struct specification (MIT), at the same commit as K, https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/README.md @@ -36,7 +39,7 @@ Sources: https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/atlas-atlas/cdr/ab_en_br.cdr - **DM**: the clip art of https://discmaster.textfiles.com/browse/31541, by file name -Status: `public-spec` (K, KR, Z, F or PR), `sample` (S), `unconfirmed` (a point no source states +Status: `public-spec` (K, KF, KR, Z, F or PR), `sample` (S), `unconfirmed` (a point no source states and no sample file shows; listed so it can be checked against a file, with what the reader does when it is wrong). @@ -48,7 +51,7 @@ file is committed. | Id | What the code relies on | Source | Status | |---|---|---|---| -| R1 | `RIFF`, the body length, then the form type `CDR` or `cdr` and a version character: `1` to `9`, `A` (10) to `H` (17), `J` (18) on, `I` unused; `cdr8` is 8.01, `CDR ` is 3, `CDRX` is another format. Files of versions 23 to 25 carry `O` (23), `P` (24), `Q` (24.3, with a `vrsn` of 2430) and `R` (25), which count differently from the version 24 update on, so their `vrsn` chunk decides (R2) | K L68-L133; S: LT `testset/23` to `testset/25`, such as `circle_redfill_nooutline_cdr25.cdr` | public-spec (letters from version 23: sample; letters of versions 26 and 27: unconfirmed, and the `vrsn` chunk decides when the file has one) | +| R1 | `RIFF`, the body length, then the form type `CDR` or `cdr` and a version character: `1` to `9`, `A` (10) to `H` (17), `J` (18) on, `I` unused; `cdr8` is 8.01 from the form type alone, whatever its `vrsn` chunk names, `CDR ` is 3, `CDRX` is another format. Files of versions 23 to 25 carry `O` (23), `P` (24), `Q` (24.3, with a `vrsn` of 2430) and `R` (25), which count differently from the version 24 update on, so their `vrsn` chunk decides (R2) | K L68-L133; S: LT `testset/23` to `testset/25`, such as `circle_redfill_nooutline_cdr25.cdr` | public-spec (letters from version 23: sample; letters of versions 26 and 27: unconfirmed, and the `vrsn` chunk decides when the file has one) | | R2 | `vrsn`: the version as a u16, in hundreds | K L276-L278 | public-spec | | R3 | `LIST cmpr`: two (compressed, uncompressed) u32 pairs, then two blocks of `CPng`, `01 00 04 00` and a zlib stream; the first inflates to the chunk stream, the second to a pool of u32 sizes that each chunk's size field indexes | K L193-L220, L2626-L2682 | public-spec | | R4 | A chunk is an id, a u32 size and the body, padded to an even length; a `LIST` body starts with its form type; from version 7 a `LIST stlt` holds the style tables, not chunks | K L68-L78, L135-L155, L307-L334 | public-spec | @@ -59,14 +62,14 @@ file is committed. | R9 | Name argument (1000): Windows-1252 up to a NUL before version 12, UTF-16LE from it | K L601-L630 | public-spec | | R10 | `mcfg`: 12 bytes (13 on), 4 (9 to 12), 28 (6) or none, then the page width and height as coordinates | K L1670-L1765 | public-spec | | R11 | `fild` (`fill` before 7): id; from 13 a record tagged 1300 with its length, which records tagged 2400 or more may precede; the fill type u16 (0 none, 1 uniform, others not read); uniform: 2 bytes then a color before 13, from 13 a record tagged 1300 holding a property list (u8 type, u32 length, body; 0 ends it; 1 a color, 8 a palette id and a UTF-16 name, 3 a UTF-16 name) | K L1025-L1302; S: LT `testset/15` to `testset/25` `circle_redfill_nooutline_cdr.cdr`, whose fill records hold a record tagged 2400 before the one tagged 1300 | public-spec (2400 records: sample) | -| R12 | `outl`: id; from 13 records (u32 id, u32 length, body) up to id 1, whose body follows; line type, caps and join u16; 2 bytes (6 to 12); width; stretch u16; 2 bytes (6 on); nib angle; 52 bytes (6 to 12) or 46 (13 on); the color; 16 bytes (10 before 6); the dash count u16 and the dashes, in multiples of the width; the arrowhead ids 22 bytes after the first dash in versions 6 to 12, 20 bytes from 13. Caps 0 butt, 1 round, 2 square; joins 0 miter, 1 round, 2 bevel | K L954-L1024; S: caps and joins in UC `outl_line_caps_cdr7.cdr` and `outl_corner_cdr7.cdr`; arrowhead ids, matched against the drawing's `arrw` records, in TP `web_cd.cdr` (6), UC `rogan_logo_cdr7.cdr`, `rogan_logo_cdr8.cdr` and `rogan_logo_cdr11.cdr`, NR `ab_en_br.cdr` (9) and `banff_ap_en.cdr` (10), TDF 76820 (12) and 140638 (13) | public-spec (caps, joins and arrowhead places: sample; arrowheads before version 6: no sample names one, and the reader does not look for them) | +| R12 | `outl`: id; from 13 records (u32 id, u32 length, body) up to id 1, whose body follows; a record of id 2 holds a property list laid out as R11's, and the reader takes the outline's color from it when it names a library color; line type, caps and join u16; 2 bytes (6 to 12); width; stretch u16; 2 bytes (6 on); nib angle; 52 bytes (6 to 12) or 46 (13 on); the color; 16 bytes (10 before 6); the dash count u16 and the dashes, in multiples of the width; the arrowhead ids 22 bytes after the first dash in versions 6 to 12, 20 bytes from 13. Caps 0 butt, 1 round, 2 square; joins 0 miter, 1 round, 2 bevel | K L954-L1024; KF L1225-L1249 (the id 2 record); S: caps and joins in UC `outl_line_caps_cdr7.cdr` and `outl_corner_cdr7.cdr`; arrowhead ids, matched against the drawing's `arrw` records, in TP `web_cd.cdr` (6), UC `rogan_logo_cdr7.cdr`, `rogan_logo_cdr8.cdr` and `rogan_logo_cdr11.cdr`, NR `ab_en_br.cdr` (9) and `banff_ap_en.cdr` (10), TDF 76820 (12) and 140638 (13) | public-spec (caps, joins and arrowhead places: sample; arrowheads before version 6: no sample names one, and the reader does not look for them; the id 2 record: no sample names a library color in it, and a wrong guess changes only the outline's color) | | R13 | Bit 0 of the outline's line type: no outline | S: LT `square_blackfill_nooutline_cdr.cdr` and the other `nooutline` files of `testset/15` to `testset/25`, whose outline records all have line type 1 and whose pictures show no outline | sample | | R14 | A color record from version 5: model u16, palette u16, 4 bytes, four value bytes. Models: 2 CMYK in percent, 3 and 17 CMYK 0 to 255, 4 CMY 0 to 255, 5 blue, green, red, 9 gray 0 to 255, 20 registration, 21 blue, green, red and a tint in percent already applied; 1, 14 and 25 a library color's number (u16) and tint in percent (u16) | K L2856-L2965; S: model 25 in LT `testset/12/square_pantoneblackfill_nooutline.cdr` (number 14, tint 100), model 1 in UC `rogan_logo_cdr11.cdr` (number 4, tint 50) | public-spec (library values of models 1 and 25: sample; model 14: unconfirmed, and its color opens as a spot color without a look) | | R15 | Rectangle coordinates: width, height and one radius, three more radii from version 9, running counterclockwise from the corner at (width, 0) | K L674-L700 | public-spec | | R16 | Point list: u32 count (before version 6 as R39 gives it), the points, then one type byte each, the count held to what fits; type bits 7 and 6 move, line, curve end, control point; bit 3 closes the subpath | K L782-L787, L840-L845, L2701-L2807 | public-spec | | R17 | Ellipse coordinates: width, height, start and end angles, pie flag (u16 before 6, else u32); the radii are half the width and height; the angles turn from the ellipse's own axes, which a negative width or height points the other way | K L754-L781; S: the pies of negative height in the ellipse-sector drawings of versions 12 and 13 in UC | public-spec (axis direction of a negative size: sample) | | R18 | Polygon argument (11000): 4 bytes before 13, the side count u32, the next point u32 (the u32 after it when it is 0 or 1, else 4 bytes), 4 more from 13, rx and ry f64, the centre; the base curve is one side on a circle of 1000 mm from the top vertex to the vertex it runs to clockwise, copied once for each side | K L631-L655; S: the polygons and stars of UC `shapes_cdr10.cdr` | public-spec (base curve: sample) | -| R19 | `flgs`: byte 3 the record type, byte 2 marks the master page. A layer's own `loda` names what it is by its object type: 11 a grid, 12 guides, 17 the desktop, any other a drawing layer (version 3 one less, R32). Only a layer without a `loda` is taken by the low four bits of its byte 0: 0x0a guides, or a grid when bit 0x10 is also set; in versions 7 to 13 0x02 the same way; 0x08 the desktop when byte 2 is set and a drawing layer when it is clear; any other a drawing layer, except [0, 1, 1] in versions 7 to 13, the desktop | K L1602-L1639 (record types); S: in every sample file of versions 3 to 25 the layer's object type agrees with its name; byte 0 does not: TDF 114901 (version 8) flags its master page's guides [2, 1, 1], desktop [0, 1, 1], grid [0x12, 0, 1] and drawing layer [8, 1, 0], and NR `ab_en_br.cdr` (version 9) flags drawing layers 0x10 and its guides 0x1a; over the sample files of versions 3 to 25, drawing layers carry 0, 0x10, 0x40, or 0x08, 0x18 or 0x58 with byte 2 clear, desktop layers 0x08, 0x18 or 0x48 with byte 2 set, guides 0x0a, 0x4a, 0x02 or (in `ab_en_br.cdr`) 0x1a, and grids 0x1a, 0x5a or 0x12 | public-spec (layer types: sample; byte 0 of a layer without a `loda`: unconfirmed, as no sample has such a layer, and a wrong guess drops or shows that layer's objects) | +| R19 | `flgs`: byte 3 the record type, byte 2 marks the master page. On a layer, group or object, bit 0x01 of byte 1 hides it and bit 0x10 of byte 0 locks it. A layer's own `loda` names what it is by its object type: 11 a grid, 12 guides, 17 the desktop, any other a drawing layer (version 3 one less, R32). Only a layer without a `loda` is taken by the low four bits of its byte 0: 0x0a guides, or a grid when bit 0x10 is also set; in versions 7 to 13 0x02 the same way; 0x08 the desktop when byte 2 is set and a drawing layer when it is clear; any other a drawing layer, except [0, 1, 1] in versions 7 to 13, the desktop | K L1602-L1639 (record types); KF L1831-L1866 (the hidden and lock bits); S: every grid layer of versions 14 to 25 in the sample files (631) carries byte 1 = 1, and 206 of the 927 of versions 7 to 13 do; desktop layers carry byte 1 = 0 except TDF 114901's [0, 1, 1]; the drawing layers with byte 1 = 1 (TDF 114901, NR `banff_ap_en.cdr` and `symbology_en.cdr`) also carry bit 0x08; of the group and object lists in the sample files, only one object of TDF 60491 (version 14) sets either bit, the lock bit; in every sample file of versions 3 to 25 the layer's object type agrees with its name; byte 0 does not: TDF 114901 (version 8) flags its master page's guides [2, 1, 1], desktop [0, 1, 1], grid [0x12, 0, 1] and drawing layer [8, 1, 0], and NR `ab_en_br.cdr` (version 9) flags drawing layers 0x10 and its guides 0x1a; over the sample files of versions 3 to 25, drawing layers carry 0, 0x10, 0x40, or 0x08, 0x18 or 0x58 with byte 2 clear, desktop layers 0x08, 0x18 or 0x48 with byte 2 set, guides 0x0a, 0x4a, 0x02 or (in `ab_en_br.cdr`) 0x1a, and grids 0x1a, 0x5a or 0x12 | public-spec (layer types: sample; byte 0 of a layer without a `loda`: unconfirmed, as no sample has such a layer, and a wrong guess drops or shows that layer's objects; bit 0x10 is also the lock bit, so a locked guides layer without a `loda` reads as a grid) | | R20 | Fill and outline arguments (20, 10): a u32 record id | K L452-L460, L548-L556 | public-spec | | R21 | Page size argument (19130): width and height | K L666-L672 | public-spec | | R22 | `LIST page` holds `LIST layr` lists, directly or in a list it holds (a `LIST gobj` in the samples); a layer holds `LIST obj ` and `LIST grp `; a page, layer or object keeps its own `loda` (and an object its `trfd`, in a `trfl` list) among its chunks or in a `LIST lgob` | K L1602-L1639 (record types); S: the chunk trees of every sample file of versions 3 to 25 | sample | @@ -92,9 +95,11 @@ file is committed. | R42 | The records of a file of version 1 or 2 run from the front of the stacking order to the back. Every record starts with the u32 24. A group or layer record is 28 bytes, and bit 0x40 of its flags byte at 26 is clear. A drawn object has that bit set (0x40 in files with the markers `e` and `m`, 0xc0 with `l`) and a u16 body size at byte 28; it is the body size plus 32 bytes long. A drawn object of another type than those of R43 gives its length otherwise, and the records after it are not read | S: TP `WI.CDR`, `FLAG.CDR`, `MENU.CDR` and `DRINKS.CDR`; the order checked against the picture of `MENU.CDR` | sample | | R43 | A drawn object of version 1 or 2: a point (two i16) at byte 32; six i32 in 16.16 fixed point at 36, `a b tx c d ty`, with x' = a x + b y + tx + the point's x and y' = c x + d y + ty + the point's y; the object type at 60 (0 rectangle, 1 ellipse, 2 curve, 3 text); a byte at 67 that is not 0 when the object is outlined, the outline's width (u16) at 68 and its color at 74; the fill type (0 none, 1 uniform) and its color after it, at 94 and 95 with the marker `e` and at 105 and 106 with `l` and `m`; the shape from byte 114 with `e` and 136 with `l` and `m`. Colors are as R36 | S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`) and `MENU.CDR` (`l`), checked against the pictures of `FLAG.CDR` and `MENU.CDR` | sample | | R44 | Shapes of version 1 or 2: a rectangle's width and height (i16), then a corner radius; an ellipse's width and height, then two angles; a curve's point list as R39 and R16 | S: rectangles in TP `FLAG.CDR`, ellipses and curves in TP `WI.CDR`, curves in TP `MENU.CDR` | sample (the radius of files with the marker `e`, which no sample shows, and how the angles make an arc: unconfirmed; a radius is kept only when it is at most half the shorter side, and an ellipse whose angles differ is left out with a warning) | -| R45 | `LIST stlt` from version 7: a u32 style count, and when it is not 0: the fill table (a u32 count, entries of a table id, 4 bytes and a `fild` id, 12 bytes each, 60 from version 13), the outline table (12-byte entries laid out the same way, naming `outl` ids), the text tables (fonts of 44 bytes, 60 from version 10; alignments of 12; spacings of 52; tables of 152 and 784; bullets whose length a u32 inside them sets; indents of 28; hyphenation of 32, 36 from 13; drop caps of 28; from 8.01 a table of 12), then the styles: kind (u32), id, parent id, 8 bytes, name length and name (bytes before 12, UTF-16 units from it), the fill and outline table ids, then 16 bytes (20 from 8.01) for kinds above 1 and 20 more for kinds above 2. An object names its style in argument 200 (u32). An object without argument 20 or 10 takes the fill or outline of its style; a style whose table id is 0 takes its parent's | K L593-L600, L852, L1926-L2198; S: UC `outl_width_cdr7.cdr`, one of whose lines carries argument 200 and neither 10 nor 20 and names the style whose outline is black and 0.003 inch wide and whose fill is none, as the file's picture shows; the table parses exactly to the end of the list in each of the 498 sample files of versions 7 to 15 that has one, and every object with argument 200 in them names a style whose table ids are in the tables | public-spec (what the table ids name, and that an object takes its style's fill and outline: sample; a style taking its parent's entry: unconfirmed, as only text styles in the samples leave theirs to the parent, and a wrong guess draws a shape without that fill or outline) | -| R46 | A clipping container carries argument 8005; its first u32 is the id that the `spnd` chunk (a u32) of one `LIST grp ` in the document's `LIST clpt` holds. That group's objects are the ones the container clips; they keep their own transforms, in page space like the container's | K L252, L860-L862, L1895-L1901 (the argument and the chunk); S: LT `powerclipsquare_blackfill_whiterectangleinside` of `testset/12` to `testset/25` and eight UC files of versions 7 to 13, in each of which the id in argument 8005 matches one group's `spnd`; in the UC file of version 7 the group's box, -1.96 to 1.97 inches across, overlaps the container's, -1.81 to 1.84 inches, and the file's picture shows the group cut to the container | public-spec (what the id names, and the space of the group's objects: sample) | -| R47 | Argument 8000 marks an object seen through: a lens or a transparency. The reader does not apply it, and names lenses in the warnings | K L859 (the argument); S: of the sample files of versions 7 to 25, the argument is on the see-through objects that the pictures of LT `square_blackfill_nooutline_transparency50percent` of `testset/12` to `testset/25`, TDF 80103 and eight UC lens test files of versions 7 to 13 show, and otherwise only on text in UC `fancytext_cdr7.cdr` to `fancytext_x3.cdr` and on two objects of TDF 114901. The value K reads at byte 10 (14 from version 13) is not the transparency in these samples | public-spec (the argument: K; what it marks: sample; its layout: unconfirmed, and it is not read) | +| R45 | `LIST stlt` from version 7: a u32 style count, and when it is not 0: the fill table (a u32 count, entries of a table id, 4 bytes and a `fild` id, 12 bytes each, 60 from version 13), the outline table (12-byte entries laid out the same way, naming `outl` ids), the text tables (fonts of 44 bytes, 60 from version 10; alignments of 12; spacings of 52; tables of 152 and 784; bullets whose length a u32 inside them sets; indents of 28; hyphenation of 32, 36 from 13; drop caps of 28; from 8.01 a table of 12), then the styles: kind (u32), id, parent id, 8 bytes, name length and name (bytes before 12, UTF-16 units from it), the fill and outline table ids, then 16 bytes (20 from 8.01) for kinds above 1 and 20 more for kinds above 2. An object names its style in argument 200 (u16 before version 6, u32 from it). An object without argument 20 or 10 takes the fill or outline of its style; a style whose table id is 0 takes its parent's | K L593-L600, L852, L1926-L2198; S: UC `outl_width_cdr7.cdr`, one of whose lines carries argument 200 and neither 10 nor 20 and names the style whose outline is black and 0.003 inch wide and whose fill is none, as the file's picture shows; the table parses exactly to the end of the list in each of the 498 sample files of versions 7 to 15 that has one, and every object with argument 200 in them names a style whose table ids are in the tables; argument 200 is 2 bytes on all 844 objects of versions 4 and 5 in the sample files that carry it, and 4 bytes on all 18 of version 6 | public-spec (what the table ids name, and that an object takes its style's fill and outline: sample; a style taking its parent's entry: unconfirmed, as only text styles in the samples leave theirs to the parent, and a wrong guess draws a shape without that fill or outline) | +| R46 | A clipping container carries argument 8005; its first u32 is the id that the `spnd` chunk (a u32, a u16 before version 6) of one `LIST grp ` in the document's `LIST clpt` holds. That group's objects are the ones the container clips; they keep their own transforms, in page space like the container's | K L252, L860-L862, L1895-L1901 (the argument and the chunk); S: LT `powerclipsquare_blackfill_whiterectangleinside` of `testset/12` to `testset/25` and eight UC files of versions 7 to 13, in each of which the id in argument 8005 matches one group's `spnd`; in the UC file of version 7 the group's box, -1.96 to 1.97 inches across, overlaps the container's, -1.81 to 1.84 inches, and the file's picture shows the group cut to the container | public-spec (what the id names, and the space of the group's objects: sample) | +| R47 | Argument 8000 marks an object seen through: a lens or a transparency. From version 13 it holds records of a u32 version, a u32 length and a body; a body of version 1300 that is 117 bytes long holds an f64 at byte 61 and a merge mode byte at byte 77, which the reader applies as a uniform transparency. VectorCraft reads the f64 as the transparency in percent (0 opaque, 100 clear) and maps the merge modes 0 normal, 9 multiply, 11 lighten, 12 darken, 14 color, 15 hue, 16 saturation, 17 luminosity, 24 difference, 28 screen, 29 overlay, 30 soft light, 31 hard light, 33 color dodge, 34 color burn and 36 exclusion to its blend modes. Other merge modes, other records (a lens record of version 13 is 84 bytes) and the argument before version 13 are not applied, and the reader names them with lenses in the warnings | K L859 (the argument); KF L707-L798 (the records, the 117-byte body and the merge modes); S: the version 1300 record of LT `square_blackfill_nooutline_transparency50percent` of `testset/15` to `testset/25` is 117 bytes long, with 50.0 at byte 61 and 0 at byte 77; the lens records of UC `corel_lens_test_x3.cdr` (13) are 84 bytes long; of the sample files of versions 7 to 25, the argument is on the see-through objects that the pictures of LT `square_blackfill_nooutline_transparency50percent` of `testset/12` to `testset/25`, TDF 80103 and eight UC lens test files of versions 7 to 13 show, and otherwise only on text in UC `fancytext_cdr7.cdr` to `fancytext_x3.cdr` and on two objects of TDF 114901. The value K reads at byte 10 (14 from version 13) is not the transparency in these samples | public-spec (the argument: K; what it marks: sample; the direction of the value: VectorCraft's own reading, as every sample is at 50%, and a wrong reading shows a 25% transparency at 75%; the layout before version 13: unconfirmed, and it is not read) | | R48 | Bit 2 (0x04) of the outline's line type marks the outline dashed; the dashes of an outline without it are not drawn | S: every outline of versions 6 to 25 in the sample files with that bit set (316 of them, in 29 files) stores dashes; TDF 76771 (version 15) stores dashes 2 and 1 in an outline of line type 0x22, and the file's picture draws that outline solid | sample | | R49 | Bit 4 (0x10) of the outline's line type puts the outline behind the fill | S: UC `outl_behind_fill_cdr7.cdr` to `outl_behind_fill_x3.cdr`, whose outline of line type 0x12 the file's picture shows behind the fill, and whose other outlines (0x02) it shows over the fill | sample | | R50 | Bit 5 (0x20) of the outline's line type scales the outline's width and dashes with the shape's matrix. The engine multiplies them by the square root of the matrix's area factor (VectorCraft's own value for a matrix that scales x and y differently) | S: UC `outl_scale_with_cdr7.cdr` to `outl_scale_with_cdr12.cdr`, of whose outlines only one, 3.969 mm wide, has line type 0x22 and the others 0x02 or 0x01; TDF 76771 (version 15), whose outline of line type 0x22 is 10 mm wide on a shape that the matrix stretches and skews, and whose picture draws that outline several times wider and skewed | sample (the bit; the single width for a matrix that scales x and y differently: VectorCraft's own) | +| R51 | A `trfd` offsets table holds one offset more than the entries; each entry runs from its offset to the next, and the last offset is the record's end | KF L1079, L1113-L1121; S: every `trfd` of versions 4 to 25 in the sample files (25,425 records) has the extra offset, equal to the record's length | public-spec | +| R52 | Byte 0 of argument 14001 is the fill's winding flag. VectorCraft reads a byte other than 0 as the nonzero fill rule, and 0 or an object without the argument as even-odd | KF L575-L583, L1047; S: the argument is 4 bytes in the sample files that carry it, with byte 0 = 1 on LT `complexshape_blackfill_nooutline` of `testset/12` and `testset/15` to `testset/25` and on objects of TDF 127576 (13) and 60026 (14), and 0 on 27 objects of TP `example.cdr` (17) | public-spec (the flag: KF; which rule each value means, and the rule without the argument: VectorCraft's own reading, and a wrong reading fills or leaves holes where a curve's subpaths overlap) | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index 266dd35638..58117d1f3c 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -13,6 +13,7 @@ with each object's transform. It does not write `.cdr` files. | ZIP packages: `content/riffData.cdr` (versions 14 and 15), `content/root.dat` with the data streams `content/dataFileList.dat` names (16 on) | the RIFF chunk tree; a data stream is inflated only when a chunk the reader reads, or a list it splits, points into it | | Pages, the page size in `mcfg` or a page's own size | pages, laid out by the engine as artboards side by side | | Layers (drawing, desktop, guides and grid layers), the master page's among them | layers by name and kind | +| The hidden and locked flags of layers, groups and objects | flags | | Guidelines (object type 0x16, and the version 7 `guid` chunk) | guidelines at their point and angle | | Groups (`LIST grp `) | groups | | Clipping containers and the groups of `LIST clpt` they clip | the container with the objects it clips | @@ -21,15 +22,22 @@ with each object's transform. It does not write `.cdr` files. | Ellipses, arcs and pies | ellipses, and paths for arcs and pies | | Polygons and stars (a base side copied for each side) | paths | | Uniform fills: CMYK, CMY, RGB, gray, registration, library colors | colors, spot colors with their tints | -| Outlines: width, caps, joins, dashes, the no-outline and behind-the-fill flags | outlines | +| The fill's winding flag | the nonzero fill rule, or even-odd | +| Outlines: width, caps, joins, dashes, the no-outline and behind-the-fill flags, and from version 13 a library color named in their property list | outlines | +| Uniform transparency (version 13 on) and its merge mode | the shape's opacity and blend mode | | Styles (`LIST stlt`, versions 7 to 15) that objects name | the fill and outline of an object that has none of its own | Text, bitmaps, linked groups (blends, contours, brush strokes), B-spline curves, fountain, -pattern, texture and PostScript fills, outline arrowheads, lenses and object transparency are not +pattern, texture and PostScript fills, outline arrowheads, lenses, transparency other than uniform +transparency of version 13 and later, and merge modes without a VectorCraft blend mode are not read; the drawing's `warnings` name each kind it held. Drawings of versions after 27 are refused, and so are packages that are encrypted, ZIP64 archives or split across files. +VectorCraft reads a uniform transparency's stored value as the transparency in percent (0 opaque, +100 clear), and a winding flag other than 0 as the nonzero fill rule. These are VectorCraft's own +readings: no public source states either direction. + ## Versions 1 to 4 Public specifications cover only parts of these versions, such as the version 3 fill and page diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs index 935021d29a..923c9155cd 100644 --- a/crates/cdr/src/build.rs +++ b/crates/cdr/src/build.rs @@ -8,7 +8,7 @@ use crate::geometry; use crate::inline; use crate::layout::{self, Profile}; use crate::limits::Budget; -use crate::model::{Color, Drawing, Geometry, Guideline, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape}; +use crate::model::{Blend, Color, Drawing, Flags, Geometry, Guideline, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape}; use crate::records::{self, Loda}; use crate::riff::{Chunk, Index, push}; use crate::styles::Styles; @@ -21,7 +21,7 @@ const CURVE: u32 = 3; const POLYGON: u32 = 0x14; const GUIDELINE: u32 = 0x16; const PATH: u32 = 0x25; -/// Argument types (R6, R20, R21, R33). +/// Argument types (R6, R20, R21, R33, R52). const ARG_OUTLINE: u32 = 10; const ARG_FILL: u32 = 20; const ARG_COORDS: u32 = 30; @@ -31,6 +31,7 @@ const ARG_NAME: u32 = 1000; const ARG_LENS: u32 = 8000; const ARG_CONTAINER: u32 = 8005; const ARG_POLYGON: u32 = 11000; +const ARG_WINDING: u32 = 14001; const ARG_GUIDE: u32 = 16000; const ARG_PAGE_SIZE: u32 = 19130; @@ -97,8 +98,10 @@ pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec) open_clips: Vec::new(), clip_cut: false, }; + // The `spnd` id is a u16 in files of 16-bit fields (R46). + let spnd = |b: &[u8]| if p.short { Rd::new(b).u16().map(u32::from) } else { Rd::new(b).u32() }; for g in found.clpt.iter().flat_map(|c| ix.children(c)).filter(|g| g.is_list(b"grp ")) { - if let Some(id) = ix.children(g).iter().find(|c| &c.id == b"spnd").and_then(|c| Rd::new(ix.data(c)).u32()) { + if let Some(id) = ix.children(g).iter().find(|c| &c.id == b"spnd").and_then(|c| spnd(ix.data(c))) { cx.clips.entry(id).or_insert(g); } } @@ -216,7 +219,16 @@ fn guideline(b: &[u8], p: &Profile) -> Option { let mut r = Rd::at(b, 12); let angle = f64::from(r.i32()?) / 1_000_000.0; let at = Pt { x: records::coord(&mut r, p)?, y: records::coord(&mut r, p)? }; - Some(Guideline { at, angle }) + Some(Guideline { at, angle, hidden: false }) +} + +/// Marks the guidelines from `from` on hidden when `flags` hide what holds them. +fn hide_guides(guides: &mut [Guideline], from: usize, flags: Flags) { + if flags.hidden { + for g in guides.iter_mut().skip(from) { + g.hidden = true; + } + } } /// A list's flags (R19): four bytes. @@ -225,6 +237,23 @@ fn flags(ix: &Index, list: &Chunk) -> Option<[u8; 4]> { ix.data(c).get(..4)?.try_into().ok() } +/// Whether a layer, group or object list is hidden (bit 0x01 of byte 1) or locked (bit 0x10 of +/// byte 0) (R19). +fn state(ix: &Index, list: &Chunk) -> Flags { + flags(ix, list).map_or(Flags::default(), |[b0, b1, _, _]| Flags { hidden: b1 & 0x01 != 0, locked: b0 & 0x10 != 0 }) +} + +/// `o` with `f` added to its own flags: the objects of a group left ungrouped keep the group's. +fn inherit(o: &mut Object, f: Flags) { + let own = match o { + Object::Shape(s) => &mut s.flags, + Object::Group { flags, .. } => flags, + Object::Clip { container, .. } => &mut container.flags, + }; + own.hidden |= f.hidden; + own.locked |= f.locked; +} + /// What a layer's object type makes it (R19): 11 a grid, 12 guides, 17 the desktop, any other a /// drawing layer. Version 3 counts its types from 0, one less (R32). fn layer_kind_of_type(kind: u32, types_from_zero: bool) -> LayerKind { @@ -297,6 +326,10 @@ struct Frame<'i> { objects: Vec, /// Whether its objects form a group in the frame below. group: bool, + /// The group's own flags. + flags: Flags, + /// The first of the guidelines read inside it. + guides_from: usize, /// What places its objects after their own transforms: the matrices of the version 3 groups /// around them (R33). The identity in other versions, whose objects hold their whole transform. outer: Matrix, @@ -339,27 +372,43 @@ impl<'a, 'b> Ctx<'a, 'b> { let name = loda.and_then(|l| l.arg(ARG_NAME).map(|b| records::name(b, &self.p, self.warn))).unwrap_or_default(); let mut guides = Vec::new(); let objects = self.objects(ix.children(list), &mut guides); - Layer { name, kind, objects, guides } + let flags = state(ix, list); + hide_guides(&mut guides, 0, flags); + Layer { name, kind, flags, objects, guides } } /// The objects of a layer's chunks, groups nested, front to back; guidelines go to `guides`. fn objects(&mut self, chunks: &'b [Chunk], guides: &mut Vec) -> Vec { let ix = self.ix; - let mut stack = vec![Frame { chunks, next: 0, objects: Vec::new(), group: false, outer: Matrix::IDENTITY }]; + let mut stack = vec![Frame { + chunks, + next: 0, + objects: Vec::new(), + group: false, + flags: Flags::default(), + guides_from: guides.len(), + outer: Matrix::IDENTITY, + }]; loop { let Some(top) = stack.last_mut() else { return Vec::new() }; let (here, outer) = (top.chunks, top.outer); let Some(c) = here.get(top.next) else { let Some(done) = stack.pop() else { return Vec::new() }; + // A hidden group hides the guidelines inside it. + hide_guides(guides, done.guides_from, done.flags); match stack.last_mut() { // A group counts toward the objects a read maps; past them its objects stay, - // ungrouped. + // ungrouped, with the group's flags. Some(parent) if done.group && !done.objects.is_empty() => { if self.budget.take_object() { - parent.objects.push(Object::Group(done.objects)); + parent.objects.push(Object::Group { objects: done.objects, flags: done.flags }); } else { push(self.warn, Warning::TooDeep); - parent.objects.extend(done.objects); + let mut objects = done.objects; + for o in &mut objects { + inherit(o, done.flags); + } + parent.objects.extend(objects); } } Some(parent) if !done.group => parent.objects.extend(done.objects), @@ -382,14 +431,17 @@ impl<'a, 'b> Ctx<'a, 'b> { } } else if c.is_list(b"grp ") { let own = self.group_placement(c); - stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: true, outer: outer.after(&own) }); + let flags = state(ix, c); + let guides_from = guides.len(); + stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: true, flags, guides_from, outer: outer.after(&own) }); } else if c.is_list(b"lnkg") { // Linked groups (brush strokes, blends, contours) place their objects with a // matrix of their own, which this reader doesn't apply: they are left out. push(self.warn, Warning::UnsupportedObjects); } else if c.id == crate::riff::LIST && !c.is_list(b"lgob") { // Other lists under a layer are looked through (R22). - stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: false, outer }); + let guides_from = guides.len(); + stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: false, flags: Flags::default(), guides_from, outer }); } } } @@ -440,18 +492,28 @@ impl<'a, 'b> Ctx<'a, 'b> { push(self.warn, Warning::TooDeep); return None; } + let flags = state(ix, list); if loda.kind == GUIDELINE { - guides.extend(loda.arg(ARG_GUIDE).and_then(|b| guideline(b, &self.p))); + guides.extend(loda.arg(ARG_GUIDE).and_then(|b| guideline(b, &self.p)).map(|g| Guideline { hidden: flags.hidden, ..g })); return None; } if self.p.inline_styles { - return self.inline_object(&loda, outer); + return self.inline_object(&loda, outer, flags); } let geometry = self.geometry(&loda)?; - // A lens or transparency (R47) is not applied: the shape shows opaque. - if loda.arg(ARG_LENS).is_some() { - push(self.warn, Warning::Lenses); - } + // A uniform transparency from version 13 applies (R47); a lens, and a transparency of + // another kind or version, is not applied: the shape shows opaque. + let (opacity, blend) = match loda.arg(ARG_LENS) { + None => (1.0, Blend::Normal), + Some(b) => match records::transparency(b).filter(|_| self.p.tagged) { + Some(t) => t, + None => { + push(self.warn, Warning::Lenses); + (1.0, Blend::Normal) + } + }, + }; + let nonzero = self.nonzero(&loda); // A transform that is there but can't be read is damage; the shape stays where it is. let matrix = match own_chunk(ix, list, &[b"trfd"]) { None => Matrix::IDENTITY, @@ -460,8 +522,9 @@ impl<'a, 'b> Ctx<'a, 'b> { Matrix::IDENTITY }), }; - // Without a fill or outline argument of its own, an object takes its style's (R45). - let style = loda.arg(ARG_STYLE).and_then(|b| self.id(b)); + // Without a fill or outline argument of its own, an object takes its style's (R45). The + // style id is a u16 in files of 16-bit fields. + let style = loda.arg(ARG_STYLE).and_then(|b| if self.p.short { self.short_id(b) } else { self.id(b) }); let fill_id = match loda.arg(ARG_FILL) { Some(b) => self.id(b), None => style.and_then(|s| self.style_entry(s, Styles::fill)), @@ -472,7 +535,7 @@ impl<'a, 'b> Ctx<'a, 'b> { }; let fill = fill_id.and_then(|id| self.fill(id)); let outline = outline_id.and_then(|id| self.outline(id)); - let shape = Box::new(Shape { geometry, matrix, fill, outline }); + let shape = Box::new(Shape { geometry, matrix, fill, outline, nonzero, opacity, blend, flags }); // A container clips the group its argument 8005 names (R46). Some(match loda.arg(ARG_CONTAINER).and_then(|b| self.id(b)) { Some(id) => self.clip(shape, id, guides), @@ -501,9 +564,18 @@ impl<'a, 'b> Ctx<'a, 'b> { guides.truncate(mark); return Object::Shape(container); } + // The clipped group's own flags hide or lock the objects it holds; it and the container + // hide its guidelines. + let flags = state(ix, group); + hide_guides(guides, mark, flags); + hide_guides(guides, mark, container.flags); if objects.is_empty() { return Object::Shape(container); } + let mut objects = objects; + for o in &mut objects { + inherit(o, flags); + } Object::Clip { container, objects } } @@ -516,6 +588,28 @@ impl<'a, 'b> Ctx<'a, 'b> { id } + /// A u16 id at the start of argument `b`; an argument too short for one is damage. + fn short_id(&mut self, b: &[u8]) -> Option { + let id = Rd::new(b).u16().map(u32::from); + if id.is_none() { + push(self.warn, Warning::Damaged); + } + id + } + + /// Whether the object's fill rule is nonzero: byte 0 of argument 14001 set (R52). Without the + /// argument the fill is even-odd; an argument without its byte is damage. + fn nonzero(&mut self, loda: &Loda) -> bool { + let Some(b) = loda.arg(ARG_WINDING) else { return false }; + match b.first() { + Some(v) => *v != 0, + None => { + push(self.warn, Warning::Damaged); + false + } + } + } + /// The fill or outline record that style `id` names; a style table that doesn't parse is /// damage, and the object is drawn without it. fn style_entry(&mut self, id: u32, entry: fn(&Styles, u32) -> Option) -> Option { @@ -530,7 +624,7 @@ impl<'a, 'b> Ctx<'a, 'b> { /// A version 3 object, whose transforms, fill and outline are arguments of its own record /// (R33, R34, R35). A fill or an outline that is there but can't be read is damage. - fn inline_object(&mut self, loda: &Loda, outer: &Matrix) -> Option { + fn inline_object(&mut self, loda: &Loda, outer: &Matrix, flags: Flags) -> Option { let own = match loda.arg(ARG_TRANSFORMS) { None => Matrix::IDENTITY, Some(arg) => self.placement(arg), @@ -558,7 +652,9 @@ impl<'a, 'b> Ctx<'a, 'b> { } o }); - Some(Object::Shape(Box::new(Shape { geometry, matrix: outer.after(&own), fill, outline }))) + let nonzero = self.nonzero(loda); + let shape = Shape { nonzero, flags, ..Shape::new(geometry, outer.after(&own), fill, outline) }; + Some(Object::Shape(Box::new(shape))) } fn geometry(&mut self, loda: &Loda) -> Option { diff --git a/crates/cdr/src/geometry.rs b/crates/cdr/src/geometry.rs index cb883f7cf7..59f336d2ee 100644 --- a/crates/cdr/src/geometry.rs +++ b/crates/cdr/src/geometry.rs @@ -151,8 +151,8 @@ pub(crate) fn rect(b: &[u8], p: &Profile) -> Option { /// A rectangle record from version 15 (R29): width and height as f64 coordinate units, two scale /// factors that repeat the transform's (not applied), the scale-with flag and 7 bytes, then the /// four radii as f64 16 bytes apart. With the flag clear each radius is a share of half the shorter -/// side; with it set the radius is in inches. A corner is held to the shorter side, and sizes to -/// the range of the 32-bit coordinates of earlier versions. +/// side; with it set the radius is in inches. A corner is held to half the shorter side, and +/// sizes to the range of the 32-bit coordinates of earlier versions. fn rect_f64(b: &[u8], p: &Profile) -> Option { let mut r = Rd::new(b); let size = |v: f64| (v.abs() <= f64::from(i32::MAX)).then(|| v * p.unit()); @@ -168,7 +168,7 @@ fn rect_f64(b: &[u8], p: &Profile) -> Option { } let v = r.f64()?.abs(); let radius = if inches { v * 72.0 } else { v * short / 2.0 }; - *slot = radius.min(short); + *slot = radius.min(short / 2.0); } Some(Geometry::Rect { w, h, radii }) } diff --git a/crates/cdr/src/model.rs b/crates/cdr/src/model.rs index 6e48fef497..c95a051ee3 100644 --- a/crates/cdr/src/model.rs +++ b/crates/cdr/src/model.rs @@ -112,18 +112,64 @@ pub struct Outline { pub scale_with: bool, } +/// Whether a layer, group or shape is hidden or locked. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Flags { + pub hidden: bool, + pub locked: bool, +} + +/// How a shape's colors combine with the art below it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Blend { + #[default] + Normal, + Multiply, + Screen, + Overlay, + SoftLight, + HardLight, + ColorDodge, + ColorBurn, + Darken, + Lighten, + Difference, + Exclusion, + Hue, + Saturation, + Color, + Luminosity, +} + #[derive(Clone, Debug, PartialEq)] pub struct Shape { pub geometry: Geometry, pub matrix: Matrix, pub fill: Option, pub outline: Option, + /// The fill covers every area its subpaths wind around (nonzero); otherwise subpaths that + /// overlap leave holes (even-odd). + pub nonzero: bool, + /// 1 opaque, 0 clear. + pub opacity: f32, + pub blend: Blend, + pub flags: Flags, +} + +impl Shape { + /// An opaque, shown shape filled even-odd. + pub fn new(geometry: Geometry, matrix: Matrix, fill: Option, outline: Option) -> Shape { + Shape { geometry, matrix, fill, outline, nonzero: false, opacity: 1.0, blend: Blend::Normal, flags: Flags::default() } + } } #[derive(Clone, Debug, PartialEq)] pub enum Object { Shape(Box), - Group(Vec), + Group { + objects: Vec, + flags: Flags, + }, /// A clipping container and the objects it clips: `objects` (front to back) show only /// inside the container's shape, with its fill behind them and its outline over them. Clip { @@ -137,6 +183,8 @@ pub enum Object { pub struct Guideline { pub at: Pt, pub angle: f64, + /// The guideline, a group around it or its layer is hidden. + pub hidden: bool, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -152,6 +200,7 @@ pub enum LayerKind { pub struct Layer { pub name: String, pub kind: LayerKind, + pub flags: Flags, /// Front to back, as the file lists them. pub objects: Vec, pub guides: Vec, @@ -180,7 +229,8 @@ pub enum Warning { Arrowheads, /// Envelopes, which are not applied: the shapes under them keep their outlines. Envelopes, - /// Lenses and object transparency, which are not applied: the objects show opaque. + /// Lenses, and object transparency that isn't read, which are not applied: the objects show + /// opaque. Lenses, /// Content nested deeper, or past the counts, that a read takes. TooDeep, diff --git a/crates/cdr/src/records.rs b/crates/cdr/src/records.rs index 0680583453..25908d414e 100644 --- a/crates/cdr/src/records.rs +++ b/crates/cdr/src/records.rs @@ -3,7 +3,7 @@ use crate::bytes::Rd; use crate::layout::{ColorLayout, Profile}; -use crate::model::{Cap, Color, Join, Matrix, Outline}; +use crate::model::{Blend, Cap, Color, Join, Matrix, Outline}; use crate::riff::push; use crate::{Limits, Warning}; @@ -74,7 +74,9 @@ pub(crate) fn loda<'a>(b: &'a [u8], p: &Profile, limits: &Limits, warn: &mut Vec Some(Loda { kind: kind as u32, args }) } -/// The matrices of a `trfd` record composed in file order, in points (R8). +/// The matrices of a `trfd` record composed in file order, in points (R8). Each entry ends where +/// the next offset points, and the last at the offset after it (R51); an entry too short for its +/// matrix makes the record unreadable. pub(crate) fn trfd(b: &[u8], p: &Profile) -> Option { let mut r = Rd::new(b); let (_len, count, offsets_at) = (word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?); @@ -82,8 +84,12 @@ pub(crate) fn trfd(b: &[u8], p: &Profile) -> Option { let k = p.unit(); // Each entry takes at least its offset's bytes, which bounds the count by the record's size. for i in 0..count.min(b.len() / p.word()) { - let at = word(&mut Rd::at(b, offsets_at.checked_add(i.checked_mul(p.word())?)?), p)?; - let mut e = Rd::at(b, at.checked_add(p.trfd_head)?); + let slot = offsets_at.checked_add(i.checked_mul(p.word())?)?; + let start = word(&mut Rd::at(b, slot), p)?; + // A table that stops before the last entry's end offset leaves that entry the rest of the + // record. + let end = word(&mut Rd::at(b, slot.checked_add(p.word())?), p).unwrap_or(b.len()); + let mut e = Rd::at(b.get(start..end)?, p.trfd_head); if e.u16()? != 8 { continue; } @@ -204,8 +210,8 @@ fn counted_utf16(r: &mut Rd, warn: &mut Vec) -> Option { Some(format!("{} {hash:016x}", String::from_utf16_lossy(&kept))) } -/// The color of a tagged uniform fill's property list (R11): its color record, named by the -/// library name it carries. +/// The color of the property list of a tagged uniform fill (R11) or outline (R12): its color +/// record, named by the library name it carries. fn property_color(b: &[u8], p: &Profile, warn: &mut Vec) -> Option { let mut r = Rd::new(b); let (mut found, mut name) = (None, None); @@ -304,6 +310,8 @@ fn tagged_body<'a>(r: &mut Rd<'a>) -> Option<&'a [u8]> { pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec) -> Option<(u32, Option)> { let mut r = Rd::new(b); let id = r.u32()?; + // A library color named in a record of type 2, with the warnings its read gave. + let mut named = None; if p.tagged { let mut found = false; for _ in 0..MAX_OUTLINE_RECORDS { @@ -312,7 +320,16 @@ pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec) -> Option< found = true; break; } - r.skip(len)?; + let body = r.bytes(len)?; + // Type 2 holds the outline's color as a property list, as a uniform fill does (R12). + // Only a library color with its name is taken from it; any other color comes from + // the fixed field below. + if rec == 2 { + let mut w = Vec::new(); + if let Some(c @ Color::Spot { look: Some(_), .. }) = property_color(body, p, &mut w) { + named = Some((c, w)); + } + } } if !found { return None; @@ -325,7 +342,16 @@ pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec) -> Option< r.skip(p.outl_after_stretch)?; let _nib = angle(&mut r, p)?; r.skip(p.outl_after_angle)?; - let color = color(&mut r, p, warn)?; + let color = match named { + Some((named, w)) => { + color(&mut r, p, &mut Vec::new())?; + for x in w { + push(warn, x); + } + named + } + None => color(&mut r, p, warn)?, + }; r.skip(p.outl_after_color)?; let count = usize::from(r.u16()?); let first_dash = r.pos(); @@ -365,6 +391,58 @@ pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec) -> Option< Some((id, Some(Outline { width, color, cap, join, dashes, behind_fill, scale_with }))) } +/// The opacity and blend of argument 8000 from version 13 (R47): records of a u32 version, a u32 +/// length and a body. A body of version 1300 that is [`UNIFORM_LEN`] bytes long is a uniform +/// transparency: an f64 at byte 61 and the merge mode at byte 77. VectorCraft reads the f64 as the +/// transparency in percent, 0 opaque and 100 clear. `None` for any other argument, such as a lens, +/// and for a value out of range or a merge mode without a VectorCraft blend mode. +pub(crate) fn transparency(b: &[u8]) -> Option<(f32, Blend)> { + let mut r = Rd::new(b); + while r.left() >= 8 { + let (since, len) = (r.u32()?, r.u32()? as usize); + let body = r.bytes(len)?; + if since != TAG_1300 { + continue; + } + if body.len() != UNIFORM_LEN { + return None; + } + let value = Rd::at(body, 61).f64()?; + if !(0.0..=100.0).contains(&value) { + return None; + } + return Some(((1.0 - value / 100.0) as f32, blend(*body.get(77)?)?)); + } + None +} + +/// The length of a uniform transparency's record body (R47). +const UNIFORM_LEN: usize = 117; + +/// The blend mode of a transparency's merge mode byte (R47); `None` for the modes VectorCraft has +/// no blend mode for. +fn blend(mode: u8) -> Option { + Some(match mode { + 0 => Blend::Normal, + 9 => Blend::Multiply, + 11 => Blend::Lighten, + 12 => Blend::Darken, + 14 => Blend::Color, + 15 => Blend::Hue, + 16 => Blend::Saturation, + 17 => Blend::Luminosity, + 24 => Blend::Difference, + 28 => Blend::Screen, + 29 => Blend::Overlay, + 30 => Blend::SoftLight, + 31 => Blend::HardLight, + 33 => Blend::ColorDodge, + 34 => Blend::ColorBurn, + 36 => Blend::Exclusion, + _ => return None, + }) +} + /// A name argument (R9): Windows-1252 up to a NUL before version 12, UTF-16LE from it. A name /// longer than [`MAX_NAME`] bytes or UTF-16 units keeps its first ones (without half of a /// surrogate pair) and a hash of the whole name, with a warning, as a library color's name does. diff --git a/crates/cdr/src/riff.rs b/crates/cdr/src/riff.rs index 1e06b00c08..3f041b4c37 100644 --- a/crates/cdr/src/riff.rs +++ b/crates/cdr/src/riff.rs @@ -203,9 +203,11 @@ impl<'a> Index<'a> { /// The version: the `vrsn` chunk's when it names one from 3 to 27, else the form type's (R1, /// R2). A template's form type names no version, so its `vrsn` chunk decides whatever it names /// (R28). Letters count differently from the version 24 update on (R1), so when both name a - /// version after 27 the `vrsn` chunk's is the one refused. + /// version after 27 the `vrsn` chunk's is the one refused. The `cdr8` form type alone makes a + /// file the 8.01 variant, whatever its `vrsn` chunk names (R1). pub(crate) fn version(&self) -> u16 { match self.vrsn.flatten() { + _ if self.form_version == 801 => 801, Some(v) if (layout::OLDEST_RIFF..=layout::NEWEST).contains(&v) => v, Some(v) if self.form_version == 0 => v, Some(v) if v > layout::NEWEST && self.form_version > layout::NEWEST => v, diff --git a/crates/cdr/src/synth.rs b/crates/cdr/src/synth.rs index 63f602b16c..e109d8bf1d 100644 --- a/crates/cdr/src/synth.rs +++ b/crates/cdr/src/synth.rs @@ -212,7 +212,8 @@ impl V { let table = head; let mut entries = Vec::new(); let mut offsets = Vec::new(); - let first = table + matrices.len() * w; + // The table holds one offset more than the entries: the record's end (R51). + let first = table + (matrices.len() + 1) * w; for m in matrices { offsets.push(first + entries.len()); if self.0 >= 1300 { @@ -232,6 +233,7 @@ impl V { entries.extend(v.to_le_bytes()); } } + offsets.push(first + entries.len()); let mut out = Vec::new(); for f in [first + entries.len(), matrices.len(), table] { out.extend(self.word(f)); @@ -588,10 +590,55 @@ pub fn container(id: u32) -> (u32, Vec) { (8005, [id, 1, 0, 1].iter().flat_map(|v| v.to_le_bytes()).collect()) } +/// The argument 8000 of a uniform transparency from version 13 (R47): one record of version 1300 +/// whose 117-byte body holds `percent` at byte 61 and `merge` at byte 77. +pub fn transparency(percent: f64, merge: u8) -> (u32, Vec) { + let mut body = vec![0; 117]; + body[61..69].copy_from_slice(&percent.to_le_bytes()); + body[77] = merge; + let mut out = 1300u32.to_le_bytes().to_vec(); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + (8000, out) +} + +/// A property list (R11, R12) of 12-byte color `color` and, when `name` is given, a type 8 +/// property with that library name. +pub fn properties(color: &[u8; 12], name: Option<&str>) -> Vec { + let mut out = vec![1]; + out.extend(12u32.to_le_bytes()); + out.extend(color); + if let Some(name) = name { + let mut body = vec![0; 16]; + body.extend((name.encode_utf16().count() as u32).to_le_bytes()); + body.extend(name.encode_utf16().flat_map(u16::to_le_bytes)); + out.push(8); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + } + out.extend([0, 0, 0, 0, 0]); + out +} + +/// `n` (an object, group or layer list) with its `flgs` chunk replaced by `flags` (R19). +pub fn flagged(n: Node, flags: [u8; 4]) -> Node { + match n { + Node::List(form, kids) => { + let kids = kids + .into_iter() + .map(|k| if matches!(&k, Node::Chunk(id, _) if id == b"flgs") { chunk(b"flgs", flags.to_vec()) } else { k }) + .collect(); + Node::List(form, kids) + } + chunk => chunk, + } +} + /// A RIFF drawing of `version` (7 to 13) with a style table, a clipping container and a lens: a rectangle /// that takes its fill and outline from its style, a container that clips two rectangles, one -/// with an outline behind the fill, and a rectangle with a lens; compressed when `compress`. -/// Before version 7, the [`sample`]. +/// with an outline behind the fill, a rectangle with a lens, a hidden and locked rectangle with a +/// winding flag and a uniform transparency, and a hidden group whose rectangle's outline names a +/// library color from version 13; compressed when `compress`. Before version 7, the [`sample`]. pub fn feature_sample(version: u16, compress: bool) -> Vec { if version < 700 { return sample(version, false); @@ -606,6 +653,15 @@ pub fn feature_sample(version: u16, compress: bool) -> Vec { let style = (200, 0x10u32.to_le_bytes().to_vec()); let clipped = vec![rect(30.0, vec![style.clone()], 10.0), rect(30.0, vec![(10, 3u32.to_le_bytes().to_vec()), (20, 1u32.to_le_bytes().to_vec())], -10.0)]; + // From version 13 outline 4 names a library color in a record of type 2 (R12). + let mut named = v.outline(4, Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }, &color(25, [7, 0, 100, 0]), &[]); + if version >= 1300 { + let props = properties(&color(5, [0, 0, 255, 0]), Some("Sky Blue")); + let mut record = 2u32.to_le_bytes().to_vec(); + record.extend((props.len() as u32).to_le_bytes()); + record.extend(props); + named.splice(4..4, record); + } let doc = list( b"doc ", vec![ @@ -616,6 +672,7 @@ pub fn feature_sample(version: u16, compress: bool) -> Vec { vec![ chunk(b"outl", v.outline(2, Pen { line_type: 4, width: 2.0, cap: 1, join: 1 }, &black, &[3, 1])), chunk(b"outl", v.outline(3, Pen { line_type: 0x12, width: 4.0, cap: 0, join: 0 }, &black, &[])), + chunk(b"outl", named), ], ), stlt(v, &[(0x100, 1)], &[(0x200, 2)], &[Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }], true), @@ -625,7 +682,10 @@ pub fn feature_sample(version: u16, compress: bool) -> Vec { let objects = vec![ rect(20.0, vec![style.clone()], 0.0), rect(40.0, vec![style.clone(), container(7)], 50.0), - rect(20.0, vec![style, (8000, vec![1, 0, 0, 0])], -50.0), + rect(20.0, vec![style.clone(), (8000, vec![1, 0, 0, 0])], -50.0), + // Hidden and locked, filled nonzero, 25% transparent with merge mode 9 (R19, R47, R52). + flagged(rect(10.0, vec![style.clone(), (14001, vec![1, 0, 0, 0]), transparency(25.0, 9)], 80.0), [0x10, 1, 0, 0x08]), + list(b"grp ", vec![chunk(b"flgs", vec![0, 1, 0, 0x10]), rect(10.0, vec![(10, 4u32.to_le_bytes().to_vec())], -80.0)]), ]; let page = page(false, vec![layer(v, [0, 0, 0, 0x98], "Art", objects)]); let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; diff --git a/crates/cdr/src/wl.rs b/crates/cdr/src/wl.rs index 3ec6f26c79..bae22ba5a0 100644 --- a/crates/cdr/src/wl.rs +++ b/crates/cdr/src/wl.rs @@ -8,7 +8,7 @@ use crate::bytes::{Rd, u32_at}; use crate::geometry; use crate::layout::{self, Profile}; use crate::limits::Budget; -use crate::model::{Cap, Drawing, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Shape}; +use crate::model::{Cap, Drawing, Flags, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Shape}; use crate::records::{self, coord, fixed}; use crate::riff::push; use crate::{Error, Warning}; @@ -118,7 +118,7 @@ pub(crate) fn drawing(b: &[u8], budget: &mut Budget) -> Result { push(&mut warn, Warning::Damaged); } let version = if marker == b'e' { 100 } else { 200 }; - let layer = Layer { name: String::new(), kind: LayerKind::Drawing, objects, guides: Vec::new() }; + let layer = Layer { name: String::new(), kind: LayerKind::Drawing, flags: Flags::default(), objects, guides: Vec::new() }; let pages = vec![Page { size: None, layers: vec![layer] }]; Ok(Drawing { version, page_size: page_box(b, settings, &p), pages, master: Vec::new(), guides: Vec::new(), warnings: warn }) } @@ -196,7 +196,7 @@ fn shape(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mu } else { None }; - Some(Some(Shape { geometry, matrix, fill, outline })) + Some(Some(Shape::new(geometry, matrix, fill, outline))) } /// A rectangle (R44): its width and height, then a corner radius, which is kept when it is at most diff --git a/crates/cdr/tests/it/read.rs b/crates/cdr/tests/it/read.rs index 370db2f2fe..3a32cc0d8a 100644 --- a/crates/cdr/tests/it/read.rs +++ b/crates/cdr/tests/it/read.rs @@ -2,7 +2,7 @@ //! hostile files. use proptest::prelude::*; -use vectorcraft_cdr::model::{Cap, Color, Geometry, Join, LayerKind, Matrix, Object, Segment}; +use vectorcraft_cdr::model::{Blend, Cap, Color, Flags, Geometry, Join, LayerKind, Matrix, Object, Segment}; use vectorcraft_cdr::synth::{self, V, chunk, list}; use vectorcraft_cdr::{Error, Limits, Warning, read}; @@ -12,7 +12,7 @@ fn shapes(objects: &[Object]) -> Vec<&vectorcraft_cdr::model::Shape> { while let Some(o) = stack.pop() { match o { Object::Shape(s) => out.push(&**s), - Object::Group(kids) => stack.extend(kids.iter().rev()), + Object::Group { objects: kids, .. } => stack.extend(kids.iter().rev()), Object::Clip { container, objects } => { out.push(&**container); stack.extend(objects.iter().rev()); @@ -30,7 +30,7 @@ fn check_pages(d: &vectorcraft_cdr::Drawing, version: u16) { assert_eq!(d.pages.len(), 1, "{version}"); let art = &d.pages[0].layers[0]; assert_eq!((art.name.as_str(), art.kind), ("Art", LayerKind::Drawing)); - assert!(matches!(art.objects[3], Object::Group(ref g) if g.len() == 2)); + assert!(matches!(art.objects[3], Object::Group { objects: ref g, .. } if g.len() == 2)); assert!(d.warnings.contains(&Warning::UnsupportedObjects)); // The master page: its guideline every page shows, and its desktop object. if version >= 600 { @@ -130,7 +130,9 @@ fn version_3_groups_place_their_objects() { let d = read(&drawing3(vec![outer, rect3(&[shift(7.2, 0.0)])]), Limits::default()).unwrap(); assert!(d.warnings.is_empty(), "{:?}", d.warnings); let objects = &d.pages[0].layers[0].objects; - assert!(matches!(&objects[0], Object::Group(g) if matches!(&g[0], Object::Group(i) if i.len() == 1) && g.len() == 2)); + assert!( + matches!(&objects[0], Object::Group { objects: g, .. } if matches!(&g[0], Object::Group { objects: i, .. } if i.len() == 1) && g.len() == 2) + ); let s = shapes(objects); let close = |m: &Matrix, want: [f64; 6]| m.0.iter().zip(want).all(|(a, b)| (a - b).abs() < 0.01); // Its own shift, then the inner group's scale, then the outer group's shift. @@ -159,7 +161,7 @@ fn version_3_objects_and_groups_under_an_envelope_keep_their_outlines_and_matric let d = read(&drawing3(vec![bent, moved, group, rect3(&[])]), Limits::default()).unwrap(); let objects = &d.pages[0].layers[0].objects; assert_eq!(objects.len(), 4); - assert!(matches!(&objects[2], Object::Group(g) if g.len() == 1)); + assert!(matches!(&objects[2], Object::Group { objects: g, .. } if g.len() == 1)); let s = shapes(objects); assert_eq!(s.len(), 4); assert!(matches!(s[0].geometry, Geometry::Rect { .. }) && s[0].matrix == Matrix::IDENTITY); @@ -832,7 +834,7 @@ fn redirect_records_that_lead_nowhere_count_toward_the_chunk_limit() { fn rectangles_from_version_15_give_radii_as_shares_of_half_the_shorter_side() { let v = V(1500); let mut c = synth::V(1500).rect(100.0, 50.0, 0.0); - // The four shares: 0.2, 0.4, 0, and 3, which the shorter side holds to 50 pt. + // The four shares: 0.2, 0.4, 0, and 3, which half the shorter side holds to 25 pt. for (k, share) in [0.2f64, 0.4, 0.0, 3.0].iter().enumerate() { let at = 40 + 24 * k; c[at..at + 8].copy_from_slice(&share.to_le_bytes()); @@ -843,16 +845,16 @@ fn rectangles_from_version_15_give_radii_as_shares_of_half_the_shorter_side() { let s = shapes(&d.pages[0].layers[0].objects); let Geometry::Rect { w, h, radii } = s[0].geometry else { panic!("{:?}", s[0].geometry) }; assert!((w - 100.0).abs() < 1e-6 && (h - 50.0).abs() < 1e-6); - for (got, want) in radii.iter().zip([5.0, 10.0, 0.0, 50.0]) { + for (got, want) in radii.iter().zip([5.0, 10.0, 0.0, 25.0]) { assert!((got - want).abs() < 1e-6, "{radii:?}"); } - // With the scale-with flag set the radii are inches, held to the shorter side as well. + // With the scale-with flag set the radii are inches, held to half the shorter side as well. c[32] = 1; let file = synth::riff(1500, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c)], None)])])]); let d = read(&file, Limits::default()).unwrap(); let s = shapes(&d.pages[0].layers[0].objects); let Geometry::Rect { radii, .. } = s[0].geometry else { panic!("{:?}", s[0].geometry) }; - for (got, want) in radii.iter().zip([14.4, 28.8, 0.0, 50.0]) { + for (got, want) in radii.iter().zip([14.4, 25.0, 0.0, 25.0]) { assert!((got - want).abs() < 1e-6, "{radii:?}"); } } @@ -1035,7 +1037,7 @@ fn arguments_past_the_limit_leave_the_first_ones_paired_with_their_types() { #[test] fn groups_count_toward_the_object_limit() { fn count(objects: &[Object]) -> usize { - objects.iter().map(|o| 1 + if let Object::Group(kids) = o { count(kids) } else { 0 }).sum() + objects.iter().map(|o| 1 + if let Object::Group { objects: kids, .. } = o { count(kids) } else { 0 }).sum() } let v = V(1100); let rect = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); @@ -1044,7 +1046,7 @@ fn groups_count_toward_the_object_limit() { let d = read(&file, Limits { objects: 2, ..Limits::default() }).unwrap(); let objects = &d.pages[0].layers[0].objects; assert_eq!(count(objects), 2, "{objects:?}"); - assert!(matches!(objects.as_slice(), [Object::Group(kids)] if matches!(kids.as_slice(), [Object::Shape(_)])), "{objects:?}"); + assert!(matches!(objects.as_slice(), [Object::Group { objects: kids, .. }] if matches!(kids.as_slice(), [Object::Shape(_)])), "{objects:?}"); assert!(d.warnings.contains(&Warning::TooDeep)); } @@ -1289,14 +1291,22 @@ fn a_container_clips_the_group_it_names() { } /// The feature sample, the seed of the importer's fuzz tests, reads its style table, clipping -/// container and lens in every version from 7 to 13, plain and compressed. +/// container, lens, flags, winding flag, transparency and named outline color in every version +/// from 7 to 13, plain and compressed. #[test] fn the_feature_sample_reads_its_styles_container_and_lens() { for version in [700, 800, 900, 1000, 1100, 1200, 1300] { for compress in [false, true] { let d = read(&synth::feature_sample(version, compress), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); let objects = &d.pages[0].layers[0].objects; - let [Object::Shape(styled), Object::Clip { objects: clipped, .. }, Object::Shape(_)] = objects.as_slice() else { + let [ + Object::Shape(styled), + Object::Clip { objects: clipped, .. }, + Object::Shape(_), + Object::Shape(flagged), + Object::Group { objects: grouped, flags }, + ] = objects.as_slice() + else { panic!("{version}: {objects:?}") }; assert_eq!(styled.fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{version}"); @@ -1304,7 +1314,20 @@ fn the_feature_sample_reads_its_styles_container_and_lens() { let s = shapes(clipped); assert_eq!(s.len(), 2, "{version}"); assert!(s[1].outline.as_ref().is_some_and(|o| o.behind_fill), "{version}"); - assert_eq!(d.warnings, vec![Warning::Lenses], "{version} {compress}"); + assert_eq!(flagged.flags, Flags { hidden: true, locked: true }, "{version}"); + assert!(flagged.nonzero, "{version}"); + assert_eq!(*flags, Flags { hidden: true, locked: false }, "{version}"); + let named = shapes(grouped)[0].outline.as_ref().map(|o| o.color.clone()); + // A transparency and a named outline color are read from version 13. + if version >= 1300 { + assert_eq!((flagged.opacity, flagged.blend), (0.75, Blend::Multiply), "{version}"); + assert_eq!(named, Some(Color::Spot { name: "Sky Blue".into(), tint: 1.0, look: Some([1.0, 0.0, 0.0]) }), "{version}"); + assert_eq!(d.warnings, vec![Warning::Lenses], "{version} {compress}"); + } else { + assert_eq!((flagged.opacity, flagged.blend), (1.0, Blend::Normal), "{version}"); + assert_eq!(named, Some(Color::Spot { name: "Spot 0:7".into(), tint: 1.0, look: None }), "{version}"); + assert_eq!(d.warnings, vec![Warning::Lenses, Warning::SpotLooks], "{version} {compress}"); + } } } } @@ -1389,6 +1412,283 @@ fn lenses_and_transparency_are_named_in_the_warnings() { } } +/// From version 13 a uniform transparency (a 117-byte record of version 1300 in argument 8000) +/// gives the shape its opacity and blend mode, records of other versions before it skipped. A +/// lens record, a value outside 0 to 100, a merge mode without a blend mode, and the record in an +/// earlier version are not applied: the shape stays opaque, with the lenses warning. +#[test] +fn a_uniform_transparency_from_version_13_applies() { + let record = |since: u32, body: Vec| [since.to_le_bytes().to_vec(), (body.len() as u32).to_le_bytes().to_vec(), body].concat(); + for version in [1300, 1500, 1600, 2000] { + let v = V(version); + let read_with = |arg: Vec| { + let d = read(&clip_drawing(version, vec![], vec![clip_rect(v, 10.0, &[(8000, arg)], [0.0, 0.0])]), Limits::default()) + .unwrap_or_else(|e| panic!("{version}: {e}")); + let s = shapes(&d.pages[0].layers[0].objects)[0]; + ((s.opacity, s.blend), d.warnings) + }; + for (percent, merge, want) in [(25.0, 0, Blend::Normal), (0.0, 9, Blend::Multiply), (100.0, 28, Blend::Screen), (60.0, 36, Blend::Exclusion)] + { + let opacity = (1.0 - percent / 100.0) as f32; + assert_eq!(read_with(synth::transparency(percent, merge).1), ((opacity, want), vec![]), "{version} {percent} {merge}"); + } + // A record of a later version comes first. + let later = [record(1600, vec![0; 20]), synth::transparency(25.0, 0).1].concat(); + assert_eq!(read_with(later), ((0.75, Blend::Normal), vec![]), "{version}"); + let opaque = ((1.0, Blend::Normal), vec![Warning::Lenses]); + assert_eq!(read_with(record(1300, vec![0; 84])), opaque, "{version}: a lens"); + for bad in [150.0, -1.0, f64::NAN] { + assert_eq!(read_with(synth::transparency(bad, 0).1), opaque, "{version} {bad}"); + } + for merge in [1, 2, 3, 6, 7, 8, 10, 13, 18, 19, 20, 27, 37, 255] { + assert_eq!(read_with(synth::transparency(25.0, merge).1), opaque, "{version} {merge}"); + } + assert_eq!(read_with(vec![]), opaque, "{version}: empty"); + } + let d = + read(&clip_drawing(1200, vec![], vec![clip_rect(V(1200), 10.0, &[synth::transparency(25.0, 0)], [0.0, 0.0])]), Limits::default()).unwrap(); + assert_eq!(shapes(&d.pages[0].layers[0].objects)[0].opacity, 1.0); + assert_eq!(d.warnings, vec![Warning::Lenses]); +} + +/// Bit 0x01 of byte 1 of a layer's, group's or object's flags hides it and bit 0x10 of byte 0 +/// locks it, in every version; a group left ungrouped at the object limit passes its flags to its +/// objects. +#[test] +fn flags_hide_and_lock_layers_groups_and_objects() { + for version in [300, 700, 1100, 1300, 1600] { + let v = V(version); + let rect = |flags: [u8; 4]| synth::flagged(synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0))], None), flags); + let group = |flags: [u8; 4], objects: Vec| { + let mut kids = vec![chunk(b"flgs", flags.to_vec())]; + kids.extend(objects); + list(b"grp ", kids) + }; + let objects = vec![ + rect([0, 0, 0, 8]), + rect([0, 1, 0, 8]), + rect([0x10, 0, 0, 8]), + rect([0x10, 1, 0, 8]), + group([0x10, 1, 0, 0x10], vec![rect([0, 0, 0, 8])]), + ]; + let layers = + vec![synth::layer(v, [0, 0, 0, 0x98], "Shown", objects), synth::layer(v, [0x10, 1, 0, 0x98], "Hidden", vec![rect([0, 0, 0, 8])])]; + let file = synth::file_of(version, vec![synth::page(false, layers)]); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let [shown, hidden] = d.pages[0].layers.as_slice() else { panic!("{version}: {:?}", d.pages[0].layers) }; + assert_eq!(shown.flags, Flags::default(), "{version}"); + assert_eq!(hidden.flags, Flags { hidden: true, locked: true }, "{version}"); + let f = |hidden: bool, locked: bool| Flags { hidden, locked }; + let own: Vec = shown + .objects + .iter() + .map(|o| match o { + Object::Shape(s) => s.flags, + Object::Group { flags, .. } => *flags, + Object::Clip { container, .. } => container.flags, + }) + .collect(); + assert_eq!(own, [f(false, false), f(true, false), f(false, true), f(true, true), f(true, true)], "{version}"); + assert!( + matches!(&shown.objects[4], Object::Group { objects, .. } if matches!(&objects[0], Object::Shape(s) if s.flags == Flags::default())), + "{version}" + ); + assert!(d.warnings.contains(&Warning::UnsupportedObjects) || d.warnings.is_empty(), "{version}: {:?}", d.warnings); + // Past the object limit the group's rectangle comes in ungrouped, hidden and locked. + let d = read(&file, Limits { objects: 5, ..Limits::default() }).unwrap_or_else(|e| panic!("{version}: {e}")); + let last = d.pages[0].layers[0].objects.last(); + assert!(matches!(last, Some(Object::Shape(s)) if s.flags == f(true, true)), "{version}: {last:?}"); + } +} + +/// A guideline is hidden when its own object, a group around it or its layer is. +#[test] +fn hidden_guidelines_say_so() { + for version in [700, 1300, 1600] { + let v = V(version); + let guide = |flags: [u8; 4]| { + let mut arg = vec![0; 12]; + arg.extend(90_000_000i32.to_le_bytes()); + arg.extend([v.coord(36.0), v.coord(0.0)].concat()); + synth::flagged(synth::object(v, 0x16, &[(16000, arg)], None), flags) + }; + let group = list(b"grp ", vec![chunk(b"flgs", vec![0, 1, 0, 0x10]), guide([0, 0, 0, 8])]); + let layers = vec![ + synth::layer(v, [0, 0, 0, 0x98], "Shown", vec![guide([0, 0, 0, 8]), guide([0, 1, 0, 8]), group]), + synth::layer(v, [0, 1, 0, 0x98], "Hidden", vec![guide([0, 0, 0, 8])]), + ]; + let d = read(&synth::file_of(version, vec![synth::page(false, layers)]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let hidden: Vec> = d.pages[0].layers.iter().map(|l| l.guides.iter().map(|g| g.hidden).collect()).collect(); + assert_eq!(hidden, [vec![false, true, true], vec![true]], "{version}"); + } +} + +/// Byte 0 of argument 14001 other than 0 fills the shape nonzero; 0, or no argument, fills it +/// even-odd; an argument without its byte is damage. +#[test] +fn a_winding_flag_fills_nonzero() { + for version in [300, 700, 1200, 1600] { + let v = V(version); + let read_with = |extra: &[(u32, Vec)]| { + let mut args = vec![(30, v.rect(10.0, 10.0, 0.0))]; + args.extend(extra.iter().cloned()); + let file = synth::file_of( + version, + vec![synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &args, None)])])], + ); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + (shapes(&d.pages[0].layers[0].objects)[0].nonzero, d.warnings) + }; + assert_eq!(read_with(&[(14001, vec![1, 0, 0, 0])]), (true, vec![]), "{version}"); + assert_eq!(read_with(&[(14001, vec![2])]), (true, vec![]), "{version}"); + assert_eq!(read_with(&[(14001, vec![0, 0, 0, 0])]), (false, vec![]), "{version}"); + assert_eq!(read_with(&[]), (false, vec![]), "{version}"); + assert_eq!(read_with(&[(14001, vec![])]), (false, vec![Warning::Damaged]), "{version}"); + } +} + +/// A `cdr8` form type makes the file the 8.01 variant whatever its `vrsn` chunk names: its style +/// table is read with the 8.01 layout. +#[test] +fn a_cdr8_file_whose_version_chunk_names_800_reads_as_801() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + for named in [800u16, 900, 1300] { + let table = synth::stlt(V(801), &[(0x100, 1)], &[(0x200, 2)], &styles, true); + let mut file = graphic_style_drawing(801, table); + file[8..12].copy_from_slice(b"cdr8"); + let at = file.windows(4).position(|w| w == b"vrsn").unwrap() + 8; + assert_eq!(&file[at..at + 2], &801u16.to_le_bytes()); + file[at..at + 2].copy_from_slice(&named.to_le_bytes()); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{named}: {e}")); + assert_eq!(d.version, 801, "{named}"); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{named}"); + assert!(d.warnings.is_empty(), "{named}: {:?}", d.warnings); + } +} + +/// Before version 6 an object names its style in 2 bytes, which is not damage; an argument too +/// short for them is. +#[test] +fn a_style_id_before_version_6_is_two_bytes() { + for version in [400, 500] { + let v = V(version); + let read_with = |style: Vec| { + let object = synth::object(v, 1, &[(200, style), (30, v.rect(10.0, 10.0, 0.0))], None); + let file = synth::file_of(version, vec![synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object])])]); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + (shapes(&d.pages[0].layers[0].objects).len(), d.warnings) + }; + assert_eq!(read_with(vec![0x10, 0]), (1, vec![]), "{version}"); + assert_eq!(read_with(vec![0x10]), (1, vec![Warning::Damaged]), "{version}"); + } +} + +/// A hidden or locked group of `LIST clpt` hides or locks the objects a container clips from it. +#[test] +fn a_clipped_groups_flags_reach_its_objects() { + for version in [700, 1300, 1600] { + let v = V(version); + let group = list( + b"grp ", + vec![chunk(b"flgs", vec![0x10, 1, 0x80, 0x10]), chunk(b"spnd", 0x77u32.to_le_bytes().to_vec()), clip_rect(v, 10.0, &[], [0.0, 0.0])], + ); + let doc = list(b"doc ", vec![synth::mcfg(v, 612.0, 792.0), list(b"clpt", vec![group])]); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0])])]); + let d = read(&synth::file_of(version, vec![doc, page]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let [Object::Clip { container, objects }] = d.pages[0].layers[0].objects.as_slice() else { + panic!("{version}: {:?}", d.pages[0].layers[0].objects) + }; + assert_eq!(container.flags, Flags::default(), "{version}"); + assert!(matches!(objects.as_slice(), [Object::Shape(s)] if s.flags == Flags { hidden: true, locked: true }), "{version}: {objects:?}"); + } +} + +/// Before version 6 a clipped group's `spnd` id is 2 bytes. +#[test] +fn a_clipped_group_id_before_version_6_is_two_bytes() { + for version in [400, 500] { + let v = V(version); + let rect = |w: f64, extra: Vec<(u32, Vec)>| { + let mut args = vec![(30, v.rect(w, w, 0.0))]; + args.extend(extra); + synth::object(v, 1, &args, None) + }; + let clpt = list(b"clpt", vec![list(b"grp ", vec![chunk(b"spnd", vec![0x77, 0]), rect(10.0, vec![])])]); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(40.0, vec![synth::container(0x77)])])]); + let d = read(&synth::file_of(version, vec![list(b"doc ", vec![synth::mcfg(v, 612.0, 792.0), clpt]), page]), Limits::default()) + .unwrap_or_else(|e| panic!("{version}: {e}")); + let objects = &d.pages[0].layers[0].objects; + assert!(matches!(objects.as_slice(), [Object::Clip { objects, .. }] if objects.len() == 1), "{version}: {objects:?}"); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + } +} + +/// A `trfd` entry ends at the next offset: one too short for its matrix makes the transform +/// damage and leaves the shape in place, even when the bytes after it would read as a matrix. A +/// table that stops before the last entry's end offset leaves that entry the rest of the record. +#[test] +fn a_transform_entry_ends_at_the_next_offset() { + for version in [400, 1100, 1300, 1600] { + let v = V(version); + let w = if version < 600 { 2 } else { 4 }; + let moved = [1.0, 0.0, 0.0, 1.0, 72.0, 0.0]; + let object = |trfd: Vec| { + let own = vec![chunk(b"loda", v.loda(1, &[(30, v.rect(10.0, 10.0, 0.0))])), list(b"trfl", vec![chunk(b"trfd", trfd)])]; + list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 8]), list(b"lgob", own)]) + }; + let read_with = |trfd: Vec| { + let file = synth::file_of(version, vec![synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object(trfd)])])]); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + (shapes(&d.pages[0].layers[0].objects)[0].matrix.0[4], d.warnings) + }; + let whole = v.trfd(&[moved]); + assert!((read_with(whole.clone()).0 - 72.0).abs() < 0.01, "{version}"); + // The end offset, right after the first, made 4 bytes past the entry's start. + let mut short = whole.clone(); + let start = if w == 2 { + usize::from(u16::from_le_bytes([short[3 * w], short[3 * w + 1]])) + } else { + u32::from_le_bytes(short[12..16].try_into().unwrap()) as usize + }; + short[4 * w..5 * w].copy_from_slice(&v.word(start + 4)); + assert_eq!(read_with(short), (0.0, vec![Warning::Damaged]), "{version}"); + // The entry first, then a table of its start alone at the record's end. + let entry = whole[5 * w..].to_vec(); + let at = 3 * w + entry.len(); + let mut end = [v.word(at + w), v.word(1), v.word(at)].concat(); + end.extend(entry); + end.extend(v.word(3 * w)); + let (x, warnings) = read_with(end); + assert!((x - 72.0).abs() < 0.01 && warnings.is_empty(), "{version}: {x} {warnings:?}"); + } +} + +/// From version 13 an outline's record of type 2 that names a library color gives the outline +/// that color; one without a name leaves the fixed color field. +#[test] +fn an_outline_takes_a_named_library_color_from_its_property_list() { + for version in [1300, 1500, 1600] { + let v = V(version); + let read_with = |props: Vec| { + let mut outl = v.outline(4, synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }, &synth::color(2, [0, 0, 0, 100]), &[]); + let mut record = 2u32.to_le_bytes().to_vec(); + record.extend((props.len() as u32).to_le_bytes()); + record.extend(props); + outl.splice(4..4, record); + let doc = list(b"doc ", vec![synth::mcfg(v, 612.0, 792.0), list(b"otlt", vec![chunk(b"outl", outl)])]); + let object = synth::object(v, 1, &[(10, 4u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let file = synth::file_of(version, vec![doc, synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object])])]); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + (shapes(&d.pages[0].layers[0].objects)[0].outline.as_ref().map(|o| o.color.clone()), d.warnings) + }; + let named = synth::properties(&synth::color(5, [0, 0, 255, 0]), Some("Sky Blue")); + assert_eq!(read_with(named), (Some(Color::Spot { name: "Sky Blue".into(), tint: 1.0, look: Some([1.0, 0.0, 0.0]) }), vec![]), "{version}"); + let plain = synth::properties(&synth::color(5, [0, 0, 255, 0]), None); + assert_eq!(read_with(plain), (Some(Color::Cmyk([0.0, 0.0, 0.0, 1.0])), vec![]), "{version}"); + } +} + #[test] fn linked_groups_are_left_out_with_a_warning() { let v = V(1100); diff --git a/crates/engine/src/cmd/fileio/cdr.rs b/crates/engine/src/cmd/fileio/cdr.rs index bd8e6a6092..e8d5321df5 100644 --- a/crates/engine/src/cmd/fileio/cdr.rs +++ b/crates/engine/src/cmd/fileio/cdr.rs @@ -1,6 +1,7 @@ //! `.cdr` drawings of versions 1 to 27 (`.cdr`, and `.cdt` templates): the pages, layers, //! guidelines, groups, curves, rectangles, ellipses, arcs and polygons with uniform fills and -//! outlines that `vectorcraft-cdr` reads, mapped to editable VectorCraft art. Pages become +//! outlines, their hidden and locked states, fill rules and uniform transparency that +//! `vectorcraft-cdr` reads, mapped to editable VectorCraft art. Pages become //! artboards side by side; layers of the same name on different pages become one layer where the //! pages stack them in the same order. What the //! reader leaves out is listed in the warnings, one line for each kind ([`note`]). @@ -49,6 +50,8 @@ fn note(w: Warning) -> &'static str { const FALLBACK_PAGE: (f64, f64) = (612.0, 792.0); /// The layer that holds guidelines at angles other than horizontal and vertical, as guide paths. const GUIDES_LAYER: &str = "Guides"; +/// The hidden layer that holds hidden guidelines. +const HIDDEN_GUIDES_LAYER: &str = "Hidden guides"; /// The most pages read, as artboards: the most a new document may have. const MAX_PAGES: usize = crate::cmd::newdoc::MAX_ARTBOARDS as usize; /// The longest page side, in points: the longest artboard side a new document may have. @@ -159,7 +162,7 @@ impl shapes::Builder { self.doc = doc; self.name_spots(); // Bottom to top: the master page's layers, then the pages' in the order first seen. - let mut layers: Vec<(String, Vec>)> = Vec::new(); + let mut layers: Vec = Vec::new(); // A layer is known by its name and how many layers of that name the page has below it, so // two layers of one name on a page stay two layers. Each key keeps every layer made for // it, bottom to top. @@ -188,8 +191,8 @@ impl shapes::Builder { // takes the art. match by_name.get(&key).and_then(|is| is.iter().copied().find(|&i| below.is_none_or(|b| i > b))) { Some(i) => { - if let Some((_, kids)) = layers.get_mut(i) { - kids.extend(art); + if let Some(out) = layers.get_mut(i) { + out.add(art, l.flags); } below = Some(i); } @@ -225,7 +228,9 @@ impl shapes::Builder { } let is = by_name.entry(key).or_default(); is.insert(is.partition_point(|&i| i < at), at); - layers.insert(at, (l.name.clone(), art)); + let mut out = LayerOut::new(l.name.clone()); + out.add(art, l.flags); + layers.insert(at, out); below = Some(at); } } @@ -237,25 +242,63 @@ impl shapes::Builder { } if !self.guide_paths.is_empty() { let paths = std::mem::take(&mut self.guide_paths); - // At the layer limit the guide paths go on the top layer instead of a layer of their own. + // At the layer limit the guide paths go on the top shown layer instead of a layer of + // their own; when every layer is hidden they go on the top one, with the limit warning. let full = layers.len() >= MAX_LAYERS; - match layers.last_mut() { - Some((_, kids)) if full => kids.extend(paths), - _ => layers.push((GUIDES_LAYER.to_string(), paths)), + let top = layers.iter().rposition(|l| !l.hidden()).unwrap_or(layers.len().saturating_sub(1)); + match layers.get_mut(top) { + Some(out) if full => { + if out.hidden() { + self.notes.push(Warning::TooDeep); + } + out.kids.extend(paths.into_iter().map(|p| (p, cd::Flags::default()))); + } + _ => { + let mut out = LayerOut::new(GUIDES_LAYER.to_string()); + out.kids.extend(paths.into_iter().map(|p| (p, cd::Flags::default()))); + layers.push(out); + } + } + } + // Hidden guidelines go on a hidden layer of their own on top; past the layer limit they + // are left out. + if !self.hidden_guides.is_empty() || !self.hidden_paths.is_empty() { + if layers.len() >= MAX_LAYERS { + self.notes.push(Warning::TooDeep); + } else { + let mut art = std::mem::take(&mut self.hidden_paths); + for g in std::mem::take(&mut self.hidden_guides) { + let kind = NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard }; + art.push(Arc::new(Node::new(self.doc.alloc_id(), kind))); + } + let mut out = LayerOut::new(HIDDEN_GUIDES_LAYER.to_string()); + out.add(art, cd::Flags { hidden: true, locked: false }); + layers.push(out); } } let mut doc = std::mem::replace(&mut self.doc, Document::new(1.0, 1.0)); - doc.layers = layers.into_iter().enumerate().map(|(i, (name, kids))| layer(&mut doc, &name, i, kids)).collect(); + doc.layers = layers.into_iter().enumerate().map(|(i, out)| out.finish(&mut doc, i)).collect(); if doc.layers.is_empty() { - let l = layer(&mut doc, "Layer 1", 0, Vec::new()); + let l = layer(&mut doc, "Layer 1", 0, Vec::new(), cd::Flags::default()); doc.layers.push(l); } - // Ruler guides go at the top of the top layer, in the order they were read. + // Ruler guides go at the top of the top shown layer, in the order they were read. When + // every layer is hidden they go on a layer of their own on top; past the layer limit they + // go on the hidden top layer, with the limit warning. let guides: Vec> = std::mem::take(&mut self.guide_list) .into_iter() .map(|g| Arc::new(Node::new(doc.alloc_id(), NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard }))) .collect(); - if let Some(kids) = doc.layers.last_mut().and_then(|l| Arc::make_mut(l).children_mut()) { + if !guides.is_empty() && !doc.layers.iter().any(|l| l.visible) && doc.layers.len() < MAX_LAYERS { + let i = doc.layers.len(); + let l = layer(&mut doc, GUIDES_LAYER, i, Vec::new(), cd::Flags::default()); + doc.layers.push(l); + } + let top = doc.layers.iter().rposition(|l| l.visible).unwrap_or(doc.layers.len().saturating_sub(1)); + if !guides.is_empty() && doc.layers.get(top).is_some_and(|l| !l.visible) { + self.notes.push(Warning::TooDeep); + } + if let Some(kids) = doc.layers.get_mut(top).and_then(|l| Arc::make_mut(l).children_mut()) { kids.extend(guides); } self.finish_swatches(&mut doc); @@ -267,7 +310,7 @@ impl shapes::Builder { /// The master page's layers: the desktop's objects once, on the first page's space; other /// layers' objects on every page, as many copies as [`MAX_MASTER_COPIES`] allows. - fn master_layers(&mut self, d: &cd::Drawing, placed: &[Placed], layers: &mut Vec<(String, Vec>)>) { + fn master_layers(&mut self, d: &cd::Drawing, placed: &[Placed], layers: &mut Vec) { for l in d.master.iter().rev() { if layers.len() >= MAX_LAYERS { self.notes.push(Warning::TooDeep); @@ -285,7 +328,9 @@ impl shapes::Builder { art.extend(self.objects(&l.objects, p.to_doc)); } let name = if l.name.is_empty() { "Master".to_string() } else { l.name.clone() }; - layers.push((name, art)); + let mut out = LayerOut::new(name); + out.add(art, l.flags); + layers.push(out); } } @@ -293,7 +338,7 @@ impl shapes::Builder { /// artboard, others as guide paths. fn guides(&mut self, guides: &[cd::Guideline], p: &Placed, artboard: Option) { for g in guides { - if self.guide_list.len() + self.guide_paths.len() >= MAX_GUIDES { + if self.guide_list.len() + self.guide_paths.len() + self.hidden_guides.len() + self.hidden_paths.len() >= MAX_GUIDES { self.notes.push(Warning::TooDeep); return; } @@ -303,12 +348,13 @@ impl shapes::Builder { self.notes.push(Warning::TooDeep); continue; } + let list = if g.hidden { &mut self.hidden_guides } else { &mut self.guide_list }; if turn.abs() < 1e-9 { - self.guide_list.push(Guide { artboard, ..Guide::new(false, at.y) }); + list.push(Guide { artboard, ..Guide::new(false, at.y) }); } else if (turn - 90.0).abs() < 1e-9 { - self.guide_list.push(Guide { artboard, ..Guide::new(true, at.x) }); + list.push(Guide { artboard, ..Guide::new(true, at.x) }); } else { - self.angled_guide(at, g.angle, p.rect); + self.angled_guide(at, g.angle, p.rect, g.hidden); } } } @@ -322,7 +368,7 @@ fn copy_cost(objects: &[cd::Object]) -> usize { while let Some(o) = stack.pop() { n = n.saturating_add(1); match o { - cd::Object::Group(kids) => stack.extend(kids), + cd::Object::Group { objects: kids, .. } => stack.extend(kids), cd::Object::Shape(s) => n = n.saturating_add(shape_cost(s)), cd::Object::Clip { container, objects } => { // A container whose outline is behind its fill is built twice, as that outline @@ -354,10 +400,52 @@ fn path_cost(s: &cd::Shape) -> usize { } } -/// A layer of the document named `name` holding `kids` (bottom to top). -fn layer(doc: &mut Document, name: &str, i: usize, kids: Vec>) -> Arc { +/// A document layer being made from the drawing's layers of one name: its art bottom to top, each +/// part with the flags of the layer it came from, and those flags for every layer merged into it. +struct LayerOut { + name: String, + kids: Vec<(Arc, cd::Flags)>, + merged: Vec, +} + +impl LayerOut { + fn new(name: String) -> Self { + LayerOut { name, kids: Vec::new(), merged: Vec::new() } + } + + /// Whether the layer node will be hidden: every drawing layer merged into it is. + fn hidden(&self) -> bool { + !self.merged.is_empty() && self.merged.iter().all(|f| f.hidden) + } + + /// Adds the art of a drawing layer with flags `flags`. + fn add(&mut self, art: Vec>, flags: cd::Flags) { + self.kids.extend(art.into_iter().map(|n| (n, flags))); + self.merged.push(flags); + } + + /// The layer node, as the `i`th layer from the bottom. It is hidden or locked when every + /// drawing layer merged into it is; otherwise the art of a hidden or locked drawing layer is + /// hidden or locked object by object. + fn finish(self, doc: &mut Document, i: usize) -> Arc { + let all = |f: fn(&cd::Flags) -> bool| !self.merged.is_empty() && self.merged.iter().all(f); + let own = cd::Flags { hidden: all(|f| f.hidden), locked: all(|f| f.locked) }; + let kids = self + .kids + .into_iter() + .map(|(n, f)| shapes::with_flags(n, cd::Flags { hidden: f.hidden && !own.hidden, locked: f.locked && !own.locked })) + .collect(); + layer(doc, &self.name, i, kids, own) + } +} + +/// A layer of the document named `name` holding `kids` (bottom to top), hidden or locked as +/// `flags` say. +fn layer(doc: &mut Document, name: &str, i: usize, kids: Vec>, flags: cd::Flags) -> Arc { let name = if name.is_empty() { format!("Layer {}", i + 1) } else { name.to_string() }; let mut n = Node::layer(doc.alloc_id(), &name, LayerColor::Preset((i % 9) as u8)); + n.visible = !flags.hidden; + n.locked = flags.locked; if let Some(c) = n.children_mut() { *c = kids; } diff --git a/crates/engine/src/cmd/fileio/cdr/shapes.rs b/crates/engine/src/cmd/fileio/cdr/shapes.rs index 070bcff762..6427d49e97 100644 --- a/crates/engine/src/cmd/fileio/cdr/shapes.rs +++ b/crates/engine/src/cmd/fileio/cdr/shapes.rs @@ -8,10 +8,10 @@ use kurbo::{Affine, BezPath, Point, Rect}; use vectorcraft_cdr::Warning; use vectorcraft_cdr::model::{self as cd, Geometry}; use vectorcraft_color::swatch::REGISTRATION; -use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_color::{BlendMode, Color, Paint, Swatch}; use vectorcraft_doc::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, StrokeLayer}; use vectorcraft_doc::geom::{FillRule, PathData}; -use vectorcraft_doc::{Document, Guide, LiveShape, Node, NodeKind}; +use vectorcraft_doc::{Document, Guide, Knockout, LiveShape, Node, NodeKind}; /// The most nested groups mapped; the reader holds nesting well below it. const MAX_DEPTH: usize = 256; @@ -32,6 +32,9 @@ pub(super) struct Builder { pub(super) guide_list: Vec, /// Guidelines at other angles, as guide paths. pub(super) guide_paths: Vec>, + /// Hidden guidelines, as guides and guide paths of a hidden layer of their own. + pub(super) hidden_guides: Vec, + pub(super) hidden_paths: Vec>, /// Colors read in each model, which picks the document's color mode. pub(super) cmyk: usize, pub(super) rgb: usize, @@ -50,6 +53,8 @@ impl Builder { copies_left: super::MAX_MASTER_COPIES, guide_list: Vec::new(), guide_paths: Vec::new(), + hidden_guides: Vec::new(), + hidden_paths: Vec::new(), cmyk: 0, rgb: 0, spots: Vec::new(), @@ -69,7 +74,7 @@ impl Builder { self.learn_spot(c); } } - cd::Object::Group(kids) => stack.extend(kids), + cd::Object::Group { objects: kids, .. } => stack.extend(kids), cd::Object::Clip { container, objects } => { for c in container.fill.iter().chain(container.outline.iter().map(|o| &o.color)) { self.learn_spot(c); @@ -117,11 +122,12 @@ impl Builder { let mut out = Vec::with_capacity(objects.len()); for o in objects.iter().rev() { match o { - cd::Object::Shape(s) => out.extend(self.shape(s, to_doc, false)), - cd::Object::Group(kids) => { + cd::Object::Shape(s) => out.extend(self.shape(s, to_doc, false).map(|n| with_flags(n, s.flags))), + cd::Object::Group { objects: kids, flags } => { let children = self.objects_at(kids, to_doc, depth + 1); if !children.is_empty() { - out.push(Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: false }))); + let group = Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: false })); + out.push(with_flags(group, *flags)); } } // A clipping group whose clipping path keeps the container's paint: its fill @@ -140,14 +146,28 @@ impl Builder { let Some(clip) = clip else { continue }; let mut children = vec![clip]; children.extend(self.objects_at(objects, to_doc, depth + 1)); - let group = Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: true })); - match outline { + let mut group = Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: true }); + // A see-through container's fill knocks out the outline behind it, so the two + // parts do not add up their transparency where they overlap; the clipped + // objects inside still combine as usual. + let knock = outline.is_some() && (container.opacity < 1.0 || container.blend != cd::Blend::Normal); + if knock { + group.knockout = Knockout::Off; + } + let group = Arc::new(group); + // The container's flags hide or lock the whole clipping group. + let whole = match outline { Some(outline) => { let children = vec![outline, group]; - out.push(Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: false }))); + let mut pair = Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: false }); + if knock { + pair.knockout = Knockout::On; + } + Arc::new(pair) } - None => out.push(group), - } + None => group, + }; + out.push(with_flags(whole, container.flags)); } } } @@ -181,11 +201,13 @@ impl Builder { if let Some(o) = s.outline.as_ref().filter(|o| !o.behind_fill) { items.push(AppearanceItem::Stroke(self.stroke(o, &s.matrix))); } - // A curve of several subpaths is filled with holes where they overlap: VectorCraft's own - // choice of rule for it. - let rule = FillRule::EvenOdd; + // Without the winding flag, a curve of several subpaths is filled with holes where they + // overlap: VectorCraft's own choice of rule for it. + let rule = if s.nonzero { FillRule::NonZero } else { FillRule::EvenOdd }; let mut n = Node::new(self.doc.alloc_id(), NodeKind::Path { path, rule, live: live.map(Box::new), clipping, guide: false }); n.appearance = Appearance { items, ..Appearance::default() }.into(); + n.opacity = if s.opacity.is_finite() { s.opacity.clamp(0.0, 1.0) } else { 1.0 }; + n.blend = blend(s.blend); Some(Arc::new(n)) } @@ -270,8 +292,9 @@ impl Builder { /// A guideline through `at` (document space) at `angle` degrees counterclockwise, as a guide /// path from edge to edge of the page `rect`, so it moves with the page's artboard. A - /// guideline that misses the page runs through `at` for the page's diagonal each way. - pub(super) fn angled_guide(&mut self, at: Point, angle: f64, rect: Rect) { + /// guideline that misses the page runs through `at` for the page's diagonal each way. A + /// `hidden` one goes with the hidden guides. + pub(super) fn angled_guide(&mut self, at: Point, angle: f64, rect: Rect, hidden: bool) { let (s, c) = angle.to_radians().sin_cos(); // The document's y axis points down. let dir = kurbo::Vec2::new(c, -s); @@ -291,7 +314,7 @@ impl Builder { return; } let n = Node::new(self.doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: true }); - self.guide_paths.push(Arc::new(n)); + if hidden { self.hidden_paths.push(Arc::new(n)) } else { self.guide_paths.push(Arc::new(n)) } } } @@ -318,6 +341,37 @@ fn affine(m: &cd::Matrix) -> Affine { Affine::new(m.0) } +fn blend(b: cd::Blend) -> BlendMode { + match b { + cd::Blend::Normal => BlendMode::Normal, + cd::Blend::Multiply => BlendMode::Multiply, + cd::Blend::Screen => BlendMode::Screen, + cd::Blend::Overlay => BlendMode::Overlay, + cd::Blend::SoftLight => BlendMode::SoftLight, + cd::Blend::HardLight => BlendMode::HardLight, + cd::Blend::ColorDodge => BlendMode::ColorDodge, + cd::Blend::ColorBurn => BlendMode::ColorBurn, + cd::Blend::Darken => BlendMode::Darken, + cd::Blend::Lighten => BlendMode::Lighten, + cd::Blend::Difference => BlendMode::Difference, + cd::Blend::Exclusion => BlendMode::Exclusion, + cd::Blend::Hue => BlendMode::Hue, + cd::Blend::Saturation => BlendMode::Saturation, + cd::Blend::Color => BlendMode::Color, + cd::Blend::Luminosity => BlendMode::Luminosity, + } +} + +/// `n` hidden or locked as `flags` say; left as it is when they say neither. +pub(super) fn with_flags(mut n: Arc, flags: cd::Flags) -> Arc { + if flags.hidden || flags.locked { + let m = Arc::make_mut(&mut n); + m.visible &= !flags.hidden; + m.locked |= flags.locked; + } + n +} + fn bez(p: &cd::Path) -> BezPath { let pt = |q: cd::Pt| Point::new(q.x, q.y); let mut bp = BezPath::new(); @@ -382,15 +436,15 @@ mod tests { fn a_spot_color_keeps_its_color_from_its_strongest_use() { let red = [1.0, 0.0, 0.0]; let shape = |tint: f32, look: [f32; 3]| { - cd::Object::Shape(Box::new(cd::Shape { - geometry: Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, - matrix: cd::Matrix::IDENTITY, - fill: Some(cd::Color::Spot { name: "Red ink".into(), tint, look: Some(look) }), - outline: None, - })) + cd::Object::Shape(Box::new(cd::Shape::new( + Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, + cd::Matrix::IDENTITY, + Some(cd::Color::Spot { name: "Red ink".into(), tint, look: Some(look) }), + None, + ))) }; for objects in [vec![shape(0.0, [1.0; 3]), shape(1.0, red)], vec![shape(1.0, red), shape(0.0, [1.0; 3])]] { - let layer = cd::Layer { name: "L".into(), kind: cd::LayerKind::Drawing, objects, guides: vec![] }; + let layer = cd::Layer { name: "L".into(), kind: cd::LayerKind::Drawing, flags: cd::Flags::default(), objects, guides: vec![] }; let d = cd::Drawing { version: 1300, page_size: None, @@ -419,14 +473,20 @@ mod tests { #[test] fn a_spot_color_named_like_a_default_swatch_stays_a_spot_color() { let shape = |name: &str| { - cd::Object::Shape(Box::new(cd::Shape { - geometry: Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, - matrix: cd::Matrix::IDENTITY, - fill: Some(cd::Color::Spot { name: name.into(), tint: 1.0, look: Some([0.0; 3]) }), - outline: None, - })) + cd::Object::Shape(Box::new(cd::Shape::new( + Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, + cd::Matrix::IDENTITY, + Some(cd::Color::Spot { name: name.into(), tint: 1.0, look: Some([0.0; 3]) }), + None, + ))) + }; + let layer = cd::Layer { + name: "L".into(), + kind: cd::LayerKind::Drawing, + flags: cd::Flags::default(), + objects: vec![shape("Black"), shape("Black 2")], + guides: vec![], }; - let layer = cd::Layer { name: "L".into(), kind: cd::LayerKind::Drawing, objects: vec![shape("Black"), shape("Black 2")], guides: vec![] }; let d = cd::Drawing { version: 1300, page_size: None, @@ -461,13 +521,13 @@ mod tests { #[test] fn master_copies_count_their_path_segments() { let segments = (1..=300).map(|i| cd::Segment::Line(cd::Pt { x: f64::from(i), y: 0.0 })).collect(); - let curve = cd::Object::Shape(Box::new(cd::Shape { - geometry: Geometry::Path(cd::Path { subpaths: vec![cd::SubPath { start: cd::Pt { x: 0.0, y: 0.0 }, segments, closed: false }] }), - matrix: cd::Matrix::IDENTITY, - fill: None, - outline: None, - })); - let master = cd::Layer { name: "M".into(), kind: cd::LayerKind::Drawing, objects: vec![curve], guides: vec![] }; + let curve = cd::Object::Shape(Box::new(cd::Shape::new( + Geometry::Path(cd::Path { subpaths: vec![cd::SubPath { start: cd::Pt { x: 0.0, y: 0.0 }, segments, closed: false }] }), + cd::Matrix::IDENTITY, + None, + None, + ))); + let master = cd::Layer { name: "M".into(), kind: cd::LayerKind::Drawing, flags: cd::Flags::default(), objects: vec![curve], guides: vec![] }; let d = cd::Drawing { version: 1300, page_size: None, @@ -497,13 +557,13 @@ mod tests { behind_fill: false, scale_with: false, }; - let rect = cd::Object::Shape(Box::new(cd::Shape { - geometry: Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, - matrix: cd::Matrix::IDENTITY, - fill: None, - outline: Some(outline), - })); - let master = cd::Layer { name: "M".into(), kind: cd::LayerKind::Drawing, objects: vec![rect], guides: vec![] }; + let rect = cd::Object::Shape(Box::new(cd::Shape::new( + Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, + cd::Matrix::IDENTITY, + None, + Some(outline), + ))); + let master = cd::Layer { name: "M".into(), kind: cd::LayerKind::Drawing, flags: cd::Flags::default(), objects: vec![rect], guides: vec![] }; let d = cd::Drawing { version: 1300, page_size: None, @@ -536,7 +596,7 @@ mod tests { behind_fill: false, scale_with, }; - let rect = cd::Shape { geometry: Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, matrix, fill: None, outline: Some(outline) }; + let rect = cd::Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, matrix, None, Some(outline)); let mut b = Builder::new(); let Some(node) = b.shape(&rect, Affine::IDENTITY, false) else { panic!("{scale_with}: no shape") }; let [AppearanceItem::Stroke(s)] = node.appearance.items.as_slice() else { panic!("{scale_with}: {:?}", node.appearance.items) }; @@ -546,6 +606,164 @@ mod tests { } } + /// A shape's opacity, blend mode and fill rule reach its path; a shape without them is opaque, + /// normal and filled even-odd. + #[test] + fn opacity_blend_and_fill_rule_reach_the_path() { + let square = Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }; + let plain = cd::Shape::new(square.clone(), cd::Matrix::IDENTITY, Some(cd::Color::Gray(1.0)), None); + let seen = cd::Shape { nonzero: true, opacity: 0.25, blend: cd::Blend::Multiply, ..plain.clone() }; + let mut b = Builder::new(); + for (s, opacity, blend, nonzero) in [(&plain, 1.0, BlendMode::Normal, false), (&seen, 0.25, BlendMode::Multiply, true)] { + let Some(n) = b.shape(s, Affine::IDENTITY, false) else { panic!("no shape") }; + let NodeKind::Path { rule, .. } = &n.kind else { panic!("{:?}", n.kind) }; + assert_eq!((n.opacity, n.blend, *rule == FillRule::NonZero), (opacity, blend, nonzero)); + } + let wild = cd::Shape { opacity: f32::NAN, ..plain }; + assert_eq!(b.shape(&wild, Affine::IDENTITY, false).map(|n| n.opacity), Some(1.0)); + } + + /// Ruler guides go on the top shown layer, or on a layer of their own when every layer is + /// hidden; hidden guidelines go on a hidden layer of their own. + #[test] + fn ruler_guides_stay_off_hidden_layers() { + let square = || cd::Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, cd::Matrix::IDENTITY, None, None); + let hidden = cd::Flags { hidden: true, locked: false }; + let layer = |name: &str, flags: cd::Flags| cd::Layer { + name: name.into(), + kind: cd::LayerKind::Drawing, + flags, + objects: vec![cd::Object::Shape(Box::new(square()))], + guides: vec![], + }; + let guides_of = |layers: Vec, hidden: bool| { + let d = cd::Drawing { + version: 1300, + page_size: None, + pages: vec![cd::Page { size: None, layers }], + master: vec![], + guides: vec![cd::Guideline { at: cd::Pt { x: 0.0, y: 0.0 }, angle: 90.0, hidden }], + warnings: vec![], + }; + let doc = Builder::new().document(&d); + doc.layers + .iter() + .map(|l| { + let n = l.children().map_or(0, |k| k.iter().filter(|n| matches!(n.kind, NodeKind::RulerGuide { .. })).count()); + (l.name.clone().unwrap_or_default(), l.visible, n) + }) + .collect::>() + }; + // Front to back: "Top" hidden over "Base" shown. + let got = guides_of(vec![layer("Top", hidden), layer("Base", cd::Flags::default())], false); + assert_eq!(got, [("Base".to_string(), true, 1), ("Top".to_string(), false, 0)]); + let got = guides_of(vec![layer("Only", hidden)], false); + assert_eq!(got, [("Only".to_string(), false, 0), ("Guides".to_string(), true, 1)]); + let got = guides_of(vec![layer("Base", cd::Flags::default())], true); + assert_eq!(got, [("Base".to_string(), true, 0), ("Hidden guides".to_string(), false, 1)]); + // At the layer limit an angled guideline's path goes on the top shown layer. + let mut layers: Vec = (0..super::super::MAX_LAYERS).map(|i| layer(&format!("L{i}"), cd::Flags::default())).collect(); + layers[0].flags = hidden; + let d = cd::Drawing { + version: 1300, + page_size: None, + pages: vec![cd::Page { size: None, layers }], + master: vec![], + guides: vec![cd::Guideline { at: cd::Pt { x: 0.0, y: 0.0 }, angle: 45.0, hidden: false }], + warnings: vec![], + }; + let mut b = Builder::new(); + let doc = b.document(&d); + let with_path: Vec<(bool, bool)> = doc + .layers + .iter() + .rev() + .take(2) + .map(|l| (l.visible, l.children().is_some_and(|k| k.iter().any(|n| matches!(n.kind, NodeKind::Path { guide: true, .. }))))) + .collect(); + assert_eq!(with_path, [(false, false), (true, true)]); + assert!(!b.notes.contains(&Warning::TooDeep)); + // With every layer hidden as well, the guides go on the top layer with the limit warning. + let mut d = d; + for l in &mut d.pages[0].layers { + l.flags = hidden; + } + d.guides.push(cd::Guideline { at: cd::Pt { x: 0.0, y: 0.0 }, angle: 90.0, hidden: false }); + let mut b = Builder::new(); + let doc = b.document(&d); + assert!(doc.layers.iter().all(|l| !l.visible)); + assert!(b.notes.contains(&Warning::TooDeep), "{:?}", b.notes); + } + + /// A see-through container whose outline is behind its fill knocks the outline out under its + /// fill, and its clipping group keeps its own objects combining as usual; an opaque one leaves + /// the pair a plain group. + #[test] + fn a_see_through_container_with_its_outline_behind_knocks_it_out() { + let outline = cd::Outline { + width: 4.0, + color: cd::Color::Gray(1.0), + cap: cd::Cap::Butt, + join: cd::Join::Miter, + dashes: vec![], + behind_fill: true, + scale_with: false, + }; + let square = || cd::Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, cd::Matrix::IDENTITY, Some(cd::Color::Gray(0.5)), None); + for (opacity, knockout, inner) in [(1.0, Knockout::Neutral, Knockout::Neutral), (0.5, Knockout::On, Knockout::Off)] { + let container = Box::new(cd::Shape { opacity, outline: Some(outline.clone()), ..square() }); + let clip = cd::Object::Clip { container, objects: vec![cd::Object::Shape(Box::new(square()))] }; + let nodes = Builder::new().objects(&[clip], Affine::IDENTITY); + let [pair] = nodes.as_slice() else { panic!("{nodes:?}") }; + let NodeKind::Group { children, clip: false } = &pair.kind else { panic!("{:?}", pair.kind) }; + assert_eq!(pair.knockout, knockout, "{opacity}"); + let clipping = children.iter().find(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })); + assert_eq!(clipping.map(|n| n.knockout), Some(inner), "{opacity}"); + } + } + + /// A hidden or locked shape, group or clipping container gives its node those states. A layer + /// is hidden or locked when every drawing layer merged into it is; otherwise only the art of + /// the hidden or locked drawing layer is. + #[test] + fn hidden_and_locked_flags_reach_the_nodes() { + let square = || cd::Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, cd::Matrix::IDENTITY, Some(cd::Color::Gray(1.0)), None); + let hidden = cd::Flags { hidden: true, locked: false }; + let locked = cd::Flags { hidden: false, locked: true }; + let objects = vec![ + cd::Object::Shape(Box::new(cd::Shape { flags: hidden, ..square() })), + cd::Object::Group { objects: vec![cd::Object::Shape(Box::new(square()))], flags: locked }, + cd::Object::Clip { container: Box::new(cd::Shape { flags: hidden, ..square() }), objects: vec![cd::Object::Shape(Box::new(square()))] }, + ]; + let layer = + |flags: cd::Flags, objects: Vec| cd::Layer { name: "L".into(), kind: cd::LayerKind::Drawing, flags, objects, guides: vec![] }; + let drawing = |pages: Vec>| cd::Drawing { + version: 1300, + page_size: None, + pages: pages.into_iter().map(|layers| cd::Page { size: None, layers }).collect(), + master: vec![], + guides: vec![], + warnings: vec![], + }; + let doc = Builder::new().document(&drawing(vec![vec![layer(cd::Flags::default(), objects)]])); + let kids = doc.layers[0].children().unwrap(); + // Bottom to top: the clipping group, the group, the shape. + let states: Vec<(bool, bool)> = kids.iter().map(|n| (n.visible, n.locked)).collect(); + assert_eq!(states, [(false, false), (true, true), (false, false)]); + assert!(doc.layers[0].visible && !doc.layers[0].locked); + // One name on two pages: hidden on the first only, then on both. + let one = || vec![cd::Object::Shape(Box::new(square()))]; + let doc = Builder::new().document(&drawing(vec![vec![layer(hidden, one())], vec![layer(cd::Flags::default(), one())]])); + assert_eq!(doc.layers.len(), 1); + assert!(doc.layers[0].visible); + let states: Vec = doc.layers[0].children().unwrap().iter().map(|n| n.visible).collect(); + assert_eq!(states, [false, true]); + let doc = Builder::new().document(&drawing(vec![vec![layer(cd::Flags { hidden: true, locked: true }, one())], vec![layer(hidden, one())]])); + assert!(!doc.layers[0].visible && !doc.layers[0].locked); + let states: Vec<(bool, bool)> = doc.layers[0].children().unwrap().iter().map(|n| (n.visible, n.locked)).collect(); + assert_eq!(states, [(true, true), (true, false)]); + } + /// A corner rounded in the file stays on the same corner of the page, however the rectangle's /// size points. #[test] diff --git a/crates/engine/src/cmd/fileio/tests_cdr.rs b/crates/engine/src/cmd/fileio/tests_cdr.rs index 8dbf876b7d..0d3477e5b8 100644 --- a/crates/engine/src/cmd/fileio/tests_cdr.rs +++ b/crates/engine/src/cmd/fileio/tests_cdr.rs @@ -546,6 +546,31 @@ fn lenses_and_transparency_are_named_in_the_warnings() { assert_eq!(warnings, ["CDR lenses and object transparency were not applied, and the objects they are on show opaque"]); } +/// A uniform transparency, a winding flag and hidden and locked flags of a drawing of version 16 +/// open as the object's opacity, blend mode and fill rule and as hidden and locked nodes, without +/// a warning. +#[test] +fn transparency_winding_and_flags_open_on_the_art() { + let v = V(1600); + let args = vec![(30, v.rect(10.0, 10.0, 0.0)), synth::transparency(40.0, 29), (14001, vec![1, 0, 0, 0])]; + let object = synth::flagged(synth::object(v, 1, &args, None), [0x10, 0, 0, 8]); + let layers = vec![ + synth::layer(v, [0, 0, 0, 0x98], "Shown", vec![object]), + synth::layer(v, [0, 1, 0, 0x98], "Hidden", vec![synth::object(v, 1, &args[..1], None)]), + ]; + let file = synth::file_of(1600, vec![synth::page(false, layers)]); + let (doc, warnings) = super::cdr::import(&file).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + // Bottom to top: "Hidden", then "Shown". + let states: Vec<(String, bool)> = doc.layers.iter().map(|l| (l.name.clone().unwrap_or_default(), l.visible)).collect(); + assert_eq!(states, [("Hidden".to_string(), false), ("Shown".to_string(), true)]); + let shown = doc.layers[1].children().unwrap(); + let [n] = shown.as_slice() else { panic!("{shown:?}") }; + assert!(matches!(n.kind, NodeKind::Path { rule: vectorcraft_doc::geom::FillRule::NonZero, .. }), "{:?}", n.kind); + assert!((n.opacity - 0.6).abs() < 1e-6 && n.blend == vectorcraft_color::BlendMode::Overlay, "{} {:?}", n.opacity, n.blend); + assert!(n.locked && n.visible); +} + #[test] fn other_versions_and_damaged_drawings_say_why() { let mut s = Session::new(); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 9a7a13e3de..b697c16821 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -301,7 +301,7 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | PICT | open, place (legacy) | yes (versions 1 and 2: shapes, lines, regions, text, bitmaps, pixel maps and QuickTime JPEG images; placed as one group clipped to the picture's frame) | no | `.pct`, `.pic` and `.pict`; a version 2 picture also opens by its content; a two-color pattern fills with its average color; inverted shapes, transfer modes other than a copy and QuickTime images in other formats come back as warnings; a picture cut short keeps what came before it; tests in `crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs` and `crates/engine/tests/import_fuzz.rs` | | Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` | | FreeHand `.fh*` | open (legacy) | no | no | | -| `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, clipping containers, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses and object transparency are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies; version 3 envelopes are not applied, so the objects and groups under one keep their outlines and matrices, with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; record layouts and their sources in `crates/cdr/PROVENANCE.md`; synthetic test files only; tests in `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` | +| `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, clipping containers, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; hidden and locked layers, groups and objects; the winding flag as the nonzero fill rule; uniform transparency of version 13 on as opacity and blend mode; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses, other transparency and merge modes without a blend mode are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies; version 3 envelopes are not applied, so the objects and groups under one keep their outlines and matrices, with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; record layouts and their sources in `crates/cdr/PROVENANCE.md`; synthetic test files only; tests in `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` | | Text `.txt` | place, export | place (Text Import Options) | yes | | | RTF `.rtf` | place | place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only | | Word `.docx` | place | place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out | diff --git a/docs/mcp.md b/docs/mcp.md index 4bc087973e..ecd42fb4be 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8050,10 +8050,16 @@ included) become paths, and rectangles and ellipses become live shapes; a rectan fills and outlines keep their colors, widths, caps, joins and dashes (an outline of width 0 becomes a 0.25 pt stroke), an outline behind the fill becomes a stroke below the fill, and an object without a fill or outline of its own takes its style's. A library color that the drawing stores with its -name and values (version 13 and later) becomes a spot swatch with its tint, and one stored only by its number opens as -a black spot color. Text, bitmaps, blends, contours, brush strokes, other objects the reader doesn't read yet, -fountain, pattern, texture and PostScript fills, and outline arrowheads are left out, and lenses and object -transparency are not applied. The `warnings` of +name and values (version 13 and later, in a fill or an outline) becomes a spot swatch with its tint, and one stored +only by its number opens as a black spot color. An object whose winding flag is set is filled with the nonzero rule, and +any other with even-odd. Hidden and locked layers, groups and objects open hidden and locked; when layers of one name +merge and only some of them are hidden or locked, their art is hidden or locked object by object. Hidden guidelines go +on a hidden layer named Hidden guides, and the other guides go on the top shown layer. A uniform +transparency (version 13 and later) becomes the object's opacity, and its merge mode the object's blend mode. +VectorCraft reads the stored value as the transparency in percent, 0 opaque and 100 clear, and a set winding flag as +the nonzero rule; both are VectorCraft's own readings. Text, bitmaps, blends, contours, brush strokes, other objects the +reader doesn't read yet, fountain, pattern, texture and PostScript fills, and outline arrowheads are left out, and +lenses, other transparency and merge modes without a VectorCraft blend mode are not applied. The `warnings` of `document.open` name each of these kinds the drawing had, and say when damaged parts or parts past the import limits were left out. Drawings of versions after 27 are refused with a message, and so are packages that are encrypted, ZIP64 archives or split across files. VectorCraft doesn't write `.cdr` files. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f54f346d48..b3ca72d7bf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1757,7 +1757,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill, or scaled with the object's matrix, where the file says so), an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, object transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). + - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill, or scaled with the object's matrix, where the file says so), an object without a fill or outline of its own taking its style's, hidden and locked layers, groups and objects, the winding flag as the nonzero fill rule, and a uniform transparency of version 13 and later as the object's opacity and blend mode. A library color stored with its name and values (version 13 and later, in a fill or an outline) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, other transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. EPS and PostScript `.ai` files are still embedded (`crates/engine/src/tests/placed_document.rs`). From 0e8a02a88341adc7027c259991a8b08dd7203912 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:51:08 -0800 Subject: [PATCH 27/34] i18n: Danish rows for the CDR import messages --- crates/ui-egui/src/i18n/da.tsv | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 59ce36d15f..27df219f20 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -267,6 +267,18 @@ @msg the HEIC or HEIF file can't be read HEIC- eller HEIF-filen kan ikke læses @msg the HEIC or HEIF file holds a kind of image that can't be read HEIC- eller HEIF-filen indeholder en billedtype, der ikke kan læses @msg HEIC and HEIF images can't be opened in this build HEIC- og HEIF-billeder kan ikke åbnes i denne version +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 tegninger fra CDR {version} kan ikke åbnes: VectorCraft læser version 1 til 27 +@msg this CDR drawing can't be read ({why}) denne CDR-tegning kan ikke læses ({why}) +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out tekst, bitmaps, blandinger, konturer, penselstrøg og andre CDR-objekter, som VectorCraft endnu ikke læser, blev udeladt +@msg CDR fountain, pattern, texture and PostScript fills were left out CDR-udfyldninger med forløb, mønster, tekstur og PostScript blev udeladt +@msg colors in CDR color models VectorCraft doesn't read were opened as black farver i CDR-farvemodeller, som VectorCraft ikke læser, blev åbnet som sorte +@msg CDR library colors that the drawing stores only by number were opened as black spot colors CDR-biblioteksfarver, som tegningen kun gemmer som et nummer, blev åbnet som sorte spotfarver +@msg CDR outline arrowheads were left out pilespidser på CDR-konturer blev udeladt +@msg CDR envelopes were not applied, and the shapes under them keep their outlines CDR-kuverter blev ikke anvendt, og figurerne under dem beholder deres omrids +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque CDR-linser og objektgennemsigtighed blev ikke anvendt, og objekterne, de ligger på, vises uigennemsigtige +@msg parts of the drawing nested too deeply, or past the import limits, were left out dele af tegningen, der er indlejret for dybt eller ligger ud over importgrænserne, blev udeladt +@msg damaged parts of the drawing were left out beskadigede dele af tegningen blev udeladt +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard CDR-sider, der er længere end 163.830 pt, blev åbnet i den længde, og grafik nær deres kanter ligger uden for tegnefladen @msg the JPEG XL file is cut short JPEG XL-filen er afkortet @msg the JPEG XL container is too large to read JPEG XL-containeren er for stor til at blive læst @msg CMYK JPEG XL images can't be read CMYK-billeder i JPEG XL kan ikke læses From 0c730007b17003ec0783cb85de2399b229e0c290 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 17:11:50 -0800 Subject: [PATCH 28/34] CDR import: an export over the opened drawing asks first when the open left things out Every warning of a .cdr or .cdt open now counts as a loss, so an export or Save As to the drawing's own path needs acknowledgeLoss, as an EPS or .ai read in part does. --- crates/engine/src/cmd/fileio/load.rs | 4 +++- crates/engine/src/cmd/fileio/tests_cdr.rs | 20 ++++++++++++++++++++ docs/file-format-parity.md | 2 +- docs/mcp.md | 3 ++- 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index f2fff3ca07..83edcc9d97 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -734,11 +734,13 @@ fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option = warnings .iter() .filter(|w| { is_loss(w) + || matches!(format.id, "cdr" | "cdt") || (format.id == "eps" && (matches!(w.as_str(), EDITING_DAMAGED | EDITING_STALE) || w.starts_with("this file's PostScript couldn't be read") diff --git a/crates/engine/src/cmd/fileio/tests_cdr.rs b/crates/engine/src/cmd/fileio/tests_cdr.rs index 0d3477e5b8..a8782eca89 100644 --- a/crates/engine/src/cmd/fileio/tests_cdr.rs +++ b/crates/engine/src/cmd/fileio/tests_cdr.rs @@ -571,6 +571,26 @@ fn transparency_winding_and_flags_open_on_the_art() { assert!(n.locked && n.visible); } +/// A drawing whose open left things out is not written over unasked: the file stays as it was +/// until the write says `acknowledgeLoss`. +#[test] +fn a_drawing_the_open_left_things_out_of_is_not_written_over_unasked() { + let d = std::env::temp_dir().join(format!("vc-cdr-lossy-{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + let src = d.join("drawing.cdr"); + let original = synth::sample_file(1300, true); + std::fs::write(&src, &original).unwrap(); + let mut s = Session::new(); + let opened = s.execute("document.open", &json!({ "path": src.to_string_lossy() })).unwrap(); + assert!(opened["warnings"].to_string().contains("text, bitmaps"), "{opened}"); + let e = s.execute("document.export", &json!({ "path": src.to_string_lossy(), "format": "svg" })).unwrap_err().to_string(); + assert!(e.contains("acknowledgeLoss"), "{e}"); + assert_eq!(std::fs::read(&src).unwrap(), original); + s.execute("document.export", &json!({ "path": src.to_string_lossy(), "format": "svg", "acknowledgeLoss": true })).unwrap(); + assert_ne!(std::fs::read(&src).unwrap(), original); + std::fs::remove_dir_all(d).ok(); +} + #[test] fn other_versions_and_damaged_drawings_say_why() { let mut s = Session::new(); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 3f517e1167..05f542321e 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -301,7 +301,7 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | PICT | open, place (legacy) | yes (versions 1 and 2: shapes, lines, regions, text, bitmaps, pixel maps and QuickTime JPEG images; placed as one group clipped to the picture's frame) | no | `.pct`, `.pic` and `.pict`; a version 2 picture also opens by its content; a two-color pattern fills with its average color; inverted shapes, transfer modes other than a copy and QuickTime images in other formats come back as warnings; a picture cut short keeps what came before it; tests in `crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs` and `crates/engine/tests/import_fuzz.rs` | | Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` | | FreeHand `.fh*` | open (legacy) | no | no | | -| `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, clipping containers, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; hidden and locked layers, groups and objects; the winding flag as the nonzero fill rule; uniform transparency of version 13 on as opacity and blend mode; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses, other transparency and merge modes without a blend mode are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies; version 3 envelopes are not applied, so the objects and groups under one keep their outlines and matrices, with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; record layouts and their sources in `crates/cdr/PROVENANCE.md`; synthetic test files only; tests in `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` | +| `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, clipping containers, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; hidden and locked layers, groups and objects; the winding flag as the nonzero fill rule; uniform transparency of version 13 on as opacity and blend mode; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses, other transparency and merge modes without a blend mode are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies; version 3 envelopes are not applied, so the objects and groups under one keep their outlines and matrices, with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; after an open with a warning, an export or Save As to the drawing's own path needs `acknowledgeLoss: true`; record layouts and their sources in `crates/cdr/PROVENANCE.md`; synthetic test files only; tests in `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` | | Text `.txt` | place, export | place (Text Import Options) | yes | | | RTF `.rtf` | place | place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only | | Word `.docx` | place | place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out | diff --git a/docs/mcp.md b/docs/mcp.md index 5dbe6051b8..7af8875042 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8310,7 +8310,8 @@ reader doesn't read yet, fountain, pattern, texture and PostScript fills, and ou lenses, other transparency and merge modes without a VectorCraft blend mode are not applied. The `warnings` of `document.open` name each of these kinds the drawing had, and say when damaged parts or parts past the import limits were left out. Drawings of versions after 27 are refused with a message, and so are packages that are -encrypted, ZIP64 archives or split across files. VectorCraft doesn't write `.cdr` files. +encrypted, ZIP64 archives or split across files. VectorCraft doesn't write `.cdr` files. After a drawing opens with +warnings, an export or Save As to its own path needs `acknowledgeLoss: true`. Public specifications cover only parts of versions 1 to 4, so for the rest the importer reads the layouts found in public sample files. A drawing of version 1 or 2 opens as one page with one layer: its rectangles, whole ellipses and curves with their From 5c28beca757f44a6b10d560c674baef67baff536 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 17:40:04 -0800 Subject: [PATCH 29/34] CDR import: a fill or outline whose record is missing is damage A shape that names a fill or outline id no record has comes in without that paint and with the damage warning, so the open counts as lossy. Id 0 without a record stays no paint. --- crates/cdr/src/build.rs | 12 ++++++++++-- crates/cdr/tests/it/read.rs | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs index 923c9155cd..758c8886b6 100644 --- a/crates/cdr/src/build.rs +++ b/crates/cdr/src/build.rs @@ -693,8 +693,11 @@ impl<'a, 'b> Ctx<'a, 'b> { if let Some(f) = self.fills.get(&id) { return f.clone(); } - // A record that is there but can't be read is damage; a missing one leaves the shape - // without a fill. + // A record that is missing or can't be read is damage, and the shape is drawn without a + // fill; id 0 without a record is no fill. + if id != 0 && !self.fill_chunks.contains_key(&id) { + push(self.warn, Warning::Damaged); + } let read = self.fill_chunks.get(&id).and_then(|b| { let read = records::fill(b, &self.p, self.warn); if read.is_none() { @@ -710,6 +713,11 @@ impl<'a, 'b> Ctx<'a, 'b> { /// uses it; past them the shape's outline is solid. fn outline(&mut self, id: u32) -> Option { if !self.outlines.contains_key(&id) { + // A record that is missing is damage, as one that can't be read is; id 0 without a + // record is no outline. + if id != 0 && !self.outline_chunks.contains_key(&id) { + push(self.warn, Warning::Damaged); + } let read = self.outline_chunks.get(&id).and_then(|b| { let read = records::outline(b, &self.p, self.warn); if read.is_none() { diff --git a/crates/cdr/tests/it/read.rs b/crates/cdr/tests/it/read.rs index 3a32cc0d8a..5c944a6c16 100644 --- a/crates/cdr/tests/it/read.rs +++ b/crates/cdr/tests/it/read.rs @@ -1396,6 +1396,25 @@ fn an_id_argument_cut_short_is_damage() { } } +/// A fill or outline id that no record has is damage: the shape comes in without that paint. Id 0 +/// without a record is no paint. +#[test] +fn a_fill_or_outline_without_its_record_is_damage() { + for version in [700, 1100, 1600] { + let v = V(version); + for kind in [20, 10] { + for (id, want) in [(9u32, vec![Warning::Damaged]), (0, vec![])] { + let object = synth::object(v, 1, &[(kind, id.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let d = + read(&clip_drawing(version, vec![], vec![object]), Limits::default()).unwrap_or_else(|e| panic!("{version} {kind} {id}: {e}")); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s.len() == 1 && s[0].fill.is_none() && s[0].outline.is_none(), "{version} {kind} {id}"); + assert_eq!(d.warnings, want, "{version} {kind} {id}"); + } + } + } +} + /// An object with a lens or transparency (argument 8000) comes in opaque, with the lenses /// warning; one without the argument gives no warning. #[test] From a75179664b9f5cc206f43dd41ff3488ed90282fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 12:05:54 -0800 Subject: [PATCH 30/34] i18n: French rows take a no-break space before the colon --- crates/ui-egui/src/i18n/fr.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 81e44c552a..2753fc9c07 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5488,7 +5488,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg the HEIC or HEIF file can't be read le fichier HEIC ou HEIF ne peut pas être lu @msg the HEIC or HEIF file holds a kind of image that can't be read le fichier HEIC ou HEIF contient un type d’image qui ne peut pas être lu @msg HEIC and HEIF images can't be opened in this build les images HEIC et HEIF ne peuvent pas être ouvertes dans cette version -@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 impossible d’ouvrir les dessins de CDR {version} : VectorCraft lit les versions 1 à 27 +@msg CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27 impossible d’ouvrir les dessins de CDR {version} : VectorCraft lit les versions 1 à 27 @msg this CDR drawing can't be read ({why}) impossible de lire ce dessin CDR ({why}) @msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out les textes, bitmaps, dégradés de formes, contours progressifs, traits de pinceau et autres objets CDR que VectorCraft ne lit pas encore ont été ignorés @msg CDR fountain, pattern, texture and PostScript fills were left out les remplissages dégradés, à motif, de texture et PostScript de CDR ont été ignorés From d4e43bab3b367210dc061f70bef15f63ea5e970e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 21:28:29 -0800 Subject: [PATCH 31/34] Docs: the formats summary row counts .cdr and PostScript among the formats opened The table opens and places PostScript through the EPS reader, so PS leaves the missing list, and .cdr drawings now open: 33 formats, missing FreeHand and DWG. --- docs/file-format-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 33ff4ff8cc..570869844e 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -21,7 +21,7 @@ Ordinary File > Save offers Save As when its own location refuses writes with a | | Illustrator | VectorCraft | Notes | |---|---:|---:|---| -| Formats opened or placed | ~30 | 31 | missing: FreeHand, DWG, PS | +| Formats opened or placed | ~30 | 33 | missing: FreeHand, DWG | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, gradients, patterns, images, type, symbols, artboards, transparency, opacity masks, clipping, text wrap options) or as legacy version 7 (layers and groups, one artboard per file) | | Formats exported | ~16 | 18 | missing: DWG; extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | | **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting | From 1f1135cd6f534336c46db63dcb8b13b6b93030af Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 14:09:03 -0800 Subject: [PATCH 32/34] i18n: Polish calls the art kompozycja in the long CDR page warning The Polish row for the warning about CDR pages longer than 163,830 pt said grafika for the art near the page edges. The catalog calls art and artwork kompozycja, and polish_rows_call_artwork_kompozycja checks every row for it. --- crates/ui-egui/src/i18n/pl.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 914c309b6c..d621d568fc 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5881,7 +5881,7 @@ variable-list-end {0}, {1} {0} i {1} @msg CDR lenses and object transparency were not applied, and the objects they are on show opaque soczewki i przezroczystość obiektów CDR nie zostały zastosowane, a obiekty, na których się znajdują, są wyświetlane jako nieprzezroczyste @msg parts of the drawing nested too deeply, or past the import limits, were left out pominięto części rysunku zagnieżdżone zbyt głęboko lub wykraczające poza limity importu @msg damaged parts of the drawing were left out pominięto uszkodzone części rysunku -@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard strony CDR dłuższe niż 163 830 pt otwarto z tą długością, a grafika przy ich krawędziach leży poza obszarem kompozycji +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard strony CDR dłuższe niż 163 830 pt otwarto z tą długością, a kompozycja przy ich krawędziach leży poza obszarem kompozycji @msg the PSD image is too large to read ({_1} × {_2} pixels) obraz PSD jest zbyt duży, aby go odczytać ({_1} × {_2} pikseli) @msg zipped 1-bit PSD image data with prediction can't be read nie można odczytać spakowanych 1-bitowych danych obrazu PSD z predykcją @msg the PSD file's layer data uses an unknown compression ({m}) dane warstw pliku PSD używają nieznanej kompresji ({m}) From c7d78a2dacffcecb6efa3a716cc16ea8eb3a3dbe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 14:59:59 -0800 Subject: [PATCH 33/34] File formats: open and place .cmx files .cmx exchange files with 32-bit coordinates open and place as editable art. vectorcraft-cdr reads the RIFF form CMX1, its header, the color, pen, line type, dash, outline and arrowhead tables, and each page's instructions in drawing order, into the drawing model the .cdr reader uses, so the importer maps pages, layers, groups and curves with uniform fills and outlines the same way. A layer that holds nothing is left out. A page that gives no size of its own takes the size of the drawing's bounds, which the page header stores, and is centered on them. Text, images, rectangles, ellipses, clipping paths, fills other than uniform ones and arrowheads are left out, and lenses are not applied; the warnings name each kind, with rows in every complete catalog. Big-endian files and files with 16-bit coordinates are refused with a message. Layouts and their sources are rows R53 to R63 of crates/cdr/PROVENANCE.md; tests use synthetic files only. --- crates/cdr/Cargo.toml | 2 +- crates/cdr/PROVENANCE.md | 24 +- crates/cdr/README.md | 24 +- crates/cdr/src/cmx.rs | 631 ++++++++++++++++++++++ crates/cdr/src/geometry.rs | 2 +- crates/cdr/src/lib.rs | 30 +- crates/cdr/src/limits.rs | 3 +- crates/cdr/src/model.rs | 3 +- crates/cdr/src/records.rs | 2 +- crates/cdr/src/synth_cmx.rs | 274 ++++++++++ crates/cdr/tests/it/cmx.rs | 433 +++++++++++++++ crates/cdr/tests/it/main.rs | 1 + crates/engine/src/cmd/fileio.rs | 5 +- crates/engine/src/cmd/fileio/cdr.rs | 49 +- crates/engine/src/cmd/fileio/formats.rs | 9 +- crates/engine/src/cmd/fileio/load.rs | 11 +- crates/engine/src/cmd/fileio/tests_cmx.rs | 124 +++++ crates/engine/tests/import_fuzz.rs | 47 ++ crates/ui-egui/src/i18n/ca.tsv | 8 + crates/ui-egui/src/i18n/cs.tsv | 8 + crates/ui-egui/src/i18n/da.tsv | 8 + crates/ui-egui/src/i18n/de.tsv | 8 + crates/ui-egui/src/i18n/el.tsv | 8 + crates/ui-egui/src/i18n/es.tsv | 8 + crates/ui-egui/src/i18n/fi.tsv | 8 + crates/ui-egui/src/i18n/fr.tsv | 8 + crates/ui-egui/src/i18n/hi.tsv | 8 + crates/ui-egui/src/i18n/hu.tsv | 8 + crates/ui-egui/src/i18n/it.tsv | 8 + crates/ui-egui/src/i18n/ja.tsv | 8 + crates/ui-egui/src/i18n/ka.tsv | 8 + crates/ui-egui/src/i18n/ko.tsv | 8 + crates/ui-egui/src/i18n/nl.tsv | 8 + crates/ui-egui/src/i18n/pl.tsv | 8 + crates/ui-egui/src/i18n/pt-br.tsv | 8 + crates/ui-egui/src/i18n/ru.tsv | 8 + crates/ui-egui/src/i18n/sv.tsv | 8 + crates/ui-egui/src/i18n/tests.rs | 20 + crates/ui-egui/src/i18n/tr.tsv | 8 + crates/ui-egui/src/i18n/uk.tsv | 8 + crates/ui-egui/src/i18n/vi.tsv | 8 + crates/ui-egui/src/i18n/zh-hans.tsv | 8 + crates/ui-egui/src/i18n/zh-hant.tsv | 8 + docs/architecture.md | 2 +- docs/file-format-parity.md | 3 +- docs/mcp.md | 17 +- docs/target-app-parity.md | 3 +- 47 files changed, 1885 insertions(+), 26 deletions(-) create mode 100644 crates/cdr/src/cmx.rs create mode 100644 crates/cdr/src/synth_cmx.rs create mode 100644 crates/cdr/tests/it/cmx.rs create mode 100644 crates/engine/src/cmd/fileio/tests_cmx.rs diff --git a/crates/cdr/Cargo.toml b/crates/cdr/Cargo.toml index 1600164c7e..ca2066c879 100644 --- a/crates/cdr/Cargo.toml +++ b/crates/cdr/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "vectorcraft-cdr" -description = "Bounded reader for .cdr drawings of versions 1 to 27: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers" +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" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 330b567440..ba2e8d642b 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -38,10 +38,17 @@ Sources: https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/approach-approch/cdr/banff_ap_en.cdr and https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/atlas-atlas/cdr/ab_en_br.cdr - **DM**: the clip art of https://discmaster.textfiles.com/browse/31541, by file name + - **CX**: the `.cmx` files of https://telparia.com/fileFormatSamples/image/cmx/, by file name. The + nine with 32-bit coordinates are `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, + `gold_bar.cmx`, `goldblue.cmx`, `PC.CMX`, `squares.cmx` and `thatch.cmx`; they carry no picture + of their drawing. +- **CN**: the `.cmx` notes of an MIT OR Apache-2.0 drawing program, which mark each layout + "confirmed" when the program's authors found it in sample files, + https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/docs/cmx-format.md -Status: `public-spec` (K, KF, KR, Z, F or PR), `sample` (S), `unconfirmed` (a point no source states -and no sample file shows; listed so it can be checked against a file, with what the reader does -when it is wrong). +Status: `public-spec` (K, KF, KR, Z, F or PR), `sample` (S), `public-notes` (a layout CN marks +confirmed that no CX file shows), `unconfirmed` (a point no source states and no sample file shows; +listed so it can be checked against a file, with what the reader does when it is wrong). Public specifications cover only parts of versions 1 to 4: the rows that cite K, F or PR, such as the version 3 fill (R34) and page settings (R38). The other rows of those versions rest on the @@ -103,3 +110,14 @@ file is committed. | R50 | Bit 5 (0x20) of the outline's line type scales the outline's width and dashes with the shape's matrix. The engine multiplies them by the square root of the matrix's area factor (VectorCraft's own value for a matrix that scales x and y differently) | S: UC `outl_scale_with_cdr7.cdr` to `outl_scale_with_cdr12.cdr`, of whose outlines only one, 3.969 mm wide, has line type 0x22 and the others 0x02 or 0x01; TDF 76771 (version 15), whose outline of line type 0x22 is 10 mm wide on a shape that the matrix stretches and skews, and whose picture draws that outline several times wider and skewed | sample (the bit; the single width for a matrix that scales x and y differently: VectorCraft's own) | | R51 | A `trfd` offsets table holds one offset more than the entries; each entry runs from its offset to the next, and the last offset is the record's end | KF L1079, L1113-L1121; S: every `trfd` of versions 4 to 25 in the sample files (25,425 records) has the extra offset, equal to the record's length | public-spec | | R52 | Byte 0 of argument 14001 is the fill's winding flag. VectorCraft reads a byte other than 0 as the nonzero fill rule, and 0 or an object without the argument as even-odd | KF L575-L583, L1047; S: the argument is 4 bytes in the sample files that carry it, with byte 0 = 1 on LT `complexshape_blackfill_nooutline` of `testset/12` and `testset/15` to `testset/25` and on objects of TDF 127576 (13) and 60026 (14), and 0 on 27 objects of TP `example.cdr` (17) | public-spec (the flag: KF; which rule each value means, and the rule without the argument: VectorCraft's own reading, and a wrong reading fills or leaves holes where a curve's subpaths overlap) | +| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id, the next id is four letters at an even distance of 2 to 64 bytes | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample | +| R54 | `cont`: byte 52 is the coordinate size as an ASCII digit, `4` for 32-bit coordinates and `2` for 16-bit ones (refused); bytes 64 to 72 hold an f64, the size of a coordinate unit in meters. A value that isn't above 0 and at most 1 reads as 0.1 µm (VectorCraft's own fallback) | CN "Container"; S: the nine CX files with `4` all hold 1e-7; `abydos.cmx`, `CM33.CMX`, `LIZARDS.CMX`, `output.000.cmx` and `test.cmx` hold `2` | sample | +| R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample | +| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 5 red, green and blue in 0 to 255. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them; a wrong reading gives a wrong color) | +| R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each) | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) | +| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist | sample | +| R59 | `rota`: a u16 count, then pairs of u16 (start and end arrowheads, 0 for none), not field lists | CN "Tables"; S: `rota` is `01 00 00 00 00 00` in every CX file | sample (pairs of 0), public-notes (other values) | +| R60 | A `page` chunk is a stream of instructions: a u16 size counting the whole instruction and an i16 code, or 0xFFFF, a u32 size and the code (the long form); then field lists. Codes: 9 and 10 begin and end a page, 11 and 12 a layer, 13 and 14 a group, 67 a curve; 20 and 21 a text object, 65 its drawn characters, 66 an ellipse, 68 a rectangle, 69 an image, 88 and 89 add and remove a clipping path, 111 a jump whose field 1 is the u32 file offset to go on from (the bytes jumped over hold images). Objects are drawn in file order, the first at the back | CN "page: instructions"; S: codes 9 to 14 and 67 in the CX files; in `squares.cmx` the large square comes first and the two smaller ones inside it after | sample (9 to 14, 67, the order), public-notes (the long form and the other codes) | +| 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) | 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 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 | 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), 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 | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index 58117d1f3c..e0ad0b1eb8 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -57,12 +57,32 @@ reports version 1 for the marker `e` and version 2 for the other two. A RIFF fil a version before 3 is refused, and so is the version 4 template form type `CDST`, which reads as not a `.cdr` drawing. +## `.cmx` files + +`read_cmx` reads `.cmx` exchange files with 32-bit coordinates (rows R53 to R63) into the same +drawing model, with a version of 0. It reads the color, pen, line type, dash, outline and +arrowhead tables, then each page's instructions in drawing order: + +| In the `.cmx` file | Read as | +|---|---| +| Pages, with the size the page gives, or else the size of the drawing's bounds that the page stores | pages; a page sized to the bounds is centered on them | +| Layers, by their UTF-16 or 8-bit name | drawing layers; a layer that holds nothing is left out | +| Groups | groups | +| Curves (moves, lines and cubic curves, as `.cdr` point lists) | paths | +| Uniform fills: CMYK in percent or 0 to 255, RGB, and library colors with their names | colors, spot colors | +| Outlines: width, color, caps, joins, dashes, the no-outline, behind-the-fill and scaled-with flags | outlines | + +Text, images, rectangles, ellipses, clipping paths, fills other than uniform ones, outline +arrowheads and lenses are not read; the drawing's `warnings` name each kind it held. A clipping +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. + ## Provenance `PROVENANCE.md` lists every record layout the reader relies on, with its public source 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` (the `synth` feature); no -third-party file is committed. +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. ## Limits diff --git a/crates/cdr/src/cmx.rs b/crates/cdr/src/cmx.rs new file mode 100644 index 0000000000..5bd7439291 --- /dev/null +++ b/crates/cdr/src/cmx.rs @@ -0,0 +1,631 @@ +//! Reader for `.cmx` exchange files with 32-bit coordinates: the RIFF form `CMX1` (R53), its +//! header (R54), the color, pen, line type, dash, outline and arrowhead tables (R55 to R59) and the +//! instructions of each page (R60): pages, layers, groups and curves (R61, R62) with uniform fills +//! and outlines (R63). Text, images, rectangles, ellipses, clipping paths, other fills and lenses +//! are left out with a warning. + +use crate::bytes::{Rd, u32_at}; +use crate::geometry::path_of; +use crate::layout::{self, Profile}; +use crate::limits::Budget; +use crate::model::{Cap, Color, Drawing, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape}; +use crate::records::{name, property_color}; +use crate::riff::{LIST, push}; +use crate::{Error, Warning}; + +const FORM: [u8; 4] = *b"CMX1"; +/// Meters per coordinate unit when the header gives no usable value: the 0.1 µm of every sample +/// file with 32-bit coordinates (R54). +const DEFAULT_UNIT: f64 = 1e-7; +/// How far past a chunk that runs short the next chunk id is looked for (R53). +const RESYNC: usize = 64; +/// The chunks the reader uses (R53 to R60). +const READ_IDS: [[u8; 4]; 9] = [*b"LIST", *b"cont", *b"page", *b"rclr", *b"rpen", *b"rott", *b"rdot", *b"rotl", *b"rota"]; +/// The most UTF-16 units read of a layer's name; [`name`] keeps 256 of them. +const MAX_NAME_UNITS: usize = 4096; + +// Instruction codes (R60). +const BEGIN_PAGE: i16 = 9; +const END_PAGE: i16 = 10; +const BEGIN_LAYER: i16 = 11; +const END_LAYER: i16 = 12; +const BEGIN_GROUP: i16 = 13; +const END_GROUP: i16 = 14; +const BEGIN_TEXT: i16 = 20; +const END_TEXT: i16 = 21; +const GLYPH_RUN: i16 = 65; +const ELLIPSE: i16 = 66; +const CURVE: i16 = 67; +const RECTANGLE: i16 = 68; +const IMAGE: i16 = 69; +const ADD_CLIP: i16 = 88; +const REMOVE_CLIP: i16 = 89; +const JUMP: i16 = 111; + +/// Does `bytes` start as a CMX file: a RIFF or RIFX form of type `CMX1` (R53)? +pub(crate) fn is_cmx(bytes: &[u8]) -> bool { + matches!(bytes.get(0..4), Some(b"RIFF" | b"RIFX")) && bytes.get(8..12) == Some(FORM.as_slice()) +} + +/// A chunk outside the `LIST` chunks: its id, its body and where the body starts in the file. +struct Chunk<'a> { + id: [u8; 4], + body: &'a [u8], + start: usize, +} + +/// The tables that page instructions refer to by 1-based index (R55 to R59). +#[derive(Default)] +struct Tables { + colors: Vec>, + /// Outline widths in points. + pens: Vec>, + /// Flags, and the caps and join. + line_types: Vec>, + dashes: Vec>, + /// Line type, screen, color, arrowheads, pen and dashes. + outlines: Vec>, + arrowheads: Vec<(u16, u16)>, +} + +pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result { + if !is_cmx(bytes) { + return Err(Error::NotCmx); + } + if bytes.get(0..4) == Some(b"RIFX") { + return Err(Error::Unsupported("big-endian CMX files")); + } + let mut warn = Vec::new(); + let chunks = chunks(bytes, budget, &mut warn)?; + let cont = chunks.iter().find(|c| c.id == *b"cont").map(|c| c.body).ok_or(Error::Damaged("CMX header"))?; + match cont.get(52) { + Some(b'4') => {} + Some(b'2') => return Err(Error::Unsupported("CMX files with 16-bit coordinates")), + _ => return Err(Error::Damaged("CMX header")), + } + let meters = Rd::at(cont, 64).f64().filter(|m| *m > 0.0 && *m <= 1.0).unwrap_or(DEFAULT_UNIT); + let unit = meters / 0.0254 * 72.0; + let tables = Tables::read(&chunks, unit, budget, &mut warn)?; + let mut pages = Vec::new(); + for c in chunks.iter().filter(|c| c.id == *b"page") { + pages.push(PageRead::new(&tables, unit, budget, &mut warn).read(c)?); + } + Ok(Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: warn }) +} + +/// The chunks of the file in order, those inside `LIST` chunks in place (R53). +fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec) -> Result>, Error> { + let declared = u32_at(b, 4).and_then(|n| (n as usize).checked_add(8)).unwrap_or(b.len()); + if declared > b.len() { + // The file was cut short of the size its header gives. + push(warn, Warning::Damaged); + } + let end = declared.min(b.len()); + let mut out = Vec::new(); + // (position, end, depth) of the lists still to walk; a list's children go before the rest of + // the list that holds it. + let mut stack = vec![(12usize, end, 0usize)]; + while let Some((mut pos, end, depth)) = stack.pop() { + while pos.saturating_add(8) <= end { + let Some(id) = Rd::at(b, pos).fourcc() else { break }; + if !id.iter().all(|c| c.is_ascii_alphanumeric() || *c == b' ') { + match resync(b, pos, end) { + Some(next) => { + pos = next; + continue; + } + None => { + push(warn, Warning::Damaged); + break; + } + } + } + budget.take_chunk()?; + let size = u32_at(b, pos + 4).map_or(0, |s| s as usize); + let start = pos + 8; + let stop = start.saturating_add(size); + if stop > end { + // Stray bytes that happen to start with four letters give a length past the list: + // look for the next chunk id after them. A chunk the reader uses is kept, cut at + // the end of the list. + if !READ_IDS.contains(&id) + && let Some(next) = resync(b, pos, end) + { + pos = next; + continue; + } + push(warn, Warning::Damaged); + } + let stop = stop.min(end); + let next = stop.saturating_add(size & 1); + if id == LIST { + if depth >= budget.limits.depth { + push(warn, Warning::TooDeep); + pos = next; + continue; + } + stack.push((next, end, depth)); + stack.push((start + 4, stop, depth + 1)); + break; + } + if let Some(body) = b.get(start..stop) { + out.push(Chunk { id, body, start }); + } + pos = next; + } + } + Ok(out) +} + +/// Where the next chunk id after `pos` lies: four letters at an even distance of 2 to [`RESYNC`] +/// bytes (R53). +fn resync(b: &[u8], pos: usize, end: usize) -> Option { + (pos + 2..=pos.saturating_add(RESYNC).min(end.saturating_sub(8))) + .step_by(2) + .find(|&p| b.get(p..p + 4).is_some_and(|t| t.iter().all(u8::is_ascii_alphabetic))) +} + +/// The end of the field list at `pos` of `b`: after its 0xff, or the end of `b` when a field runs +/// past it (R55). +fn list_end(b: &[u8], mut pos: usize) -> usize { + while let Some(&tag) = b.get(pos) { + if tag == 0xff { + return pos + 1; + } + match Rd::at(b, pos + 1).u16().map(usize::from).filter(|n| *n >= 3) { + Some(n) if pos + n <= b.len() => pos += n, + _ => break, + } + } + b.len() +} + +/// The data of field `tag` in the field list `b` (R55). +fn field(b: &[u8], tag: u8) -> Option<&[u8]> { + let mut pos = 0; + while let Some(&t) = b.get(pos) { + if t == 0xff { + return None; + } + let n = usize::from(Rd::at(b, pos + 1).u16()?); + let data = b.get(pos + 3..pos.checked_add(n)?).filter(|_| n >= 3)?; + if t == tag { + return Some(data); + } + pos += n; + } + None +} + +/// The field lists of a table: a u16 count, then that many lists (R55). Each entry counts toward +/// the chunk limit. +fn entries<'a>(d: &'a [u8], budget: &mut Budget) -> Result, Error> { + let count = Rd::new(d).u16().map_or(0, usize::from); + let mut out = Vec::new(); + let mut pos = 2; + for _ in 0..count { + if pos >= d.len() { + break; + } + budget.take_chunk()?; + let end = list_end(d, pos); + out.push(d.get(pos..end).unwrap_or_default()); + pos = end; + } + Ok(out) +} + +impl Tables { + /// The first chunk of each table; a table that is missing is empty. + fn read(chunks: &[Chunk], unit: f64, budget: &mut Budget, warn: &mut Vec) -> Result { + let first = |id: &[u8; 4]| chunks.iter().find(|c| c.id == *id).map_or(&[][..], |c| c.body); + // A color record of field 10 holds a property list as a `.cdr` fill does (R56). + let record = layout::for_version(1300); + let mut t = Tables::default(); + for e in entries(first(b"rclr"), budget)? { + t.colors.push(color(e, record.as_ref(), warn)); + } + for e in entries(first(b"rpen"), budget)? { + t.pens.push(field(e, 1).and_then(|f| Rd::new(f).u32()).map(|w| f64::from(w) * unit)); + } + for e in entries(first(b"rott"), budget)? { + t.line_types.push(field(e, 1).and_then(|f| Some((*f.first()?, f.get(1).copied().unwrap_or(0))))); + } + for e in entries(first(b"rdot"), budget)? { + let mut r = Rd::new(field(e, 1).unwrap_or_default()); + let n = r.u16().map_or(0, usize::from); + t.dashes.push((0..n).map_while(|_| r.u16()).collect()); + } + for e in entries(first(b"rotl"), budget)? { + t.outlines.push(field(e, 1).and_then(|f| { + let mut r = Rd::new(f); + Some([r.u16()?, r.u16()?, r.u16()?, r.u16()?, r.u16()?, r.u16()?]) + })); + } + // Arrowhead pairs are plain u16 pairs after the count, not field lists (R59). + let mut r = Rd::new(first(b"rota")); + let n = r.u16().map_or(0, usize::from); + for _ in 0..n { + let Some(pair) = r.u16().zip(r.u16()) else { break }; + budget.take_chunk()?; + t.arrowheads.push(pair); + } + Ok(t) + } + + /// Entry `index` (1-based) of `list`, or `None` with a warning when there is none. + fn get(list: &[Option], index: u16, warn: &mut Vec) -> Option { + let found = usize::from(index).checked_sub(1).and_then(|i| list.get(i)).cloned().flatten(); + if found.is_none() { + push(warn, Warning::Damaged); + } + found + } + + fn color(&self, index: u16, warn: &mut Vec) -> Color { + Tables::get(&self.colors, index, warn).unwrap_or(Color::Rgb([0.0; 3])) + } + + /// The outline of `rotl` entry `index`, or `None` when its line type draws none (R57, R58). + fn outline(&self, index: u16, budget: &mut Budget, warn: &mut Vec) -> Option { + let [line, _screen, color, arrows, pen, dash] = Tables::get(&self.outlines, index, warn)?; + let (flags, caps_join) = Tables::get(&self.line_types, line, warn).unwrap_or((2, 0)); + if flags & 1 != 0 { + return None; + } + let width = Tables::get(&self.pens, pen, warn).unwrap_or(0.0); + let mut dashes = Vec::new(); + if flags & 4 != 0 { + let stored = usize::from(dash).checked_sub(1).and_then(|i| self.dashes.get(i)); + match stored { + Some(d) if budget.take_dashes(d.len()) => dashes = d.iter().map(|x| f64::from(*x)).collect(), + Some(_) => push(warn, Warning::TooDeep), + None => push(warn, Warning::Damaged), + } + } + if usize::from(arrows).checked_sub(1).and_then(|i| self.arrowheads.get(i)).is_some_and(|(s, e)| *s != 0 || *e != 0) { + push(warn, Warning::Arrowheads); + } + Some(Outline { + width, + color: self.color(color, warn), + cap: match caps_join & 0x0f { + 1 => Cap::Round, + 2 => Cap::Square, + _ => Cap::Butt, + }, + join: match caps_join >> 4 { + 1 => Join::Round, + 2 => Join::Bevel, + _ => Join::Miter, + }, + dashes, + behind_fill: flags & 8 != 0, + scale_with: flags & 16 != 0, + }) + } +} + +/// A color entry (R56): the property list of field 10 when there is one, else the model and +/// palette bytes of field 1 and the values of field 2. Colors in other models read as black with a +/// warning. +fn color(e: &[u8], record: Option<&Profile>, warn: &mut Vec) -> Option { + if let (Some(f), Some(p)) = (field(e, 10), record) { + let mut r = Rd::new(f); + let len = r.u32()? as usize; + return property_color(r.bytes(len.min(r.left()))?, p, warn); + } + let model = *field(e, 1)?.first()?; + let v = field(e, 2)?; + let byte = |i: usize| v.get(i).map(|b| f32::from(*b)); + let pct = |i: usize| byte(i).map(|x| (x / 100.0).clamp(0.0, 1.0)); + let full = |i: usize| byte(i).map(|x| x / 255.0); + Some(match model { + 2 => Color::Cmyk([pct(0)?, pct(1)?, pct(2)?, pct(3)?]), + 3 => Color::Cmyk([full(0)?, full(1)?, full(2)?, full(3)?]), + 5 => Color::Rgb([full(0)?, full(1)?, full(2)?]), + _ => { + push(warn, Warning::UnknownColors); + Color::Rgb([0.0; 3]) + } + }) +} + +/// The objects of one layer while it is read: the layer's own list, then one list for each group +/// left open. +struct LayerRead { + name: String, + lists: Vec>, +} + +impl LayerRead { + /// The layer, its open groups closed. Lists are drawn back to front (R60), and the model holds + /// them front to back. + fn finish(mut self) -> Layer { + while self.lists.len() > 1 { + close_group(&mut self.lists); + } + let mut objects = self.lists.pop().unwrap_or_default(); + objects.reverse(); + Layer { name: self.name, kind: LayerKind::Drawing, flags: Default::default(), objects, guides: Vec::new() } + } +} + +/// Close the innermost open group of `lists` into the one that holds it. +fn close_group(lists: &mut Vec>) { + if lists.len() < 2 { + return; + } + let mut objects = lists.pop().unwrap_or_default(); + objects.reverse(); + if let Some(top) = lists.last_mut() { + top.push(Object::Group { objects, flags: Default::default() }); + } +} + +/// The reading of one page chunk. +struct PageRead<'t, 'b> { + tables: &'t Tables, + unit: f64, + budget: &'b mut Budget, + warn: &'b mut Vec, + size: Option<(f64, f64)>, + /// The page's center in the file's coordinates when the page takes its size from the + /// drawing's bounds; points are moved by it so the art lies on the page. + center: (f64, f64), + layers: Vec, + open: Option, + /// Groups nested past the depth limit that are still open; their content is left out. + skipped: usize, +} + +impl<'t, 'b> PageRead<'t, 'b> { + fn new(tables: &'t Tables, unit: f64, budget: &'b mut Budget, warn: &'b mut Vec) -> Self { + PageRead { tables, unit, budget, warn, size: None, center: (0.0, 0.0), layers: Vec::new(), open: None, skipped: 0 } + } + + /// The instructions of a page chunk: a u16 size counting the whole instruction and an i16 code, + /// or 0xFFFF, a u32 size and the code; then the code's field lists (R60). + fn read(mut self, c: &Chunk) -> Result { + let d = c.body; + let mut pos = 0usize; + while pos.saturating_add(4) <= d.len() { + self.budget.take_chunk()?; + let mut r = Rd::at(d, pos); + let (size, code, head) = match r.u16() { + Some(0xFFFF) => match (r.u32(), r.i16()) { + (Some(size), Some(code)) => (size as usize, code, 8), + _ => break, + }, + Some(size) => match r.i16() { + Some(code) => (usize::from(size), code, 4), + None => break, + }, + None => break, + }; + if size < head { + push(self.warn, Warning::Damaged); + break; + } + let end = pos.saturating_add(size); + if end > d.len() { + push(self.warn, Warning::Damaged); + } + let body = d.get(pos + head..end.min(d.len())).unwrap_or_default(); + if code == JUMP { + // Field 1 is the file offset the instructions go on from; the bytes passed over + // hold the page's images (R60). + let target = field(body, 1).and_then(|f| Rd::new(f).u32()).and_then(|t| (t as usize).checked_sub(c.start)); + pos = target.filter(|t| *t >= end && *t <= d.len()).unwrap_or(end); + if pos > end { + push(self.warn, Warning::UnsupportedObjects); + } + continue; + } + self.instruction(code, body); + pos = end; + } + if pos < d.len() { + // An instruction whose head runs past the page was not read. + push(self.warn, Warning::Damaged); + } + self.close_layer(); + // A layer that holds nothing (the special layers every sample file lists empty) is left + // out. The file lists layers back to front. + let mut layers = self.layers; + layers.retain(|l| !l.objects.is_empty()); + layers.reverse(); + Ok(Page { size: self.size, layers }) + } + + fn instruction(&mut self, code: i16, body: &[u8]) { + match code { + BEGIN_PAGE => { + // Field 4: the page's width and height (R61). + let mut r = Rd::new(field(body, 4).unwrap_or_default()); + if let (Some(w), Some(h)) = (r.u32(), r.u32()) { + let (w, h) = (f64::from(w) * self.unit, f64::from(h) * self.unit); + self.size = (w > 0.0 && h > 0.0).then_some((w, h)); + } + if self.size.is_none() { + self.size_from_bounds(field(body, 1).unwrap_or_default()); + } + } + BEGIN_LAYER => { + self.close_layer(); + let name = self.layer_name(body).unwrap_or_else(|| format!("Layer {}", self.layers.len() + 1)); + self.open = Some(LayerRead { name, lists: vec![Vec::new()] }); + } + END_LAYER => self.close_layer(), + BEGIN_GROUP => { + let open = self.layer().lists.len(); + if self.skipped > 0 || open > self.budget.limits.depth { + self.skipped += 1; + push(self.warn, Warning::TooDeep); + } else if self.budget.take_object() { + self.layer().lists.push(Vec::new()); + } else { + // Past the object limit the group's content joins the group that holds it. + self.skipped += 1; + push(self.warn, Warning::TooDeep); + } + } + END_GROUP => { + if self.skipped > 0 { + self.skipped -= 1; + } else { + close_group(&mut self.layer().lists); + } + } + CURVE if self.skipped == 0 => { + if let Some(shape) = self.curve(body) { + if self.budget.take_object() { + if let Some(list) = self.layer().lists.last_mut() { + list.push(Object::Shape(Box::new(shape))); + } + } else { + push(self.warn, Warning::TooDeep); + } + } + } + BEGIN_TEXT | GLYPH_RUN | ELLIPSE | RECTANGLE | IMAGE | ADD_CLIP => push(self.warn, Warning::UnsupportedObjects), + // These and the other codes (text styles and characters, color contexts) draw nothing + // on their own. + END_PAGE | END_TEXT | REMOVE_CLIP => {} + _ => {} + } + } + + /// A page without a size of its own is sized to the drawing's bounds in field 1 (R61): a u16 + /// page number, a u32 of flags, then the left, top, right and bottom edges as i32 in + /// coordinate units. The page is centered on those bounds. + fn size_from_bounds(&mut self, f: &[u8]) { + let mut r = Rd::new(f); + if r.u16().is_none() || r.u32().is_none() { + return; + } + let (Some(l), Some(t), Some(rt), Some(b)) = (r.i32(), r.i32(), r.i32(), r.i32()) else { + return; + }; + let (l, t, rt, b) = (f64::from(l) * self.unit, f64::from(t) * self.unit, f64::from(rt) * self.unit, f64::from(b) * self.unit); + let (w, h) = ((rt - l).abs(), (t - b).abs()); + if w > 0.0 && h > 0.0 { + self.size = Some((w, h)); + self.center = ((l + rt) / 2.0, (t + b) / 2.0); + } + } + + /// The open layer, or a new one when objects come before any layer begins. + fn layer(&mut self) -> &mut LayerRead { + let n = self.layers.len() + 1; + self.open.get_or_insert_with(|| LayerRead { name: format!("Layer {n}"), lists: vec![Vec::new()] }) + } + + fn close_layer(&mut self) { + self.skipped = 0; + if let Some(l) = self.open.take() { + self.layers.push(l.finish()); + } + } + + /// A layer's name: field 4 as a u32 count and UTF-16 units, else field 1 from byte 12 as a + /// u16 count and 8-bit characters (R62). + fn layer_name(&mut self, body: &[u8]) -> Option { + // A field 4 that can't be read leaves the name to field 1. + let wide = field(body, 4).and_then(|f| { + let mut r = Rd::new(f); + let n = (r.u32()? as usize).min(MAX_NAME_UNITS).min(r.left() / 2); + Some((r.bytes(n * 2)?, layout::for_version(1200)?)) + }); + if let Some((units, l)) = wide { + let s = name(units, &l, self.warn); + if !s.trim().is_empty() { + return Some(s); + } + } + let mut r = Rd::at(field(body, 1)?, 12); + let n = usize::from(r.u16()?).min(r.left()); + let s = name(r.bytes(n)?, &layout::for_version(1100)?, self.warn); + (!s.trim().is_empty()).then_some(s) + } + + /// A curve (R62): field 1 its rendering attributes, field 2 a u16 point count, the points (i32 + /// x and y) and one type byte for each. Points are from the page's center, y up. + fn curve(&mut self, body: &[u8]) -> Option { + let mut r = Rd::new(field(body, 2).unwrap_or_default()); + let Some(count) = r.u16().map(usize::from) else { + // A curve without its points is lost. + push(self.warn, Warning::Damaged); + return None; + }; + // `stored` points are read, so the type bytes are found after all of them, and the first + // `n`, those that have a type byte, are kept. When the field holds every point, a short + // field has lost type bytes; otherwise it holds as many whole points and types as fit. + let left = r.left(); + let (stored, n) = match count.checked_mul(8).filter(|c| *c <= left) { + Some(c) => (count, count.min(left - c)), + None => (count.min(left / 9), count.min(left / 9)), + }; + if n < count { + push(self.warn, Warning::Damaged); + } + if !self.budget.take_coordinates(stored) { + push(self.warn, Warning::TooDeep); + return None; + } + let mut points = Vec::with_capacity(stored); + for _ in 0..stored { + let (x, y) = (f64::from(r.i32()?) * self.unit, f64::from(r.i32()?) * self.unit); + points.push(Pt { x: x - self.center.0, y: y - self.center.1 }); + } + points.truncate(n); + let path = path_of(&points, r.bytes(n)?); + if path.subpaths.is_empty() { + return None; + } + let (fill, outline) = self.attributes(field(body, 1).unwrap_or_default()); + Some(Shape::new(Geometry::Path(path), Matrix::IDENTITY, fill, outline)) + } + + /// Rendering attributes (R63): a mask (1 fill, 2 outline, 4 lens), then a field list for the + /// fill and one for the outline when the mask names them. + fn attributes(&mut self, a: &[u8]) -> (Option, Option) { + let Some(&mask) = a.first() else { return (None, None) }; + let mut pos = 1; + let mut fill = None; + if mask & 1 != 0 { + let end = list_end(a, pos); + let list = a.get(pos..end).unwrap_or_default(); + pos = end; + // Field 1: the fill type (u16), then its own field list; type 1, uniform, names its + // color in field 1. + let v = field(list, 1).unwrap_or_default(); + match Rd::new(v).u16() { + Some(0) | None => {} + Some(1) => { + let index = field(v.get(2..).unwrap_or_default(), 1).and_then(|c| Rd::new(c).u16()); + fill = Some(match index { + Some(i) => self.tables.color(i, self.warn), + None => { + push(self.warn, Warning::Damaged); + Color::Rgb([0.0; 3]) + } + }); + } + Some(_) => push(self.warn, Warning::UnsupportedFills), + } + } + let mut outline = None; + if mask & 2 != 0 { + let list = a.get(pos..list_end(a, pos)).unwrap_or_default(); + match field(list, 1).and_then(|f| Rd::new(f).u16()) { + Some(i) => outline = self.tables.outline(i, self.budget, self.warn), + None => push(self.warn, Warning::Damaged), + } + } + if mask & 4 != 0 { + push(self.warn, Warning::Lenses); + } + (fill, outline) + } +} diff --git a/crates/cdr/src/geometry.rs b/crates/cdr/src/geometry.rs index 59f336d2ee..61b776f23a 100644 --- a/crates/cdr/src/geometry.rs +++ b/crates/cdr/src/geometry.rs @@ -91,7 +91,7 @@ fn points(b: &[u8], mut r: Rd, count: usize, p: &Profile, budget: &mut Budget, w } /// The subpaths that points and their type bytes draw. -fn path_of(points: &[Pt], types: &[u8]) -> Path { +pub(crate) fn path_of(points: &[Pt], types: &[u8]) -> Path { let mut subpaths = Vec::new(); let mut cur: Option = None; // The last two control points: a curve end uses only those. diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs index 6d642cc2b7..64cdae512a 100644 --- a/crates/cdr/src/lib.rs +++ b/crates/cdr/src/lib.rs @@ -1,11 +1,13 @@ //! Reader for `.cdr` drawings of versions 1 to 27 (`.cdr`, and `.cdt` templates): the `WL` files //! of versions 1 and 2, the RIFF chunk tree of versions 3 on with its compressed lists, the ZIP //! packages of versions 14 on with their data streams, then pages, layers, guidelines, groups, -//! curves, rectangles, ellipses, arcs and polygons with uniform fills and outlines. +//! curves, rectangles, ellipses, arcs and polygons with uniform fills and outlines. It also reads +//! `.cmx` exchange files with 32-bit coordinates ([`read_cmx`]): their pages, layers, groups and +//! curves with uniform fills and outlines. //! //! 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` files. +//! panic. Nothing here writes `.cdr` or `.cmx` files. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -13,6 +15,7 @@ use std::fmt; mod build; mod bytes; +mod cmx; mod geometry; mod inline; mod layout; @@ -24,6 +27,8 @@ mod riff; mod styles; #[cfg(any(test, feature = "synth"))] pub mod synth; +#[cfg(any(test, feature = "synth"))] +pub mod synth_cmx; mod wl; mod zip; @@ -36,11 +41,19 @@ pub fn is_cdr(bytes: &[u8]) -> bool { riff::is_cdr_riff(bytes) || package::is_package(bytes) || wl::is_wl(bytes) } +/// Does `bytes` start as a `.cmx` exchange file: a RIFF form (or its big-endian RIFX form) of type +/// `CMX1`? +pub fn is_cmx(bytes: &[u8]) -> bool { + cmx::is_cmx(bytes) +} + /// Why a file can't be read. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Error { /// Not a `.cdr` drawing. NotCdr, + /// Not a `.cmx` file. + NotCmx, /// A drawing of a version this reader doesn't read (hundreds: 2800 is version 28). Version(u16), /// A container structure that doesn't parse. @@ -48,7 +61,7 @@ pub enum Error { /// Past one of the [`Limits`]. Limit(&'static str), /// A file this reader doesn't open: an encrypted, ZIP64 or split package, or a RIFF file that - /// names a version before 3. + /// names a version before 3; a big-endian `.cmx` file or one with 16-bit coordinates. Unsupported(&'static str), } @@ -56,6 +69,7 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::NotCdr => write!(f, "not a CDR drawing"), + Error::NotCmx => write!(f, "not a CMX file"), Error::Version(v) => write!(f, "version {} drawings are not read", v / 100), Error::Damaged(what) => write!(f, "damaged {what}"), Error::Limit(what) => write!(f, "past the {what} limit"), @@ -84,3 +98,13 @@ pub fn read(bytes: &[u8], limits: Limits) -> Result { ix.stream_warnings(&mut drawing.warnings); Ok(drawing) } + +/// Read a `.cmx` exchange file within `limits`. Files in big-endian byte order and files with +/// 16-bit coordinates are refused with [`Error::Unsupported`]. Its [`Drawing::version`] is 0. +pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result { + if bytes.len() > limits.input { + return Err(Error::Limit("input size")); + } + let mut budget = limits::Budget::new(limits); + cmx::drawing(bytes, &mut budget) +} diff --git a/crates/cdr/src/limits.rs b/crates/cdr/src/limits.rs index b5f030b025..684029c014 100644 --- a/crates/cdr/src/limits.rs +++ b/crates/cdr/src/limits.rs @@ -15,7 +15,8 @@ pub struct Limits { pub members: usize, /// Nested lists below the file's own. Deeper content is left out with a warning. pub depth: usize, - /// Chunks in the index, nested ones included, and the entries and styles of the style table. + /// Chunks in the index, nested ones included, and the entries and styles of the style table; + /// in a `.cmx` file, its chunks, table entries and page instructions. pub chunks: usize, /// Objects mapped (shapes, groups and guidelines). pub objects: usize, diff --git a/crates/cdr/src/model.rs b/crates/cdr/src/model.rs index c95a051ee3..e4af34f365 100644 --- a/crates/cdr/src/model.rs +++ b/crates/cdr/src/model.rs @@ -241,7 +241,8 @@ pub enum Warning { #[derive(Clone, Debug, PartialEq)] pub struct Drawing { /// In hundreds, as a RIFF file stores it: 300 to 2799. A file of version 1 or 2 stores no - /// number: it gives 200 when its marker byte is the one of version 2, and 100 otherwise. + /// number: it gives 200 when its marker byte is the one of version 2, and 100 otherwise. A + /// `.cmx` file gives 0. pub version: u16, /// Page size from the document settings, in points. pub page_size: Option<(f64, f64)>, diff --git a/crates/cdr/src/records.rs b/crates/cdr/src/records.rs index 25908d414e..f4f2a3b6ef 100644 --- a/crates/cdr/src/records.rs +++ b/crates/cdr/src/records.rs @@ -212,7 +212,7 @@ fn counted_utf16(r: &mut Rd, warn: &mut Vec) -> Option { /// The color of the property list of a tagged uniform fill (R11) or outline (R12): its color /// record, named by the library name it carries. -fn property_color(b: &[u8], p: &Profile, warn: &mut Vec) -> Option { +pub(crate) fn property_color(b: &[u8], p: &Profile, warn: &mut Vec) -> Option { let mut r = Rd::new(b); let (mut found, mut name) = (None, None); while r.left() >= 5 { diff --git a/crates/cdr/src/synth_cmx.rs b/crates/cdr/src/synth_cmx.rs new file mode 100644 index 0000000000..8cb07aadb6 --- /dev/null +++ b/crates/cdr/src/synth_cmx.rs @@ -0,0 +1,274 @@ +//! Synthetic `.cmx` files for tests and fuzz seeds, built from the layouts in `PROVENANCE.md` (R53 +//! to R63). Not a `.cmx` writer: nothing checks that other programs open these files. + +/// A chunk: its id, a u32 size, the body and a pad byte after an odd body (R53). +pub fn chunk(id: &[u8; 4], body: &[u8]) -> Vec { + let mut out = id.to_vec(); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + if body.len() % 2 == 1 { + out.push(0); + } + out +} + +/// A `LIST` chunk of form `form`. +pub fn list(form: &[u8; 4], children: &[Vec]) -> Vec { + let mut body = form.to_vec(); + body.extend(children.concat()); + chunk(b"LIST", &body) +} + +/// The RIFF form `CMX1` around `children`. +pub fn riff(children: &[Vec]) -> Vec { + let mut body = b"CMX1".to_vec(); + body.extend(children.concat()); + chunk(b"RIFF", &body) +} + +/// The header (R54): `coord` is the coordinate size digit (`b'4'` or `b'2'`) and `meters` the size +/// of a coordinate unit. The header string and the system name, which the reader doesn't read, +/// are left as zeros. +pub fn cont(coord: u8, meters: f64) -> Vec { + let mut c = vec![0u8; 180]; + c[48] = b'2'; + c[52] = coord; + c[54] = b'2'; + c[64..72].copy_from_slice(&meters.to_le_bytes()); + chunk(b"cont", &c) +} + +/// A field: its tag, a u16 length counting the 3 header bytes, then `data` (R55). +pub fn field(tag: u8, data: &[u8]) -> Vec { + let mut f = vec![tag]; + f.extend(((data.len() + 3) as u16).to_le_bytes()); + f.extend(data); + f +} + +/// A field list: the fields, then 0xff (R55). +pub fn fields(fields: &[Vec]) -> Vec { + let mut l = fields.concat(); + l.push(0xff); + l +} + +/// A table chunk: a u16 count, then the entries (field lists) (R55). +pub fn table(id: &[u8; 4], entries: &[Vec]) -> Vec { + let mut d = (entries.len() as u16).to_le_bytes().to_vec(); + d.extend(entries.concat()); + chunk(id, &d) +} + +/// A color entry in the older form: the model and palette bytes in field 1, the values in field 2 +/// (R56). +pub fn color(model: u8, values: &[u8]) -> Vec { + fields(&[field(1, &[model, 5]), field(2, values)]) +} + +/// A color entry with a property list in field 10 whose color record (part 1) holds `model` and +/// the four value bytes `v` (R56). +pub fn color_record(model: u16, v: [u8; 4]) -> Vec { + let mut part = vec![1u8]; + part.extend(12u32.to_le_bytes()); + part.extend(model.to_le_bytes()); + part.extend(5u16.to_le_bytes()); + part.extend([0; 4]); + part.extend(v); + let mut rec = (part.len() as u32).to_le_bytes().to_vec(); + rec.extend(part); + fields(&[field(10, &rec)]) +} + +/// A pen entry (R57): the width in coordinate units, an aspect of 100 and no angle, with the +/// identity matrix. +pub fn pen(width: u32) -> Vec { + let mut d = width.to_le_bytes().to_vec(); + d.extend(100u16.to_le_bytes()); + d.extend(0i32.to_le_bytes()); + d.extend(1u16.to_le_bytes()); + fields(&[field(1, &d)]) +} + +/// A line type entry (R57): its flags and the caps (low 4 bits) and join (high 4 bits). +pub fn line_type(flags: u8, caps_join: u8) -> Vec { + fields(&[field(1, &[flags, caps_join])]) +} + +/// A dash pattern entry (R57): the lengths in outline widths. +pub fn dashes(lengths: &[u16]) -> Vec { + let mut d = (lengths.len() as u16).to_le_bytes().to_vec(); + d.extend(lengths.iter().flat_map(|l| l.to_le_bytes())); + fields(&[field(1, &d)]) +} + +/// An outline entry (R58): 1-based indexes of the line type, screen, color, arrowhead pair, pen and +/// dash pattern. +pub fn outline(parts: [u16; 6]) -> Vec { + fields(&[field(1, &parts.iter().flat_map(|p| p.to_le_bytes()).collect::>())]) +} + +/// The arrowhead pairs chunk (R59): a u16 count, then start and end (u16 each). +pub fn arrowheads(pairs: &[(u16, u16)]) -> Vec { + let mut d = (pairs.len() as u16).to_le_bytes().to_vec(); + for (s, e) in pairs { + d.extend(s.to_le_bytes()); + d.extend(e.to_le_bytes()); + } + chunk(b"rota", &d) +} + +/// An instruction in the short form: a u16 size counting the whole instruction, the code, the +/// body (R60). +pub fn instr(code: i16, body: &[u8]) -> Vec { + let mut i = ((body.len() + 4) as u16).to_le_bytes().to_vec(); + i.extend(code.to_le_bytes()); + i.extend(body); + i +} + +/// An instruction in the long form: 0xFFFF, a u32 size counting the whole instruction, the code, +/// the body (R60). +pub fn long_instr(code: i16, body: &[u8]) -> Vec { + let mut i = 0xFFFFu16.to_le_bytes().to_vec(); + i.extend(((body.len() + 8) as u32).to_le_bytes()); + i.extend(code.to_le_bytes()); + i.extend(body); + i +} + +/// Begin a page (R61), with its width and height in coordinate units in field 4 when given. +pub fn begin_page(size: Option<(u32, u32)>) -> Vec { + let mut f = vec![field(1, &[1, 0, 0, 0, 0, 0])]; + if let Some((w, h)) = size { + let mut d = w.to_le_bytes().to_vec(); + d.extend(h.to_le_bytes()); + f.push(field(4, &d)); + } + instr(9, &fields(&f)) +} + +/// Begin a page (R61) without a size of its own, with the drawing's left, top, right and bottom +/// edges in field 1. +pub fn begin_page_in_bounds(left: i32, top: i32, right: i32, bottom: i32) -> Vec { + let mut d = vec![1, 0, 0, 0, 0, 0]; + for v in [left, top, right, bottom] { + d.extend(v.to_le_bytes()); + } + instr(9, &fields(&[field(1, &d)])) +} + +/// Begin a layer (R62) named in 8-bit characters in field 1 from byte 12, and in UTF-16 in +/// field 4 when `wide` is given. +pub fn begin_layer(name: &str, wide: Option<&str>) -> Vec { + let mut d = vec![1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + d.extend((name.len() as u16).to_le_bytes()); + d.extend(name.bytes()); + let mut f = vec![field(1, &d)]; + if let Some(w) = wide { + let units: Vec = w.encode_utf16().collect(); + let mut d = (units.len() as u32).to_le_bytes().to_vec(); + d.extend(units.iter().flat_map(|u| u.to_le_bytes())); + f.push(field(4, &d)); + } + instr(11, &fields(&f)) +} + +pub fn end_layer() -> Vec { + instr(12, &[]) +} + +pub fn end_page() -> Vec { + instr(10, &[]) +} + +pub fn begin_group() -> Vec { + instr(13, &fields(&[field(1, &[0; 26])])) +} + +pub fn end_group() -> Vec { + instr(14, &[]) +} + +/// Rendering attributes (R63): a uniform fill of color `fill` and the outline `outline` (1-based +/// indexes; `None` leaves the part out of the mask), and `lens` sets the lens bit. +pub fn attrs(fill: Option, outline: Option, lens: bool) -> Vec { + let mask = u8::from(fill.is_some()) | (u8::from(outline.is_some()) << 1) | (u8::from(lens) << 2); + let mut a = vec![mask]; + if let Some(c) = fill { + let mut v = 1u16.to_le_bytes().to_vec(); + let mut uniform = c.to_le_bytes().to_vec(); + uniform.extend(0u16.to_le_bytes()); + v.extend(fields(&[field(1, &uniform)])); + a.extend(fields(&[field(1, &v)])); + } + if let Some(o) = outline { + a.extend(fields(&[field(1, &o.to_le_bytes())])); + } + a +} + +/// Rendering attributes with a fill of type `kind` and no settings of its own. +pub fn attrs_fill_type(kind: u16) -> Vec { + let mut a = vec![1u8]; + a.extend(fields(&[field(1, &kind.to_le_bytes())])); + a +} + +/// A curve (R62): `attrs`, then a u16 count, the points (i32 x, y) and their type bytes. +pub fn curve(attrs: &[u8], points: &[(i32, i32)], types: &[u8]) -> Vec { + let mut g = (points.len() as u16).to_le_bytes().to_vec(); + for (x, y) in points { + g.extend(x.to_le_bytes()); + g.extend(y.to_le_bytes()); + } + g.extend(types); + instr(67, &fields(&[field(1, attrs), field(2, &g), field(3, &[0; 16])])) +} + +/// A closed square of side `side` with its lower left corner at (`x`, `y`). +pub fn square(attrs: &[u8], x: i32, y: i32, side: i32) -> Vec { + curve(attrs, &[(x, y), (x + side, y), (x + side, y + side), (x, y + side), (x, y)], &[0x0c, 0x44, 0x44, 0x44, 0x48]) +} + +/// A `page` chunk of `instructions`. +pub fn page(instructions: &[Vec]) -> Vec { + chunk(b"page", &instructions.concat()) +} + +/// The tables of [`sample`]: colors red (RGB), black (CMYK in percent) and blue (a color record, +/// blue, green, red); pens of 0.5 mm and 1 mm; line types solid with round caps and joins, none, +/// and dashed behind the fill; one dash pattern; three outlines; one empty arrowhead pair. +pub fn tables() -> Vec> { + vec![ + table(b"rclr", &[color(5, &[255, 0, 0]), color(2, &[0, 0, 0, 100]), color_record(5, [255, 0, 0, 0])]), + table(b"rpen", &[pen(5_000), pen(10_000)]), + table(b"rott", &[line_type(2, 0x11), line_type(1, 0), line_type(2 | 4 | 8, 0x02)]), + table(b"rdot", &[dashes(&[3, 1])]), + table(b"rotl", &[outline([1, 1, 2, 1, 1, 1]), outline([2, 1, 2, 1, 1, 1]), outline([3, 1, 3, 1, 2, 1])]), + arrowheads(&[(0, 0)]), + ] +} + +/// One page of 210 x 297 mm with two layers: "Art" holds a red square outlined in black, then a +/// group of a square with no outline and a blue one with the dashed outline; "Top" holds a black +/// square drawn last. Units are 0.1 µm. +pub fn sample() -> Vec { + let p = page(&[ + begin_page(Some((2_100_000, 2_970_000))), + begin_layer("Art", None), + square(&attrs(Some(1), Some(1), false), -500_000, -500_000, 1_000_000), + begin_group(), + square(&attrs(Some(2), Some(2), false), 0, 0, 100_000), + square(&attrs(Some(3), Some(3), false), 200_000, 0, 100_000), + end_group(), + end_layer(), + begin_layer("Top", Some("Top")), + square(&attrs(Some(2), None, false), 0, 0, 10_000), + end_layer(), + end_page(), + ]); + let mut children = vec![cont(b'4', 1e-7), p]; + children.extend(tables()); + riff(&children) +} diff --git a/crates/cdr/tests/it/cmx.rs b/crates/cdr/tests/it/cmx.rs new file mode 100644 index 0000000000..643df2779b --- /dev/null +++ b/crates/cdr/tests/it/cmx.rs @@ -0,0 +1,433 @@ +//! Reading synthetic `.cmx` files built from the layouts in `PROVENANCE.md` (R53 to R63), and +//! hostile ones. + +use proptest::prelude::*; +use vectorcraft_cdr::model::{Cap, Color, Geometry, Join, Object, Shape}; +use vectorcraft_cdr::synth_cmx::*; +use vectorcraft_cdr::{Error, Limits, Warning, is_cdr, is_cmx, read_cmx}; + +fn shape(o: &Object) -> &Shape { + match o { + Object::Shape(s) => s, + other => panic!("not a shape: {other:?}"), + } +} + +/// The (x, y) bounds of a shape's path. +fn bounds(s: &Shape) -> (f64, f64, f64, f64) { + let Geometry::Path(p) = &s.geometry else { panic!("not a path") }; + let mut b = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for sp in &p.subpaths { + for pt in std::iter::once(sp.start).chain(sp.segments.iter().map(|s| match s { + vectorcraft_cdr::model::Segment::Line(p) | vectorcraft_cdr::model::Segment::Cubic(_, _, p) => *p, + })) { + b = (b.0.min(pt.x), b.1.min(pt.y), b.2.max(pt.x), b.3.max(pt.y)); + } + } + b +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +/// The file with `children` after a 32-bit header and the sample tables. +fn file(pages: &[Vec]) -> Vec { + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(pages.iter().cloned()); + children.extend(tables()); + riff(&children) +} + +#[test] +fn a_cmx_file_is_told_from_a_cdr_drawing() { + let f = sample(); + assert!(is_cmx(&f) && !is_cdr(&f)); + let mut rifx = f.clone(); + rifx[..4].copy_from_slice(b"RIFX"); + assert!(is_cmx(&rifx)); + assert!(!is_cmx(b"RIFF\0\0\0\0CDR9")); + assert_eq!(read_cmx(b"RIFF\0\0\0\0CDR9", Limits::default()), Err(Error::NotCmx)); +} + +#[test] +fn pages_layers_groups_and_curves() { + let d = read_cmx(&sample(), Limits::default()).unwrap(); + assert_eq!(d.version, 0); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + let page = &d.pages[0]; + // 2,100,000 units of 0.1 µm are 210 mm. + let (w, h) = page.size.unwrap(); + assert!(near(w, 210.0 / 25.4 * 72.0) && near(h, 297.0 / 25.4 * 72.0), "{w} {h}"); + // The layer drawn last is in front: the model lists layers front to back. + let names: Vec<&str> = page.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Top", "Art"]); + let art = &page.layers[1].objects; + assert_eq!(art.len(), 2); + // The group, drawn after the red square, is in front of it. + let Object::Group { objects: kids, .. } = &art[0] else { panic!("{:?}", art[0]) }; + assert_eq!(kids.len(), 2); + let red = shape(&art[1]); + assert_eq!(red.fill, Some(Color::Rgb([1.0, 0.0, 0.0]))); + // 1,000,000 units are 100 mm; the square's corner is 50 mm left of and below the center. + let mm = 72.0 / 25.4; + let b = bounds(red); + assert!(near(b.0, -50.0 * mm) && near(b.1, -50.0 * mm) && near(b.2, 50.0 * mm) && near(b.3, 50.0 * mm), "{b:?}"); + let Geometry::Path(p) = &red.geometry else { panic!() }; + assert!(p.subpaths.len() == 1 && p.subpaths[0].closed && p.subpaths[0].segments.len() == 4); + let o = red.outline.as_ref().unwrap(); + assert!(near(o.width, 0.5 * mm)); + assert_eq!((o.color.clone(), o.cap, o.join), (Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Cap::Round, Join::Round)); + assert!(o.dashes.is_empty() && !o.behind_fill && !o.scale_with); + // Line type 1 draws no outline. + let blue = shape(&kids[0]); + let black = shape(&kids[1]); + assert!(black.outline.is_none()); + assert_eq!(black.fill, Some(Color::Cmyk([0.0, 0.0, 0.0, 1.0]))); + // The color record's values are blue, green and red. + assert_eq!(blue.fill, Some(Color::Rgb([0.0, 0.0, 1.0]))); + let o = blue.outline.as_ref().unwrap(); + assert!(near(o.width, 1.0 * mm)); + assert_eq!((o.dashes.clone(), o.behind_fill, o.cap, o.join), (vec![3.0, 1.0], true, Cap::Square, Join::Miter)); + assert_eq!(page.layers[0].name, "Top"); +} + +#[test] +fn layer_names_and_layers_without_objects() { + let p = page(&[ + begin_page(None), + begin_layer("Ebene 1", Some("Слой 1")), + square(&attrs(Some(1), None, false), 0, 0, 1000), + end_layer(), + begin_layer("Gitter", None), + end_layer(), + begin_layer("Caf\u{e9}", None), + square(&attrs(Some(1), None, false), 0, 0, 1000), + end_layer(), + end_page(), + ]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let page = &d.pages[0]; + assert_eq!(page.size, None); + // The empty layer is left out, and the UTF-16 name wins over the 8-bit one. + let names: Vec<&str> = page.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Caf\u{c3}\u{a9}", "Слой 1"]); +} + +#[test] +fn objects_before_any_layer_get_one() { + let p = page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert_eq!(d.pages[0].layers.len(), 1); + assert_eq!(d.pages[0].layers[0].name, "Layer 1"); +} + +#[test] +fn a_page_without_a_size_takes_the_drawings_bounds() { + // A square of 100 mm whose bounds lie off the file's origin, above and to the right. + let p = page(&[ + begin_page_in_bounds(1_000_000, 3_000_000, 2_000_000, 2_000_000), + begin_layer("L", None), + square(&attrs(Some(1), None, false), 1_000_000, 2_000_000, 1_000_000), + end_layer(), + end_page(), + ]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let page = &d.pages[0]; + let side = 100.0 / 25.4 * 72.0; + let (w, h) = page.size.unwrap(); + assert!(near(w, side) && near(h, side), "{w} x {h}"); + // The page is centered on the bounds, so the square fills it. + let (x0, y0, x1, y1) = bounds(shape(&page.layers[0].objects[0])); + assert!(near(x0, -side / 2.0) && near(x1, side / 2.0) && near(y0, -side / 2.0) && near(y1, side / 2.0), "{x0} {y0} {x1} {y1}"); +} + +#[test] +fn curves_and_open_groups() { + let c = + curve(&attrs(None, Some(1), false), &[(0, 0), (100, 0), (100, 100), (0, 100), (200, 200), (300, 200)], &[0x00, 0xc0, 0xc0, 0x84, 0x00, 0x44]); + // A group the layer leaves open closes with it. + let p = page(&[begin_page(None), begin_layer("L", None), begin_group(), c, end_layer()]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let objects = &d.pages[0].layers[0].objects; + let Object::Group { objects: kids, .. } = &objects[0] else { panic!("{objects:?}") }; + let s = shape(&kids[0]); + assert!(s.fill.is_none()); + let Geometry::Path(p) = &s.geometry else { panic!() }; + assert_eq!(p.subpaths.len(), 2); + assert!(matches!(p.subpaths[0].segments[..], [vectorcraft_cdr::model::Segment::Cubic(..)])); + assert!(!p.subpaths[1].closed); +} + +#[test] +fn a_curve_without_its_points_is_reported() { + let p = page(&[begin_page(None), begin_layer("L", None), instr(67, &fields(&[field(1, &attrs(Some(1), None, false))])), end_layer()]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); +} + +#[test] +fn a_layer_name_too_short_to_read_in_utf_16_reads_in_8_bit() { + let mut d = vec![1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0]; + d.extend(b"Art"); + let layer = instr(11, &fields(&[field(1, &d), field(4, &[3, 0])])); + let p = page(&[begin_page(None), layer, square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert_eq!(d.pages[0].layers[0].name, "Art"); +} + +#[test] +fn what_is_not_read_is_reported() { + let other = |code: i16| instr(code, &fields(&[field(1, &[0; 8])])); + let p = page(&[ + begin_page(None), + begin_layer("L", None), + other(66), + other(68), + other(20), + other(88), + square(&attrs_fill_type(2), 0, 0, 1000), + square(&attrs(Some(1), None, true), 0, 0, 1000), + end_layer(), + ]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + for w in [Warning::UnsupportedObjects, Warning::UnsupportedFills, Warning::Lenses] { + assert!(d.warnings.contains(&w), "{w:?}: {:?}", d.warnings); + } + // A fill of another type leaves the curve unfilled; the curve is still read. + let objects = &d.pages[0].layers[0].objects; + assert_eq!(objects.len(), 2); + assert!(shape(&objects[1]).fill.is_none()); +} + +#[test] +fn colors_of_other_models_and_missing_entries() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[ + begin_page(None), + begin_layer("L", None), + square(&attrs(Some(1), None, false), 0, 0, 1000), + square(&attrs(Some(9), None, false), 0, 0, 1000), + square(&attrs(Some(2), None, false), 0, 0, 1000), + ])); + children.push(table(b"rclr", &[color(7, &[1, 2, 3, 4]), color(3, &[255, 0, 0, 255])])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::UnknownColors) && d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + let objects = &d.pages[0].layers[0].objects; + assert_eq!(shape(&objects[0]).fill, Some(Color::Cmyk([1.0, 0.0, 0.0, 1.0]))); + assert_eq!(shape(&objects[1]).fill, Some(Color::Rgb([0.0; 3]))); +} + +#[test] +fn outline_arrowheads_are_reported() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)])); + children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rota"))); + children.push(arrowheads(&[(0, 2)])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.warnings, vec![Warning::Arrowheads]); +} + +#[test] +fn a_long_instruction_and_a_jump_over_image_bytes() { + // The jump's target counts from the start of the file: header, `cont`, then the page body. + let before = riff(&[cont(b'4', 1e-7), page(&[])]).len() - 8; + let head = [begin_page(None), begin_layer("L", None)].concat(); + let jump_len = 4 + 1 + 3 + 4; + let image = vec![0xEEu8; 37]; + let target = (before + 8 + head.len() + jump_len + image.len()) as u32; + let jump = instr(111, &fields(&[field(1, &target.to_le_bytes())])); + assert_eq!(jump.len(), jump_len); + let body = [ + head, + jump, + image, + long_instr(67, &curve(&attrs(Some(1), None, false), &[(0, 0), (10, 0), (10, 10)], &[0x0c, 0x44, 0x48])[4..]), + end_layer(), + ] + .concat(); + let mut children = vec![cont(b'4', 1e-7), chunk(b"page", &body)]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + // The images jumped over are not read, and the warning says so. + assert_eq!(d.warnings, [Warning::UnsupportedObjects]); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn bytes_after_a_chunk_that_runs_short_are_passed_over() { + let stray = vec![0x10, 0x00, 0x16, 0x00, 0x01, 0x0b, 0x00, 0x01, 0, 0, 0, 0, 0, 0, 0, 0xff]; + let mut children = vec![cont(b'4', 1e-7), stray, list(b"pgls", &[page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)])])]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn other_byte_orders_and_coordinate_sizes_are_refused() { + let mut f = sample(); + f[..4].copy_from_slice(b"RIFX"); + assert_eq!(read_cmx(&f, Limits::default()), Err(Error::Unsupported("big-endian CMX files"))); + let mut children = vec![cont(b'2', 1e-3)]; + children.extend(tables()); + assert_eq!(read_cmx(&riff(&children), Limits::default()), Err(Error::Unsupported("CMX files with 16-bit coordinates"))); + assert_eq!(read_cmx(&riff(&tables()), Limits::default()), Err(Error::Damaged("CMX header"))); + assert_eq!(read_cmx(&riff(&[cont(b'9', 1e-7)]), Limits::default()), Err(Error::Damaged("CMX header"))); +} + +#[test] +fn a_header_without_a_usable_unit_reads_0_1_micrometers() { + for meters in [0.0, -1.0, f64::NAN, 2.0] { + let mut children = vec![cont(b'4', meters), page(&[begin_page(Some((2_100_000, 2_970_000)))])]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let (w, _) = d.pages[0].size.unwrap(); + assert!(near(w, 210.0 / 25.4 * 72.0), "{meters}: {w}"); + } +} + +#[test] +fn groups_past_the_depth_limit_are_left_out() { + let mut ins = vec![begin_page(None), begin_layer("L", None)]; + for _ in 0..6 { + ins.push(begin_group()); + } + ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000)); + for _ in 0..6 { + ins.push(end_group()); + } + ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000)); + let d = read_cmx(&file(&[page(&ins)]), Limits { depth: 3, ..Limits::default() }).unwrap(); + assert!(d.warnings.contains(&Warning::TooDeep)); + // The square after the groups is still read, beside the three groups kept. + let objects = &d.pages[0].layers[0].objects; + assert_eq!(objects.len(), 2); + let mut depth = 0; + let mut o = &objects[1]; + while let Object::Group { objects: kids, .. } = o { + depth += 1; + match kids.first() { + Some(k) => o = k, + None => break, + } + } + assert_eq!(depth, 3); +} + +#[test] +fn counts_past_the_limits_are_bounded() { + let ins: Vec> = std::iter::once(begin_page(None)).chain((0..50).map(|_| square(&attrs(Some(1), None, false), 0, 0, 1000))).collect(); + let f = file(&[page(&ins)]); + let d = read_cmx(&f, Limits { objects: 10, ..Limits::default() }).unwrap(); + assert_eq!(d.pages[0].layers[0].objects.len(), 10); + assert!(d.warnings.contains(&Warning::TooDeep)); + let d = read_cmx(&f, Limits { coordinates: 12, ..Limits::default() }).unwrap(); + assert_eq!(d.pages[0].layers[0].objects.len(), 2); + assert_eq!(read_cmx(&f, Limits { chunks: 20, ..Limits::default() }), Err(Error::Limit("chunk count"))); + assert_eq!(read_cmx(&f, Limits { input: 10, ..Limits::default() }), Err(Error::Limit("input size"))); + let dashed = |n: u16| { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), square(&attrs(None, Some(3), false), 0, 0, 1000), square(&attrs(None, Some(3), false), 0, 0, 1000)])); + children.extend(tables()); + read_cmx(&riff(&children), Limits { dashes: usize::from(n), ..Limits::default() }).unwrap() + }; + let d = dashed(3); + let o: Vec = d.pages[0].layers[0].objects.iter().map(|o| shape(o).outline.as_ref().unwrap().dashes.len()).collect(); + assert_eq!(o, [0, 2]); + assert!(d.warnings.contains(&Warning::TooDeep)); +} + +#[test] +fn a_curve_cut_short_keeps_the_points_it_holds() { + let mut c = curve(&attrs(Some(1), None, false), &[(0, 0), (10, 0), (10, 10)], &[0x0c, 0x44, 0x48]); + // Claim 9 points where 3 are stored: the field's own length still covers only 3. + let at = c.windows(2).position(|w| w == [3, 0]).unwrap(); + c[at] = 9; + let p = page(&[begin_page(None), c]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged)); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_curve_that_lost_type_bytes_keeps_its_first_points() { + // Three whole points and only two of their type bytes. + let mut g = 3u16.to_le_bytes().to_vec(); + for (x, y) in [(0i32, 0i32), (1_000_000, 0), (1_000_000, 1_000_000)] { + g.extend(x.to_le_bytes()); + g.extend(y.to_le_bytes()); + } + g.extend([0x0c, 0x44]); + let c = instr(67, &fields(&[field(1, &attrs(None, Some(1), false)), field(2, &g)])); + let d = read_cmx(&file(&[page(&[begin_page(None), c])]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + let Geometry::Path(p) = &shape(&d.pages[0].layers[0].objects[0]).geometry else { panic!() }; + let side = 100.0 / 25.4 * 72.0; + assert!(near(p.subpaths[0].start.x, 0.0) && near(p.subpaths[0].start.y, 0.0)); + match p.subpaths[0].segments[..] { + [vectorcraft_cdr::model::Segment::Line(e)] => assert!(near(e.x, side) && near(e.y, 0.0), "{e:?}"), + ref other => panic!("{other:?}"), + } +} + +#[test] +fn a_file_cut_short_of_its_declared_size_is_reported() { + let mut f = file(&[]); + let declared = (f.len() as u32 - 8 + 100).to_le_bytes(); + f[4..8].copy_from_slice(&declared); + let d = read_cmx(&f, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); +} + +#[test] +fn a_page_that_ends_inside_an_instruction_is_reported() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), vec![1, 0]]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_chunk_64_bytes_past_stray_bytes_is_found() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut children = vec![cont(b'4', 1e-7), [vec![1u8; 64], p].concat()]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn stray_letters_with_a_length_past_the_file_are_passed_over() { + let mut stray = b"abcd".to_vec(); + stray.extend(0xFFFF_FF00u32.to_le_bytes()); + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut children = vec![cont(b'4', 1e-7), [stray, p].concat()]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] + + #[test] + fn never_panics_on_garbage(bytes in prop::collection::vec(any::(), 0..2048)) { + let mut b = b"RIFF\0\0\0\0CMX1".to_vec(); + b.extend(bytes); + let _ = read_cmx(&b, Limits::default()); + } + + #[test] + fn never_panics_on_mutated_samples(edits in prop::collection::vec((any::(), any::()), 1..24)) { + let mut b = sample(); + let n = b.len(); + for (at, v) in edits { + b[at % n] = v; + } + let _ = read_cmx(&b, Limits::default()); + } +} diff --git a/crates/cdr/tests/it/main.rs b/crates/cdr/tests/it/main.rs index 0c1aeef38e..4fc7dcbdc9 100644 --- a/crates/cdr/tests/it/main.rs +++ b/crates/cdr/tests/it/main.rs @@ -3,5 +3,6 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod bench; +mod cmx; mod provenance; mod read; diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index fd03ff9749..64da2b736a 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -17,7 +17,8 @@ //! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`. //! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`. //! - `metafile`: EMF and WMF export, open and place; PICT open and place. -//! - `cdr`: `.cdr` drawings of versions 1 to 27 and `.cdt` templates, open and place. +//! - `cdr`: `.cdr` drawings of versions 1 to 27 and `.cdt` templates, and `.cmx` files with +//! 32-bit coordinates, open and place. //! - `hpgl`: HP-GL export options and plots. //! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no //! built-in format reads). @@ -179,6 +180,8 @@ mod tests_artboard_fill; #[cfg(test)] mod tests_cdr; #[cfg(test)] +mod tests_cmx; +#[cfg(test)] mod tests_pdf; #[cfg(test)] mod tests_pdfcolor; diff --git a/crates/engine/src/cmd/fileio/cdr.rs b/crates/engine/src/cmd/fileio/cdr.rs index e8d5321df5..aaa3f46ad0 100644 --- a/crates/engine/src/cmd/fileio/cdr.rs +++ b/crates/engine/src/cmd/fileio/cdr.rs @@ -4,7 +4,8 @@ //! `vectorcraft-cdr` reads, mapped to editable VectorCraft art. Pages become //! artboards side by side; layers of the same name on different pages become one layer where the //! pages stack them in the same order. What the -//! reader leaves out is listed in the warnings, one line for each kind ([`note`]). +//! reader leaves out is listed in the warnings, one line for each kind ([`note`]). `.cmx` exchange +//! files with 32-bit coordinates are mapped the same way, with their own warnings ([`cmx_note`]). use std::collections::HashMap; use std::sync::Arc; @@ -30,6 +31,15 @@ const TOO_DEEP: &str = "parts of the drawing nested too deeply, or past the impo const DAMAGED: &str = "damaged parts of the drawing were left out"; const PAGES_CUT: &str = "CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard"; +const CMX_UNSUPPORTED_OBJECTS: &str = + "CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out"; +const CMX_UNSUPPORTED_FILLS: &str = "CMX fills other than uniform colors were left out"; +const CMX_UNKNOWN_COLORS: &str = "colors in CMX color models VectorCraft doesn't read were opened as black"; +const CMX_SPOT_LOOKS: &str = "CMX library colors that the file stores only by number were opened as black spot colors"; +const CMX_ARROWHEADS: &str = "CMX outline arrowheads were left out"; +const CMX_LENSES: &str = "CMX lenses were not applied"; +const CMX_PAGES_CUT: &str = "CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard"; + /// What reading a drawing left out or changed, for each kind the reader reports. fn note(w: Warning) -> &'static str { match w { @@ -45,6 +55,20 @@ fn note(w: Warning) -> &'static str { } } +/// What reading a `.cmx` file left out or changed. The reader reports no envelopes in one. +fn cmx_note(w: Warning) -> &'static str { + match w { + Warning::UnsupportedObjects | Warning::Envelopes => CMX_UNSUPPORTED_OBJECTS, + Warning::UnsupportedFills => CMX_UNSUPPORTED_FILLS, + Warning::UnknownColors => CMX_UNKNOWN_COLORS, + Warning::SpotLooks => CMX_SPOT_LOOKS, + Warning::Arrowheads => CMX_ARROWHEADS, + Warning::Lenses => CMX_LENSES, + Warning::TooDeep => TOO_DEEP, + Warning::Damaged => DAMAGED, + } +} + /// The page size used when neither the page nor the document settings give one: US Letter, /// VectorCraft's own choice. const FALLBACK_PAGE: (f64, f64) = (612.0, 792.0); @@ -79,8 +103,25 @@ pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec)> { } why => err(format!("this CDR drawing can't be read ({why})")), })?; + Ok(build(&d, note, PAGES_CUT)) +} + +/// Is `bytes` a `.cmx` file, of any byte order or coordinate size? +pub(super) fn is_cmx(bytes: &[u8]) -> bool { + vectorcraft_cdr::is_cmx(bytes) +} + +/// A `.cmx` file with 32-bit coordinates: its pages, layers, groups and curves with uniform fills +/// and outlines, mapped as a `.cdr` drawing's are. +pub(super) fn import_cmx(bytes: &[u8]) -> Result<(Document, Vec)> { + let d = vectorcraft_cdr::read_cmx(bytes, Limits::default()).map_err(|why| err(format!("this CMX file can't be read ({why})")))?; + Ok(build(&d, cmx_note, CMX_PAGES_CUT)) +} + +/// The document of `d`, and one warning for each kind of content left out or changed. +fn build(d: &cd::Drawing, note: fn(Warning) -> &'static str, pages_cut: &str) -> (Document, Vec) { let mut b = shapes::Builder::new(); - let mut doc = b.document(&d); + let mut doc = b.document(d); let mut warnings: Vec = Vec::new(); for w in d.warnings.iter().chain(&b.notes) { if !warnings.iter().any(|x| x == note(*w)) { @@ -88,10 +129,10 @@ pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec)> { } } if b.pages_cut { - warnings.push(PAGES_CUT.to_string()); + warnings.push(pages_cut.to_string()); } doc.limit_depth_noting(&mut warnings); - Ok((doc, warnings)) + (doc, warnings) } /// Where each page lies in the document: its artboard, and the map from its own space (points diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index b53e8df400..3b520d5635 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -537,6 +537,9 @@ pub const FORMATS: &[Format] = &[ // them. reader("cdr", "CDR Drawing", &["cdr"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type reader("cdt", "CDR Template", &["cdt"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type + // `.cmx` exchange files with 32-bit coordinates, read by `vectorcraft-cdr`; exports don't write + // them. + reader("cmx", "CMX", &["cmx"], "image/x-cmx", false), // QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images. reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false), ]; @@ -598,17 +601,18 @@ pub const OPEN_EXTS: &[&str] = &[ "afpub", "cdr", "cdt", + "cmx", ]; /// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to /// raster editors, so Finder and file managers don't offer a vector app for them, and there is no -/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL or `.cdr` type, nor one for the `.pns`, `.dib` and `.rle` names of +/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib` and `.rle` names of /// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS /// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it. /// The packaging declares no type for HP-GL plot files or PICT pictures either. pub const UNASSOCIATED_EXTS: &[&str] = &[ "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc", - "heic", "heif", "jxl", "cdr", "cdt", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", + "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", ]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares @@ -697,6 +701,7 @@ pub const PLACE_EXTS: &[&str] = &[ "afpub", "cdr", "cdt", + "cmx", "txt", "rtf", "docx", diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 6d8683cd11..648a8b9426 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -96,6 +96,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { // A template keeps its meaning from the extension. return by_name.filter(|f| f.id == "cdt").or_else(|| format("cdr")); } + if super::cdr::is_cmx(bytes) { + return format("cmx"); + } if vectorcraft_format::sniff(bytes) { // A template keeps its meaning from the extension, like .ait. return by_name.filter(|f| f.id == "template").or_else(|| format("vectorcraft")); @@ -549,6 +552,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result let (doc, warnings) = super::cdr::import(bytes)?; (doc, warnings, false) } + "cmx" => { + let (doc, warnings) = super::cdr::import_cmx(bytes)?; + (doc, warnings, false) + } // A PSD or PSB file's layers become layers (`layers`, default on); without layers, or with // `layers: false`, its merged image opens. Layers that can't be read leave the merged image. "psd" | "psb" if opts.layers => match super::psdlayers::import_active(bytes, opts.hidden_layers) { @@ -800,12 +807,12 @@ fn open_loaded( loaded.with_grid_prefs(&s.prefs).with_unit_prefs(&s.prefs); // EPS now has an ordinary Save path. Its preview, partial-program and damaged-editing // fallbacks must ask before overwriting the richer source they could not fully read. Every - // warning of a `.cdr` drawing names content the import left out or changed. + // warning of a `.cdr` drawing or a `.cmx` file names content the import left out or changed. let losses: Vec = warnings .iter() .filter(|w| { is_loss(w) - || matches!(format.id, "cdr" | "cdt") + || matches!(format.id, "cdr" | "cdt" | "cmx") || (format.id == "eps" && (matches!(w.as_str(), EDITING_DAMAGED | EDITING_STALE) || w.starts_with("this file's PostScript couldn't be read") diff --git a/crates/engine/src/cmd/fileio/tests_cmx.rs b/crates/engine/src/cmd/fileio/tests_cmx.rs new file mode 100644 index 0000000000..d374737143 --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_cmx.rs @@ -0,0 +1,124 @@ +//! `.cmx` files: Open and Place, by extension and by content, mapped to artboards, layers, groups, +//! paths, solid paint and strokes, with their warnings and refusals. + +use super::*; +use serde_json::json; +use vectorcraft_cdr::synth_cmx::*; +use vectorcraft_doc::{Node, NodeKind}; + +fn paths(nodes: &[std::sync::Arc], out: &mut Vec) { + for n in nodes { + match &n.kind { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => paths(children, out), + _ => out.push((**n).clone()), + } + } +} + +fn warnings(r: &serde_json::Value) -> Vec { + r["warnings"].as_array().map(|w| w.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default() +} + +#[test] +fn a_cmx_file_opens_as_editable_art() { + let mut s = Session::new(); + let r = open_bytes(&mut s, "drawing.cmx", &sample(), None).unwrap(); + assert_eq!(r["format"], "cmx"); + assert!(warnings(&r).is_empty(), "{r}"); + let doc = &s.doc().unwrap().doc; + // One 210 x 297 mm page. + assert_eq!(doc.artboards.len(), 1); + let ab = doc.artboards[0].rect; + assert_eq!((ab.width().round(), ab.height().round()), (595.0, 842.0)); + // Bottom to top: the layer drawn first is at the bottom. + let names: Vec = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, ["Art", "Top"]); + let art = doc.layers[0].children().unwrap(); + assert_eq!(art.len(), 2); + assert!(matches!(art[1].kind, NodeKind::Group { .. }), "the group drawn after the red square is above it"); + let mut all = Vec::new(); + paths(&doc.layers, &mut all); + assert_eq!(all.len(), 4); + // The red square: 100 mm on a side, centered on the page, with a fill and a stroke. + let red = &all[0]; + let b = doc.bounds_of(&[red.id], false).unwrap(); + let mm = 72.0 / 25.4; + assert!((b.width() - 100.0 * mm).abs() < 0.01 && (b.center().x - ab.center().x).abs() < 0.01, "{b:?}"); + assert_eq!(red.appearance.items.len(), 2); + // The square whose line type draws no outline has a fill only. + assert_eq!(all[1].appearance.items.len(), 1); +} + +#[test] +fn detection_by_content_and_place() { + let bytes = sample(); + let mut s = Session::new(); + // A renamed file is found by its content, and a .cmx extension alone reads it as one. + assert_eq!(open_bytes(&mut s, "renamed.bin", &bytes, None).unwrap()["format"], "cmx"); + assert_eq!(detect("drawing.png", &bytes).map(|f| f.id), Some("cmx")); + assert_eq!(detect("drawing.cmx", b"").map(|f| f.id), Some("cmx")); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + s.execute("file.place", &json!({"name":"art.cmx", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap(); + assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty())); + let f = format("cmx").unwrap(); + assert!(f.read && !f.write); + assert!(OPEN_EXTS.contains(&"cmx") && PLACE_EXTS.contains(&"cmx") && UNASSOCIATED_EXTS.contains(&"cmx")); + assert!(!SAVE_FORMATS.contains(&"cmx")); +} + +#[test] +fn what_is_left_out_is_named_in_the_warnings() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[ + begin_page(None), + begin_layer("L", None), + instr(66, &fields(&[field(1, &[0; 8])])), + square(&attrs_fill_type(2), 0, 0, 1000), + square(&attrs(Some(1), Some(1), true), 0, 0, 1000), + ])); + children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rota"))); + children.push(arrowheads(&[(1, 0)])); + let mut s = Session::new(); + let w = warnings(&open_bytes(&mut s, "drawing.cmx", &riff(&children), None).unwrap()); + assert_eq!( + w, + [ + "CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out", + "CMX fills other than uniform colors were left out", + "CMX outline arrowheads were left out", + "CMX lenses were not applied", + ] + ); +} + +#[test] +fn a_file_the_open_left_things_out_of_is_not_written_over_unasked() { + let d = std::env::temp_dir().join(format!("vc-cmx-loss-{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + let src = d.join("drawing.cmx"); + let mut children = vec![cont(b'4', 1e-7), page(&[begin_page(None), square(&attrs_fill_type(2), 0, 0, 1000)])]; + children.extend(tables()); + let original = riff(&children); + std::fs::write(&src, &original).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({ "path": src.to_string_lossy() })).unwrap(); + let e = s.execute("document.export", &json!({ "path": src.to_string_lossy(), "format": "svg" })).unwrap_err().to_string(); + assert!(e.contains("acknowledgeLoss"), "{e}"); + assert_eq!(std::fs::read(&src).unwrap(), original); + std::fs::remove_dir_all(d).ok(); +} + +#[test] +fn files_that_are_not_read_say_why() { + let mut s = Session::new(); + let mut rifx = sample(); + rifx[..4].copy_from_slice(b"RIFX"); + let e = open_bytes(&mut s, "a.cmx", &rifx, None).unwrap_err().to_string(); + assert!(e.contains("this CMX file can't be read (big-endian CMX files are not read)"), "{e}"); + let e = open_bytes(&mut s, "b.cmx", &riff(&[cont(b'2', 1e-3)]), None).unwrap_err().to_string(); + assert!(e.contains("this CMX file can't be read (CMX files with 16-bit coordinates are not read)"), "{e}"); + let e = open_bytes(&mut s, "c.cmx", &riff(&[]), None).unwrap_err().to_string(); + assert!(e.contains("this CMX file can't be read (damaged CMX header)"), "{e}"); + let e = open_bytes(&mut s, "d.cmx", b"not a cmx file", None).unwrap_err().to_string(); + assert!(e.contains("this CMX file can't be read (not a CMX file)"), "{e}"); +} diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 4d09b57f55..27ce315d92 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -9,6 +9,7 @@ //! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor Affinity documents //! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor //! `.cdr` drawings (mutated and cut short, plain, compressed and packaged, opened and placed), +//! nor `.cmx` files (mutated, cut short and garbage after the header, opened and placed), //! nor the font files a folder search reads (damaged fonts, collections whose headers give any count of //! faces), nor scripts written for the reference app checked without running them (garbage, //! generated script text and mutated scripts). @@ -433,6 +434,52 @@ proptest! { } } +// ---------- .cmx files ---------- + +proptest! { + #![proptest_config(config())] + + #[test] + fn cmx_mutated_files_render_and_export( + cut in prop::option::of(12usize..4096), + edits in prop::collection::vec((0usize..8192, any::()), 0..24), + ) { + let mut bytes = vectorcraft_cdr::synth_cmx::sample(); + let n = bytes.len(); + for (at, b) in edits { bytes[at % n] = b; } + if let Some(cut) = cut { + bytes.truncate(cut); + } + survive("CMX file", || vectorcraft_engine::cmd::fileio::load("x.cmx", &bytes).ok().map(|l| l.doc))?; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let p = json!({"name":"x.cmx", "dataBase64":vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "CMX placement panicked: {:?}", r.err()); + } + + #[test] + fn cmx_garbage_opens_and_places_without_panicking(tail in prop::collection::vec(any::(), 0..2048)) { + // A 32-bit header, so the garbage is walked as chunks, tables and instructions. + let mut bytes = b"RIFF".to_vec(); + let cont = vectorcraft_cdr::synth_cmx::cont(b'4', 1e-7); + bytes.extend(((4 + cont.len() + tail.len()) as u32).to_le_bytes()); + bytes.extend(b"CMX1"); + bytes.extend(cont); + bytes.extend(tail); + survive("CMX garbage", || vectorcraft_engine::cmd::fileio::load("x.cmx", &bytes).ok().map(|l| l.doc))?; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let p = json!({"name":"x.cmx", "dataBase64":vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "CMX placement panicked: {:?}", r.err()); + } +} + // ---------- Affinity documents with every feature the reader maps ---------- #[path = "support/affinity_docs.rs"] diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 2760a6bfaa..8e3977d1d3 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8078,6 +8078,14 @@ breakText Glyphs Glifs @msg parts of the drawing nested too deeply, or past the import limits, were left out s’han omès les parts del dibuix imbricades massa a fons o fora dels límits d’importació @msg damaged parts of the drawing were left out s’han omès les parts danyades del dibuix @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard les pàgines del CDR de més de 163.830 pt s’han obert amb aquesta longitud, i el dibuix a prop de les vores queda fora del tauler +@msg this CMX file can't be read ({why}) no es pot llegir aquest fitxer CMX ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out s’han omès els textos, les imatges, els rectangles, les el·lipses, els camins de retall i altres objectes del CMX que el VectorCraft encara no llegeix +@msg CMX fills other than uniform colors were left out s’han omès els emplenaments del CMX que no són colors uniformes +@msg colors in CMX color models VectorCraft doesn't read were opened as black els colors en models de color del CMX que el VectorCraft no llegeix s’han obert en negre +@msg CMX library colors that the file stores only by number were opened as black spot colors els colors de biblioteca del CMX que el fitxer desa només pel número s’han obert com a colors directes negres +@msg CMX outline arrowheads were left out s’han omès les puntes de fletxa dels contorns del CMX +@msg CMX lenses were not applied no s’han aplicat les lents del CMX +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard les pàgines del CMX de més de 163.830 pt s’han obert amb aquesta longitud, i el dibuix a prop de les vores queda fora del tauler @msg You must choose a side pattern. Heu de triar un patró lateral. @msg invalid pattern tile choice opció de mosaic de patró no vàlida @msg no pattern named `{choice}` no hi ha cap patró anomenat `{choice}` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 0be0ce098a..98ab4cd101 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6108,6 +6108,14 @@ variable-list-end {0}, {1} {0} a {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out části výkresu vnořené příliš hluboko nebo za hranicemi importu byly vynechány @msg damaged parts of the drawing were left out poškozené části výkresu byly vynechány @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard stránky CDR delší než 163 830 pt byly otevřeny v této délce a kresba u jejich okrajů leží mimo pracovní plochu +@msg this CMX file can't be read ({why}) tento soubor CMX nelze přečíst ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out texty, obrázky, obdélníky, elipsy, ořezové cesty a další objekty CMX, které VectorCraft zatím nečte, byly vynechány +@msg CMX fills other than uniform colors were left out výplně CMX jiné než jednolité barvy byly vynechány +@msg colors in CMX color models VectorCraft doesn't read were opened as black barvy v barevných modelech CMX, které VectorCraft nečte, byly otevřeny jako černé +@msg CMX library colors that the file stores only by number were opened as black spot colors knihovní barvy CMX, které soubor ukládá jen číslem, byly otevřeny jako černé přímé barvy +@msg CMX outline arrowheads were left out šipky na obrysových čarách CMX byly vynechány +@msg CMX lenses were not applied čočky CMX nebyly použity +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard stránky CMX delší než 163 830 pt byly otevřeny v této délce a kresba u jejich okrajů leží mimo pracovní plochu @msg the PSD image is too large to read ({_1} × {_2} pixels) obraz PSD je příliš velký na přečtení ({_1} × {_2} obrazových bodů) @msg zipped 1-bit PSD image data with prediction can't be read zazipovaná 1bitová obrazová data PSD s predikcí nelze přečíst @msg the PSD file's layer data uses an unknown compression ({m}) data vrstev souboru PSD používají neznámou kompresi ({m}) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 06eee77db0..47de0a9978 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -379,6 +379,14 @@ liquify-list-end {0}, {1} {0} og {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out dele af tegningen, der er indlejret for dybt eller ligger ud over importgrænserne, blev udeladt @msg damaged parts of the drawing were left out beskadigede dele af tegningen blev udeladt @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard CDR-sider, der er længere end 163.830 pt, blev åbnet i den længde, og grafik nær deres kanter ligger uden for tegnefladen +@msg this CMX file can't be read ({why}) denne CMX-fil kan ikke læses ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out tekst, billeder, rektangler, ellipser, beskæringsstier og andre CMX-objekter, som VectorCraft endnu ikke læser, blev udeladt +@msg CMX fills other than uniform colors were left out CMX-udfyldninger, der ikke er ensfarvede, blev udeladt +@msg colors in CMX color models VectorCraft doesn't read were opened as black farver i CMX-farvemodeller, som VectorCraft ikke læser, blev åbnet som sorte +@msg CMX library colors that the file stores only by number were opened as black spot colors CMX-biblioteksfarver, som filen kun gemmer som et nummer, blev åbnet som sorte spotfarver +@msg CMX outline arrowheads were left out pilespidser på CMX-konturer blev udeladt +@msg CMX lenses were not applied CMX-linser blev ikke anvendt +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard CMX-sider, der er længere end 163.830 pt, blev åbnet i den længde, og grafik nær deres kanter ligger uden for tegnefladen @msg the JPEG XL file is cut short JPEG XL-filen er afkortet @msg the JPEG XL container is too large to read JPEG XL-containeren er for stor til at blive læst @msg CMYK JPEG XL images can't be read CMYK-billeder i JPEG XL kan ikke læses diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 47e86a9200..83e530e0c5 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5850,6 +5850,14 @@ variable-list-end {0}, {1} {0} und {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out Teile der Zeichnung, die zu tief verschachtelt sind oder die Importgrenzen überschreiten, wurden ausgelassen @msg damaged parts of the drawing were left out beschädigte Teile der Zeichnung wurden ausgelassen @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard CDR-Seiten, die länger als 163.830 pt sind, wurden in dieser Länge geöffnet, und Grafik nahe ihren Rändern liegt außerhalb der Zeichenfläche +@msg this CMX file can't be read ({why}) diese CMX-Datei kann nicht gelesen werden ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out Texte, Bilder, Rechtecke, Ellipsen, Beschneidungspfade und andere CMX-Objekte, die VectorCraft noch nicht liest, wurden ausgelassen +@msg CMX fills other than uniform colors were left out CMX-Füllungen außer einheitlichen Farben wurden ausgelassen +@msg colors in CMX color models VectorCraft doesn't read were opened as black Farben in CMX-Farbmodellen, die VectorCraft nicht liest, wurden als Schwarz geöffnet +@msg CMX library colors that the file stores only by number were opened as black spot colors CMX-Bibliotheksfarben, die die Datei nur als Nummer speichert, wurden als schwarze Volltonfarben geöffnet +@msg CMX outline arrowheads were left out Pfeilspitzen an CMX-Umrisslinien wurden ausgelassen +@msg CMX lenses were not applied CMX-Linsen wurden nicht angewendet +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard CMX-Seiten, die länger als 163.830 pt sind, wurden in dieser Länge geöffnet, und Grafik nahe ihren Rändern liegt außerhalb der Zeichenfläche @msg the PSD image is too large to read ({_1} × {_2} pixels) das PSD-Bild ist zu groß zum Lesen ({_1} × {_2} Pixel) @msg zipped 1-bit PSD image data with prediction can't be read ZIP-komprimierte 1-Bit-PSD-Bilddaten mit Vorhersage können nicht gelesen werden @msg the PSD file's layer data uses an unknown compression ({m}) die Ebenendaten der PSD-Datei verwenden eine unbekannte Komprimierung ({m}) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 91f66dbe77..a18e76b6ab 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5802,6 +5802,14 @@ variable-list-end {0}, {1} {0} και {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out παραλείφθηκαν τμήματα του σχεδίου με υπερβολικά βαθιά ένθεση ή πέρα από τα όρια εισαγωγής @msg damaged parts of the drawing were left out παραλείφθηκαν κατεστραμμένα τμήματα του σχεδίου @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard οι σελίδες του CDR με μήκος πάνω από 163.830 pt ανοίχτηκαν σε αυτό το μήκος και το γραφικό κοντά στα άκρα τους βρίσκεται έξω από τον πίνακα σχεδίασης +@msg this CMX file can't be read ({why}) δεν είναι δυνατή η ανάγνωση αυτού του αρχείου CMX ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out παραλείφθηκαν κείμενα, εικόνες, ορθογώνια, ελλείψεις, διαδρομές αποκοπής και άλλα αντικείμενα του CMX που το VectorCraft δεν διαβάζει ακόμη +@msg CMX fills other than uniform colors were left out παραλείφθηκαν τα γεμίσματα του CMX εκτός από τα ενιαία χρώματα +@msg colors in CMX color models VectorCraft doesn't read were opened as black τα χρώματα σε χρωματικά μοντέλα του CMX που δεν διαβάζει το VectorCraft ανοίχτηκαν ως μαύρα +@msg CMX library colors that the file stores only by number were opened as black spot colors τα χρώματα βιβλιοθήκης του CMX που το αρχείο αποθηκεύει μόνο με αριθμό ανοίχτηκαν ως μαύρα πλακάτα χρώματα +@msg CMX outline arrowheads were left out παραλείφθηκαν οι αιχμές βελών των γραμμών περιγράμματος του CMX +@msg CMX lenses were not applied δεν εφαρμόστηκαν οι φακοί του CMX +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard οι σελίδες του CMX με μήκος πάνω από 163.830 pt ανοίχτηκαν σε αυτό το μήκος και το γραφικό κοντά στα άκρα τους βρίσκεται έξω από τον πίνακα σχεδίασης @msg the PSD image is too large to read ({_1} × {_2} pixels) η εικόνα PSD είναι πολύ μεγάλη για ανάγνωση ({_1} × {_2} εικονοστοιχεία) @msg zipped 1-bit PSD image data with prediction can't be read τα συμπιεσμένα δεδομένα εικόνας PSD 1 bit με πρόβλεψη δεν διαβάζονται @msg the PSD file's layer data uses an unknown compression ({m}) τα δεδομένα επιπέδων του αρχείου PSD χρησιμοποιούν άγνωστη συμπίεση ({m}) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 6b673163e7..85ed49785d 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5846,6 +5846,14 @@ variable-list-end {0}, {1} {0} y {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out se omitieron partes del dibujo anidadas a demasiada profundidad o fuera de los límites de importación @msg damaged parts of the drawing were left out se omitieron partes dañadas del dibujo @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard las páginas de CDR de más de 163.830 pt se abrieron con esa longitud, y el arte cerca de sus bordes queda fuera de la mesa de trabajo +@msg this CMX file can't be read ({why}) no se puede leer este archivo CMX ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out se omitieron textos, imágenes, rectángulos, elipses, trazados de recorte y otros objetos de CMX que VectorCraft aún no lee +@msg CMX fills other than uniform colors were left out se omitieron los rellenos de CMX que no son colores uniformes +@msg colors in CMX color models VectorCraft doesn't read were opened as black los colores en modelos de color de CMX que VectorCraft no lee se abrieron en negro +@msg CMX library colors that the file stores only by number were opened as black spot colors los colores de biblioteca de CMX que el archivo guarda solo por número se abrieron como tintas planas negras +@msg CMX outline arrowheads were left out se omitieron las puntas de flecha de los contornos de CMX +@msg CMX lenses were not applied no se aplicaron las lentes de CMX +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard las páginas de CMX de más de 163.830 pt se abrieron con esa longitud, y el arte cerca de sus bordes queda fuera de la mesa de trabajo @msg the PSD image is too large to read ({_1} × {_2} pixels) la imagen PSD es demasiado grande para leerla ({_1} × {_2} píxeles) @msg zipped 1-bit PSD image data with prediction can't be read no se pueden leer datos de imagen PSD de 1 bit comprimidos en ZIP con predicción @msg the PSD file's layer data uses an unknown compression ({m}) los datos de capa del archivo PSD usan una compresión desconocida ({m}) diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index f76ca964a3..d65c914d87 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6025,6 +6025,14 @@ variable-list-end {0}, {1} {0} ja {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out liian syvälle sisäkkäiset tai tuontirajojen ylittävät piirroksen osat jätettiin pois @msg damaged parts of the drawing were left out piirroksen vahingoittuneet osat jätettiin pois @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard yli 163 830 pt pitkät CDR-sivut avattiin tämän pituisina, ja niiden reunojen lähellä oleva grafiikka on piirtoalustan ulkopuolella +@msg this CMX file can't be read ({why}) tätä CMX-tiedostoa ei voi lukea ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out CMX-tekstit, kuvat, suorakulmiot, ellipsit, rajauspolut ja muut objektit, joita VectorCraft ei vielä lue, jätettiin pois +@msg CMX fills other than uniform colors were left out CMX-täytöt, jotka eivät ole tasaisia värejä, jätettiin pois +@msg colors in CMX color models VectorCraft doesn't read were opened as black värit CMX-värimalleissa, joita VectorCraft ei lue, avattiin mustina +@msg CMX library colors that the file stores only by number were opened as black spot colors CMX-kirjastovärit, jotka tiedosto tallentaa vain numerona, avattiin mustina spottiväreinä +@msg CMX outline arrowheads were left out CMX-ääriviivojen nuolenkärjet jätettiin pois +@msg CMX lenses were not applied CMX-linssejä ei käytetty +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard yli 163 830 pt pitkät CMX-sivut avattiin tämän pituisina, ja niiden reunojen lähellä oleva grafiikka on piirtoalustan ulkopuolella @msg the PSD image is too large to read ({_1} × {_2} pixels) tämä PSD-kuva on liian suuri luettavaksi ({_1} × {_2} pikseliä) @msg zipped 1-bit PSD image data with prediction can't be read ennustusta käyttävää zip-pakattua 1-bittistä PSD-kuvadataa ei voi lukea @msg the PSD file's layer data uses an unknown compression ({m}) tämän PSD-tiedoston tasodata käyttää tuntematonta pakkausta ({m}) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 0079b8ddd5..7e1b89dae7 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5823,6 +5823,14 @@ variable-list-end {0}, {1} {0} et {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out les parties du dessin trop profondément imbriquées ou au-delà des limites d’importation ont été ignorées @msg damaged parts of the drawing were left out les parties endommagées du dessin ont été ignorées @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard les pages CDR de plus de 163 830 pt ont été ouvertes à cette longueur, et l’illustration proche de leurs bords se trouve hors du plan de travail +@msg this CMX file can't be read ({why}) impossible de lire ce fichier CMX ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out les textes, images, rectangles, ellipses, tracés de détourage et autres objets CMX que VectorCraft ne lit pas encore ont été ignorés +@msg CMX fills other than uniform colors were left out les remplissages CMX autres que les couleurs unies ont été ignorés +@msg colors in CMX color models VectorCraft doesn't read were opened as black les couleurs des modèles colorimétriques CMX que VectorCraft ne lit pas ont été ouvertes en noir +@msg CMX library colors that the file stores only by number were opened as black spot colors les couleurs de bibliothèque CMX que le fichier enregistre uniquement par numéro ont été ouvertes comme tons directs noirs +@msg CMX outline arrowheads were left out les pointes de flèche des contours CMX ont été ignorées +@msg CMX lenses were not applied les lentilles CMX n’ont pas été appliquées +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard les pages CMX de plus de 163 830 pt ont été ouvertes à cette longueur, et l’illustration proche de leurs bords se trouve hors du plan de travail @msg the PSD image is too large to read ({_1} × {_2} pixels) l’image PSD est trop grande pour être lue ({_1} × {_2} pixels) @msg zipped 1-bit PSD image data with prediction can't be read les données d’image PSD 1 bit compressées en ZIP avec prédiction ne peuvent pas être lues @msg the PSD file's layer data uses an unknown compression ({m}) les données de calque du fichier PSD utilisent une compression inconnue ({m}) diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 25104aa9ac..33944a6970 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -9103,6 +9103,14 @@ liquify-list-end {0}, {1} {0} और {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out ड्रॉइंग के बहुत गहराई तक नेस्ट किए गए या आयात सीमाओं से परे के हिस्से छोड़ दिए गए @msg damaged parts of the drawing were left out ड्रॉइंग के क्षतिग्रस्त हिस्से छोड़ दिए गए @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163,830 pt से लंबे CDR पेज उसी लंबाई पर खोले गए, और उनके किनारों के पास का आर्ट आर्टबोर्ड के बाहर है +@msg this CMX file can't be read ({why}) इस CMX फ़ाइल को पढ़ा नहीं जा सकता ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out CMX के टेक्स्ट, इमेज, आयत, दीर्घवृत्त, क्लिपिंग पाथ और अन्य ऑब्जेक्ट, जिन्हें VectorCraft अभी नहीं पढ़ता, छोड़ दिए गए +@msg CMX fills other than uniform colors were left out एकसमान रंगों के अलावा CMX के फ़िल छोड़ दिए गए +@msg colors in CMX color models VectorCraft doesn't read were opened as black जिन CMX रंग मॉडलों को VectorCraft नहीं पढ़ता, उनके रंग काले के रूप में खोले गए +@msg CMX library colors that the file stores only by number were opened as black spot colors CMX लाइब्रेरी के जिन रंगों को फ़ाइल केवल संख्या से सहेजती है, वे काले स्पॉट रंगों के रूप में खोले गए +@msg CMX outline arrowheads were left out CMX आउटलाइन के तीर-शीर्ष छोड़ दिए गए +@msg CMX lenses were not applied CMX लेंस लागू नहीं किए गए +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163,830 pt से लंबे CMX पेज उसी लंबाई पर खोले गए, और उनके किनारों के पास का आर्ट आर्टबोर्ड के बाहर है @msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000 फ़ाइल में असमर्थित कलर स्पेस या JPX सामग्री है @msg The last start of VectorCraft ended on {name} before its window appeared, so it started on {summary}. To try that graphics processor again, change Preferences › Performance › Graphics Processor or start with WGPU_BACKEND set वेक्टर क्रेफ्ट की अंतिम शुरुआत अपनी विंडो दिखाई देने से पहले {name} पर समाप्त हुई, इसलिए यह {summary} पर शुरू हुआ। उस ग्राफिक्स प्रोसेसर को फिर से आज़माने के लिए, वरीयताओं को बदलें › प्रदर्शन › ग्राफिक्स प्रोसेसर या WGPU_BACKEND सेट के साथ शुरू होता है। @msg The last start of VectorCraft ended while it listed the graphics processors, so it started on {summary} with OpenGL alone. To try the other graphics backends again, change Preferences › Performance › Graphics Processor or start with WGPU_BACKEND set जब यह ग्राफिक्स प्रोसेसर को सूचीबद्ध करता है, तो यह केवल ओपनजीएल के साथ {summary} पर शुरू हुआ। फिर से अन्य ग्राफिक्स बैकेंड की कोशिश करने के लिए, वरीयताओं को बदलें › प्रदर्शन › ग्राफिक्स प्रोसेसर या WGPU_BACKEND सेट के साथ शुरू होता है। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e30b56ef4e..5fe79f9ca1 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6330,6 +6330,14 @@ liquify-list-end {0}, {1} {0} és {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out kimaradtak a rajz túl mélyen egymásba ágyazott vagy az importálási korlátokon túli részei @msg damaged parts of the drawing were left out kimaradtak a rajz sérült részei @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard a 163 830 pt-nál hosszabb CDR-oldalak ekkora hosszal nyíltak meg, és a szélük közelében lévő grafika a rajztáblán kívül esik +@msg this CMX file can't be read ({why}) ez a CMX-fájl nem olvasható ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out kimaradtak a CMX szövegei, képei, téglalapjai, ellipszisei, vágógörbéi és egyéb objektumai, amelyeket a VectorCraft még nem olvas +@msg CMX fills other than uniform colors were left out kimaradtak a CMX kitöltései, amelyek nem egyszínűek +@msg colors in CMX color models VectorCraft doesn't read were opened as black a CMX olyan színmodelljeiben megadott színek, amelyeket a VectorCraft nem olvas, feketeként nyíltak meg +@msg CMX library colors that the file stores only by number were opened as black spot colors a CMX könyvtári színei, amelyeket a fájl csak számként tárol, fekete direktszínként nyíltak meg +@msg CMX outline arrowheads were left out kimaradtak a CMX körvonalainak nyílhegyei +@msg CMX lenses were not applied a CMX lencsék nem lettek alkalmazva +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard a 163 830 pt-nál hosszabb CMX-oldalak ekkora hosszal nyíltak meg, és a szélük közelében lévő grafika a rajztáblán kívül esik @msg the PSD image is too large to read ({_1} × {_2} pixels) a PSD-kép túl nagy a beolvasáshoz ({_1} × {_2} pixel) @msg the Save PDF dialog didn't open a PDF mentése párbeszédablak nem nyílt meg @msg the scale is not a usable number a méretarány nem használható szám diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index eb33dd2775..cd1bc2b8cc 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5868,6 +5868,14 @@ variable-list-end {0}, {1} {0} e {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out le parti del disegno annidate troppo in profondità o oltre i limiti di importazione sono state omesse @msg damaged parts of the drawing were left out le parti danneggiate del disegno sono state omesse @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard le pagine di CDR più lunghe di 163.830 pt sono state aperte con quella lunghezza, e la grafica vicina ai loro bordi si trova fuori dalla tavola da disegno +@msg this CMX file can't be read ({why}) impossibile leggere questo file CMX ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out testi, immagini, rettangoli, ellissi, tracciati di ritaglio e altri oggetti di CMX che VectorCraft non legge ancora sono stati omessi +@msg CMX fills other than uniform colors were left out i riempimenti di CMX diversi dai colori uniformi sono stati omessi +@msg colors in CMX color models VectorCraft doesn't read were opened as black i colori in modelli di colore di CMX che VectorCraft non legge sono stati aperti in nero +@msg CMX library colors that the file stores only by number were opened as black spot colors i colori di libreria di CMX che il file salva solo per numero sono stati aperti come colori spot neri +@msg CMX outline arrowheads were left out le punte di freccia dei contorni di CMX sono state omesse +@msg CMX lenses were not applied le lenti di CMX non sono state applicate +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard le pagine di CMX più lunghe di 163.830 pt sono state aperte con quella lunghezza, e la grafica vicina ai loro bordi si trova fuori dalla tavola da disegno @msg the PSD image is too large to read ({_1} × {_2} pixels) l'immagine PSD è troppo grande per essere letta ({_1} × {_2} pixel) @msg zipped 1-bit PSD image data with prediction can't be read i dati immagine PSD a 1 bit compressi ZIP con previsione non possono essere letti @msg the PSD file's layer data uses an unknown compression ({m}) i dati dei livelli del file PSD usano una compressione sconosciuta ({m}) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index a59abcd052..8d8228bc33 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5916,6 +5916,14 @@ liquify-list-end {0}, {1} {0}、{1} @msg parts of the drawing nested too deeply, or past the import limits, were left out 入れ子が深すぎる図面の部分や読み込みの上限を超えた部分は除外されました @msg damaged parts of the drawing were left out 図面の破損した部分は除外されました @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163,830 pt より長い CDR のページはその長さで開いたため、端の近くのアートはアートボードの外にあります +@msg this CMX file can't be read ({why}) この CMX ファイルは読み込めません ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out VectorCraft でまだ読み込めない CMX のテキスト、画像、長方形、楕円、クリッピングパス、その他のオブジェクトは除外されました +@msg CMX fills other than uniform colors were left out 均一な色以外の CMX の塗りは除外されました +@msg colors in CMX color models VectorCraft doesn't read were opened as black VectorCraft で読み込めない CMX のカラーモデルの色は黒として開きました +@msg CMX library colors that the file stores only by number were opened as black spot colors ファイルが番号だけで保存している CMX のライブラリカラーは黒の特色として開きました +@msg CMX outline arrowheads were left out CMX のアウトラインの矢印は除外されました +@msg CMX lenses were not applied CMX のレンズは適用されませんでした +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163,830 pt より長い CMX のページはその長さで開いたため、端の近くのアートはアートボードの外にあります @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 画像が大きすぎて読み込めません({_1} × {_2} ピクセル) @msg zipped 1-bit PSD image data with prediction can't be read 予測付き ZIP 圧縮の 1 bit PSD 画像データは読み込めません @msg the PSD file's layer data uses an unknown compression ({m}) PSD ファイルのレイヤーデータの圧縮方式が不明です({m}) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index f4284b0857..df1fe0a68b 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7512,6 +7512,14 @@ font-technology Variable ცვლადი @msg parts of the drawing nested too deeply, or past the import limits, were left out ნახაზის ზედმეტად ღრმად ჩადგმული ან იმპორტის ლიმიტებს მიღმა არსებული ნაწილები გამოტოვებულია @msg damaged parts of the drawing were left out ნახაზის დაზიანებული ნაწილები გამოტოვებულია @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163 830 pt-ზე გრძელი CDR-ის გვერდები ამ სიგრძით გაიხსნა და მათ კიდეებთან ახლოს მყოფი გრაფიკა სამუშაო დაფის გარეთაა +@msg this CMX file can't be read ({why}) ამ CMX ფაილის წაკითხვა შეუძლებელია ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out CMX-ის ტექსტები, გამოსახულებები, მართკუთხედები, ელიფსები, ამოჭრის კონტურები და სხვა ობიექტები, რომლებსაც VectorCraft ჯერ ვერ კითხულობს, გამოტოვებულია +@msg CMX fills other than uniform colors were left out CMX-ის შევსებები, გარდა ერთგვაროვანი ფერებისა, გამოტოვებულია +@msg colors in CMX color models VectorCraft doesn't read were opened as black CMX-ის იმ ფერის მოდელების ფერები, რომლებსაც VectorCraft ვერ კითხულობს, შავად გაიხსნა +@msg CMX library colors that the file stores only by number were opened as black spot colors CMX-ის ბიბლიოთეკის ფერები, რომლებსაც ფაილი მხოლოდ ნომრით ინახავს, შავ სპოტ-ფერებად გაიხსნა +@msg CMX outline arrowheads were left out CMX-ის მოხაზულობების ისრისპირები გამოტოვებულია +@msg CMX lenses were not applied CMX-ის ლინზები არ იქნა გამოყენებული +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163 830 pt-ზე გრძელი CMX-ის გვერდები ამ სიგრძით გაიხსნა და მათ კიდეებთან ახლოს მყოფი გრაფიკა სამუშაო დაფის გარეთაა @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD გამოსახულება ზედმეტად დიდია წასაკითხად ({_1} × {_2} პიქსელი) @msg zipped 1-bit PSD image data with prediction can't be read zip-ით შეკუმშული 1-ბიტიანი PSD გამოსახულების მონაცემების წაკითხვა პროგნოზირებით ვერ ხერხდება @msg the PSD file's layer data uses an unknown compression ({m}) PSD ფაილის შრეების მონაცემები უცნობ შეკუმშვას იყენებს ({m}) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index b1afe97154..74131e39a9 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5845,6 +5845,14 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out 너무 깊이 중첩되었거나 가져오기 한도를 넘은 도면 부분은 제외했습니다 @msg damaged parts of the drawing were left out 도면의 손상된 부분은 제외했습니다 @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163,830pt보다 긴 CDR 페이지는 그 길이로 열었으며, 가장자리 근처의 아트는 아트보드 밖에 있습니다 +@msg this CMX file can't be read ({why}) 이 CMX 파일을 읽을 수 없습니다 ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out VectorCraft가 아직 읽지 못하는 CMX 텍스트, 이미지, 사각형, 타원, 클리핑 패스 및 기타 개체는 제외했습니다 +@msg CMX fills other than uniform colors were left out 균일한 색상이 아닌 CMX 칠은 제외했습니다 +@msg colors in CMX color models VectorCraft doesn't read were opened as black VectorCraft가 읽지 못하는 CMX 색상 모델의 색상은 검정으로 열었습니다 +@msg CMX library colors that the file stores only by number were opened as black spot colors 파일이 번호로만 저장한 CMX 라이브러리 색상은 검정 별색으로 열었습니다 +@msg CMX outline arrowheads were left out CMX 외곽선의 화살촉은 제외했습니다 +@msg CMX lenses were not applied CMX 렌즈는 적용하지 않았습니다 +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163,830pt보다 긴 CMX 페이지는 그 길이로 열었으며, 가장자리 근처의 아트는 아트보드 밖에 있습니다 @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 이미지가 너무 커서 읽을 수 없습니다({_1} × {_2}픽셀) @msg zipped 1-bit PSD image data with prediction can't be read 예측이 적용된 ZIP 압축 1비트 PSD 이미지 데이터는 읽을 수 없습니다 @msg the PSD file's layer data uses an unknown compression ({m}) PSD 파일의 레이어 데이터가 알 수 없는 압축({m})을 사용합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index cfd7f846a0..080d05070a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -331,6 +331,14 @@ liquify-list-end {0}, {1} {0} en {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out delen van de tekening die te diep genest zijn of buiten de importlimieten vallen, zijn weggelaten @msg damaged parts of the drawing were left out beschadigde delen van de tekening zijn weggelaten @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard CDR-pagina’s langer dan 163.830 pt zijn op die lengte geopend, en illustraties bij de randen ervan liggen buiten het tekengebied +@msg this CMX file can't be read ({why}) dit CMX-bestand kan niet worden gelezen ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out CMX-tekst, afbeeldingen, rechthoeken, ellipsen, uitknippaden en andere objecten die VectorCraft nog niet leest, zijn weggelaten +@msg CMX fills other than uniform colors were left out CMX-vullingen die geen egale kleuren zijn, zijn weggelaten +@msg colors in CMX color models VectorCraft doesn't read were opened as black kleuren in CMX-kleurmodellen die VectorCraft niet leest, zijn als zwart geopend +@msg CMX library colors that the file stores only by number were opened as black spot colors CMX-bibliotheekkleuren die het bestand alleen als nummer opslaat, zijn als zwarte steunkleuren geopend +@msg CMX outline arrowheads were left out pijlpunten van CMX-contouren zijn weggelaten +@msg CMX lenses were not applied CMX-lenzen zijn niet toegepast +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard CMX-pagina’s langer dan 163.830 pt zijn op die lengte geopend, en illustraties bij de randen ervan liggen buiten het tekengebied @msg the JPEG XL file is cut short het JPEG XL-bestand is afgebroken @msg the JPEG XL container is too large to read de JPEG XL-container is te groot om te lezen @msg CMYK JPEG XL images can't be read CMYK-afbeeldingen in JPEG XL kunnen niet worden gelezen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index df6ef029f6..0cce1a6ff0 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5928,6 +5928,14 @@ variable-list-end {0}, {1} {0} i {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out pominięto części rysunku zagnieżdżone zbyt głęboko lub wykraczające poza limity importu @msg damaged parts of the drawing were left out pominięto uszkodzone części rysunku @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard strony CDR dłuższe niż 163 830 pt otwarto z tą długością, a kompozycja przy ich krawędziach leży poza obszarem kompozycji +@msg this CMX file can't be read ({why}) nie można odczytać tego pliku CMX ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out pominięto teksty, obrazy, prostokąty, elipsy, ścieżki przycinające i inne obiekty CMX, których VectorCraft jeszcze nie odczytuje +@msg CMX fills other than uniform colors were left out pominięto wypełnienia CMX inne niż jednolite kolory +@msg colors in CMX color models VectorCraft doesn't read were opened as black kolory w modelach kolorów CMX, których VectorCraft nie odczytuje, otwarto jako czarne +@msg CMX library colors that the file stores only by number were opened as black spot colors kolory z bibliotek CMX, które plik zapisuje tylko jako numer, otwarto jako czarne kolory dodatkowe +@msg CMX outline arrowheads were left out pominięto groty strzałek na obrysach CMX +@msg CMX lenses were not applied soczewki CMX nie zostały zastosowane +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard strony CMX dłuższe niż 163 830 pt otwarto z tą długością, a kompozycja przy ich krawędziach leży poza obszarem kompozycji @msg the PSD image is too large to read ({_1} × {_2} pixels) obraz PSD jest zbyt duży, aby go odczytać ({_1} × {_2} pikseli) @msg zipped 1-bit PSD image data with prediction can't be read nie można odczytać spakowanych 1-bitowych danych obrazu PSD z predykcją @msg the PSD file's layer data uses an unknown compression ({m}) dane warstw pliku PSD używają nieznanej kompresji ({m}) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 2b55c18e55..52e474823a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5058,6 +5058,14 @@ variable-list-end {0}, {1} {0} e {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out partes do desenho aninhadas profundamente demais ou além dos limites de importação foram omitidas @msg damaged parts of the drawing were left out partes danificadas do desenho foram omitidas @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard páginas do CDR com mais de 163.830 pt foram abertas com esse comprimento, e a arte perto das bordas fica fora da prancheta +@msg this CMX file can't be read ({why}) não é possível ler este arquivo CMX ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out textos, imagens, retângulos, elipses, demarcadores de recorte e outros objetos do CMX que o VectorCraft ainda não lê foram omitidos +@msg CMX fills other than uniform colors were left out os preenchimentos do CMX que não são cores uniformes foram omitidos +@msg colors in CMX color models VectorCraft doesn't read were opened as black cores em modelos de cor do CMX que o VectorCraft não lê foram abertas em preto +@msg CMX library colors that the file stores only by number were opened as black spot colors cores de biblioteca do CMX que o arquivo guarda apenas pelo número foram abertas como cores spot pretas +@msg CMX outline arrowheads were left out as pontas de seta das linhas de contorno do CMX foram omitidas +@msg CMX lenses were not applied as lentes do CMX não foram aplicadas +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard páginas do CMX com mais de 163.830 pt foram abertas com esse comprimento, e a arte perto das bordas fica fora da prancheta @msg the PSD image is too large to read ({_1} × {_2} pixels) a imagem PSD é grande demais para ser lida ({_1} × {_2} pixels) @msg zipped 1-bit PSD image data with prediction can't be read dados de imagem PSD de 1 bit compactados em zip com previsão não podem ser lidos @msg the PSD file's layer data uses an unknown compression ({m}) os dados de camada do arquivo PSD usam uma compactação desconhecida ({m}) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e39717c08f..9d6d4e3ebb 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5867,6 +5867,14 @@ variable-list-end {0}, {1} {0} и {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out части рисунка со слишком глубокой вложенностью или за пределами ограничений импорта были пропущены @msg damaged parts of the drawing were left out поврежденные части рисунка были пропущены @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard страницы CDR длиннее 163 830 pt открыты с этой длиной, и графика у их краев находится за пределами монтажной области +@msg this CMX file can't be read ({why}) не удается прочитать этот файл CMX ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out текст, изображения, прямоугольники, эллипсы, обтравочные контуры и другие объекты CMX, которые VectorCraft пока не читает, были пропущены +@msg CMX fills other than uniform colors were left out заливки CMX, кроме однородных цветов, были пропущены +@msg colors in CMX color models VectorCraft doesn't read were opened as black цвета в цветовых моделях CMX, которые VectorCraft не читает, открыты как черные +@msg CMX library colors that the file stores only by number were opened as black spot colors библиотечные цвета CMX, которые файл хранит только по номеру, открыты как черные плашечные цвета +@msg CMX outline arrowheads were left out наконечники стрелок абрисов CMX были пропущены +@msg CMX lenses were not applied линзы CMX не были применены +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard страницы CMX длиннее 163 830 pt открыты с этой длиной, и графика у их краев находится за пределами монтажной области @msg the PSD image is too large to read ({_1} × {_2} pixels) изображение PSD слишком велико для чтения ({_1} × {_2} пикс.) @msg zipped 1-bit PSD image data with prediction can't be read 1-битные данные изображения PSD со сжатием ZIP с предсказанием не читаются @msg the PSD file's layer data uses an unknown compression ({m}) данные слоёв файла PSD используют неизвестное сжатие ({m}) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index d78cf4d835..e761028cf2 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5740,6 +5740,14 @@ variable-list-end {0}, {1} {0} och {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out delar av teckningen som är för djupt nästlade eller ligger utanför importgränserna utelämnades @msg damaged parts of the drawing were left out skadade delar av teckningen utelämnades @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard CDR-sidor längre än 163 830 pt öppnades med den längden, och grafik nära deras kanter ligger utanför ritytan +@msg this CMX file can't be read ({why}) den här CMX-filen kan inte läsas ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out text, bilder, rektanglar, ellipser, urklippsbanor och andra CMX-objekt som VectorCraft ännu inte läser utelämnades +@msg CMX fills other than uniform colors were left out CMX-fyllningar som inte är enfärgade utelämnades +@msg colors in CMX color models VectorCraft doesn't read were opened as black färger i CMX-färgmodeller som VectorCraft inte läser öppnades som svarta +@msg CMX library colors that the file stores only by number were opened as black spot colors CMX-biblioteksfärger som filen bara lagrar som nummer öppnades som svarta dekorfärger +@msg CMX outline arrowheads were left out pilspetsar på CMX-linjer utelämnades +@msg CMX lenses were not applied CMX-linser tillämpades inte +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard CMX-sidor längre än 163 830 pt öppnades med den längden, och grafik nära deras kanter ligger utanför ritytan @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD-bilden är för stor för att läsas ({_1} × {_2} pixlar) @msg zipped 1-bit PSD image data with prediction can't be read zippad 1-bitars PSD-bilddata med prediktion kan inte läsas @msg the PSD file's layer data uses an unknown compression ({m}) PSD-filens lagerdata använder en okänd komprimering ({m}) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index aa2de5a5e6..c67b0bed70 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -3607,6 +3607,26 @@ fn cdr_import_notes_are_translated() { } } +/// The notes a CMX import adds to its warnings are translated in every complete catalog. +#[test] +fn cmx_import_notes_are_translated() { + let notes = [ + "CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out", + "CMX fills other than uniform colors were left out", + "colors in CMX color models VectorCraft doesn't read were opened as black", + "CMX library colors that the file stores only by number were opened as black spot colors", + "CMX outline arrowheads were left out", + "CMX lenses were not applied", + "CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard", + ]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for note in notes { + assert_ne!(message(lang, note), note, "{code}: {note}"); + } + } +} + /// The plug-in host's status and error messages (manifests, modules, runs and the output of /// importers, exporters and effects) have an `@msg` row in every complete-message catalog. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9df59d6522..2d0e3a8847 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5568,6 +5568,14 @@ liquify-list-end {0}, {1} {0} ve {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out çizimin fazla derin iç içe geçmiş veya içe aktarma sınırlarının ötesindeki kısımları dışarıda bırakıldı @msg damaged parts of the drawing were left out çizimin hasarlı kısımları dışarıda bırakıldı @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163.830 pt'den uzun CDR sayfaları bu uzunlukta açıldı ve kenarlarına yakın çizimler çalışma yüzeyinin dışında kalıyor +@msg this CMX file can't be read ({why}) bu CMX dosyası okunamıyor ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out VectorCraft'ın henüz okumadığı CMX metinleri, görüntüleri, dikdörtgenleri, elipsleri, kırpma yolları ve diğer nesneleri dışarıda bırakıldı +@msg CMX fills other than uniform colors were left out düz renkler dışındaki CMX dolguları dışarıda bırakıldı +@msg colors in CMX color models VectorCraft doesn't read were opened as black VectorCraft'ın okumadığı CMX renk modellerindeki renkler siyah olarak açıldı +@msg CMX library colors that the file stores only by number were opened as black spot colors dosyanın yalnızca numarayla sakladığı CMX kitaplık renkleri siyah nokta renkleri olarak açıldı +@msg CMX outline arrowheads were left out CMX anahatlarının ok uçları dışarıda bırakıldı +@msg CMX lenses were not applied CMX mercekleri uygulanmadı +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 163.830 pt'den uzun CMX sayfaları bu uzunlukta açıldı ve kenarlarına yakın çizimler çalışma yüzeyinin dışında kalıyor @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD görüntüsü okunamayacak kadar büyük ({_1} × {_2} piksel) @msg zipped 1-bit PSD image data with prediction can't be read Tahmin içeren sıkıştırılmış 1 bit PSD görüntü verileri okunamıyor @msg the PSD file's layer data uses an unknown compression ({m}) PSD dosyasının katman verileri bilinmeyen bir sıkıştırma kullanıyor ({m}) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0b7c24266c..e3f4f04ade 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5852,6 +5852,14 @@ variable-list-end {0}, {1} {0} і {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out частини малюнка із надто глибоким вкладенням або поза межами обмежень імпорту було пропущено @msg damaged parts of the drawing were left out пошкоджені частини малюнка було пропущено @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard сторінки CDR, довші за 163 830 pt, відкрито з цією довжиною, і графіка біля їхніх країв лежить поза монтажною областю +@msg this CMX file can't be read ({why}) не вдається прочитати цей файл CMX ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out текст, зображення, прямокутники, еліпси, обтравлювальні контури та інші об’єкти CMX, які VectorCraft поки не читає, було пропущено +@msg CMX fills other than uniform colors were left out заливки CMX, крім однорідних кольорів, було пропущено +@msg colors in CMX color models VectorCraft doesn't read were opened as black кольори в колірних моделях CMX, які VectorCraft не читає, відкрито як чорні +@msg CMX library colors that the file stores only by number were opened as black spot colors бібліотечні кольори CMX, які файл зберігає лише за номером, відкрито як чорні плашкові кольори +@msg CMX outline arrowheads were left out наконечники стрілок абрисів CMX було пропущено +@msg CMX lenses were not applied лінзи CMX не було застосовано +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard сторінки CMX, довші за 163 830 pt, відкрито з цією довжиною, і графіка біля їхніх країв лежить поза монтажною областю @msg the PSD image is too large to read ({_1} × {_2} pixels) зображення PSD завелике для читання ({_1} × {_2} пікс.) @msg zipped 1-bit PSD image data with prediction can't be read 1-бітні дані зображення PSD зі стисненням ZIP із передбаченням не читаються @msg the PSD file's layer data uses an unknown compression ({m}) дані шарів файлу PSD використовують невідоме стиснення ({m}) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 8abc7b3253..60dcd246ac 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6118,6 +6118,14 @@ liquify-list-end {0}, {1} {0} và {1} @msg parts of the drawing nested too deeply, or past the import limits, were left out các phần của bản vẽ lồng nhau quá sâu hoặc vượt quá giới hạn nhập đã bị bỏ qua @msg damaged parts of the drawing were left out các phần bị hỏng của bản vẽ đã bị bỏ qua @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard các trang CDR dài hơn 163.830 pt đã được mở với độ dài đó, và hình vẽ gần mép trang nằm ngoài bảng vẽ +@msg this CMX file can't be read ({why}) không thể đọc tệp CMX này ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out văn bản, hình ảnh, hình chữ nhật, hình elip, đường cắt xén và các đối tượng CMX khác mà VectorCraft chưa đọc được đã bị bỏ qua +@msg CMX fills other than uniform colors were left out các kiểu tô CMX không phải màu đồng nhất đã bị bỏ qua +@msg colors in CMX color models VectorCraft doesn't read were opened as black các màu trong mô hình màu CMX mà VectorCraft không đọc được đã được mở thành màu đen +@msg CMX library colors that the file stores only by number were opened as black spot colors các màu thư viện CMX mà tệp chỉ lưu theo số đã được mở thành màu đặc biệt đen +@msg CMX outline arrowheads were left out các đầu mũi tên của đường viền CMX đã bị bỏ qua +@msg CMX lenses were not applied thấu kính CMX không được áp dụng +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard các trang CMX dài hơn 163.830 pt đã được mở với độ dài đó, và hình vẽ gần mép trang nằm ngoài bảng vẽ @msg the PSD image is too large to read ({_1} × {_2} pixels) ảnh PSD quá lớn để đọc ({_1} × {_2} pixel) @msg the Save PDF dialog didn't open hộp thoại Lưu PDF không mở @msg the scale is not a usable number tỷ lệ không phải là số dùng được diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 12d8c05e30..3a276b52ad 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5579,6 +5579,14 @@ liquify-list-end {0}, {1} {0}和{1} @msg parts of the drawing nested too deeply, or past the import limits, were left out 已略去绘图中嵌套过深或超出导入限制的部分 @msg damaged parts of the drawing were left out 已略去绘图中损坏的部分 @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 长度超过 163,830 pt 的 CDR 页面已按该长度打开,其边缘附近的图稿位于画板之外 +@msg this CMX file can't be read ({why}) 无法读取此 CMX 文件 ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out 已略去 VectorCraft 尚不能读取的 CMX 文本、图像、矩形、椭圆、剪切路径和其他对象 +@msg CMX fills other than uniform colors were left out 已略去 CMX 中均匀颜色以外的填充 +@msg colors in CMX color models VectorCraft doesn't read were opened as black VectorCraft 不能读取的 CMX 颜色模型中的颜色已作为黑色打开 +@msg CMX library colors that the file stores only by number were opened as black spot colors 文件仅按编号存储的 CMX 库颜色已作为黑色专色打开 +@msg CMX outline arrowheads were left out 已略去 CMX 轮廓线的箭头 +@msg CMX lenses were not applied 未应用 CMX 透镜 +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 长度超过 163,830 pt 的 CMX 页面已按该长度打开,其边缘附近的图稿位于画板之外 @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 图像过大,无法读取 ({_1} × {_2} 像素) @msg zipped 1-bit PSD image data with prediction can't be read 无法读取带预测的 ZIP 压缩 1 位 PSD 图像数据 @msg the PSD file's layer data uses an unknown compression ({m}) PSD 文件的图层数据使用了未知的压缩方式 ({m}) diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index c6c3a8f50b..f4254fb6f2 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3034,6 +3034,14 @@ liquify-list-end {0}, {1} {0}和{1} @msg parts of the drawing nested too deeply, or past the import limits, were left out 已略過繪圖中巢狀過深或超出讀入限制的部分 @msg damaged parts of the drawing were left out 已略過繪圖中損壞的部分 @msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 長度超過 163,830 pt 的 CDR 頁面已以該長度開啟,其邊緣附近的圖稿位於工作區域之外 +@msg this CMX file can't be read ({why}) 無法讀取此 CMX 檔案 ({why}) +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out 已略過 VectorCraft 尚無法讀取的 CMX 文字、影像、矩形、橢圓、剪裁路徑和其他物件 +@msg CMX fills other than uniform colors were left out 已略過 CMX 中均勻色彩以外的填色 +@msg colors in CMX color models VectorCraft doesn't read were opened as black VectorCraft 無法讀取的 CMX 色彩模式中的顏色已以黑色開啟 +@msg CMX library colors that the file stores only by number were opened as black spot colors 檔案僅以編號儲存的 CMX 色彩庫顏色已以黑色特別色開啟 +@msg CMX outline arrowheads were left out 已略過 CMX 外框線的箭頭 +@msg CMX lenses were not applied 未套用 CMX 透鏡 +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard 長度超過 163,830 pt 的 CMX 頁面已以該長度開啟,其邊緣附近的圖稿位於工作區域之外 @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD 影像過大,無法讀取 ({_1} × {_2} 像素) @msg zipped 1-bit PSD image data with prediction can't be read 無法讀取使用預測的 ZIP 壓縮 1 位元 PSD 影像資料 @msg the PSD file's layer data uses an unknown compression ({m}) PSD 檔案的圖層資料使用了不明的壓縮方式 ({m}) diff --git a/docs/architecture.md b/docs/architecture.md index 16521e3e0c..a64d04fefb 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -19,7 +19,7 @@ nothing below L6 depends on a UI toolkit (egui, eframe, winit, rfd). Table: `xta | Layer | Crates | Role | |---|---|---| -| L0 | `geom`, `color`; `affinity`, `cdr` (standalone, no workspace deps) | curves and transforms (on `kurbo`), colour models, ICC and conversions; the Affinity and `.cdr` readers | +| L0 | `geom`, `color`; `affinity`, `cdr` (standalone, no workspace deps) | curves and transforms (on `kurbo`), colour models, ICC and conversions; the Affinity and `.cdr`/`.cmx` readers | | L1 | `doc` | the document model: artboards, layers, objects, appearance, text, symbols; pure data + serde, structural sharing | | L2 | `pathops`, `brush`, `trace`, `text`, `effects`, `plugins`, `three-d` | booleans/Shape Builder/offset/outline; brushes; Image Trace; fonts, shaping (HarfRust, skrifa), bidi and layout; live effects and the pixel-filter pipeline; sandboxed WebAssembly plug-ins (wasmi); 3D surfaces of revolution, projection and shading (`three-d`, on `geom` only) | | L3 | `render`, `svg`, `pdf`, `format`, `eps`, `cad`, `metafile` | document to pixels (`vello_cpu`, multithreaded); SVG, PDF, native JSON, EPS/PostScript (with its own interpreter), DXF, EMF/WMF readers and writers | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 3761762f4c..9f7fe56646 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -21,7 +21,7 @@ Ordinary File > Save offers Save As when its own location refuses writes with a | | Illustrator | VectorCraft | Notes | |---|---:|---:|---| -| Formats opened or placed | ~30 | 33 | missing: FreeHand, DWG | +| Formats opened or placed | ~30 | 34 | missing: FreeHand, DWG; extra: `.cmx` | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, gradients, patterns, images, type, symbols, artboards, transparency, opacity masks, clipping, text wrap options) or as legacy version 7 (layers and groups, one artboard per file) | | Formats exported | ~16 | 18 | missing: DWG; extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | | **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting | @@ -336,6 +336,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` | | FreeHand `.fh*` | open (legacy) | no | no | | | `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, clipping containers, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; hidden and locked layers, groups and objects; the winding flag as the nonzero fill rule; uniform transparency of version 13 on as opacity and blend mode; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses, other transparency and merge modes without a blend mode are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies; version 3 envelopes are not applied, so the objects and groups under one keep their outlines and matrices, with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; after an open with a warning, an export or Save As to the drawing's own path needs `acknowledgeLoss: true`; record layouts and their sources in `crates/cdr/PROVENANCE.md`; synthetic test files only; tests in `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` | +| `.cmx` exchange files | no (not in the [supported formats](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/supported-file-formats-in-illustrator.html) list) | yes (files with 32-bit coordinates: pages, layers, groups, curves, uniform fills and outlines with their width, color, caps, joins and dashes; text, images, rectangles, ellipses, clipping paths, other fills and arrowheads are left out with a warning, and lenses are not applied, with a warning; big-endian files and files with 16-bit coordinates are refused) | no | File › Place reads them too; after an open with a warning, an export or Save As to the file's own path needs `acknowledgeLoss: true`; layouts and their sources in `crates/cdr/PROVENANCE.md` (R53 to R63); synthetic test files only; tests in `crates/cdr/tests/it/cmx.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs` and `crates/engine/tests/import_fuzz.rs` | | Text `.txt` | place, export | place (Text Import Options) | yes | place reads Unicode and ANSI, and Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European through the WHATWG Encoding Standard's decoders (VectorCraft's own mapping); `tests/textimport.rs`, `place/text.rs`; fuzzed (`text_import_fuzz.rs`) | | RTF `.rtf` | place | place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only | | Word `.docx` | place | place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out | diff --git a/docs/mcp.md b/docs/mcp.md index 413ef1748b..f6532754bf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -724,7 +724,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. UI commands such as `view.*` and `window.*` are in `command_list` with `ui: true`; running them needs the desktop app (`--connect`). | | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | | `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. An app that does not send the image back writes a window capture without `path` to a file in a new folder inside the system's temporary folder (on Unix only the user can open it); the server reads the file and then removes the folder, also when the capture or the read fails. | -| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | +| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | | `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `_.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a PDF-compatible `.ai` file reads `compress` but not `version`, `preview`, `precision`, `outlineText`, `hiddenObjects`, `transparentImages` or `preserveEditing`, and a legacy `.ai` file reads only its own options). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for each key given beside the path or in `options` that the file doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). In the desktop app, a save that runs in the background shows in the progress window after 0.4 s with a moving bar. `file.cancelSave` stops every such save before it replaces its file → `{cancelled: n}`: the file stays as it was, and the document keeps its file and format and stays modified. A save whose file was already being replaced finishes and is reported as saved. `file.saveInBackground` closes the window while the saves go on → `{hidden: n}`. | | `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` for type on a path (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning). An invalid effect is rejected before editing. `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | @@ -10193,6 +10193,21 @@ an envelope is not applied, so an object or a group under one keeps its outline, version 4 opens as one of version 5 does. A file is taken for version 1 or 2 by its content only when the offsets in its header fit the file. A RIFF file that names a version before 3 is refused with a message. +## CMX import + +`.cmx` exchange files with 32-bit coordinates open and place as editable art, found by their content whatever their +extension. Each page becomes an artboard, side by side, at the size the page gives. A page that gives no size takes +the size of the drawing's bounds stored with it, centered on the art, or 612 × 792 pt when it stores none either. +Layers keep their names, and a layer that holds nothing is left out. Groups stay groups, and curves become paths with +their uniform fills and outlines: colors in CMYK or RGB, and library colors stored with their names as spot swatches; +outline widths, caps, joins, dashes, an outline behind the fill and an outline scaled with the object. Text, images, +rectangles, ellipses, clipping paths and other objects the reader doesn't read yet, fills other than uniform ones and +outline arrowheads are left out, and lenses are not applied. The objects a clipping path clips come in without it. The +`warnings` of `document.open` name each of these kinds the file had, and say when damaged parts or parts past the +import limits were left out. Files in big-endian byte order and files with 16-bit coordinates are refused with a +message. VectorCraft doesn't write `.cmx` files. After a file opens with warnings, an export or Save As to its own path +needs `acknowledgeLoss: true`. + ## Printing `print.setup {settings?}` keeps print settings with the document (one undo step; without `settings` it answers the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 103db3b38b..1270ee8e34 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -881,7 +881,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Artboard deletion keys:** Delete/Backspace delete selected boards in one Undo step, retaining the original first board in the current order when all are selected, as in the public [Delete artboards guide](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html). The last board and active drags stay protected; neither key clears selected artwork. Headless shortcut regressions in `tests/distortkeys.rs` cover reordered boards, artwork, saved state and Undo/Redo. - **Locked artboards:** a click in the Artboards panel's lock column locks or unlocks an artboard in one undo step (`artboard.setProps {index, locked}`), and the native format saves the lock. The Artboard tool doesn't move, copy, resize or delete a locked artboard, Rearrange and Fit to Artwork Bounds leave it as it is, and its name isn't edited on the canvas. The art on it (each object whose bounds overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, `select.set`, `select.all` and the tools pass over it, and commands that act on the selection leave it; art drawn or pasted onto it stays selected and editable until the selection leaves it out. Tests in `crates/doc/src/lib.rs`, `tests/panelcmds.rs`, `xform/artboard.rs`, `panels/artboards.rs` and `canvas.rs` cover them. Public references: [Lock artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/lock-artboards.html) and [Managing Artboards in Illustrator](https://creativepro.com/managing-artboards-in-illustrator/). - **Linux RPM packaging:** 64-bit runtime capabilities replace Fedora-specific required package names (#1275); glibc 2.35, libm and libgcc_s are declared alongside dynamically loaded xkbcommon and Vulkan/EGL. Generated x86_64/aarch64 metadata and isolated synthetic-provider resolution checked; real-distro install/start-up QA remains pending. -- **Linux file associations:** the desktop entry lists the MIME type of every format File › Open reads but PSD, PSB, `.ps` PostScript, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, HP-GL and `.cdr`, `.ai`, `.ait` and EPS included, and the MIME package declares the types shared-mime-info lacks (VectorCraft documents and templates, `.ait`, Affinity), so file managers list VectorCraft under Open With for them, as Finder does on macOS. `the_linux_desktop_entry_opens_every_readable_format` in `apps/vectorcraft/src/tests.rs` checks both files against `OPEN_EXTS`. On Debian 13, Ubuntu 24.04 and Fedora 42, `desktop-file-validate` accepts the desktop entry, `update-mime-database` accepts the MIME package, and `gio` registers the app for every one of these types. +- **Linux file associations:** the desktop entry lists the MIME type of every format File › Open reads but PSD, PSB, `.ps` PostScript, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, HP-GL, `.cdr` and `.cmx`, `.ai`, `.ait` and EPS included, and the MIME package declares the types shared-mime-info lacks (VectorCraft documents and templates, `.ait`, Affinity), so file managers list VectorCraft under Open With for them, as Finder does on macOS. `the_linux_desktop_entry_opens_every_readable_format` in `apps/vectorcraft/src/tests.rs` checks both files against `OPEN_EXTS`. On Debian 13, Ubuntu 24.04 and Fedora 42, `desktop-file-validate` accepts the desktop entry, `update-mime-database` accepts the MIME package, and `gio` registers the app for every one of these types. - **Architecture:** 19+ crates with enforced layering (`cargo xtask layers`). Every action is a command (~400 engine + ~50 UI). Undo is unlimited via structural sharing. `command.batch` runs several commands as one transaction. - **Parameter schemas:** a command can carry a machine-readable parameter schema (the new `vectorcraft-apischema` crate): each parameter's type, range, unit, whether it is required, its default, whether null counts as left out, and the API levels it was added and deprecated at. `engine.commands` lists the schema in the shape of a JSON Schema 2020-12 object schema, a test keeps the command's `params` text equal to the text the schema writes, and a new call has the params checked against it before the command runs (batch steps before the first step), with an error naming the parameter and no change to the document (a value nested past the schema's 16 levels is such a parameter error, and only a schema that is wrong in itself is an internal error); saved steps keep a key the schema does not name, and their values are checked. The View commands `view.capsLock`, `view.saved.new`, `view.saved.edit`, `view.saved.list`, `view.transparencyGrid` and `view.snapToGlyph.options` have schemas. The schemas belong to API level 1 (`vectorcraft_engine::schemas::API_VERSION`), and a test fails when a schema changes without a new level. Tests: `crates/apischema/src/tests.rs` (with `conformance.rs`, a separate check of the JSON form against the JSON Schema 2020-12 rules), `schemas::tests` and `cmd::views::tests::each_view_command_refuses_a_bad_value_naming_the_parameter` in `vectorcraft-engine`. @@ -2234,6 +2234,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export with Use Artboards applies live effects and places symbols' art once for all the artboards' drawings instead of once for each drawing; each drawing's bytes, linked images, warnings and notes are the same as before (`drawings_apply_the_live_effects_once_and_match_drawings_written_alone`, `each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone`). - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill, or scaled with the object's matrix, where the file says so), an object without a fill or outline of its own taking its style's, hidden and locked layers, groups and objects, the winding flag as the nonzero fill rule, and a uniform transparency of version 13 and later as the object's opacity and blend mode. A library color stored with its name and values (version 13 and later, in a fill or an outline) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, other transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). + - `.cmx` exchange files with 32-bit coordinates open and place: `vectorcraft-cdr` reads their color, pen, line type, dash and outline tables and each page's instructions, and the importer maps pages, layers (a layer that holds nothing is left out), groups and curves, with uniform fills and outlines, as it maps a `.cdr` drawing's. Text, images, rectangles, ellipses, clipping paths, other fills, arrowheads and lenses are named in the warnings, and big-endian files and files with 16-bit coordinates are refused with a message (`crates/cdr/tests/it/cmx.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs`, `crates/engine/tests/import_fuzz.rs`). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. An EPS file, a PostScript file or a PostScript `.ai` placed from a file with Link is a placed document the same way, showing the art placing it without Link gives (clipped to its bounding box, or its art's bounds with `crop: "bounding"`); Links lists it as `EPS` or `PostScript`, and a save, Package, Break Link and Object › Expand treat it as they treat a placed PDF page. Package also copies the files that the native document of an EPS file written by VectorCraft links, beside the EPS file's copy, which finds them there by name. Placing one keeps the file linked rather than embedding it, as [the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/eps-and-dcs-file-import-in-illustrator.html) describes; a DCS file stays a linked image (`crates/engine/src/tests/placed_document.rs`, `crates/engine/src/tests/package.rs`). From 1c5f97acfcbf961da9a65589afe9aac425f891bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 17:43:31 -0800 Subject: [PATCH 34/34] File formats: .cmx gray and CMY colors, unnamed layers, stricter chunk search - Colors in the older color fields read gray (model 9) and CMY (model 4) as the .cdr reader numbers them, instead of opening as black. - A dash pattern whose lengths are all 0 draws a solid line, as for a .cdr outline. - A curve whose point field is too short for its count and is not whole points with their type bytes is left out as damaged, instead of reading coordinates as point types. - A layer without a name comes in unnamed, and the importer names it by its place, as for a .cdr drawing. - After stray bytes, a chunk id starts with a letter and may hold digits and spaces, and the id found must name a chunk the reader uses or have a length that fits its list. Padding is no longer taken for a chunk. - A canvas or a container in an object's attributes gives the unsupported-objects warning. - A page with no size and no bounds is 612 x 792 pt, VectorCraft's own size, as for a .cdr page; PROVENANCE R61 says so. PROVENANCE also names the other program's .cmx reader, read for field order. --- crates/cdr/PROVENANCE.md | 18 +-- crates/cdr/README.md | 4 +- crates/cdr/src/cmx.rs | 44 +++++-- crates/cdr/src/synth_cmx.rs | 13 ++ crates/cdr/tests/it/cmx.rs | 137 +++++++++++++++++++++- crates/engine/src/cmd/fileio/tests_cmx.rs | 21 ++++ docs/file-format-parity.md | 4 +- docs/mcp.md | 11 +- 8 files changed, 223 insertions(+), 29 deletions(-) diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index ba2e8d642b..b710c7d4b2 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -44,7 +44,11 @@ Sources: of their drawing. - **CN**: the `.cmx` notes of an MIT OR Apache-2.0 drawing program, which mark each layout "confirmed" when the program's authors found it in sample files, - https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/docs/cmx-format.md + https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/docs/cmx-format.md. + The same program's `.cmx` reader at that commit, + https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/crates/cdr/src/cmx.rs, + was read for the order of fields that the notes do not spell out (the table entries, the rendering + attributes and the curve body); no code was copied from it Status: `public-spec` (K, KF, KR, Z, F or PR), `sample` (S), `public-notes` (a layout CN marks confirmed that no CX file shows), `unconfirmed` (a point no source states and no sample file shows; @@ -110,14 +114,14 @@ file is committed. | R50 | Bit 5 (0x20) of the outline's line type scales the outline's width and dashes with the shape's matrix. The engine multiplies them by the square root of the matrix's area factor (VectorCraft's own value for a matrix that scales x and y differently) | S: UC `outl_scale_with_cdr7.cdr` to `outl_scale_with_cdr12.cdr`, of whose outlines only one, 3.969 mm wide, has line type 0x22 and the others 0x02 or 0x01; TDF 76771 (version 15), whose outline of line type 0x22 is 10 mm wide on a shape that the matrix stretches and skews, and whose picture draws that outline several times wider and skewed | sample (the bit; the single width for a matrix that scales x and y differently: VectorCraft's own) | | R51 | A `trfd` offsets table holds one offset more than the entries; each entry runs from its offset to the next, and the last offset is the record's end | KF L1079, L1113-L1121; S: every `trfd` of versions 4 to 25 in the sample files (25,425 records) has the extra offset, equal to the record's length | public-spec | | R52 | Byte 0 of argument 14001 is the fill's winding flag. VectorCraft reads a byte other than 0 as the nonzero fill rule, and 0 or an object without the argument as even-odd | KF L575-L583, L1047; S: the argument is 4 bytes in the sample files that carry it, with byte 0 = 1 on LT `complexshape_blackfill_nooutline` of `testset/12` and `testset/15` to `testset/25` and on objects of TDF 127576 (13) and 60026 (14), and 0 on 27 objects of TP `example.cdr` (17) | public-spec (the flag: KF; which rule each value means, and the rule without the argument: VectorCraft's own reading, and a wrong reading fills or leaves holes where a curve's subpaths overlap) | -| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id, the next id is four letters at an even distance of 2 to 64 bytes | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample | +| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list (VectorCraft's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample | | R54 | `cont`: byte 52 is the coordinate size as an ASCII digit, `4` for 32-bit coordinates and `2` for 16-bit ones (refused); bytes 64 to 72 hold an f64, the size of a coordinate unit in meters. A value that isn't above 0 and at most 1 reads as 0.1 µm (VectorCraft's own fallback) | CN "Container"; S: the nine CX files with `4` all hold 1e-7; `abydos.cmx`, `CM33.CMX`, `LIZARDS.CMX`, `output.000.cmx` and `test.cmx` hold `2` | sample | | R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample | -| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 5 red, green and blue in 0 to 255. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them; a wrong reading gives a wrong color) | -| R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each) | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) | +| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) | +| R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each). A pattern whose lengths are all 0 draws a solid line, as R48's | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) | | R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist | sample | | R59 | `rota`: a u16 count, then pairs of u16 (start and end arrowheads, 0 for none), not field lists | CN "Tables"; S: `rota` is `01 00 00 00 00 00` in every CX file | sample (pairs of 0), public-notes (other values) | | R60 | A `page` chunk is a stream of instructions: a u16 size counting the whole instruction and an i16 code, or 0xFFFF, a u32 size and the code (the long form); then field lists. Codes: 9 and 10 begin and end a page, 11 and 12 a layer, 13 and 14 a group, 67 a curve; 20 and 21 a text object, 65 its drawn characters, 66 an ellipse, 68 a rectangle, 69 an image, 88 and 89 add and remove a clipping path, 111 a jump whose field 1 is the u32 file offset to go on from (the bytes jumped over hold images). Objects are drawn in file order, the first at the back | CN "page: instructions"; S: codes 9 to 14 and 67 in the CX files; in `squares.cmx` the large square comes first and the two smaller ones inside it after | sample (9 to 14, 67, the order), public-notes (the long form and the other codes) | -| 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) | 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 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 | 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), 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 | +| 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 | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index e0ad0b1eb8..007258e931 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -66,10 +66,10 @@ arrowhead tables, then each page's instructions in drawing order: | In the `.cmx` file | Read as | |---|---| | Pages, with the size the page gives, or else the size of the drawing's bounds that the page stores | pages; a page sized to the bounds is centered on them | -| Layers, by their UTF-16 or 8-bit name | drawing layers; a layer that holds nothing is left out | +| Layers, by their UTF-16 or 8-bit name | drawing layers, unnamed when the file gives no name; a layer that holds nothing is left out | | Groups | groups | | Curves (moves, lines and cubic curves, as `.cdr` point lists) | paths | -| Uniform fills: CMYK in percent or 0 to 255, RGB, and library colors with their names | colors, spot colors | +| Uniform fills: CMYK in percent or 0 to 255, CMY, RGB, gray, and library colors with their names | colors, spot colors | | Outlines: width, color, caps, joins, dashes, the no-outline, behind-the-fill and scaled-with flags | outlines | Text, images, rectangles, ellipses, clipping paths, fills other than uniform ones, outline diff --git a/crates/cdr/src/cmx.rs b/crates/cdr/src/cmx.rs index 5bd7439291..fc343a1870 100644 --- a/crates/cdr/src/cmx.rs +++ b/crates/cdr/src/cmx.rs @@ -108,7 +108,7 @@ fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec) -> Resu while let Some((mut pos, end, depth)) = stack.pop() { while pos.saturating_add(8) <= end { let Some(id) = Rd::at(b, pos).fourcc() else { break }; - if !id.iter().all(|c| c.is_ascii_alphanumeric() || *c == b' ') { + if !is_id(&id) { match resync(b, pos, end) { Some(next) => { pos = next; @@ -157,12 +157,18 @@ fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec) -> Resu Ok(out) } -/// Where the next chunk id after `pos` lies: four letters at an even distance of 2 to [`RESYNC`] -/// bytes (R53). +/// Is `t` a chunk id: an ASCII letter, then three ASCII letters, digits or spaces (R53)? +fn is_id(t: &[u8]) -> bool { + matches!(t, [first, rest @ ..] if t.len() == 4 && first.is_ascii_alphabetic() && rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b' ')) +} + +/// Where the next chunk after `pos` lies: the first chunk id at an even distance of 2 to [`RESYNC`] +/// bytes that names a chunk the reader uses, or another chunk whose length keeps it inside the list +/// that ends at `end` (R53). fn resync(b: &[u8], pos: usize, end: usize) -> Option { - (pos + 2..=pos.saturating_add(RESYNC).min(end.saturating_sub(8))) - .step_by(2) - .find(|&p| b.get(p..p + 4).is_some_and(|t| t.iter().all(u8::is_ascii_alphabetic))) + let fits = |p: usize| u32_at(b, p + 4).and_then(|s| (p + 8).checked_add(s as usize)).is_some_and(|stop| stop <= end); + let chunk_at = |p: usize| Rd::at(b, p).fourcc().is_some_and(|id| is_id(&id) && (READ_IDS.contains(&id) || fits(p))); + (pos + 2..=pos.saturating_add(RESYNC).min(end.saturating_sub(8))).step_by(2).find(|&p| chunk_at(p)) } /// The end of the field list at `pos` of `b`: after its 0xff, or the end of `b` when a field runs @@ -278,6 +284,8 @@ impl Tables { if flags & 4 != 0 { let stored = usize::from(dash).checked_sub(1).and_then(|i| self.dashes.get(i)); match stored { + // A pattern of zero lengths draws as a solid line, as in a `.cdr` outline (R48). + Some(d) if d.iter().all(|x| *x == 0) => {} Some(d) if budget.take_dashes(d.len()) => dashes = d.iter().map(|x| f64::from(*x)).collect(), Some(_) => push(warn, Warning::TooDeep), None => push(warn, Warning::Damaged), @@ -323,7 +331,9 @@ fn color(e: &[u8], record: Option<&Profile>, warn: &mut Vec) -> Option< Some(match model { 2 => Color::Cmyk([pct(0)?, pct(1)?, pct(2)?, pct(3)?]), 3 => Color::Cmyk([full(0)?, full(1)?, full(2)?, full(3)?]), + 4 => Color::Cmyk([full(0)?, full(1)?, full(2)?, 0.0]), 5 => Color::Rgb([full(0)?, full(1)?, full(2)?]), + 9 => Color::Gray(1.0 - full(0)?), _ => { push(warn, Warning::UnknownColors); Color::Rgb([0.0; 3]) @@ -453,7 +463,8 @@ impl<'t, 'b> PageRead<'t, 'b> { } BEGIN_LAYER => { self.close_layer(); - let name = self.layer_name(body).unwrap_or_else(|| format!("Layer {}", self.layers.len() + 1)); + // A layer without a name is left unnamed, as in a `.cdr` drawing. + let name = self.layer_name(body).unwrap_or_default(); self.open = Some(LayerRead { name, lists: vec![Vec::new()] }); } END_LAYER => self.close_layer(), @@ -515,10 +526,9 @@ impl<'t, 'b> PageRead<'t, 'b> { } } - /// The open layer, or a new one when objects come before any layer begins. + /// The open layer, or a new unnamed one when objects come before any layer begins. fn layer(&mut self) -> &mut LayerRead { - let n = self.layers.len() + 1; - self.open.get_or_insert_with(|| LayerRead { name: format!("Layer {n}"), lists: vec![Vec::new()] }) + self.open.get_or_insert_with(|| LayerRead { name: String::new(), lists: vec![Vec::new()] }) } fn close_layer(&mut self) { @@ -560,11 +570,17 @@ impl<'t, 'b> PageRead<'t, 'b> { }; // `stored` points are read, so the type bytes are found after all of them, and the first // `n`, those that have a type byte, are kept. When the field holds every point, a short - // field has lost type bytes; otherwise it holds as many whole points and types as fit. + // field has lost type bytes. When it holds whole points and their types for fewer points, + // the count is too large. Otherwise the field lost points, and its type bytes can't be + // found: the curve is lost. let left = r.left(); let (stored, n) = match count.checked_mul(8).filter(|c| *c <= left) { Some(c) => (count, count.min(left - c)), - None => (count.min(left / 9), count.min(left / 9)), + None if left.is_multiple_of(9) => (left / 9, left / 9), + None => { + push(self.warn, Warning::Damaged); + return None; + } }; if n < count { push(self.warn, Warning::Damaged); @@ -626,6 +642,10 @@ impl<'t, 'b> PageRead<'t, 'b> { if mask & 4 != 0 { push(self.warn, Warning::Lenses); } + // A canvas (8) or a container (16) is not read. + if mask & (8 | 16) != 0 { + push(self.warn, Warning::UnsupportedObjects); + } (fill, outline) } } diff --git a/crates/cdr/src/synth_cmx.rs b/crates/cdr/src/synth_cmx.rs index 8cb07aadb6..c70fd8545c 100644 --- a/crates/cdr/src/synth_cmx.rs +++ b/crates/cdr/src/synth_cmx.rs @@ -69,12 +69,25 @@ pub fn color(model: u8, values: &[u8]) -> Vec { /// A color entry with a property list in field 10 whose color record (part 1) holds `model` and /// the four value bytes `v` (R56). pub fn color_record(model: u16, v: [u8; 4]) -> Vec { + color_record_named(model, v, None) +} + +/// A color entry as [`color_record`], with a name part (part 3: a u32 count and UTF-16 units) +/// after the color when `name` is given (R56). +pub fn color_record_named(model: u16, v: [u8; 4], name: Option<&str>) -> Vec { let mut part = vec![1u8]; part.extend(12u32.to_le_bytes()); part.extend(model.to_le_bytes()); part.extend(5u16.to_le_bytes()); part.extend([0; 4]); part.extend(v); + if let Some(name) = name { + let units: Vec = name.encode_utf16().collect(); + part.push(3); + part.extend((4 + 2 * units.len() as u32).to_le_bytes()); + part.extend((units.len() as u32).to_le_bytes()); + part.extend(units.iter().flat_map(|u| u.to_le_bytes())); + } let mut rec = (part.len() as u32).to_le_bytes().to_vec(); rec.extend(part); fields(&[field(10, &rec)]) diff --git a/crates/cdr/tests/it/cmx.rs b/crates/cdr/tests/it/cmx.rs index 643df2779b..381eaddfcb 100644 --- a/crates/cdr/tests/it/cmx.rs +++ b/crates/cdr/tests/it/cmx.rs @@ -120,7 +120,8 @@ fn objects_before_any_layer_get_one() { let p = page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)]); let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); assert_eq!(d.pages[0].layers.len(), 1); - assert_eq!(d.pages[0].layers[0].name, "Layer 1"); + // The layer is left unnamed, as a `.cdr` drawing's is; the importer names it by its place. + assert_eq!(d.pages[0].layers[0].name, ""); } #[test] @@ -219,6 +220,31 @@ fn colors_of_other_models_and_missing_entries() { assert_eq!(shape(&objects[1]).fill, Some(Color::Rgb([0.0; 3]))); } +#[test] +fn gray_cmy_and_rgb_colors_of_the_older_fields() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[ + begin_page(None), + begin_layer("L", None), + square(&attrs(Some(1), None, false), 0, 0, 1000), + square(&attrs(Some(2), None, false), 0, 0, 1000), + square(&attrs(Some(3), None, false), 0, 0, 1000), + ])); + children.push(table(b"rclr", &[color(9, &[51]), color(4, &[255, 0, 51]), color(5, &[255, 0, 0])])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + let objects = &d.pages[0].layers[0].objects; + // The model holds objects front to back: the RGB square, the CMY one, then the gray one. + assert_eq!(shape(&objects[0]).fill, Some(Color::Rgb([1.0, 0.0, 0.0]))); + match (shape(&objects[1]).fill.clone(), shape(&objects[2]).fill.clone()) { + (Some(Color::Cmyk([c, m, y, k])), Some(Color::Gray(g))) => { + assert!((c - 1.0).abs() < 1e-6 && m == 0.0 && (y - 0.2).abs() < 1e-6 && k == 0.0, "{c} {m} {y} {k}"); + assert!((g - 0.8).abs() < 1e-6, "{g}"); + } + other => panic!("{other:?}"), + } +} + #[test] fn outline_arrowheads_are_reported() { let mut children = vec![cont(b'4', 1e-7)]; @@ -411,6 +437,115 @@ fn stray_letters_with_a_length_past_the_file_are_passed_over() { assert_eq!(d.pages[0].layers[0].objects.len(), 1); } +#[test] +fn a_dash_pattern_of_zero_lengths_draws_a_solid_line() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)])); + children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rdot") && !t.starts_with(b"rotl"))); + children.push(table(b"rdot", &[dashes(&[0, 0])])); + children.push(table(b"rotl", &[outline([3, 1, 2, 1, 1, 1])])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + let o = shape(&d.pages[0].layers[0].objects[0]).outline.clone().unwrap(); + assert!(o.dashes.is_empty(), "{:?}", o.dashes); +} + +#[test] +fn a_curve_field_that_lost_points_is_left_out() { + // Three points claimed, two whole points stored and the third cut inside its y: the type + // bytes can't be found, so no node types are read from coordinates. + let mut g = 3u16.to_le_bytes().to_vec(); + for (x, y) in [(0i32, 0i32), (1_000_000, 0)] { + g.extend(x.to_le_bytes()); + g.extend(y.to_le_bytes()); + } + g.extend(1_000_000i32.to_le_bytes()); + g.extend([0x40, 0x42]); + let c = instr(67, &fields(&[field(1, &attrs(Some(1), None, false)), field(2, &g)])); + let d = read_cmx(&file(&[page(&[begin_page(None), begin_layer("L", None), c])]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert!(d.pages[0].layers.is_empty(), "{:?}", d.pages[0].layers); +} + +#[test] +fn a_chunk_whose_id_has_a_digit_is_found_after_stray_bytes() { + // Stray bytes, a chunk the reader passes over whose id ends in a digit, then the page. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 6]; + b.extend(chunk(b"inf1", &[0; 70])); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn padding_and_ids_with_impossible_lengths_are_not_taken_for_chunks() { + // After stray bytes, four spaces with a small length, or letters with a length past the list, + // come before the page: neither is taken for a chunk, so the page is found. + for filler in [b" \x08\x00\x00\x00".to_vec(), b"junk\x40\x42\x0f\x00".to_vec()] { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(filler); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); + } +} + +#[test] +fn after_stray_bytes_a_chunk_the_reader_passes_over_keeps_what_it_holds() { + // Stray bytes, then a chunk the reader passes over whose body starts with the letters of a + // page chunk, then the page: only the page is read. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut inner = b"page".to_vec(); + inner.extend(4u32.to_le_bytes()); + inner.extend([0; 10]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &inner)); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_canvas_or_a_container_is_reported() { + for bit in [8u8, 16] { + let mut a = attrs(Some(1), None, false); + a[0] |= bit; + let p = page(&[begin_page(None), begin_layer("L", None), square(&a, 0, 0, 1000), end_layer()]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert_eq!(d.warnings, vec![Warning::UnsupportedObjects], "{bit}"); + assert!(shape(&d.pages[0].layers[0].objects[0]).fill.is_some()); + } +} + +#[test] +fn a_library_color_with_its_name_reads_as_a_spot_color() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)])); + children.push(table(b"rclr", &[color_record_named(5, [0, 0, 255, 0], Some("Brick 12"))])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + match shape(&d.pages[0].layers[0].objects[0]).fill.clone() { + Some(Color::Spot { name, tint, look }) => { + assert_eq!((name.as_str(), tint), ("Brick 12", 1.0)); + assert!(look.is_some()); + } + other => panic!("{other:?}"), + } +} + proptest! { #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] diff --git a/crates/engine/src/cmd/fileio/tests_cmx.rs b/crates/engine/src/cmd/fileio/tests_cmx.rs index d374737143..527c0be1be 100644 --- a/crates/engine/src/cmd/fileio/tests_cmx.rs +++ b/crates/engine/src/cmd/fileio/tests_cmx.rs @@ -122,3 +122,24 @@ fn files_that_are_not_read_say_why() { let e = open_bytes(&mut s, "d.cmx", b"not a cmx file", None).unwrap_err().to_string(); assert!(e.contains("this CMX file can't be read (not a CMX file)"), "{e}"); } + +#[test] +fn a_layer_without_a_name_is_named_by_its_place() { + // An empty layer, which is left out, then a layer named only by spaces: it comes in unnamed, + // and the importer numbers it by its place among the layers it keeps, as for a `.cdr` drawing. + let p = page(&[ + begin_page(None), + begin_layer("Grid", None), + end_layer(), + begin_layer(" ", None), + square(&attrs(Some(2), None, false), 0, 0, 1000), + end_layer(), + ]); + let mut children = vec![cont(b'4', 1e-7), p]; + children.extend(tables()); + let mut s = Session::new(); + let r = open_bytes(&mut s, "drawing.cmx", &riff(&children), None).unwrap(); + assert!(warnings(&r).is_empty(), "{r}"); + let names: Vec = s.doc().unwrap().doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, ["Layer 1"]); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 9f7fe56646..61a01148a8 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -21,7 +21,7 @@ Ordinary File > Save offers Save As when its own location refuses writes with a | | Illustrator | VectorCraft | Notes | |---|---:|---:|---| -| Formats opened or placed | ~30 | 34 | missing: FreeHand, DWG; extra: `.cmx` | +| Formats opened or placed | ~30 | 34 | missing: FreeHand, DWG | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, gradients, patterns, images, type, symbols, artboards, transparency, opacity masks, clipping, text wrap options) or as legacy version 7 (layers and groups, one artboard per file) | | Formats exported | ~16 | 18 | missing: DWG; extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | | **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting | @@ -336,7 +336,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` | | FreeHand `.fh*` | open (legacy) | no | no | | | `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, clipping containers, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; hidden and locked layers, groups and objects; the winding flag as the nonzero fill rule; uniform transparency of version 13 on as opacity and blend mode; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses, other transparency and merge modes without a blend mode are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies; version 3 envelopes are not applied, so the objects and groups under one keep their outlines and matrices, with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; after an open with a warning, an export or Save As to the drawing's own path needs `acknowledgeLoss: true`; record layouts and their sources in `crates/cdr/PROVENANCE.md`; synthetic test files only; tests in `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` | -| `.cmx` exchange files | no (not in the [supported formats](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/supported-file-formats-in-illustrator.html) list) | yes (files with 32-bit coordinates: pages, layers, groups, curves, uniform fills and outlines with their width, color, caps, joins and dashes; text, images, rectangles, ellipses, clipping paths, other fills and arrowheads are left out with a warning, and lenses are not applied, with a warning; big-endian files and files with 16-bit coordinates are refused) | no | File › Place reads them too; after an open with a warning, an export or Save As to the file's own path needs `acknowledgeLoss: true`; layouts and their sources in `crates/cdr/PROVENANCE.md` (R53 to R63); synthetic test files only; tests in `crates/cdr/tests/it/cmx.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs` and `crates/engine/tests/import_fuzz.rs` | +| `.cmx` exchange files | | yes (files with 32-bit coordinates: pages, layers, groups, curves, uniform fills and outlines with their width, color, caps, joins and dashes; text, images, rectangles, ellipses, clipping paths, other fills and arrowheads are left out with a warning, and lenses are not applied, with a warning; big-endian files and files with 16-bit coordinates are refused) | no | File › Place reads them too; after an open with a warning, an export or Save As to the file's own path needs `acknowledgeLoss: true`; layouts and their sources in `crates/cdr/PROVENANCE.md` (R53 to R63); synthetic test files only; tests in `crates/cdr/tests/it/cmx.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs` and `crates/engine/tests/import_fuzz.rs` | | Text `.txt` | place, export | place (Text Import Options) | yes | place reads Unicode and ANSI, and Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European through the WHATWG Encoding Standard's decoders (VectorCraft's own mapping); `tests/textimport.rs`, `place/text.rs`; fuzzed (`text_import_fuzz.rs`) | | RTF `.rtf` | place | place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only | | Word `.docx` | place | place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out | diff --git a/docs/mcp.md b/docs/mcp.md index f6532754bf..041747af0c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10197,12 +10197,13 @@ its header fit the file. A RIFF file that names a version before 3 is refused wi `.cmx` exchange files with 32-bit coordinates open and place as editable art, found by their content whatever their extension. Each page becomes an artboard, side by side, at the size the page gives. A page that gives no size takes -the size of the drawing's bounds stored with it, centered on the art, or 612 × 792 pt when it stores none either. -Layers keep their names, and a layer that holds nothing is left out. Groups stay groups, and curves become paths with -their uniform fills and outlines: colors in CMYK or RGB, and library colors stored with their names as spot swatches; -outline widths, caps, joins, dashes, an outline behind the fill and an outline scaled with the object. Text, images, +the size of the drawing's bounds stored with it, centered on the art, or 612 × 792 pt (VectorCraft's own size, as +for a `.cdr` page without one) when it stores none either. Layers keep their names, a layer without one is named by +its place as in a `.cdr` drawing, and a layer that holds nothing is left out. Groups stay groups, and curves become +paths with their uniform fills and outlines: colors in CMYK, CMY, RGB or gray, and library colors stored with their +names as spot swatches; outline widths, caps, joins, dashes, an outline behind the fill and an outline scaled with the object. Text, images, rectangles, ellipses, clipping paths and other objects the reader doesn't read yet, fills other than uniform ones and -outline arrowheads are left out, and lenses are not applied. The objects a clipping path clips come in without it. The +outline arrowheads are left out, and lenses, canvases and containers are not applied. The objects a clipping path clips come in without it. The `warnings` of `document.open` name each of these kinds the file had, and say when damaged parts or parts past the import limits were left out. Files in big-endian byte order and files with 16-bit coordinates are refused with a message. VectorCraft doesn't write `.cmx` files. After a file opens with warnings, an export or Save As to its own path