mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-24 11:23:43 +01:00
File formats: open and place .cdr drawings, versions 1 to 27
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.
This commit is contained in:
1 parent
10ea235ee4
commit
59db4313b1
61 files changed
+7844
-13
No files matched your search
Generated
+11
@@ -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",
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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"] }
|
||||
@@ -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.
|
||||
@@ -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) |
|
||||
@@ -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.
|
||||
@@ -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<Warning>,
|
||||
/// Fill and outline records by id, decoded on first use.
|
||||
fill_chunks: HashMap<u32, &'b [u8]>,
|
||||
outline_chunks: HashMap<u32, &'b [u8]>,
|
||||
fills: HashMap<u32, Option<Color>>,
|
||||
outlines: HashMap<u32, Option<Outline>>,
|
||||
}
|
||||
|
||||
pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Drawing, Error> {
|
||||
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<Warning>) -> Vec<Guideline> {
|
||||
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<Guideline> {
|
||||
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<Object>,
|
||||
/// 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<Guideline>) -> Vec<Object> {
|
||||
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<Guideline>, outer: &Matrix) -> Option<Object> {
|
||||
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<Object> {
|
||||
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<Geometry> {
|
||||
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<Color> {
|
||||
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<Outline> {
|
||||
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<u32> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<const N: usize>(&mut self) -> Option<[u8; N]> {
|
||||
self.bytes(N)?.try_into().ok()
|
||||
}
|
||||
|
||||
pub(crate) fn u8(&mut self) -> Option<u8> {
|
||||
Some(self.array::<1>()?[0])
|
||||
}
|
||||
|
||||
pub(crate) fn u16(&mut self) -> Option<u16> {
|
||||
self.array().map(u16::from_le_bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn i16(&mut self) -> Option<i16> {
|
||||
self.array().map(i16::from_le_bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn u32(&mut self) -> Option<u32> {
|
||||
self.array().map(u32::from_le_bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn i32(&mut self) -> Option<i32> {
|
||||
self.array().map(i32::from_le_bytes)
|
||||
}
|
||||
|
||||
/// A finite f64; NaN and the infinities read as `None`.
|
||||
pub(crate) fn f64(&mut self) -> Option<f64> {
|
||||
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<u32> {
|
||||
Rd::at(b, pos).u32()
|
||||
}
|
||||
@@ -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<Warning>) -> Option<Path> {
|
||||
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<Warning>) -> Option<Path> {
|
||||
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<Warning>) -> Option<Path> {
|
||||
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<SubPath> = None;
|
||||
// The last two control points: a curve end uses only those.
|
||||
let mut controls: Vec<Pt> = 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<Geometry> {
|
||||
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<Geometry> {
|
||||
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<Geometry> {
|
||||
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<Warning>) -> Option<Geometry> {
|
||||
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<Pt> = (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<u8> {
|
||||
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<Pt> {
|
||||
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<Pt> = [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))));
|
||||
}
|
||||
}
|
||||
@@ -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<Warning>) -> Option<Placement> {
|
||||
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<Warning>) -> Option<Option<Color>> {
|
||||
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<Warning>) -> Option<Option<Outline>> {
|
||||
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<f64> = 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<u8> {
|
||||
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<u8> {
|
||||
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::<f64>::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);
|
||||
}
|
||||
}
|
||||
@@ -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<usize>,
|
||||
/// 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<Profile> {
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -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<Drawing, Error> {
|
||||
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)
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Segment>,
|
||||
pub closed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Path {
|
||||
pub subpaths: Vec<SubPath>,
|
||||
}
|
||||
|
||||
/// 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<f64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Shape {
|
||||
pub geometry: Geometry,
|
||||
pub matrix: Matrix,
|
||||
pub fill: Option<Color>,
|
||||
pub outline: Option<Outline>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Object {
|
||||
Shape(Box<Shape>),
|
||||
Group(Vec<Object>),
|
||||
}
|
||||
|
||||
/// 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<Object>,
|
||||
pub guides: Vec<Guideline>,
|
||||
}
|
||||
|
||||
#[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<Layer>,
|
||||
}
|
||||
|
||||
/// 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<Page>,
|
||||
/// Layers every page shows, from the master page.
|
||||
pub master: Vec<Layer>,
|
||||
/// Guidelines every page shows, kept outside any layer.
|
||||
pub guides: Vec<Guideline>,
|
||||
pub warnings: Vec<Warning>,
|
||||
}
|
||||
@@ -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<Streams<'a>>), 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<Cow<'a, [u8]>, 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<Option<usize>>,
|
||||
/// Each member's bytes once read, so that streams naming one member read it once.
|
||||
loaded: Vec<OnceCell<Slot<'a>>>,
|
||||
member_limit: usize,
|
||||
/// A stream, or a chunk's bytes in one, could not be found.
|
||||
damaged: Cell<bool>,
|
||||
}
|
||||
|
||||
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<usize> {
|
||||
*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<usize> {
|
||||
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<usize>) -> 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<Warning>) {
|
||||
if self.damaged.get() {
|
||||
push(warn, Warning::Damaged);
|
||||
}
|
||||
if self.loaded.iter().any(|s| matches!(s.get(), Some(Slot::PastLimit))) {
|
||||
push(warn, Warning::TooDeep);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<usize> {
|
||||
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<f64> {
|
||||
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<f64> {
|
||||
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<Warning>) -> Option<Loda<'a>> {
|
||||
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<Matrix> {
|
||||
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<f64> {
|
||||
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<Matrix> {
|
||||
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<Warning>) -> Option<Color> {
|
||||
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<Warning>) -> 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<Warning>) -> 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<Warning>) -> 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<Warning>) -> Option<String> {
|
||||
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<u16> = 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<u16> = 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<Warning>) -> Option<Color> {
|
||||
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<f32> {
|
||||
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<Warning>) -> Option<(u32, Option<Color>)> {
|
||||
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<Warning>) -> Option<(u32, Option<Outline>)> {
|
||||
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<f64> = (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<Warning>) -> 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<T: Copy + Into<u64>>(units: impl Iterator<Item = T> + Clone, warn: &mut Vec<Warning>) -> (Vec<T>, Option<u64>) {
|
||||
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<u64>) -> 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::<Vec<u8>>() } 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<u8> = 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<u8> = 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<u8> = [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);
|
||||
}
|
||||
}
|
||||
@@ -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<u8>,
|
||||
chunks: Vec<Chunk>,
|
||||
/// 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<Streams<'a>>,
|
||||
/// Bytes that inflating may still produce.
|
||||
left: Cell<usize>,
|
||||
/// The bytes redirected lists have taken: (package member, start) to end.
|
||||
lists: Cell<BTreeMap<(usize, usize), usize>>,
|
||||
/// The bytes other redirected chunks have taken, the same way.
|
||||
leaves: Cell<BTreeMap<(usize, usize), usize>>,
|
||||
/// Bytes that redirects to bytes another chunk already took may still read.
|
||||
shared_left: Cell<usize>,
|
||||
}
|
||||
|
||||
/// 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<u16> {
|
||||
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<Streams<'a>>, budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Self, Error> {
|
||||
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<Warning>) {
|
||||
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<Pending>, budget: &mut Budget, warn: &mut Vec<Warning>) -> 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<Chunk> {
|
||||
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<Read> {
|
||||
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<BTreeMap<(usize, usize), usize>>, 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<Warning>, w: Warning) {
|
||||
if !warn.contains(&w) {
|
||||
warn.push(w);
|
||||
}
|
||||
}
|
||||
@@ -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<u8>),
|
||||
List([u8; 4], Vec<Node>),
|
||||
}
|
||||
|
||||
pub fn chunk(id: &[u8; 4], data: Vec<u8>) -> Node {
|
||||
Node::Chunk(*id, data)
|
||||
}
|
||||
|
||||
pub fn list(form: &[u8; 4], children: Vec<Node>) -> Node {
|
||||
Node::List(*form, children)
|
||||
}
|
||||
|
||||
fn put(out: &mut Vec<u8>, 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<u8> {
|
||||
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<u32>) -> Vec<u8> {
|
||||
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<u8> {
|
||||
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<u8> = children.iter().flat_map(|c| pooled(c, &mut pool)).collect();
|
||||
let sizes: Vec<u8> = 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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8>)]) -> Vec<u8> {
|
||||
let w = if self.short() { 2 } else { 4 };
|
||||
let head = 5 * w;
|
||||
let mut body: Vec<u8> = 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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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>) -> 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<u8>)], 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>) -> Node {
|
||||
let name: Vec<u8> =
|
||||
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>) -> 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<Node> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> = [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<u8>,
|
||||
pub deflate: bool,
|
||||
}
|
||||
|
||||
fn deflate(data: &[u8]) -> Vec<u8> {
|
||||
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<u8> {
|
||||
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<u8>, deflate: bool) -> Vec<u8> {
|
||||
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<n>.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<u8> {
|
||||
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<u8> {
|
||||
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<Member> {
|
||||
let mut streams: Vec<(String, Vec<u8>)> = 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<String> = 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<u8>)], moved_lists: &[[u8; 4]]) -> Vec<u8> {
|
||||
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<u8> {
|
||||
let v = V(300);
|
||||
let (kind, body): (u8, Vec<u8>) = 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<u8> {
|
||||
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<u8>]) -> Vec<u8> {
|
||||
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<u8> {
|
||||
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)
|
||||
}
|
||||
@@ -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<Drawing, Error> {
|
||||
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<Warning>) -> Option<Object> {
|
||||
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<Warning>) -> Option<Option<Shape>> {
|
||||
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<Warning>| 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<Geometry> {
|
||||
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, Error> {
|
||||
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::<Vec<u8>>();
|
||||
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]));
|
||||
}
|
||||
}
|
||||
@@ -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<Entry<'a>>,
|
||||
/// The entries in name order, for lookups.
|
||||
by_name: Vec<usize>,
|
||||
}
|
||||
|
||||
/// 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<Self, Error> {
|
||||
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<usize> = (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<usize> {
|
||||
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<Cow<'a, [u8]>, 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<usize> {
|
||||
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<Entry<'a>, 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());
|
||||
}
|
||||
}
|
||||
@@ -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<u8> {
|
||||
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]);
|
||||
}
|
||||
}
|
||||
@@ -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<n>` in `text`.
|
||||
fn ids(text: &str) -> BTreeSet<u32> {
|
||||
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<u32> = 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]));
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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 }
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<String>)> {
|
||||
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<String> = 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<Placed>,
|
||||
/// 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<Arc<Node>>)> = 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<usize>> = 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<usize> = 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<Arc<Node>> = 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<Arc<Node>>)>) {
|
||||
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<u32>) {
|
||||
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<Node>>) -> Arc<Node> {
|
||||
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)
|
||||
}
|
||||
@@ -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<Warning>,
|
||||
/// 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<Guide>,
|
||||
/// Guidelines at other angles, as guide paths.
|
||||
pub(super) guide_paths: Vec<Arc<Node>>,
|
||||
/// 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<f32>)>,
|
||||
spot_index: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
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<Color> {
|
||||
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<Arc<Node>> {
|
||||
self.objects_at(objects, to_doc, 0)
|
||||
}
|
||||
|
||||
fn objects_at(&mut self, objects: &[cd::Object], to_doc: Affine, depth: usize) -> Vec<Arc<Node>> {
|
||||
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<Arc<Node>> {
|
||||
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<f64> = 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<bool> = 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<LiveShape>)> {
|
||||
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<String> = 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<Point> = 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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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<Loaded>
|
||||
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<St
|
||||
.cloned()
|
||||
.collect();
|
||||
let source_path = path.clone().filter(|_| !losses.is_empty());
|
||||
// A template (saved by Save as Template, or an .ait/.vctemplate file) opens as a new untitled
|
||||
// document.
|
||||
let template = as_template || doc.template || matches!(format.id, "ait" | "template");
|
||||
// A template (saved by Save as Template, or an .ait, .vctemplate or .cdt file) opens as a new
|
||||
// untitled document.
|
||||
let template = as_template || doc.template || matches!(format.id, "ait" | "template" | "cdt");
|
||||
if template {
|
||||
doc.template = false;
|
||||
doc.title = s.next_untitled();
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
//! `.cdr` drawings: Open, Place and New from Template, by extension and by content, mapped to
|
||||
//! artboards, layers, guides, live shapes, solid paint and strokes.
|
||||
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use vectorcraft_cdr::synth::{self, V, chunk, list};
|
||||
use vectorcraft_doc::{LiveShape, Node, NodeKind};
|
||||
|
||||
fn walk(nodes: &[std::sync::Arc<Node>], out: &mut Vec<Node>) {
|
||||
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<Node> {
|
||||
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<String> = 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<String> = 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<f64> = 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<String> = 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<String> = 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<usize> = 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<String> = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, ["A", "B", "A"], "bottom to top");
|
||||
let got: Vec<usize> = 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<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());
|
||||
}
|
||||
@@ -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::<u8>()), 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::<usize>(), 0usize..8192, any::<u8>()), 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::<u8>(), 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::<u8>()), 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::<u8>(), 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"]
|
||||
|
||||
@@ -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}`
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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})
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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})
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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})
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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})
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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})
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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 सेट के साथ शुरू होता है।
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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})
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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})
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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})을 사용합니다
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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})
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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})
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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})
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 5 and column 25.
|
@@ -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]
|
||||
|
||||
@@ -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})
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 5 and column 25.
|
@@ -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})
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 182 and column 5.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 204 and column 5.
|
@@ -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})
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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})
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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 |
|
||||
|
||||
@@ -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 |
|
||||
|
||||
+25
-1
@@ -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.<id>"` 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.<id>"` 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 `<name>_<artboard>.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: <reason>` 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
|
||||
|
||||
@@ -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`).
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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).
|
||||
|
||||
Reference in new issue
Block a user