CDR import: hidden and locked art, fill rule, outline spot colors and uniform transparency

- Layers, groups and objects open hidden and locked from their flags (bit
  0x01 of byte 1, bit 0x10 of byte 0). Layers of one name merged across
  pages are hidden or locked only when all of them are; otherwise their
  art is, object by object. A clipped group's flags reach its objects.
  Hidden guidelines go on a hidden "Hidden guides" layer, and the other
  guides on the top shown layer.
- Byte 0 of argument 14001 other than 0 fills the shape with the nonzero
  rule; other shapes stay even-odd.
- From version 13 an outline's property list record that names a library
  color gives the outline that spot color.
- From version 13 a uniform transparency (a 117-byte record of version
  1300 in argument 8000) becomes the object's opacity, read as the
  transparency in percent, and its merge mode the blend mode where one
  matches. Lenses, other records and other merge modes keep the warning.
- A cdr8 file is the 8.01 variant whatever its vrsn chunk names. The
  argument 200 style id and the spnd id are u16 before version 6. A trfd
  entry ends at the next offset. A version 15 corner radius is held to
  half the shorter side.
- PROVENANCE.md adds source KF, the MIT-licensed fork of the
  specification by Zach Wolfe, and rows R51 and R52; LICENSE-kaitai.txt
  and NOTICE credit it.
This commit is contained in:
dotCooCoo committed 2026-11-14 16:31:24 -08:00
1 parent 676628015b
commit ca804d921e
18 files changed
+1084 -142

No files matched your search

+3 -2
View File
@@ -36,8 +36,9 @@ WebAssembly plug-ins run in the wasmi interpreter (MIT OR Apache-2.0); its wasmp
under the Apache License 2.0 with the LLVM exception.
The .cdr reader (crates/cdr) reads the record layouts that the Kaitai Struct specification
coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy, MIT License) describes. No part
of the specification is copied into the crate; its license text is in crates/cdr/LICENSE-kaitai.txt.
coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy, MIT License) and its fork by Zach
Wolfe (https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, MIT License) describe. No part
of either specification is copied into the crate; the license text is in crates/cdr/LICENSE-kaitai.txt.
Builds made with craft-fonts (the CRAFT_FONTS_DIR build option; all official releases) embed the
fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (BIZ UDPGothic,
+5
View File
@@ -5,6 +5,11 @@ specification `coreldraw_cdr.ksy`
license below. No part of that specification is copied into this crate;
`PROVENANCE.md` cites it by line.
Some layouts are also taken from the fork of that specification by Zach Wolfe
(https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, commit
2189b68f07e0cafe9afec3dcf699ebc0342144c7), which is published under the same
license and copyright notice.
MIT License
Copyright (c) 2020 Kaitai team
+12 -7
View File
@@ -7,6 +7,9 @@ Sources:
- **K**: the Kaitai Struct specification `coreldraw_cdr.ksy` (MIT, notice in `LICENSE-kaitai.txt`),
https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/coreldraw_cdr.ksy
- **KF**: the fork of K by Zach Wolfe, `filestar/coreldraw_cdr.ksy`, branch `new_stuff`, under the same
MIT license and notice as K (`LICENSE-kaitai.txt`),
https://github.com/filestar/coreldraw_cdr.ksy/blob/2189b68f07e0cafe9afec3dcf699ebc0342144c7/coreldraw_cdr.ksy
- **KR**: the README and the `bin/cdr-unpk` script of the Kaitai Struct specification (MIT), at
the same commit as K,
https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/README.md
@@ -36,7 +39,7 @@ Sources:
https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/atlas-atlas/cdr/ab_en_br.cdr
- **DM**: the clip art of https://discmaster.textfiles.com/browse/31541, by file name
Status: `public-spec` (K, KR, Z, F or PR), `sample` (S), `unconfirmed` (a point no source states
Status: `public-spec` (K, KF, KR, Z, F or PR), `sample` (S), `unconfirmed` (a point no source states
and no sample file shows; listed so it can be checked against a file, with what the reader does
when it is wrong).
@@ -48,7 +51,7 @@ file is committed.
| Id | What the code relies on | Source | Status |
|---|---|---|---|
| R1 | `RIFF`, the body length, then the form type `CDR` or `cdr` and a version character: `1` to `9`, `A` (10) to `H` (17), `J` (18) on, `I` unused; `cdr8` is 8.01, `CDR ` is 3, `CDRX` is another format. Files of versions 23 to 25 carry `O` (23), `P` (24), `Q` (24.3, with a `vrsn` of 2430) and `R` (25), which count differently from the version 24 update on, so their `vrsn` chunk decides (R2) | K L68-L133; S: LT `testset/23` to `testset/25`, such as `circle_redfill_nooutline_cdr25.cdr` | public-spec (letters from version 23: sample; letters of versions 26 and 27: unconfirmed, and the `vrsn` chunk decides when the file has one) |
| R1 | `RIFF`, the body length, then the form type `CDR` or `cdr` and a version character: `1` to `9`, `A` (10) to `H` (17), `J` (18) on, `I` unused; `cdr8` is 8.01 from the form type alone, whatever its `vrsn` chunk names, `CDR ` is 3, `CDRX` is another format. Files of versions 23 to 25 carry `O` (23), `P` (24), `Q` (24.3, with a `vrsn` of 2430) and `R` (25), which count differently from the version 24 update on, so their `vrsn` chunk decides (R2) | K L68-L133; S: LT `testset/23` to `testset/25`, such as `circle_redfill_nooutline_cdr25.cdr` | public-spec (letters from version 23: sample; letters of versions 26 and 27: unconfirmed, and the `vrsn` chunk decides when the file has one) |
| R2 | `vrsn`: the version as a u16, in hundreds | K L276-L278 | public-spec |
| R3 | `LIST cmpr`: two (compressed, uncompressed) u32 pairs, then two blocks of `CPng`, `01 00 04 00` and a zlib stream; the first inflates to the chunk stream, the second to a pool of u32 sizes that each chunk's size field indexes | K L193-L220, L2626-L2682 | public-spec |
| R4 | A chunk is an id, a u32 size and the body, padded to an even length; a `LIST` body starts with its form type; from version 7 a `LIST stlt` holds the style tables, not chunks | K L68-L78, L135-L155, L307-L334 | public-spec |
@@ -59,14 +62,14 @@ file is committed.
| R9 | Name argument (1000): Windows-1252 up to a NUL before version 12, UTF-16LE from it | K L601-L630 | public-spec |
| R10 | `mcfg`: 12 bytes (13 on), 4 (9 to 12), 28 (6) or none, then the page width and height as coordinates | K L1670-L1765 | public-spec |
| R11 | `fild` (`fill` before 7): id; from 13 a record tagged 1300 with its length, which records tagged 2400 or more may precede; the fill type u16 (0 none, 1 uniform, others not read); uniform: 2 bytes then a color before 13, from 13 a record tagged 1300 holding a property list (u8 type, u32 length, body; 0 ends it; 1 a color, 8 a palette id and a UTF-16 name, 3 a UTF-16 name) | K L1025-L1302; S: LT `testset/15` to `testset/25` `circle_redfill_nooutline_cdr<version>.cdr`, whose fill records hold a record tagged 2400 before the one tagged 1300 | public-spec (2400 records: sample) |
| R12 | `outl`: id; from 13 records (u32 id, u32 length, body) up to id 1, whose body follows; line type, caps and join u16; 2 bytes (6 to 12); width; stretch u16; 2 bytes (6 on); nib angle; 52 bytes (6 to 12) or 46 (13 on); the color; 16 bytes (10 before 6); the dash count u16 and the dashes, in multiples of the width; the arrowhead ids 22 bytes after the first dash in versions 6 to 12, 20 bytes from 13. Caps 0 butt, 1 round, 2 square; joins 0 miter, 1 round, 2 bevel | K L954-L1024; S: caps and joins in UC `outl_line_caps_cdr7.cdr` and `outl_corner_cdr7.cdr`; arrowhead ids, matched against the drawing's `arrw` records, in TP `web_cd.cdr` (6), UC `rogan_logo_cdr7.cdr`, `rogan_logo_cdr8.cdr` and `rogan_logo_cdr11.cdr`, NR `ab_en_br.cdr` (9) and `banff_ap_en.cdr` (10), TDF 76820 (12) and 140638 (13) | public-spec (caps, joins and arrowhead places: sample; arrowheads before version 6: no sample names one, and the reader does not look for them) |
| R12 | `outl`: id; from 13 records (u32 id, u32 length, body) up to id 1, whose body follows; a record of id 2 holds a property list laid out as R11's, and the reader takes the outline's color from it when it names a library color; line type, caps and join u16; 2 bytes (6 to 12); width; stretch u16; 2 bytes (6 on); nib angle; 52 bytes (6 to 12) or 46 (13 on); the color; 16 bytes (10 before 6); the dash count u16 and the dashes, in multiples of the width; the arrowhead ids 22 bytes after the first dash in versions 6 to 12, 20 bytes from 13. Caps 0 butt, 1 round, 2 square; joins 0 miter, 1 round, 2 bevel | K L954-L1024; KF L1225-L1249 (the id 2 record); S: caps and joins in UC `outl_line_caps_cdr7.cdr` and `outl_corner_cdr7.cdr`; arrowhead ids, matched against the drawing's `arrw` records, in TP `web_cd.cdr` (6), UC `rogan_logo_cdr7.cdr`, `rogan_logo_cdr8.cdr` and `rogan_logo_cdr11.cdr`, NR `ab_en_br.cdr` (9) and `banff_ap_en.cdr` (10), TDF 76820 (12) and 140638 (13) | public-spec (caps, joins and arrowhead places: sample; arrowheads before version 6: no sample names one, and the reader does not look for them; the id 2 record: no sample names a library color in it, and a wrong guess changes only the outline's color) |
| R13 | Bit 0 of the outline's line type: no outline | S: LT `square_blackfill_nooutline_cdr<version>.cdr` and the other `nooutline` files of `testset/15` to `testset/25`, whose outline records all have line type 1 and whose pictures show no outline | sample |
| R14 | A color record from version 5: model u16, palette u16, 4 bytes, four value bytes. Models: 2 CMYK in percent, 3 and 17 CMYK 0 to 255, 4 CMY 0 to 255, 5 blue, green, red, 9 gray 0 to 255, 20 registration, 21 blue, green, red and a tint in percent already applied; 1, 14 and 25 a library color's number (u16) and tint in percent (u16) | K L2856-L2965; S: model 25 in LT `testset/12/square_pantoneblackfill_nooutline.cdr` (number 14, tint 100), model 1 in UC `rogan_logo_cdr11.cdr` (number 4, tint 50) | public-spec (library values of models 1 and 25: sample; model 14: unconfirmed, and its color opens as a spot color without a look) |
| R15 | Rectangle coordinates: width, height and one radius, three more radii from version 9, running counterclockwise from the corner at (width, 0) | K L674-L700 | public-spec |
| R16 | Point list: u32 count (before version 6 as R39 gives it), the points, then one type byte each, the count held to what fits; type bits 7 and 6 move, line, curve end, control point; bit 3 closes the subpath | K L782-L787, L840-L845, L2701-L2807 | public-spec |
| R17 | Ellipse coordinates: width, height, start and end angles, pie flag (u16 before 6, else u32); the radii are half the width and height; the angles turn from the ellipse's own axes, which a negative width or height points the other way | K L754-L781; S: the pies of negative height in the ellipse-sector drawings of versions 12 and 13 in UC | public-spec (axis direction of a negative size: sample) |
| R18 | Polygon argument (11000): 4 bytes before 13, the side count u32, the next point u32 (the u32 after it when it is 0 or 1, else 4 bytes), 4 more from 13, rx and ry f64, the centre; the base curve is one side on a circle of 1000 mm from the top vertex to the vertex it runs to clockwise, copied once for each side | K L631-L655; S: the polygons and stars of UC `shapes_cdr10.cdr` | public-spec (base curve: sample) |
| R19 | `flgs`: byte 3 the record type, byte 2 marks the master page. A layer's own `loda` names what it is by its object type: 11 a grid, 12 guides, 17 the desktop, any other a drawing layer (version 3 one less, R32). Only a layer without a `loda` is taken by the low four bits of its byte 0: 0x0a guides, or a grid when bit 0x10 is also set; in versions 7 to 13 0x02 the same way; 0x08 the desktop when byte 2 is set and a drawing layer when it is clear; any other a drawing layer, except [0, 1, 1] in versions 7 to 13, the desktop | K L1602-L1639 (record types); S: in every sample file of versions 3 to 25 the layer's object type agrees with its name; byte 0 does not: TDF 114901 (version 8) flags its master page's guides [2, 1, 1], desktop [0, 1, 1], grid [0x12, 0, 1] and drawing layer [8, 1, 0], and NR `ab_en_br.cdr` (version 9) flags drawing layers 0x10 and its guides 0x1a; over the sample files of versions 3 to 25, drawing layers carry 0, 0x10, 0x40, or 0x08, 0x18 or 0x58 with byte 2 clear, desktop layers 0x08, 0x18 or 0x48 with byte 2 set, guides 0x0a, 0x4a, 0x02 or (in `ab_en_br.cdr`) 0x1a, and grids 0x1a, 0x5a or 0x12 | public-spec (layer types: sample; byte 0 of a layer without a `loda`: unconfirmed, as no sample has such a layer, and a wrong guess drops or shows that layer's objects) |
| R19 | `flgs`: byte 3 the record type, byte 2 marks the master page. On a layer, group or object, bit 0x01 of byte 1 hides it and bit 0x10 of byte 0 locks it. A layer's own `loda` names what it is by its object type: 11 a grid, 12 guides, 17 the desktop, any other a drawing layer (version 3 one less, R32). Only a layer without a `loda` is taken by the low four bits of its byte 0: 0x0a guides, or a grid when bit 0x10 is also set; in versions 7 to 13 0x02 the same way; 0x08 the desktop when byte 2 is set and a drawing layer when it is clear; any other a drawing layer, except [0, 1, 1] in versions 7 to 13, the desktop | K L1602-L1639 (record types); KF L1831-L1866 (the hidden and lock bits); S: every grid layer of versions 14 to 25 in the sample files (631) carries byte 1 = 1, and 206 of the 927 of versions 7 to 13 do; desktop layers carry byte 1 = 0 except TDF 114901's [0, 1, 1]; the drawing layers with byte 1 = 1 (TDF 114901, NR `banff_ap_en.cdr` and `symbology_en.cdr`) also carry bit 0x08; of the group and object lists in the sample files, only one object of TDF 60491 (version 14) sets either bit, the lock bit; in every sample file of versions 3 to 25 the layer's object type agrees with its name; byte 0 does not: TDF 114901 (version 8) flags its master page's guides [2, 1, 1], desktop [0, 1, 1], grid [0x12, 0, 1] and drawing layer [8, 1, 0], and NR `ab_en_br.cdr` (version 9) flags drawing layers 0x10 and its guides 0x1a; over the sample files of versions 3 to 25, drawing layers carry 0, 0x10, 0x40, or 0x08, 0x18 or 0x58 with byte 2 clear, desktop layers 0x08, 0x18 or 0x48 with byte 2 set, guides 0x0a, 0x4a, 0x02 or (in `ab_en_br.cdr`) 0x1a, and grids 0x1a, 0x5a or 0x12 | public-spec (layer types: sample; byte 0 of a layer without a `loda`: unconfirmed, as no sample has such a layer, and a wrong guess drops or shows that layer's objects; bit 0x10 is also the lock bit, so a locked guides layer without a `loda` reads as a grid) |
| R20 | Fill and outline arguments (20, 10): a u32 record id | K L452-L460, L548-L556 | public-spec |
| R21 | Page size argument (19130): width and height | K L666-L672 | public-spec |
| R22 | `LIST page` holds `LIST layr` lists, directly or in a list it holds (a `LIST gobj` in the samples); a layer holds `LIST obj ` and `LIST grp `; a page, layer or object keeps its own `loda` (and an object its `trfd`, in a `trfl` list) among its chunks or in a `LIST lgob` | K L1602-L1639 (record types); S: the chunk trees of every sample file of versions 3 to 25 | sample |
@@ -92,9 +95,11 @@ file is committed.
| R42 | The records of a file of version 1 or 2 run from the front of the stacking order to the back. Every record starts with the u32 24. A group or layer record is 28 bytes, and bit 0x40 of its flags byte at 26 is clear. A drawn object has that bit set (0x40 in files with the markers `e` and `m`, 0xc0 with `l`) and a u16 body size at byte 28; it is the body size plus 32 bytes long. A drawn object of another type than those of R43 gives its length otherwise, and the records after it are not read | S: TP `WI.CDR`, `FLAG.CDR`, `MENU.CDR` and `DRINKS.CDR`; the order checked against the picture of `MENU.CDR` | sample |
| R43 | A drawn object of version 1 or 2: a point (two i16) at byte 32; six i32 in 16.16 fixed point at 36, `a b tx c d ty`, with x' = a x + b y + tx + the point's x and y' = c x + d y + ty + the point's y; the object type at 60 (0 rectangle, 1 ellipse, 2 curve, 3 text); a byte at 67 that is not 0 when the object is outlined, the outline's width (u16) at 68 and its color at 74; the fill type (0 none, 1 uniform) and its color after it, at 94 and 95 with the marker `e` and at 105 and 106 with `l` and `m`; the shape from byte 114 with `e` and 136 with `l` and `m`. Colors are as R36 | S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`) and `MENU.CDR` (`l`), checked against the pictures of `FLAG.CDR` and `MENU.CDR` | sample |
| R44 | Shapes of version 1 or 2: a rectangle's width and height (i16), then a corner radius; an ellipse's width and height, then two angles; a curve's point list as R39 and R16 | S: rectangles in TP `FLAG.CDR`, ellipses and curves in TP `WI.CDR`, curves in TP `MENU.CDR` | sample (the radius of files with the marker `e`, which no sample shows, and how the angles make an arc: unconfirmed; a radius is kept only when it is at most half the shorter side, and an ellipse whose angles differ is left out with a warning) |
| R45 | `LIST stlt` from version 7: a u32 style count, and when it is not 0: the fill table (a u32 count, entries of a table id, 4 bytes and a `fild` id, 12 bytes each, 60 from version 13), the outline table (12-byte entries laid out the same way, naming `outl` ids), the text tables (fonts of 44 bytes, 60 from version 10; alignments of 12; spacings of 52; tables of 152 and 784; bullets whose length a u32 inside them sets; indents of 28; hyphenation of 32, 36 from 13; drop caps of 28; from 8.01 a table of 12), then the styles: kind (u32), id, parent id, 8 bytes, name length and name (bytes before 12, UTF-16 units from it), the fill and outline table ids, then 16 bytes (20 from 8.01) for kinds above 1 and 20 more for kinds above 2. An object names its style in argument 200 (u32). An object without argument 20 or 10 takes the fill or outline of its style; a style whose table id is 0 takes its parent's | K L593-L600, L852, L1926-L2198; S: UC `outl_width_cdr7.cdr`, one of whose lines carries argument 200 and neither 10 nor 20 and names the style whose outline is black and 0.003 inch wide and whose fill is none, as the file's picture shows; the table parses exactly to the end of the list in each of the 498 sample files of versions 7 to 15 that has one, and every object with argument 200 in them names a style whose table ids are in the tables | public-spec (what the table ids name, and that an object takes its style's fill and outline: sample; a style taking its parent's entry: unconfirmed, as only text styles in the samples leave theirs to the parent, and a wrong guess draws a shape without that fill or outline) |
| R46 | A clipping container carries argument 8005; its first u32 is the id that the `spnd` chunk (a u32) of one `LIST grp ` in the document's `LIST clpt` holds. That group's objects are the ones the container clips; they keep their own transforms, in page space like the container's | K L252, L860-L862, L1895-L1901 (the argument and the chunk); S: LT `powerclipsquare_blackfill_whiterectangleinside` of `testset/12` to `testset/25` and eight UC files of versions 7 to 13, in each of which the id in argument 8005 matches one group's `spnd`; in the UC file of version 7 the group's box, -1.96 to 1.97 inches across, overlaps the container's, -1.81 to 1.84 inches, and the file's picture shows the group cut to the container | public-spec (what the id names, and the space of the group's objects: sample) |
| R47 | Argument 8000 marks an object seen through: a lens or a transparency. The reader does not apply it, and names lenses in the warnings | K L859 (the argument); S: of the sample files of versions 7 to 25, the argument is on the see-through objects that the pictures of LT `square_blackfill_nooutline_transparency50percent` of `testset/12` to `testset/25`, TDF 80103 and eight UC lens test files of versions 7 to 13 show, and otherwise only on text in UC `fancytext_cdr7.cdr` to `fancytext_x3.cdr` and on two objects of TDF 114901. The value K reads at byte 10 (14 from version 13) is not the transparency in these samples | public-spec (the argument: K; what it marks: sample; its layout: unconfirmed, and it is not read) |
| R45 | `LIST stlt` from version 7: a u32 style count, and when it is not 0: the fill table (a u32 count, entries of a table id, 4 bytes and a `fild` id, 12 bytes each, 60 from version 13), the outline table (12-byte entries laid out the same way, naming `outl` ids), the text tables (fonts of 44 bytes, 60 from version 10; alignments of 12; spacings of 52; tables of 152 and 784; bullets whose length a u32 inside them sets; indents of 28; hyphenation of 32, 36 from 13; drop caps of 28; from 8.01 a table of 12), then the styles: kind (u32), id, parent id, 8 bytes, name length and name (bytes before 12, UTF-16 units from it), the fill and outline table ids, then 16 bytes (20 from 8.01) for kinds above 1 and 20 more for kinds above 2. An object names its style in argument 200 (u16 before version 6, u32 from it). An object without argument 20 or 10 takes the fill or outline of its style; a style whose table id is 0 takes its parent's | K L593-L600, L852, L1926-L2198; S: UC `outl_width_cdr7.cdr`, one of whose lines carries argument 200 and neither 10 nor 20 and names the style whose outline is black and 0.003 inch wide and whose fill is none, as the file's picture shows; the table parses exactly to the end of the list in each of the 498 sample files of versions 7 to 15 that has one, and every object with argument 200 in them names a style whose table ids are in the tables; argument 200 is 2 bytes on all 844 objects of versions 4 and 5 in the sample files that carry it, and 4 bytes on all 18 of version 6 | public-spec (what the table ids name, and that an object takes its style's fill and outline: sample; a style taking its parent's entry: unconfirmed, as only text styles in the samples leave theirs to the parent, and a wrong guess draws a shape without that fill or outline) |
| R46 | A clipping container carries argument 8005; its first u32 is the id that the `spnd` chunk (a u32, a u16 before version 6) of one `LIST grp ` in the document's `LIST clpt` holds. That group's objects are the ones the container clips; they keep their own transforms, in page space like the container's | K L252, L860-L862, L1895-L1901 (the argument and the chunk); S: LT `powerclipsquare_blackfill_whiterectangleinside` of `testset/12` to `testset/25` and eight UC files of versions 7 to 13, in each of which the id in argument 8005 matches one group's `spnd`; in the UC file of version 7 the group's box, -1.96 to 1.97 inches across, overlaps the container's, -1.81 to 1.84 inches, and the file's picture shows the group cut to the container | public-spec (what the id names, and the space of the group's objects: sample) |
| R47 | Argument 8000 marks an object seen through: a lens or a transparency. From version 13 it holds records of a u32 version, a u32 length and a body; a body of version 1300 that is 117 bytes long holds an f64 at byte 61 and a merge mode byte at byte 77, which the reader applies as a uniform transparency. VectorCraft reads the f64 as the transparency in percent (0 opaque, 100 clear) and maps the merge modes 0 normal, 9 multiply, 11 lighten, 12 darken, 14 color, 15 hue, 16 saturation, 17 luminosity, 24 difference, 28 screen, 29 overlay, 30 soft light, 31 hard light, 33 color dodge, 34 color burn and 36 exclusion to its blend modes. Other merge modes, other records (a lens record of version 13 is 84 bytes) and the argument before version 13 are not applied, and the reader names them with lenses in the warnings | K L859 (the argument); KF L707-L798 (the records, the 117-byte body and the merge modes); S: the version 1300 record of LT `square_blackfill_nooutline_transparency50percent` of `testset/15` to `testset/25` is 117 bytes long, with 50.0 at byte 61 and 0 at byte 77; the lens records of UC `corel_lens_test_x3.cdr` (13) are 84 bytes long; of the sample files of versions 7 to 25, the argument is on the see-through objects that the pictures of LT `square_blackfill_nooutline_transparency50percent` of `testset/12` to `testset/25`, TDF 80103 and eight UC lens test files of versions 7 to 13 show, and otherwise only on text in UC `fancytext_cdr7.cdr` to `fancytext_x3.cdr` and on two objects of TDF 114901. The value K reads at byte 10 (14 from version 13) is not the transparency in these samples | public-spec (the argument: K; what it marks: sample; the direction of the value: VectorCraft's own reading, as every sample is at 50%, and a wrong reading shows a 25% transparency at 75%; the layout before version 13: unconfirmed, and it is not read) |
| R48 | Bit 2 (0x04) of the outline's line type marks the outline dashed; the dashes of an outline without it are not drawn | S: every outline of versions 6 to 25 in the sample files with that bit set (316 of them, in 29 files) stores dashes; TDF 76771 (version 15) stores dashes 2 and 1 in an outline of line type 0x22, and the file's picture draws that outline solid | sample |
| R49 | Bit 4 (0x10) of the outline's line type puts the outline behind the fill | S: UC `outl_behind_fill_cdr7.cdr` to `outl_behind_fill_x3.cdr`, whose outline of line type 0x12 the file's picture shows behind the fill, and whose other outlines (0x02) it shows over the fill | sample |
| R50 | Bit 5 (0x20) of the outline's line type scales the outline's width and dashes with the shape's matrix. The engine multiplies them by the square root of the matrix's area factor (VectorCraft's own value for a matrix that scales x and y differently) | S: UC `outl_scale_with_cdr7.cdr` to `outl_scale_with_cdr12.cdr`, of whose outlines only one, 3.969 mm wide, has line type 0x22 and the others 0x02 or 0x01; TDF 76771 (version 15), whose outline of line type 0x22 is 10 mm wide on a shape that the matrix stretches and skews, and whose picture draws that outline several times wider and skewed | sample (the bit; the single width for a matrix that scales x and y differently: VectorCraft's own) |
| R51 | A `trfd` offsets table holds one offset more than the entries; each entry runs from its offset to the next, and the last offset is the record's end | KF L1079, L1113-L1121; S: every `trfd` of versions 4 to 25 in the sample files (25,425 records) has the extra offset, equal to the record's length | public-spec |
| R52 | Byte 0 of argument 14001 is the fill's winding flag. VectorCraft reads a byte other than 0 as the nonzero fill rule, and 0 or an object without the argument as even-odd | KF L575-L583, L1047; S: the argument is 4 bytes in the sample files that carry it, with byte 0 = 1 on LT `complexshape_blackfill_nooutline` of `testset/12` and `testset/15` to `testset/25` and on objects of TDF 127576 (13) and 60026 (14), and 0 on 27 objects of TP `example.cdr` (17) | public-spec (the flag: KF; which rule each value means, and the rule without the argument: VectorCraft's own reading, and a wrong reading fills or leaves holes where a curve's subpaths overlap) |
+10 -2
View File
@@ -13,6 +13,7 @@ with each object's transform. It does not write `.cdr` files.
| ZIP packages: `content/riffData.cdr` (versions 14 and 15), `content/root.dat` with the data streams `content/dataFileList.dat` names (16 on) | the RIFF chunk tree; a data stream is inflated only when a chunk the reader reads, or a list it splits, points into it |
| Pages, the page size in `mcfg` or a page's own size | pages, laid out by the engine as artboards side by side |
| Layers (drawing, desktop, guides and grid layers), the master page's among them | layers by name and kind |
| The hidden and locked flags of layers, groups and objects | flags |
| Guidelines (object type 0x16, and the version 7 `guid` chunk) | guidelines at their point and angle |
| Groups (`LIST grp `) | groups |
| Clipping containers and the groups of `LIST clpt` they clip | the container with the objects it clips |
@@ -21,15 +22,22 @@ with each object's transform. It does not write `.cdr` files.
| Ellipses, arcs and pies | ellipses, and paths for arcs and pies |
| Polygons and stars (a base side copied for each side) | paths |
| Uniform fills: CMYK, CMY, RGB, gray, registration, library colors | colors, spot colors with their tints |
| Outlines: width, caps, joins, dashes, the no-outline and behind-the-fill flags | outlines |
| The fill's winding flag | the nonzero fill rule, or even-odd |
| Outlines: width, caps, joins, dashes, the no-outline and behind-the-fill flags, and from version 13 a library color named in their property list | outlines |
| Uniform transparency (version 13 on) and its merge mode | the shape's opacity and blend mode |
| Styles (`LIST stlt`, versions 7 to 15) that objects name | the fill and outline of an object that has none of its own |
Text, bitmaps, linked groups (blends, contours, brush strokes), B-spline curves, fountain,
pattern, texture and PostScript fills, outline arrowheads, lenses and object transparency are not
pattern, texture and PostScript fills, outline arrowheads, lenses, transparency other than uniform
transparency of version 13 and later, and merge modes without a VectorCraft blend mode are not
read; the drawing's
`warnings` name each kind it held. Drawings of versions after 27 are refused, and so are packages
that are encrypted, ZIP64 archives or split across files.
VectorCraft reads a uniform transparency's stored value as the transparency in percent (0 opaque,
100 clear), and a winding flag other than 0 as the nonzero fill rule. These are VectorCraft's own
readings: no public source states either direction.
## Versions 1 to 4
Public specifications cover only parts of these versions, such as the version 3 fill and page
+118 -22
View File
@@ -8,7 +8,7 @@ use crate::geometry;
use crate::inline;
use crate::layout::{self, Profile};
use crate::limits::Budget;
use crate::model::{Color, Drawing, Geometry, Guideline, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape};
use crate::model::{Blend, Color, Drawing, Flags, Geometry, Guideline, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape};
use crate::records::{self, Loda};
use crate::riff::{Chunk, Index, push};
use crate::styles::Styles;
@@ -21,7 +21,7 @@ const CURVE: u32 = 3;
const POLYGON: u32 = 0x14;
const GUIDELINE: u32 = 0x16;
const PATH: u32 = 0x25;
/// Argument types (R6, R20, R21, R33).
/// Argument types (R6, R20, R21, R33, R52).
const ARG_OUTLINE: u32 = 10;
const ARG_FILL: u32 = 20;
const ARG_COORDS: u32 = 30;
@@ -31,6 +31,7 @@ const ARG_NAME: u32 = 1000;
const ARG_LENS: u32 = 8000;
const ARG_CONTAINER: u32 = 8005;
const ARG_POLYGON: u32 = 11000;
const ARG_WINDING: u32 = 14001;
const ARG_GUIDE: u32 = 16000;
const ARG_PAGE_SIZE: u32 = 19130;
@@ -97,8 +98,10 @@ pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec<Warning>)
open_clips: Vec::new(),
clip_cut: false,
};
// The `spnd` id is a u16 in files of 16-bit fields (R46).
let spnd = |b: &[u8]| if p.short { Rd::new(b).u16().map(u32::from) } else { Rd::new(b).u32() };
for g in found.clpt.iter().flat_map(|c| ix.children(c)).filter(|g| g.is_list(b"grp ")) {
if let Some(id) = ix.children(g).iter().find(|c| &c.id == b"spnd").and_then(|c| Rd::new(ix.data(c)).u32()) {
if let Some(id) = ix.children(g).iter().find(|c| &c.id == b"spnd").and_then(|c| spnd(ix.data(c))) {
cx.clips.entry(id).or_insert(g);
}
}
@@ -216,7 +219,16 @@ fn guideline(b: &[u8], p: &Profile) -> Option<Guideline> {
let mut r = Rd::at(b, 12);
let angle = f64::from(r.i32()?) / 1_000_000.0;
let at = Pt { x: records::coord(&mut r, p)?, y: records::coord(&mut r, p)? };
Some(Guideline { at, angle })
Some(Guideline { at, angle, hidden: false })
}
/// Marks the guidelines from `from` on hidden when `flags` hide what holds them.
fn hide_guides(guides: &mut [Guideline], from: usize, flags: Flags) {
if flags.hidden {
for g in guides.iter_mut().skip(from) {
g.hidden = true;
}
}
}
/// A list's flags (R19): four bytes.
@@ -225,6 +237,23 @@ fn flags(ix: &Index, list: &Chunk) -> Option<[u8; 4]> {
ix.data(c).get(..4)?.try_into().ok()
}
/// Whether a layer, group or object list is hidden (bit 0x01 of byte 1) or locked (bit 0x10 of
/// byte 0) (R19).
fn state(ix: &Index, list: &Chunk) -> Flags {
flags(ix, list).map_or(Flags::default(), |[b0, b1, _, _]| Flags { hidden: b1 & 0x01 != 0, locked: b0 & 0x10 != 0 })
}
/// `o` with `f` added to its own flags: the objects of a group left ungrouped keep the group's.
fn inherit(o: &mut Object, f: Flags) {
let own = match o {
Object::Shape(s) => &mut s.flags,
Object::Group { flags, .. } => flags,
Object::Clip { container, .. } => &mut container.flags,
};
own.hidden |= f.hidden;
own.locked |= f.locked;
}
/// What a layer's object type makes it (R19): 11 a grid, 12 guides, 17 the desktop, any other a
/// drawing layer. Version 3 counts its types from 0, one less (R32).
fn layer_kind_of_type(kind: u32, types_from_zero: bool) -> LayerKind {
@@ -297,6 +326,10 @@ struct Frame<'i> {
objects: Vec<Object>,
/// Whether its objects form a group in the frame below.
group: bool,
/// The group's own flags.
flags: Flags,
/// The first of the guidelines read inside it.
guides_from: usize,
/// What places its objects after their own transforms: the matrices of the version 3 groups
/// around them (R33). The identity in other versions, whose objects hold their whole transform.
outer: Matrix,
@@ -339,27 +372,43 @@ impl<'a, 'b> Ctx<'a, 'b> {
let name = loda.and_then(|l| l.arg(ARG_NAME).map(|b| records::name(b, &self.p, self.warn))).unwrap_or_default();
let mut guides = Vec::new();
let objects = self.objects(ix.children(list), &mut guides);
Layer { name, kind, objects, guides }
let flags = state(ix, list);
hide_guides(&mut guides, 0, flags);
Layer { name, kind, flags, objects, guides }
}
/// The objects of a layer's chunks, groups nested, front to back; guidelines go to `guides`.
fn objects(&mut self, chunks: &'b [Chunk], guides: &mut Vec<Guideline>) -> Vec<Object> {
let ix = self.ix;
let mut stack = vec![Frame { chunks, next: 0, objects: Vec::new(), group: false, outer: Matrix::IDENTITY }];
let mut stack = vec![Frame {
chunks,
next: 0,
objects: Vec::new(),
group: false,
flags: Flags::default(),
guides_from: guides.len(),
outer: Matrix::IDENTITY,
}];
loop {
let Some(top) = stack.last_mut() else { return Vec::new() };
let (here, outer) = (top.chunks, top.outer);
let Some(c) = here.get(top.next) else {
let Some(done) = stack.pop() else { return Vec::new() };
// A hidden group hides the guidelines inside it.
hide_guides(guides, done.guides_from, done.flags);
match stack.last_mut() {
// A group counts toward the objects a read maps; past them its objects stay,
// ungrouped.
// ungrouped, with the group's flags.
Some(parent) if done.group && !done.objects.is_empty() => {
if self.budget.take_object() {
parent.objects.push(Object::Group(done.objects));
parent.objects.push(Object::Group { objects: done.objects, flags: done.flags });
} else {
push(self.warn, Warning::TooDeep);
parent.objects.extend(done.objects);
let mut objects = done.objects;
for o in &mut objects {
inherit(o, done.flags);
}
parent.objects.extend(objects);
}
}
Some(parent) if !done.group => parent.objects.extend(done.objects),
@@ -382,14 +431,17 @@ impl<'a, 'b> Ctx<'a, 'b> {
}
} else if c.is_list(b"grp ") {
let own = self.group_placement(c);
stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: true, outer: outer.after(&own) });
let flags = state(ix, c);
let guides_from = guides.len();
stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: true, flags, guides_from, outer: outer.after(&own) });
} else if c.is_list(b"lnkg") {
// Linked groups (brush strokes, blends, contours) place their objects with a
// matrix of their own, which this reader doesn't apply: they are left out.
push(self.warn, Warning::UnsupportedObjects);
} else if c.id == crate::riff::LIST && !c.is_list(b"lgob") {
// Other lists under a layer are looked through (R22).
stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: false, outer });
let guides_from = guides.len();
stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: false, flags: Flags::default(), guides_from, outer });
}
}
}
@@ -440,18 +492,28 @@ impl<'a, 'b> Ctx<'a, 'b> {
push(self.warn, Warning::TooDeep);
return None;
}
let flags = state(ix, list);
if loda.kind == GUIDELINE {
guides.extend(loda.arg(ARG_GUIDE).and_then(|b| guideline(b, &self.p)));
guides.extend(loda.arg(ARG_GUIDE).and_then(|b| guideline(b, &self.p)).map(|g| Guideline { hidden: flags.hidden, ..g }));
return None;
}
if self.p.inline_styles {
return self.inline_object(&loda, outer);
return self.inline_object(&loda, outer, flags);
}
let geometry = self.geometry(&loda)?;
// A lens or transparency (R47) is not applied: the shape shows opaque.
if loda.arg(ARG_LENS).is_some() {
push(self.warn, Warning::Lenses);
}
// A uniform transparency from version 13 applies (R47); a lens, and a transparency of
// another kind or version, is not applied: the shape shows opaque.
let (opacity, blend) = match loda.arg(ARG_LENS) {
None => (1.0, Blend::Normal),
Some(b) => match records::transparency(b).filter(|_| self.p.tagged) {
Some(t) => t,
None => {
push(self.warn, Warning::Lenses);
(1.0, Blend::Normal)
}
},
};
let nonzero = self.nonzero(&loda);
// A transform that is there but can't be read is damage; the shape stays where it is.
let matrix = match own_chunk(ix, list, &[b"trfd"]) {
None => Matrix::IDENTITY,
@@ -460,8 +522,9 @@ impl<'a, 'b> Ctx<'a, 'b> {
Matrix::IDENTITY
}),
};
// Without a fill or outline argument of its own, an object takes its style's (R45).
let style = loda.arg(ARG_STYLE).and_then(|b| self.id(b));
// Without a fill or outline argument of its own, an object takes its style's (R45). The
// style id is a u16 in files of 16-bit fields.
let style = loda.arg(ARG_STYLE).and_then(|b| if self.p.short { self.short_id(b) } else { self.id(b) });
let fill_id = match loda.arg(ARG_FILL) {
Some(b) => self.id(b),
None => style.and_then(|s| self.style_entry(s, Styles::fill)),
@@ -472,7 +535,7 @@ impl<'a, 'b> Ctx<'a, 'b> {
};
let fill = fill_id.and_then(|id| self.fill(id));
let outline = outline_id.and_then(|id| self.outline(id));
let shape = Box::new(Shape { geometry, matrix, fill, outline });
let shape = Box::new(Shape { geometry, matrix, fill, outline, nonzero, opacity, blend, flags });
// A container clips the group its argument 8005 names (R46).
Some(match loda.arg(ARG_CONTAINER).and_then(|b| self.id(b)) {
Some(id) => self.clip(shape, id, guides),
@@ -501,9 +564,18 @@ impl<'a, 'b> Ctx<'a, 'b> {
guides.truncate(mark);
return Object::Shape(container);
}
// The clipped group's own flags hide or lock the objects it holds; it and the container
// hide its guidelines.
let flags = state(ix, group);
hide_guides(guides, mark, flags);
hide_guides(guides, mark, container.flags);
if objects.is_empty() {
return Object::Shape(container);
}
let mut objects = objects;
for o in &mut objects {
inherit(o, flags);
}
Object::Clip { container, objects }
}
@@ -516,6 +588,28 @@ impl<'a, 'b> Ctx<'a, 'b> {
id
}
/// A u16 id at the start of argument `b`; an argument too short for one is damage.
fn short_id(&mut self, b: &[u8]) -> Option<u32> {
let id = Rd::new(b).u16().map(u32::from);
if id.is_none() {
push(self.warn, Warning::Damaged);
}
id
}
/// Whether the object's fill rule is nonzero: byte 0 of argument 14001 set (R52). Without the
/// argument the fill is even-odd; an argument without its byte is damage.
fn nonzero(&mut self, loda: &Loda) -> bool {
let Some(b) = loda.arg(ARG_WINDING) else { return false };
match b.first() {
Some(v) => *v != 0,
None => {
push(self.warn, Warning::Damaged);
false
}
}
}
/// The fill or outline record that style `id` names; a style table that doesn't parse is
/// damage, and the object is drawn without it.
fn style_entry(&mut self, id: u32, entry: fn(&Styles, u32) -> Option<u32>) -> Option<u32> {
@@ -530,7 +624,7 @@ impl<'a, 'b> Ctx<'a, 'b> {
/// A version 3 object, whose transforms, fill and outline are arguments of its own record
/// (R33, R34, R35). A fill or an outline that is there but can't be read is damage.
fn inline_object(&mut self, loda: &Loda, outer: &Matrix) -> Option<Object> {
fn inline_object(&mut self, loda: &Loda, outer: &Matrix, flags: Flags) -> Option<Object> {
let own = match loda.arg(ARG_TRANSFORMS) {
None => Matrix::IDENTITY,
Some(arg) => self.placement(arg),
@@ -558,7 +652,9 @@ impl<'a, 'b> Ctx<'a, 'b> {
}
o
});
Some(Object::Shape(Box::new(Shape { geometry, matrix: outer.after(&own), fill, outline })))
let nonzero = self.nonzero(loda);
let shape = Shape { nonzero, flags, ..Shape::new(geometry, outer.after(&own), fill, outline) };
Some(Object::Shape(Box::new(shape)))
}
fn geometry(&mut self, loda: &Loda) -> Option<Geometry> {
+3 -3
View File
@@ -151,8 +151,8 @@ pub(crate) fn rect(b: &[u8], p: &Profile) -> Option<Geometry> {
/// A rectangle record from version 15 (R29): width and height as f64 coordinate units, two scale
/// factors that repeat the transform's (not applied), the scale-with flag and 7 bytes, then the
/// four radii as f64 16 bytes apart. With the flag clear each radius is a share of half the shorter
/// side; with it set the radius is in inches. A corner is held to the shorter side, and sizes to
/// the range of the 32-bit coordinates of earlier versions.
/// side; with it set the radius is in inches. A corner is held to half the shorter side, and
/// sizes to the range of the 32-bit coordinates of earlier versions.
fn rect_f64(b: &[u8], p: &Profile) -> Option<Geometry> {
let mut r = Rd::new(b);
let size = |v: f64| (v.abs() <= f64::from(i32::MAX)).then(|| v * p.unit());
@@ -168,7 +168,7 @@ fn rect_f64(b: &[u8], p: &Profile) -> Option<Geometry> {
}
let v = r.f64()?.abs();
let radius = if inches { v * 72.0 } else { v * short / 2.0 };
*slot = radius.min(short);
*slot = radius.min(short / 2.0);
}
Some(Geometry::Rect { w, h, radii })
}
+52 -2
View File
@@ -112,18 +112,64 @@ pub struct Outline {
pub scale_with: bool,
}
/// Whether a layer, group or shape is hidden or locked.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Flags {
pub hidden: bool,
pub locked: bool,
}
/// How a shape's colors combine with the art below it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Blend {
#[default]
Normal,
Multiply,
Screen,
Overlay,
SoftLight,
HardLight,
ColorDodge,
ColorBurn,
Darken,
Lighten,
Difference,
Exclusion,
Hue,
Saturation,
Color,
Luminosity,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Shape {
pub geometry: Geometry,
pub matrix: Matrix,
pub fill: Option<Color>,
pub outline: Option<Outline>,
/// The fill covers every area its subpaths wind around (nonzero); otherwise subpaths that
/// overlap leave holes (even-odd).
pub nonzero: bool,
/// 1 opaque, 0 clear.
pub opacity: f32,
pub blend: Blend,
pub flags: Flags,
}
impl Shape {
/// An opaque, shown shape filled even-odd.
pub fn new(geometry: Geometry, matrix: Matrix, fill: Option<Color>, outline: Option<Outline>) -> Shape {
Shape { geometry, matrix, fill, outline, nonzero: false, opacity: 1.0, blend: Blend::Normal, flags: Flags::default() }
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Object {
Shape(Box<Shape>),
Group(Vec<Object>),
Group {
objects: Vec<Object>,
flags: Flags,
},
/// A clipping container and the objects it clips: `objects` (front to back) show only
/// inside the container's shape, with its fill behind them and its outline over them.
Clip {
@@ -137,6 +183,8 @@ pub enum Object {
pub struct Guideline {
pub at: Pt,
pub angle: f64,
/// The guideline, a group around it or its layer is hidden.
pub hidden: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -152,6 +200,7 @@ pub enum LayerKind {
pub struct Layer {
pub name: String,
pub kind: LayerKind,
pub flags: Flags,
/// Front to back, as the file lists them.
pub objects: Vec<Object>,
pub guides: Vec<Guideline>,
@@ -180,7 +229,8 @@ pub enum Warning {
Arrowheads,
/// Envelopes, which are not applied: the shapes under them keep their outlines.
Envelopes,
/// Lenses and object transparency, which are not applied: the objects show opaque.
/// Lenses, and object transparency that isn't read, which are not applied: the objects show
/// opaque.
Lenses,
/// Content nested deeper, or past the counts, that a read takes.
TooDeep,
+86 -8
View File
@@ -3,7 +3,7 @@
use crate::bytes::Rd;
use crate::layout::{ColorLayout, Profile};
use crate::model::{Cap, Color, Join, Matrix, Outline};
use crate::model::{Blend, Cap, Color, Join, Matrix, Outline};
use crate::riff::push;
use crate::{Limits, Warning};
@@ -74,7 +74,9 @@ pub(crate) fn loda<'a>(b: &'a [u8], p: &Profile, limits: &Limits, warn: &mut Vec
Some(Loda { kind: kind as u32, args })
}
/// The matrices of a `trfd` record composed in file order, in points (R8).
/// The matrices of a `trfd` record composed in file order, in points (R8). Each entry ends where
/// the next offset points, and the last at the offset after it (R51); an entry too short for its
/// matrix makes the record unreadable.
pub(crate) fn trfd(b: &[u8], p: &Profile) -> Option<Matrix> {
let mut r = Rd::new(b);
let (_len, count, offsets_at) = (word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?);
@@ -82,8 +84,12 @@ pub(crate) fn trfd(b: &[u8], p: &Profile) -> Option<Matrix> {
let k = p.unit();
// Each entry takes at least its offset's bytes, which bounds the count by the record's size.
for i in 0..count.min(b.len() / p.word()) {
let at = word(&mut Rd::at(b, offsets_at.checked_add(i.checked_mul(p.word())?)?), p)?;
let mut e = Rd::at(b, at.checked_add(p.trfd_head)?);
let slot = offsets_at.checked_add(i.checked_mul(p.word())?)?;
let start = word(&mut Rd::at(b, slot), p)?;
// A table that stops before the last entry's end offset leaves that entry the rest of the
// record.
let end = word(&mut Rd::at(b, slot.checked_add(p.word())?), p).unwrap_or(b.len());
let mut e = Rd::at(b.get(start..end)?, p.trfd_head);
if e.u16()? != 8 {
continue;
}
@@ -204,8 +210,8 @@ fn counted_utf16(r: &mut Rd, warn: &mut Vec<Warning>) -> Option<String> {
Some(format!("{} {hash:016x}", String::from_utf16_lossy(&kept)))
}
/// The color of a tagged uniform fill's property list (R11): its color record, named by the
/// library name it carries.
/// The color of the property list of a tagged uniform fill (R11) or outline (R12): its color
/// record, named by the library name it carries.
fn property_color(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<Color> {
let mut r = Rd::new(b);
let (mut found, mut name) = (None, None);
@@ -304,6 +310,8 @@ fn tagged_body<'a>(r: &mut Rd<'a>) -> Option<&'a [u8]> {
pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<(u32, Option<Outline>)> {
let mut r = Rd::new(b);
let id = r.u32()?;
// A library color named in a record of type 2, with the warnings its read gave.
let mut named = None;
if p.tagged {
let mut found = false;
for _ in 0..MAX_OUTLINE_RECORDS {
@@ -312,7 +320,16 @@ pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<
found = true;
break;
}
r.skip(len)?;
let body = r.bytes(len)?;
// Type 2 holds the outline's color as a property list, as a uniform fill does (R12).
// Only a library color with its name is taken from it; any other color comes from
// the fixed field below.
if rec == 2 {
let mut w = Vec::new();
if let Some(c @ Color::Spot { look: Some(_), .. }) = property_color(body, p, &mut w) {
named = Some((c, w));
}
}
}
if !found {
return None;
@@ -325,7 +342,16 @@ pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<
r.skip(p.outl_after_stretch)?;
let _nib = angle(&mut r, p)?;
r.skip(p.outl_after_angle)?;
let color = color(&mut r, p, warn)?;
let color = match named {
Some((named, w)) => {
color(&mut r, p, &mut Vec::new())?;
for x in w {
push(warn, x);
}
named
}
None => color(&mut r, p, warn)?,
};
r.skip(p.outl_after_color)?;
let count = usize::from(r.u16()?);
let first_dash = r.pos();
@@ -365,6 +391,58 @@ pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<
Some((id, Some(Outline { width, color, cap, join, dashes, behind_fill, scale_with })))
}
/// The opacity and blend of argument 8000 from version 13 (R47): records of a u32 version, a u32
/// length and a body. A body of version 1300 that is [`UNIFORM_LEN`] bytes long is a uniform
/// transparency: an f64 at byte 61 and the merge mode at byte 77. VectorCraft reads the f64 as the
/// transparency in percent, 0 opaque and 100 clear. `None` for any other argument, such as a lens,
/// and for a value out of range or a merge mode without a VectorCraft blend mode.
pub(crate) fn transparency(b: &[u8]) -> Option<(f32, Blend)> {
let mut r = Rd::new(b);
while r.left() >= 8 {
let (since, len) = (r.u32()?, r.u32()? as usize);
let body = r.bytes(len)?;
if since != TAG_1300 {
continue;
}
if body.len() != UNIFORM_LEN {
return None;
}
let value = Rd::at(body, 61).f64()?;
if !(0.0..=100.0).contains(&value) {
return None;
}
return Some(((1.0 - value / 100.0) as f32, blend(*body.get(77)?)?));
}
None
}
/// The length of a uniform transparency's record body (R47).
const UNIFORM_LEN: usize = 117;
/// The blend mode of a transparency's merge mode byte (R47); `None` for the modes VectorCraft has
/// no blend mode for.
fn blend(mode: u8) -> Option<Blend> {
Some(match mode {
0 => Blend::Normal,
9 => Blend::Multiply,
11 => Blend::Lighten,
12 => Blend::Darken,
14 => Blend::Color,
15 => Blend::Hue,
16 => Blend::Saturation,
17 => Blend::Luminosity,
24 => Blend::Difference,
28 => Blend::Screen,
29 => Blend::Overlay,
30 => Blend::SoftLight,
31 => Blend::HardLight,
33 => Blend::ColorDodge,
34 => Blend::ColorBurn,
36 => Blend::Exclusion,
_ => return None,
})
}
/// A name argument (R9): Windows-1252 up to a NUL before version 12, UTF-16LE from it. A name
/// longer than [`MAX_NAME`] bytes or UTF-16 units keeps its first ones (without half of a
/// surrogate pair) and a hash of the whole name, with a warning, as a library color's name does.
+3 -1
View File
@@ -203,9 +203,11 @@ impl<'a> Index<'a> {
/// The version: the `vrsn` chunk's when it names one from 3 to 27, else the form type's (R1,
/// R2). A template's form type names no version, so its `vrsn` chunk decides whatever it names
/// (R28). Letters count differently from the version 24 update on (R1), so when both name a
/// version after 27 the `vrsn` chunk's is the one refused.
/// version after 27 the `vrsn` chunk's is the one refused. The `cdr8` form type alone makes a
/// file the 8.01 variant, whatever its `vrsn` chunk names (R1).
pub(crate) fn version(&self) -> u16 {
match self.vrsn.flatten() {
_ if self.form_version == 801 => 801,
Some(v) if (layout::OLDEST_RIFF..=layout::NEWEST).contains(&v) => v,
Some(v) if self.form_version == 0 => v,
Some(v) if v > layout::NEWEST && self.form_version > layout::NEWEST => v,
+64 -4
View File
@@ -212,7 +212,8 @@ impl V {
let table = head;
let mut entries = Vec::new();
let mut offsets = Vec::new();
let first = table + matrices.len() * w;
// The table holds one offset more than the entries: the record's end (R51).
let first = table + (matrices.len() + 1) * w;
for m in matrices {
offsets.push(first + entries.len());
if self.0 >= 1300 {
@@ -232,6 +233,7 @@ impl V {
entries.extend(v.to_le_bytes());
}
}
offsets.push(first + entries.len());
let mut out = Vec::new();
for f in [first + entries.len(), matrices.len(), table] {
out.extend(self.word(f));
@@ -588,10 +590,55 @@ pub fn container(id: u32) -> (u32, Vec<u8>) {
(8005, [id, 1, 0, 1].iter().flat_map(|v| v.to_le_bytes()).collect())
}
/// The argument 8000 of a uniform transparency from version 13 (R47): one record of version 1300
/// whose 117-byte body holds `percent` at byte 61 and `merge` at byte 77.
pub fn transparency(percent: f64, merge: u8) -> (u32, Vec<u8>) {
let mut body = vec![0; 117];
body[61..69].copy_from_slice(&percent.to_le_bytes());
body[77] = merge;
let mut out = 1300u32.to_le_bytes().to_vec();
out.extend((body.len() as u32).to_le_bytes());
out.extend(body);
(8000, out)
}
/// A property list (R11, R12) of 12-byte color `color` and, when `name` is given, a type 8
/// property with that library name.
pub fn properties(color: &[u8; 12], name: Option<&str>) -> Vec<u8> {
let mut out = vec![1];
out.extend(12u32.to_le_bytes());
out.extend(color);
if let Some(name) = name {
let mut body = vec![0; 16];
body.extend((name.encode_utf16().count() as u32).to_le_bytes());
body.extend(name.encode_utf16().flat_map(u16::to_le_bytes));
out.push(8);
out.extend((body.len() as u32).to_le_bytes());
out.extend(body);
}
out.extend([0, 0, 0, 0, 0]);
out
}
/// `n` (an object, group or layer list) with its `flgs` chunk replaced by `flags` (R19).
pub fn flagged(n: Node, flags: [u8; 4]) -> Node {
match n {
Node::List(form, kids) => {
let kids = kids
.into_iter()
.map(|k| if matches!(&k, Node::Chunk(id, _) if id == b"flgs") { chunk(b"flgs", flags.to_vec()) } else { k })
.collect();
Node::List(form, kids)
}
chunk => chunk,
}
}
/// A RIFF drawing of `version` (7 to 13) with a style table, a clipping container and a lens: a rectangle
/// that takes its fill and outline from its style, a container that clips two rectangles, one
/// with an outline behind the fill, and a rectangle with a lens; compressed when `compress`.
/// Before version 7, the [`sample`].
/// with an outline behind the fill, a rectangle with a lens, a hidden and locked rectangle with a
/// winding flag and a uniform transparency, and a hidden group whose rectangle's outline names a
/// library color from version 13; compressed when `compress`. Before version 7, the [`sample`].
pub fn feature_sample(version: u16, compress: bool) -> Vec<u8> {
if version < 700 {
return sample(version, false);
@@ -606,6 +653,15 @@ pub fn feature_sample(version: u16, compress: bool) -> Vec<u8> {
let style = (200, 0x10u32.to_le_bytes().to_vec());
let clipped =
vec![rect(30.0, vec![style.clone()], 10.0), rect(30.0, vec![(10, 3u32.to_le_bytes().to_vec()), (20, 1u32.to_le_bytes().to_vec())], -10.0)];
// From version 13 outline 4 names a library color in a record of type 2 (R12).
let mut named = v.outline(4, Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }, &color(25, [7, 0, 100, 0]), &[]);
if version >= 1300 {
let props = properties(&color(5, [0, 0, 255, 0]), Some("Sky Blue"));
let mut record = 2u32.to_le_bytes().to_vec();
record.extend((props.len() as u32).to_le_bytes());
record.extend(props);
named.splice(4..4, record);
}
let doc = list(
b"doc ",
vec![
@@ -616,6 +672,7 @@ pub fn feature_sample(version: u16, compress: bool) -> Vec<u8> {
vec![
chunk(b"outl", v.outline(2, Pen { line_type: 4, width: 2.0, cap: 1, join: 1 }, &black, &[3, 1])),
chunk(b"outl", v.outline(3, Pen { line_type: 0x12, width: 4.0, cap: 0, join: 0 }, &black, &[])),
chunk(b"outl", named),
],
),
stlt(v, &[(0x100, 1)], &[(0x200, 2)], &[Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }], true),
@@ -625,7 +682,10 @@ pub fn feature_sample(version: u16, compress: bool) -> Vec<u8> {
let objects = vec![
rect(20.0, vec![style.clone()], 0.0),
rect(40.0, vec![style.clone(), container(7)], 50.0),
rect(20.0, vec![style, (8000, vec![1, 0, 0, 0])], -50.0),
rect(20.0, vec![style.clone(), (8000, vec![1, 0, 0, 0])], -50.0),
// Hidden and locked, filled nonzero, 25% transparent with merge mode 9 (R19, R47, R52).
flagged(rect(10.0, vec![style.clone(), (14001, vec![1, 0, 0, 0]), transparency(25.0, 9)], 80.0), [0x10, 1, 0, 0x08]),
list(b"grp ", vec![chunk(b"flgs", vec![0, 1, 0, 0x10]), rect(10.0, vec![(10, 4u32.to_le_bytes().to_vec())], -80.0)]),
];
let page = page(false, vec![layer(v, [0, 0, 0, 0x98], "Art", objects)]);
let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())];
+3 -3
View File
@@ -8,7 +8,7 @@ use crate::bytes::{Rd, u32_at};
use crate::geometry;
use crate::layout::{self, Profile};
use crate::limits::Budget;
use crate::model::{Cap, Drawing, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Shape};
use crate::model::{Cap, Drawing, Flags, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Shape};
use crate::records::{self, coord, fixed};
use crate::riff::push;
use crate::{Error, Warning};
@@ -118,7 +118,7 @@ pub(crate) fn drawing(b: &[u8], budget: &mut Budget) -> Result<Drawing, Error> {
push(&mut warn, Warning::Damaged);
}
let version = if marker == b'e' { 100 } else { 200 };
let layer = Layer { name: String::new(), kind: LayerKind::Drawing, objects, guides: Vec::new() };
let layer = Layer { name: String::new(), kind: LayerKind::Drawing, flags: Flags::default(), objects, guides: Vec::new() };
let pages = vec![Page { size: None, layers: vec![layer] }];
Ok(Drawing { version, page_size: page_box(b, settings, &p), pages, master: Vec::new(), guides: Vec::new(), warnings: warn })
}
@@ -196,7 +196,7 @@ fn shape(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mu
} else {
None
};
Some(Some(Shape { geometry, matrix, fill, outline }))
Some(Some(Shape::new(geometry, matrix, fill, outline)))
}
/// A rectangle (R44): its width and height, then a corner radius, which is kept when it is at most
+314 -14
View File
@@ -2,7 +2,7 @@
//! hostile files.
use proptest::prelude::*;
use vectorcraft_cdr::model::{Cap, Color, Geometry, Join, LayerKind, Matrix, Object, Segment};
use vectorcraft_cdr::model::{Blend, Cap, Color, Flags, Geometry, Join, LayerKind, Matrix, Object, Segment};
use vectorcraft_cdr::synth::{self, V, chunk, list};
use vectorcraft_cdr::{Error, Limits, Warning, read};
@@ -12,7 +12,7 @@ fn shapes(objects: &[Object]) -> Vec<&vectorcraft_cdr::model::Shape> {
while let Some(o) = stack.pop() {
match o {
Object::Shape(s) => out.push(&**s),
Object::Group(kids) => stack.extend(kids.iter().rev()),
Object::Group { objects: kids, .. } => stack.extend(kids.iter().rev()),
Object::Clip { container, objects } => {
out.push(&**container);
stack.extend(objects.iter().rev());
@@ -30,7 +30,7 @@ fn check_pages(d: &vectorcraft_cdr::Drawing, version: u16) {
assert_eq!(d.pages.len(), 1, "{version}");
let art = &d.pages[0].layers[0];
assert_eq!((art.name.as_str(), art.kind), ("Art", LayerKind::Drawing));
assert!(matches!(art.objects[3], Object::Group(ref g) if g.len() == 2));
assert!(matches!(art.objects[3], Object::Group { objects: ref g, .. } if g.len() == 2));
assert!(d.warnings.contains(&Warning::UnsupportedObjects));
// The master page: its guideline every page shows, and its desktop object.
if version >= 600 {
@@ -130,7 +130,9 @@ fn version_3_groups_place_their_objects() {
let d = read(&drawing3(vec![outer, rect3(&[shift(7.2, 0.0)])]), Limits::default()).unwrap();
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
let objects = &d.pages[0].layers[0].objects;
assert!(matches!(&objects[0], Object::Group(g) if matches!(&g[0], Object::Group(i) if i.len() == 1) && g.len() == 2));
assert!(
matches!(&objects[0], Object::Group { objects: g, .. } if matches!(&g[0], Object::Group { objects: i, .. } if i.len() == 1) && g.len() == 2)
);
let s = shapes(objects);
let close = |m: &Matrix, want: [f64; 6]| m.0.iter().zip(want).all(|(a, b)| (a - b).abs() < 0.01);
// Its own shift, then the inner group's scale, then the outer group's shift.
@@ -159,7 +161,7 @@ fn version_3_objects_and_groups_under_an_envelope_keep_their_outlines_and_matric
let d = read(&drawing3(vec![bent, moved, group, rect3(&[])]), Limits::default()).unwrap();
let objects = &d.pages[0].layers[0].objects;
assert_eq!(objects.len(), 4);
assert!(matches!(&objects[2], Object::Group(g) if g.len() == 1));
assert!(matches!(&objects[2], Object::Group { objects: g, .. } if g.len() == 1));
let s = shapes(objects);
assert_eq!(s.len(), 4);
assert!(matches!(s[0].geometry, Geometry::Rect { .. }) && s[0].matrix == Matrix::IDENTITY);
@@ -832,7 +834,7 @@ fn redirect_records_that_lead_nowhere_count_toward_the_chunk_limit() {
fn rectangles_from_version_15_give_radii_as_shares_of_half_the_shorter_side() {
let v = V(1500);
let mut c = synth::V(1500).rect(100.0, 50.0, 0.0);
// The four shares: 0.2, 0.4, 0, and 3, which the shorter side holds to 50 pt.
// The four shares: 0.2, 0.4, 0, and 3, which half the shorter side holds to 25 pt.
for (k, share) in [0.2f64, 0.4, 0.0, 3.0].iter().enumerate() {
let at = 40 + 24 * k;
c[at..at + 8].copy_from_slice(&share.to_le_bytes());
@@ -843,16 +845,16 @@ fn rectangles_from_version_15_give_radii_as_shares_of_half_the_shorter_side() {
let s = shapes(&d.pages[0].layers[0].objects);
let Geometry::Rect { w, h, radii } = s[0].geometry else { panic!("{:?}", s[0].geometry) };
assert!((w - 100.0).abs() < 1e-6 && (h - 50.0).abs() < 1e-6);
for (got, want) in radii.iter().zip([5.0, 10.0, 0.0, 50.0]) {
for (got, want) in radii.iter().zip([5.0, 10.0, 0.0, 25.0]) {
assert!((got - want).abs() < 1e-6, "{radii:?}");
}
// With the scale-with flag set the radii are inches, held to the shorter side as well.
// With the scale-with flag set the radii are inches, held to half the shorter side as well.
c[32] = 1;
let file = synth::riff(1500, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c)], None)])])]);
let d = read(&file, Limits::default()).unwrap();
let s = shapes(&d.pages[0].layers[0].objects);
let Geometry::Rect { radii, .. } = s[0].geometry else { panic!("{:?}", s[0].geometry) };
for (got, want) in radii.iter().zip([14.4, 28.8, 0.0, 50.0]) {
for (got, want) in radii.iter().zip([14.4, 25.0, 0.0, 25.0]) {
assert!((got - want).abs() < 1e-6, "{radii:?}");
}
}
@@ -1035,7 +1037,7 @@ fn arguments_past_the_limit_leave_the_first_ones_paired_with_their_types() {
#[test]
fn groups_count_toward_the_object_limit() {
fn count(objects: &[Object]) -> usize {
objects.iter().map(|o| 1 + if let Object::Group(kids) = o { count(kids) } else { 0 }).sum()
objects.iter().map(|o| 1 + if let Object::Group { objects: kids, .. } = o { count(kids) } else { 0 }).sum()
}
let v = V(1100);
let rect = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None);
@@ -1044,7 +1046,7 @@ fn groups_count_toward_the_object_limit() {
let d = read(&file, Limits { objects: 2, ..Limits::default() }).unwrap();
let objects = &d.pages[0].layers[0].objects;
assert_eq!(count(objects), 2, "{objects:?}");
assert!(matches!(objects.as_slice(), [Object::Group(kids)] if matches!(kids.as_slice(), [Object::Shape(_)])), "{objects:?}");
assert!(matches!(objects.as_slice(), [Object::Group { objects: kids, .. }] if matches!(kids.as_slice(), [Object::Shape(_)])), "{objects:?}");
assert!(d.warnings.contains(&Warning::TooDeep));
}
@@ -1289,14 +1291,22 @@ fn a_container_clips_the_group_it_names() {
}
/// The feature sample, the seed of the importer's fuzz tests, reads its style table, clipping
/// container and lens in every version from 7 to 13, plain and compressed.
/// container, lens, flags, winding flag, transparency and named outline color in every version
/// from 7 to 13, plain and compressed.
#[test]
fn the_feature_sample_reads_its_styles_container_and_lens() {
for version in [700, 800, 900, 1000, 1100, 1200, 1300] {
for compress in [false, true] {
let d = read(&synth::feature_sample(version, compress), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}"));
let objects = &d.pages[0].layers[0].objects;
let [Object::Shape(styled), Object::Clip { objects: clipped, .. }, Object::Shape(_)] = objects.as_slice() else {
let [
Object::Shape(styled),
Object::Clip { objects: clipped, .. },
Object::Shape(_),
Object::Shape(flagged),
Object::Group { objects: grouped, flags },
] = objects.as_slice()
else {
panic!("{version}: {objects:?}")
};
assert_eq!(styled.fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{version}");
@@ -1304,7 +1314,20 @@ fn the_feature_sample_reads_its_styles_container_and_lens() {
let s = shapes(clipped);
assert_eq!(s.len(), 2, "{version}");
assert!(s[1].outline.as_ref().is_some_and(|o| o.behind_fill), "{version}");
assert_eq!(d.warnings, vec![Warning::Lenses], "{version} {compress}");
assert_eq!(flagged.flags, Flags { hidden: true, locked: true }, "{version}");
assert!(flagged.nonzero, "{version}");
assert_eq!(*flags, Flags { hidden: true, locked: false }, "{version}");
let named = shapes(grouped)[0].outline.as_ref().map(|o| o.color.clone());
// A transparency and a named outline color are read from version 13.
if version >= 1300 {
assert_eq!((flagged.opacity, flagged.blend), (0.75, Blend::Multiply), "{version}");
assert_eq!(named, Some(Color::Spot { name: "Sky Blue".into(), tint: 1.0, look: Some([1.0, 0.0, 0.0]) }), "{version}");
assert_eq!(d.warnings, vec![Warning::Lenses], "{version} {compress}");
} else {
assert_eq!((flagged.opacity, flagged.blend), (1.0, Blend::Normal), "{version}");
assert_eq!(named, Some(Color::Spot { name: "Spot 0:7".into(), tint: 1.0, look: None }), "{version}");
assert_eq!(d.warnings, vec![Warning::Lenses, Warning::SpotLooks], "{version} {compress}");
}
}
}
}
@@ -1389,6 +1412,283 @@ fn lenses_and_transparency_are_named_in_the_warnings() {
}
}
/// From version 13 a uniform transparency (a 117-byte record of version 1300 in argument 8000)
/// gives the shape its opacity and blend mode, records of other versions before it skipped. A
/// lens record, a value outside 0 to 100, a merge mode without a blend mode, and the record in an
/// earlier version are not applied: the shape stays opaque, with the lenses warning.
#[test]
fn a_uniform_transparency_from_version_13_applies() {
let record = |since: u32, body: Vec<u8>| [since.to_le_bytes().to_vec(), (body.len() as u32).to_le_bytes().to_vec(), body].concat();
for version in [1300, 1500, 1600, 2000] {
let v = V(version);
let read_with = |arg: Vec<u8>| {
let d = read(&clip_drawing(version, vec![], vec![clip_rect(v, 10.0, &[(8000, arg)], [0.0, 0.0])]), Limits::default())
.unwrap_or_else(|e| panic!("{version}: {e}"));
let s = shapes(&d.pages[0].layers[0].objects)[0];
((s.opacity, s.blend), d.warnings)
};
for (percent, merge, want) in [(25.0, 0, Blend::Normal), (0.0, 9, Blend::Multiply), (100.0, 28, Blend::Screen), (60.0, 36, Blend::Exclusion)]
{
let opacity = (1.0 - percent / 100.0) as f32;
assert_eq!(read_with(synth::transparency(percent, merge).1), ((opacity, want), vec![]), "{version} {percent} {merge}");
}
// A record of a later version comes first.
let later = [record(1600, vec![0; 20]), synth::transparency(25.0, 0).1].concat();
assert_eq!(read_with(later), ((0.75, Blend::Normal), vec![]), "{version}");
let opaque = ((1.0, Blend::Normal), vec![Warning::Lenses]);
assert_eq!(read_with(record(1300, vec![0; 84])), opaque, "{version}: a lens");
for bad in [150.0, -1.0, f64::NAN] {
assert_eq!(read_with(synth::transparency(bad, 0).1), opaque, "{version} {bad}");
}
for merge in [1, 2, 3, 6, 7, 8, 10, 13, 18, 19, 20, 27, 37, 255] {
assert_eq!(read_with(synth::transparency(25.0, merge).1), opaque, "{version} {merge}");
}
assert_eq!(read_with(vec![]), opaque, "{version}: empty");
}
let d =
read(&clip_drawing(1200, vec![], vec![clip_rect(V(1200), 10.0, &[synth::transparency(25.0, 0)], [0.0, 0.0])]), Limits::default()).unwrap();
assert_eq!(shapes(&d.pages[0].layers[0].objects)[0].opacity, 1.0);
assert_eq!(d.warnings, vec![Warning::Lenses]);
}
/// Bit 0x01 of byte 1 of a layer's, group's or object's flags hides it and bit 0x10 of byte 0
/// locks it, in every version; a group left ungrouped at the object limit passes its flags to its
/// objects.
#[test]
fn flags_hide_and_lock_layers_groups_and_objects() {
for version in [300, 700, 1100, 1300, 1600] {
let v = V(version);
let rect = |flags: [u8; 4]| synth::flagged(synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0))], None), flags);
let group = |flags: [u8; 4], objects: Vec<synth::Node>| {
let mut kids = vec![chunk(b"flgs", flags.to_vec())];
kids.extend(objects);
list(b"grp ", kids)
};
let objects = vec![
rect([0, 0, 0, 8]),
rect([0, 1, 0, 8]),
rect([0x10, 0, 0, 8]),
rect([0x10, 1, 0, 8]),
group([0x10, 1, 0, 0x10], vec![rect([0, 0, 0, 8])]),
];
let layers =
vec![synth::layer(v, [0, 0, 0, 0x98], "Shown", objects), synth::layer(v, [0x10, 1, 0, 0x98], "Hidden", vec![rect([0, 0, 0, 8])])];
let file = synth::file_of(version, vec![synth::page(false, layers)]);
let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}"));
let [shown, hidden] = d.pages[0].layers.as_slice() else { panic!("{version}: {:?}", d.pages[0].layers) };
assert_eq!(shown.flags, Flags::default(), "{version}");
assert_eq!(hidden.flags, Flags { hidden: true, locked: true }, "{version}");
let f = |hidden: bool, locked: bool| Flags { hidden, locked };
let own: Vec<Flags> = shown
.objects
.iter()
.map(|o| match o {
Object::Shape(s) => s.flags,
Object::Group { flags, .. } => *flags,
Object::Clip { container, .. } => container.flags,
})
.collect();
assert_eq!(own, [f(false, false), f(true, false), f(false, true), f(true, true), f(true, true)], "{version}");
assert!(
matches!(&shown.objects[4], Object::Group { objects, .. } if matches!(&objects[0], Object::Shape(s) if s.flags == Flags::default())),
"{version}"
);
assert!(d.warnings.contains(&Warning::UnsupportedObjects) || d.warnings.is_empty(), "{version}: {:?}", d.warnings);
// Past the object limit the group's rectangle comes in ungrouped, hidden and locked.
let d = read(&file, Limits { objects: 5, ..Limits::default() }).unwrap_or_else(|e| panic!("{version}: {e}"));
let last = d.pages[0].layers[0].objects.last();
assert!(matches!(last, Some(Object::Shape(s)) if s.flags == f(true, true)), "{version}: {last:?}");
}
}
/// A guideline is hidden when its own object, a group around it or its layer is.
#[test]
fn hidden_guidelines_say_so() {
for version in [700, 1300, 1600] {
let v = V(version);
let guide = |flags: [u8; 4]| {
let mut arg = vec![0; 12];
arg.extend(90_000_000i32.to_le_bytes());
arg.extend([v.coord(36.0), v.coord(0.0)].concat());
synth::flagged(synth::object(v, 0x16, &[(16000, arg)], None), flags)
};
let group = list(b"grp ", vec![chunk(b"flgs", vec![0, 1, 0, 0x10]), guide([0, 0, 0, 8])]);
let layers = vec![
synth::layer(v, [0, 0, 0, 0x98], "Shown", vec![guide([0, 0, 0, 8]), guide([0, 1, 0, 8]), group]),
synth::layer(v, [0, 1, 0, 0x98], "Hidden", vec![guide([0, 0, 0, 8])]),
];
let d = read(&synth::file_of(version, vec![synth::page(false, layers)]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}"));
let hidden: Vec<Vec<bool>> = d.pages[0].layers.iter().map(|l| l.guides.iter().map(|g| g.hidden).collect()).collect();
assert_eq!(hidden, [vec![false, true, true], vec![true]], "{version}");
}
}
/// Byte 0 of argument 14001 other than 0 fills the shape nonzero; 0, or no argument, fills it
/// even-odd; an argument without its byte is damage.
#[test]
fn a_winding_flag_fills_nonzero() {
for version in [300, 700, 1200, 1600] {
let v = V(version);
let read_with = |extra: &[(u32, Vec<u8>)]| {
let mut args = vec![(30, v.rect(10.0, 10.0, 0.0))];
args.extend(extra.iter().cloned());
let file = synth::file_of(
version,
vec![synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &args, None)])])],
);
let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}"));
(shapes(&d.pages[0].layers[0].objects)[0].nonzero, d.warnings)
};
assert_eq!(read_with(&[(14001, vec![1, 0, 0, 0])]), (true, vec![]), "{version}");
assert_eq!(read_with(&[(14001, vec![2])]), (true, vec![]), "{version}");
assert_eq!(read_with(&[(14001, vec![0, 0, 0, 0])]), (false, vec![]), "{version}");
assert_eq!(read_with(&[]), (false, vec![]), "{version}");
assert_eq!(read_with(&[(14001, vec![])]), (false, vec![Warning::Damaged]), "{version}");
}
}
/// A `cdr8` form type makes the file the 8.01 variant whatever its `vrsn` chunk names: its style
/// table is read with the 8.01 layout.
#[test]
fn a_cdr8_file_whose_version_chunk_names_800_reads_as_801() {
let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }];
for named in [800u16, 900, 1300] {
let table = synth::stlt(V(801), &[(0x100, 1)], &[(0x200, 2)], &styles, true);
let mut file = graphic_style_drawing(801, table);
file[8..12].copy_from_slice(b"cdr8");
let at = file.windows(4).position(|w| w == b"vrsn").unwrap() + 8;
assert_eq!(&file[at..at + 2], &801u16.to_le_bytes());
file[at..at + 2].copy_from_slice(&named.to_le_bytes());
let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{named}: {e}"));
assert_eq!(d.version, 801, "{named}");
let s = shapes(&d.pages[0].layers[0].objects);
assert_eq!(s[0].fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{named}");
assert!(d.warnings.is_empty(), "{named}: {:?}", d.warnings);
}
}
/// Before version 6 an object names its style in 2 bytes, which is not damage; an argument too
/// short for them is.
#[test]
fn a_style_id_before_version_6_is_two_bytes() {
for version in [400, 500] {
let v = V(version);
let read_with = |style: Vec<u8>| {
let object = synth::object(v, 1, &[(200, style), (30, v.rect(10.0, 10.0, 0.0))], None);
let file = synth::file_of(version, vec![synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object])])]);
let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}"));
(shapes(&d.pages[0].layers[0].objects).len(), d.warnings)
};
assert_eq!(read_with(vec![0x10, 0]), (1, vec![]), "{version}");
assert_eq!(read_with(vec![0x10]), (1, vec![Warning::Damaged]), "{version}");
}
}
/// A hidden or locked group of `LIST clpt` hides or locks the objects a container clips from it.
#[test]
fn a_clipped_groups_flags_reach_its_objects() {
for version in [700, 1300, 1600] {
let v = V(version);
let group = list(
b"grp ",
vec![chunk(b"flgs", vec![0x10, 1, 0x80, 0x10]), chunk(b"spnd", 0x77u32.to_le_bytes().to_vec()), clip_rect(v, 10.0, &[], [0.0, 0.0])],
);
let doc = list(b"doc ", vec![synth::mcfg(v, 612.0, 792.0), list(b"clpt", vec![group])]);
let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0])])]);
let d = read(&synth::file_of(version, vec![doc, page]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}"));
let [Object::Clip { container, objects }] = d.pages[0].layers[0].objects.as_slice() else {
panic!("{version}: {:?}", d.pages[0].layers[0].objects)
};
assert_eq!(container.flags, Flags::default(), "{version}");
assert!(matches!(objects.as_slice(), [Object::Shape(s)] if s.flags == Flags { hidden: true, locked: true }), "{version}: {objects:?}");
}
}
/// Before version 6 a clipped group's `spnd` id is 2 bytes.
#[test]
fn a_clipped_group_id_before_version_6_is_two_bytes() {
for version in [400, 500] {
let v = V(version);
let rect = |w: f64, extra: Vec<(u32, Vec<u8>)>| {
let mut args = vec![(30, v.rect(w, w, 0.0))];
args.extend(extra);
synth::object(v, 1, &args, None)
};
let clpt = list(b"clpt", vec![list(b"grp ", vec![chunk(b"spnd", vec![0x77, 0]), rect(10.0, vec![])])]);
let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(40.0, vec![synth::container(0x77)])])]);
let d = read(&synth::file_of(version, vec![list(b"doc ", vec![synth::mcfg(v, 612.0, 792.0), clpt]), page]), Limits::default())
.unwrap_or_else(|e| panic!("{version}: {e}"));
let objects = &d.pages[0].layers[0].objects;
assert!(matches!(objects.as_slice(), [Object::Clip { objects, .. }] if objects.len() == 1), "{version}: {objects:?}");
assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings);
}
}
/// A `trfd` entry ends at the next offset: one too short for its matrix makes the transform
/// damage and leaves the shape in place, even when the bytes after it would read as a matrix. A
/// table that stops before the last entry's end offset leaves that entry the rest of the record.
#[test]
fn a_transform_entry_ends_at_the_next_offset() {
for version in [400, 1100, 1300, 1600] {
let v = V(version);
let w = if version < 600 { 2 } else { 4 };
let moved = [1.0, 0.0, 0.0, 1.0, 72.0, 0.0];
let object = |trfd: Vec<u8>| {
let own = vec![chunk(b"loda", v.loda(1, &[(30, v.rect(10.0, 10.0, 0.0))])), list(b"trfl", vec![chunk(b"trfd", trfd)])];
list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 8]), list(b"lgob", own)])
};
let read_with = |trfd: Vec<u8>| {
let file = synth::file_of(version, vec![synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object(trfd)])])]);
let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}"));
(shapes(&d.pages[0].layers[0].objects)[0].matrix.0[4], d.warnings)
};
let whole = v.trfd(&[moved]);
assert!((read_with(whole.clone()).0 - 72.0).abs() < 0.01, "{version}");
// The end offset, right after the first, made 4 bytes past the entry's start.
let mut short = whole.clone();
let start = if w == 2 {
usize::from(u16::from_le_bytes([short[3 * w], short[3 * w + 1]]))
} else {
u32::from_le_bytes(short[12..16].try_into().unwrap()) as usize
};
short[4 * w..5 * w].copy_from_slice(&v.word(start + 4));
assert_eq!(read_with(short), (0.0, vec![Warning::Damaged]), "{version}");
// The entry first, then a table of its start alone at the record's end.
let entry = whole[5 * w..].to_vec();
let at = 3 * w + entry.len();
let mut end = [v.word(at + w), v.word(1), v.word(at)].concat();
end.extend(entry);
end.extend(v.word(3 * w));
let (x, warnings) = read_with(end);
assert!((x - 72.0).abs() < 0.01 && warnings.is_empty(), "{version}: {x} {warnings:?}");
}
}
/// From version 13 an outline's record of type 2 that names a library color gives the outline
/// that color; one without a name leaves the fixed color field.
#[test]
fn an_outline_takes_a_named_library_color_from_its_property_list() {
for version in [1300, 1500, 1600] {
let v = V(version);
let read_with = |props: Vec<u8>| {
let mut outl = v.outline(4, synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }, &synth::color(2, [0, 0, 0, 100]), &[]);
let mut record = 2u32.to_le_bytes().to_vec();
record.extend((props.len() as u32).to_le_bytes());
record.extend(props);
outl.splice(4..4, record);
let doc = list(b"doc ", vec![synth::mcfg(v, 612.0, 792.0), list(b"otlt", vec![chunk(b"outl", outl)])]);
let object = synth::object(v, 1, &[(10, 4u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None);
let file = synth::file_of(version, vec![doc, synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object])])]);
let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}"));
(shapes(&d.pages[0].layers[0].objects)[0].outline.as_ref().map(|o| o.color.clone()), d.warnings)
};
let named = synth::properties(&synth::color(5, [0, 0, 255, 0]), Some("Sky Blue"));
assert_eq!(read_with(named), (Some(Color::Spot { name: "Sky Blue".into(), tint: 1.0, look: Some([1.0, 0.0, 0.0]) }), vec![]), "{version}");
let plain = synth::properties(&synth::color(5, [0, 0, 255, 0]), None);
assert_eq!(read_with(plain), (Some(Color::Cmyk([0.0, 0.0, 0.0, 1.0])), vec![]), "{version}");
}
}
#[test]
fn linked_groups_are_left_out_with_a_warning() {
let v = V(1100);
+110 -22
View File
@@ -1,6 +1,7 @@
//! `.cdr` drawings of versions 1 to 27 (`.cdr`, and `.cdt` templates): the pages, layers,
//! guidelines, groups, curves, rectangles, ellipses, arcs and polygons with uniform fills and
//! outlines that `vectorcraft-cdr` reads, mapped to editable VectorCraft art. Pages become
//! outlines, their hidden and locked states, fill rules and uniform transparency that
//! `vectorcraft-cdr` reads, mapped to editable VectorCraft art. Pages become
//! artboards side by side; layers of the same name on different pages become one layer where the
//! pages stack them in the same order. What the
//! reader leaves out is listed in the warnings, one line for each kind ([`note`]).
@@ -49,6 +50,8 @@ fn note(w: Warning) -> &'static str {
const FALLBACK_PAGE: (f64, f64) = (612.0, 792.0);
/// The layer that holds guidelines at angles other than horizontal and vertical, as guide paths.
const GUIDES_LAYER: &str = "Guides";
/// The hidden layer that holds hidden guidelines.
const HIDDEN_GUIDES_LAYER: &str = "Hidden guides";
/// The most pages read, as artboards: the most a new document may have.
const MAX_PAGES: usize = crate::cmd::newdoc::MAX_ARTBOARDS as usize;
/// The longest page side, in points: the longest artboard side a new document may have.
@@ -159,7 +162,7 @@ impl shapes::Builder {
self.doc = doc;
self.name_spots();
// Bottom to top: the master page's layers, then the pages' in the order first seen.
let mut layers: Vec<(String, Vec<Arc<Node>>)> = Vec::new();
let mut layers: Vec<LayerOut> = Vec::new();
// A layer is known by its name and how many layers of that name the page has below it, so
// two layers of one name on a page stay two layers. Each key keeps every layer made for
// it, bottom to top.
@@ -188,8 +191,8 @@ impl shapes::Builder {
// takes the art.
match by_name.get(&key).and_then(|is| is.iter().copied().find(|&i| below.is_none_or(|b| i > b))) {
Some(i) => {
if let Some((_, kids)) = layers.get_mut(i) {
kids.extend(art);
if let Some(out) = layers.get_mut(i) {
out.add(art, l.flags);
}
below = Some(i);
}
@@ -225,7 +228,9 @@ impl shapes::Builder {
}
let is = by_name.entry(key).or_default();
is.insert(is.partition_point(|&i| i < at), at);
layers.insert(at, (l.name.clone(), art));
let mut out = LayerOut::new(l.name.clone());
out.add(art, l.flags);
layers.insert(at, out);
below = Some(at);
}
}
@@ -237,25 +242,63 @@ impl shapes::Builder {
}
if !self.guide_paths.is_empty() {
let paths = std::mem::take(&mut self.guide_paths);
// At the layer limit the guide paths go on the top layer instead of a layer of their own.
// At the layer limit the guide paths go on the top shown layer instead of a layer of
// their own; when every layer is hidden they go on the top one, with the limit warning.
let full = layers.len() >= MAX_LAYERS;
match layers.last_mut() {
Some((_, kids)) if full => kids.extend(paths),
_ => layers.push((GUIDES_LAYER.to_string(), paths)),
let top = layers.iter().rposition(|l| !l.hidden()).unwrap_or(layers.len().saturating_sub(1));
match layers.get_mut(top) {
Some(out) if full => {
if out.hidden() {
self.notes.push(Warning::TooDeep);
}
out.kids.extend(paths.into_iter().map(|p| (p, cd::Flags::default())));
}
_ => {
let mut out = LayerOut::new(GUIDES_LAYER.to_string());
out.kids.extend(paths.into_iter().map(|p| (p, cd::Flags::default())));
layers.push(out);
}
}
}
// Hidden guidelines go on a hidden layer of their own on top; past the layer limit they
// are left out.
if !self.hidden_guides.is_empty() || !self.hidden_paths.is_empty() {
if layers.len() >= MAX_LAYERS {
self.notes.push(Warning::TooDeep);
} else {
let mut art = std::mem::take(&mut self.hidden_paths);
for g in std::mem::take(&mut self.hidden_guides) {
let kind = NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard };
art.push(Arc::new(Node::new(self.doc.alloc_id(), kind)));
}
let mut out = LayerOut::new(HIDDEN_GUIDES_LAYER.to_string());
out.add(art, cd::Flags { hidden: true, locked: false });
layers.push(out);
}
}
let mut doc = std::mem::replace(&mut self.doc, Document::new(1.0, 1.0));
doc.layers = layers.into_iter().enumerate().map(|(i, (name, kids))| layer(&mut doc, &name, i, kids)).collect();
doc.layers = layers.into_iter().enumerate().map(|(i, out)| out.finish(&mut doc, i)).collect();
if doc.layers.is_empty() {
let l = layer(&mut doc, "Layer 1", 0, Vec::new());
let l = layer(&mut doc, "Layer 1", 0, Vec::new(), cd::Flags::default());
doc.layers.push(l);
}
// Ruler guides go at the top of the top layer, in the order they were read.
// Ruler guides go at the top of the top shown layer, in the order they were read. When
// every layer is hidden they go on a layer of their own on top; past the layer limit they
// go on the hidden top layer, with the limit warning.
let guides: Vec<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()) {
if !guides.is_empty() && !doc.layers.iter().any(|l| l.visible) && doc.layers.len() < MAX_LAYERS {
let i = doc.layers.len();
let l = layer(&mut doc, GUIDES_LAYER, i, Vec::new(), cd::Flags::default());
doc.layers.push(l);
}
let top = doc.layers.iter().rposition(|l| l.visible).unwrap_or(doc.layers.len().saturating_sub(1));
if !guides.is_empty() && doc.layers.get(top).is_some_and(|l| !l.visible) {
self.notes.push(Warning::TooDeep);
}
if let Some(kids) = doc.layers.get_mut(top).and_then(|l| Arc::make_mut(l).children_mut()) {
kids.extend(guides);
}
self.finish_swatches(&mut doc);
@@ -267,7 +310,7 @@ impl shapes::Builder {
/// The master page's layers: the desktop's objects once, on the first page's space; other
/// layers' objects on every page, as many copies as [`MAX_MASTER_COPIES`] allows.
fn master_layers(&mut self, d: &cd::Drawing, placed: &[Placed], layers: &mut Vec<(String, Vec<Arc<Node>>)>) {
fn master_layers(&mut self, d: &cd::Drawing, placed: &[Placed], layers: &mut Vec<LayerOut>) {
for l in d.master.iter().rev() {
if layers.len() >= MAX_LAYERS {
self.notes.push(Warning::TooDeep);
@@ -285,7 +328,9 @@ impl shapes::Builder {
art.extend(self.objects(&l.objects, p.to_doc));
}
let name = if l.name.is_empty() { "Master".to_string() } else { l.name.clone() };
layers.push((name, art));
let mut out = LayerOut::new(name);
out.add(art, l.flags);
layers.push(out);
}
}
@@ -293,7 +338,7 @@ impl shapes::Builder {
/// artboard, others as guide paths.
fn guides(&mut self, guides: &[cd::Guideline], p: &Placed, artboard: Option<u32>) {
for g in guides {
if self.guide_list.len() + self.guide_paths.len() >= MAX_GUIDES {
if self.guide_list.len() + self.guide_paths.len() + self.hidden_guides.len() + self.hidden_paths.len() >= MAX_GUIDES {
self.notes.push(Warning::TooDeep);
return;
}
@@ -303,12 +348,13 @@ impl shapes::Builder {
self.notes.push(Warning::TooDeep);
continue;
}
let list = if g.hidden { &mut self.hidden_guides } else { &mut self.guide_list };
if turn.abs() < 1e-9 {
self.guide_list.push(Guide { artboard, ..Guide::new(false, at.y) });
list.push(Guide { artboard, ..Guide::new(false, at.y) });
} else if (turn - 90.0).abs() < 1e-9 {
self.guide_list.push(Guide { artboard, ..Guide::new(true, at.x) });
list.push(Guide { artboard, ..Guide::new(true, at.x) });
} else {
self.angled_guide(at, g.angle, p.rect);
self.angled_guide(at, g.angle, p.rect, g.hidden);
}
}
}
@@ -322,7 +368,7 @@ fn copy_cost(objects: &[cd::Object]) -> usize {
while let Some(o) = stack.pop() {
n = n.saturating_add(1);
match o {
cd::Object::Group(kids) => stack.extend(kids),
cd::Object::Group { objects: kids, .. } => stack.extend(kids),
cd::Object::Shape(s) => n = n.saturating_add(shape_cost(s)),
cd::Object::Clip { container, objects } => {
// A container whose outline is behind its fill is built twice, as that outline
@@ -354,10 +400,52 @@ fn path_cost(s: &cd::Shape) -> usize {
}
}
/// A layer of the document named `name` holding `kids` (bottom to top).
fn layer(doc: &mut Document, name: &str, i: usize, kids: Vec<Arc<Node>>) -> Arc<Node> {
/// A document layer being made from the drawing's layers of one name: its art bottom to top, each
/// part with the flags of the layer it came from, and those flags for every layer merged into it.
struct LayerOut {
name: String,
kids: Vec<(Arc<Node>, cd::Flags)>,
merged: Vec<cd::Flags>,
}
impl LayerOut {
fn new(name: String) -> Self {
LayerOut { name, kids: Vec::new(), merged: Vec::new() }
}
/// Whether the layer node will be hidden: every drawing layer merged into it is.
fn hidden(&self) -> bool {
!self.merged.is_empty() && self.merged.iter().all(|f| f.hidden)
}
/// Adds the art of a drawing layer with flags `flags`.
fn add(&mut self, art: Vec<Arc<Node>>, flags: cd::Flags) {
self.kids.extend(art.into_iter().map(|n| (n, flags)));
self.merged.push(flags);
}
/// The layer node, as the `i`th layer from the bottom. It is hidden or locked when every
/// drawing layer merged into it is; otherwise the art of a hidden or locked drawing layer is
/// hidden or locked object by object.
fn finish(self, doc: &mut Document, i: usize) -> Arc<Node> {
let all = |f: fn(&cd::Flags) -> bool| !self.merged.is_empty() && self.merged.iter().all(f);
let own = cd::Flags { hidden: all(|f| f.hidden), locked: all(|f| f.locked) };
let kids = self
.kids
.into_iter()
.map(|(n, f)| shapes::with_flags(n, cd::Flags { hidden: f.hidden && !own.hidden, locked: f.locked && !own.locked }))
.collect();
layer(doc, &self.name, i, kids, own)
}
}
/// A layer of the document named `name` holding `kids` (bottom to top), hidden or locked as
/// `flags` say.
fn layer(doc: &mut Document, name: &str, i: usize, kids: Vec<Arc<Node>>, flags: cd::Flags) -> 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));
n.visible = !flags.hidden;
n.locked = flags.locked;
if let Some(c) = n.children_mut() {
*c = kids;
}
+264 -46
View File
@@ -8,10 +8,10 @@ use kurbo::{Affine, BezPath, Point, Rect};
use vectorcraft_cdr::Warning;
use vectorcraft_cdr::model::{self as cd, Geometry};
use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_color::{BlendMode, Color, Paint, Swatch};
use vectorcraft_doc::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, StrokeLayer};
use vectorcraft_doc::geom::{FillRule, PathData};
use vectorcraft_doc::{Document, Guide, LiveShape, Node, NodeKind};
use vectorcraft_doc::{Document, Guide, Knockout, LiveShape, Node, NodeKind};
/// The most nested groups mapped; the reader holds nesting well below it.
const MAX_DEPTH: usize = 256;
@@ -32,6 +32,9 @@ pub(super) struct Builder {
pub(super) guide_list: Vec<Guide>,
/// Guidelines at other angles, as guide paths.
pub(super) guide_paths: Vec<Arc<Node>>,
/// Hidden guidelines, as guides and guide paths of a hidden layer of their own.
pub(super) hidden_guides: Vec<Guide>,
pub(super) hidden_paths: Vec<Arc<Node>>,
/// Colors read in each model, which picks the document's color mode.
pub(super) cmyk: usize,
pub(super) rgb: usize,
@@ -50,6 +53,8 @@ impl Builder {
copies_left: super::MAX_MASTER_COPIES,
guide_list: Vec::new(),
guide_paths: Vec::new(),
hidden_guides: Vec::new(),
hidden_paths: Vec::new(),
cmyk: 0,
rgb: 0,
spots: Vec::new(),
@@ -69,7 +74,7 @@ impl Builder {
self.learn_spot(c);
}
}
cd::Object::Group(kids) => stack.extend(kids),
cd::Object::Group { objects: kids, .. } => stack.extend(kids),
cd::Object::Clip { container, objects } => {
for c in container.fill.iter().chain(container.outline.iter().map(|o| &o.color)) {
self.learn_spot(c);
@@ -117,11 +122,12 @@ impl Builder {
let mut out = Vec::with_capacity(objects.len());
for o in objects.iter().rev() {
match o {
cd::Object::Shape(s) => out.extend(self.shape(s, to_doc, false)),
cd::Object::Group(kids) => {
cd::Object::Shape(s) => out.extend(self.shape(s, to_doc, false).map(|n| with_flags(n, s.flags))),
cd::Object::Group { objects: kids, flags } => {
let children = self.objects_at(kids, to_doc, depth + 1);
if !children.is_empty() {
out.push(Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: false })));
let group = Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: false }));
out.push(with_flags(group, *flags));
}
}
// A clipping group whose clipping path keeps the container's paint: its fill
@@ -140,14 +146,28 @@ impl Builder {
let Some(clip) = clip else { continue };
let mut children = vec![clip];
children.extend(self.objects_at(objects, to_doc, depth + 1));
let group = Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: true }));
match outline {
let mut group = Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: true });
// A see-through container's fill knocks out the outline behind it, so the two
// parts do not add up their transparency where they overlap; the clipped
// objects inside still combine as usual.
let knock = outline.is_some() && (container.opacity < 1.0 || container.blend != cd::Blend::Normal);
if knock {
group.knockout = Knockout::Off;
}
let group = Arc::new(group);
// The container's flags hide or lock the whole clipping group.
let whole = match outline {
Some(outline) => {
let children = vec![outline, group];
out.push(Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: false })));
let mut pair = Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: false });
if knock {
pair.knockout = Knockout::On;
}
Arc::new(pair)
}
None => out.push(group),
}
None => group,
};
out.push(with_flags(whole, container.flags));
}
}
}
@@ -181,11 +201,13 @@ impl Builder {
if let Some(o) = s.outline.as_ref().filter(|o| !o.behind_fill) {
items.push(AppearanceItem::Stroke(self.stroke(o, &s.matrix)));
}
// A curve of several subpaths is filled with holes where they overlap: VectorCraft's own
// choice of rule for it.
let rule = FillRule::EvenOdd;
// Without the winding flag, a curve of several subpaths is filled with holes where they
// overlap: VectorCraft's own choice of rule for it.
let rule = if s.nonzero { FillRule::NonZero } else { FillRule::EvenOdd };
let mut n = Node::new(self.doc.alloc_id(), NodeKind::Path { path, rule, live: live.map(Box::new), clipping, guide: false });
n.appearance = Appearance { items, ..Appearance::default() }.into();
n.opacity = if s.opacity.is_finite() { s.opacity.clamp(0.0, 1.0) } else { 1.0 };
n.blend = blend(s.blend);
Some(Arc::new(n))
}
@@ -270,8 +292,9 @@ impl Builder {
/// A guideline through `at` (document space) at `angle` degrees counterclockwise, as a guide
/// path from edge to edge of the page `rect`, so it moves with the page's artboard. A
/// guideline that misses the page runs through `at` for the page's diagonal each way.
pub(super) fn angled_guide(&mut self, at: Point, angle: f64, rect: Rect) {
/// guideline that misses the page runs through `at` for the page's diagonal each way. A
/// `hidden` one goes with the hidden guides.
pub(super) fn angled_guide(&mut self, at: Point, angle: f64, rect: Rect, hidden: bool) {
let (s, c) = angle.to_radians().sin_cos();
// The document's y axis points down.
let dir = kurbo::Vec2::new(c, -s);
@@ -291,7 +314,7 @@ impl Builder {
return;
}
let n = Node::new(self.doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: true });
self.guide_paths.push(Arc::new(n));
if hidden { self.hidden_paths.push(Arc::new(n)) } else { self.guide_paths.push(Arc::new(n)) }
}
}
@@ -318,6 +341,37 @@ fn affine(m: &cd::Matrix) -> Affine {
Affine::new(m.0)
}
fn blend(b: cd::Blend) -> BlendMode {
match b {
cd::Blend::Normal => BlendMode::Normal,
cd::Blend::Multiply => BlendMode::Multiply,
cd::Blend::Screen => BlendMode::Screen,
cd::Blend::Overlay => BlendMode::Overlay,
cd::Blend::SoftLight => BlendMode::SoftLight,
cd::Blend::HardLight => BlendMode::HardLight,
cd::Blend::ColorDodge => BlendMode::ColorDodge,
cd::Blend::ColorBurn => BlendMode::ColorBurn,
cd::Blend::Darken => BlendMode::Darken,
cd::Blend::Lighten => BlendMode::Lighten,
cd::Blend::Difference => BlendMode::Difference,
cd::Blend::Exclusion => BlendMode::Exclusion,
cd::Blend::Hue => BlendMode::Hue,
cd::Blend::Saturation => BlendMode::Saturation,
cd::Blend::Color => BlendMode::Color,
cd::Blend::Luminosity => BlendMode::Luminosity,
}
}
/// `n` hidden or locked as `flags` say; left as it is when they say neither.
pub(super) fn with_flags(mut n: Arc<Node>, flags: cd::Flags) -> Arc<Node> {
if flags.hidden || flags.locked {
let m = Arc::make_mut(&mut n);
m.visible &= !flags.hidden;
m.locked |= flags.locked;
}
n
}
fn bez(p: &cd::Path) -> BezPath {
let pt = |q: cd::Pt| Point::new(q.x, q.y);
let mut bp = BezPath::new();
@@ -382,15 +436,15 @@ mod tests {
fn a_spot_color_keeps_its_color_from_its_strongest_use() {
let red = [1.0, 0.0, 0.0];
let shape = |tint: f32, look: [f32; 3]| {
cd::Object::Shape(Box::new(cd::Shape {
geometry: Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] },
matrix: cd::Matrix::IDENTITY,
fill: Some(cd::Color::Spot { name: "Red ink".into(), tint, look: Some(look) }),
outline: None,
}))
cd::Object::Shape(Box::new(cd::Shape::new(
Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] },
cd::Matrix::IDENTITY,
Some(cd::Color::Spot { name: "Red ink".into(), tint, look: Some(look) }),
None,
)))
};
for objects in [vec![shape(0.0, [1.0; 3]), shape(1.0, red)], vec![shape(1.0, red), shape(0.0, [1.0; 3])]] {
let layer = cd::Layer { name: "L".into(), kind: cd::LayerKind::Drawing, objects, guides: vec![] };
let layer = cd::Layer { name: "L".into(), kind: cd::LayerKind::Drawing, flags: cd::Flags::default(), objects, guides: vec![] };
let d = cd::Drawing {
version: 1300,
page_size: None,
@@ -419,14 +473,20 @@ mod tests {
#[test]
fn a_spot_color_named_like_a_default_swatch_stays_a_spot_color() {
let shape = |name: &str| {
cd::Object::Shape(Box::new(cd::Shape {
geometry: Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] },
matrix: cd::Matrix::IDENTITY,
fill: Some(cd::Color::Spot { name: name.into(), tint: 1.0, look: Some([0.0; 3]) }),
outline: None,
}))
cd::Object::Shape(Box::new(cd::Shape::new(
Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] },
cd::Matrix::IDENTITY,
Some(cd::Color::Spot { name: name.into(), tint: 1.0, look: Some([0.0; 3]) }),
None,
)))
};
let layer = cd::Layer {
name: "L".into(),
kind: cd::LayerKind::Drawing,
flags: cd::Flags::default(),
objects: vec![shape("Black"), shape("Black 2")],
guides: vec![],
};
let layer = cd::Layer { name: "L".into(), kind: cd::LayerKind::Drawing, objects: vec![shape("Black"), shape("Black 2")], guides: vec![] };
let d = cd::Drawing {
version: 1300,
page_size: None,
@@ -461,13 +521,13 @@ mod tests {
#[test]
fn master_copies_count_their_path_segments() {
let segments = (1..=300).map(|i| cd::Segment::Line(cd::Pt { x: f64::from(i), y: 0.0 })).collect();
let curve = cd::Object::Shape(Box::new(cd::Shape {
geometry: Geometry::Path(cd::Path { subpaths: vec![cd::SubPath { start: cd::Pt { x: 0.0, y: 0.0 }, segments, closed: false }] }),
matrix: cd::Matrix::IDENTITY,
fill: None,
outline: None,
}));
let master = cd::Layer { name: "M".into(), kind: cd::LayerKind::Drawing, objects: vec![curve], guides: vec![] };
let curve = cd::Object::Shape(Box::new(cd::Shape::new(
Geometry::Path(cd::Path { subpaths: vec![cd::SubPath { start: cd::Pt { x: 0.0, y: 0.0 }, segments, closed: false }] }),
cd::Matrix::IDENTITY,
None,
None,
)));
let master = cd::Layer { name: "M".into(), kind: cd::LayerKind::Drawing, flags: cd::Flags::default(), objects: vec![curve], guides: vec![] };
let d = cd::Drawing {
version: 1300,
page_size: None,
@@ -497,13 +557,13 @@ mod tests {
behind_fill: false,
scale_with: false,
};
let rect = cd::Object::Shape(Box::new(cd::Shape {
geometry: Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] },
matrix: cd::Matrix::IDENTITY,
fill: None,
outline: Some(outline),
}));
let master = cd::Layer { name: "M".into(), kind: cd::LayerKind::Drawing, objects: vec![rect], guides: vec![] };
let rect = cd::Object::Shape(Box::new(cd::Shape::new(
Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] },
cd::Matrix::IDENTITY,
None,
Some(outline),
)));
let master = cd::Layer { name: "M".into(), kind: cd::LayerKind::Drawing, flags: cd::Flags::default(), objects: vec![rect], guides: vec![] };
let d = cd::Drawing {
version: 1300,
page_size: None,
@@ -536,7 +596,7 @@ mod tests {
behind_fill: false,
scale_with,
};
let rect = cd::Shape { geometry: Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, matrix, fill: None, outline: Some(outline) };
let rect = cd::Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, matrix, None, Some(outline));
let mut b = Builder::new();
let Some(node) = b.shape(&rect, Affine::IDENTITY, false) else { panic!("{scale_with}: no shape") };
let [AppearanceItem::Stroke(s)] = node.appearance.items.as_slice() else { panic!("{scale_with}: {:?}", node.appearance.items) };
@@ -546,6 +606,164 @@ mod tests {
}
}
/// A shape's opacity, blend mode and fill rule reach its path; a shape without them is opaque,
/// normal and filled even-odd.
#[test]
fn opacity_blend_and_fill_rule_reach_the_path() {
let square = Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] };
let plain = cd::Shape::new(square.clone(), cd::Matrix::IDENTITY, Some(cd::Color::Gray(1.0)), None);
let seen = cd::Shape { nonzero: true, opacity: 0.25, blend: cd::Blend::Multiply, ..plain.clone() };
let mut b = Builder::new();
for (s, opacity, blend, nonzero) in [(&plain, 1.0, BlendMode::Normal, false), (&seen, 0.25, BlendMode::Multiply, true)] {
let Some(n) = b.shape(s, Affine::IDENTITY, false) else { panic!("no shape") };
let NodeKind::Path { rule, .. } = &n.kind else { panic!("{:?}", n.kind) };
assert_eq!((n.opacity, n.blend, *rule == FillRule::NonZero), (opacity, blend, nonzero));
}
let wild = cd::Shape { opacity: f32::NAN, ..plain };
assert_eq!(b.shape(&wild, Affine::IDENTITY, false).map(|n| n.opacity), Some(1.0));
}
/// Ruler guides go on the top shown layer, or on a layer of their own when every layer is
/// hidden; hidden guidelines go on a hidden layer of their own.
#[test]
fn ruler_guides_stay_off_hidden_layers() {
let square = || cd::Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, cd::Matrix::IDENTITY, None, None);
let hidden = cd::Flags { hidden: true, locked: false };
let layer = |name: &str, flags: cd::Flags| cd::Layer {
name: name.into(),
kind: cd::LayerKind::Drawing,
flags,
objects: vec![cd::Object::Shape(Box::new(square()))],
guides: vec![],
};
let guides_of = |layers: Vec<cd::Layer>, hidden: bool| {
let d = cd::Drawing {
version: 1300,
page_size: None,
pages: vec![cd::Page { size: None, layers }],
master: vec![],
guides: vec![cd::Guideline { at: cd::Pt { x: 0.0, y: 0.0 }, angle: 90.0, hidden }],
warnings: vec![],
};
let doc = Builder::new().document(&d);
doc.layers
.iter()
.map(|l| {
let n = l.children().map_or(0, |k| k.iter().filter(|n| matches!(n.kind, NodeKind::RulerGuide { .. })).count());
(l.name.clone().unwrap_or_default(), l.visible, n)
})
.collect::<Vec<_>>()
};
// Front to back: "Top" hidden over "Base" shown.
let got = guides_of(vec![layer("Top", hidden), layer("Base", cd::Flags::default())], false);
assert_eq!(got, [("Base".to_string(), true, 1), ("Top".to_string(), false, 0)]);
let got = guides_of(vec![layer("Only", hidden)], false);
assert_eq!(got, [("Only".to_string(), false, 0), ("Guides".to_string(), true, 1)]);
let got = guides_of(vec![layer("Base", cd::Flags::default())], true);
assert_eq!(got, [("Base".to_string(), true, 0), ("Hidden guides".to_string(), false, 1)]);
// At the layer limit an angled guideline's path goes on the top shown layer.
let mut layers: Vec<cd::Layer> = (0..super::super::MAX_LAYERS).map(|i| layer(&format!("L{i}"), cd::Flags::default())).collect();
layers[0].flags = hidden;
let d = cd::Drawing {
version: 1300,
page_size: None,
pages: vec![cd::Page { size: None, layers }],
master: vec![],
guides: vec![cd::Guideline { at: cd::Pt { x: 0.0, y: 0.0 }, angle: 45.0, hidden: false }],
warnings: vec![],
};
let mut b = Builder::new();
let doc = b.document(&d);
let with_path: Vec<(bool, bool)> = doc
.layers
.iter()
.rev()
.take(2)
.map(|l| (l.visible, l.children().is_some_and(|k| k.iter().any(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })))))
.collect();
assert_eq!(with_path, [(false, false), (true, true)]);
assert!(!b.notes.contains(&Warning::TooDeep));
// With every layer hidden as well, the guides go on the top layer with the limit warning.
let mut d = d;
for l in &mut d.pages[0].layers {
l.flags = hidden;
}
d.guides.push(cd::Guideline { at: cd::Pt { x: 0.0, y: 0.0 }, angle: 90.0, hidden: false });
let mut b = Builder::new();
let doc = b.document(&d);
assert!(doc.layers.iter().all(|l| !l.visible));
assert!(b.notes.contains(&Warning::TooDeep), "{:?}", b.notes);
}
/// A see-through container whose outline is behind its fill knocks the outline out under its
/// fill, and its clipping group keeps its own objects combining as usual; an opaque one leaves
/// the pair a plain group.
#[test]
fn a_see_through_container_with_its_outline_behind_knocks_it_out() {
let outline = cd::Outline {
width: 4.0,
color: cd::Color::Gray(1.0),
cap: cd::Cap::Butt,
join: cd::Join::Miter,
dashes: vec![],
behind_fill: true,
scale_with: false,
};
let square = || cd::Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, cd::Matrix::IDENTITY, Some(cd::Color::Gray(0.5)), None);
for (opacity, knockout, inner) in [(1.0, Knockout::Neutral, Knockout::Neutral), (0.5, Knockout::On, Knockout::Off)] {
let container = Box::new(cd::Shape { opacity, outline: Some(outline.clone()), ..square() });
let clip = cd::Object::Clip { container, objects: vec![cd::Object::Shape(Box::new(square()))] };
let nodes = Builder::new().objects(&[clip], Affine::IDENTITY);
let [pair] = nodes.as_slice() else { panic!("{nodes:?}") };
let NodeKind::Group { children, clip: false } = &pair.kind else { panic!("{:?}", pair.kind) };
assert_eq!(pair.knockout, knockout, "{opacity}");
let clipping = children.iter().find(|n| matches!(n.kind, NodeKind::Group { clip: true, .. }));
assert_eq!(clipping.map(|n| n.knockout), Some(inner), "{opacity}");
}
}
/// A hidden or locked shape, group or clipping container gives its node those states. A layer
/// is hidden or locked when every drawing layer merged into it is; otherwise only the art of
/// the hidden or locked drawing layer is.
#[test]
fn hidden_and_locked_flags_reach_the_nodes() {
let square = || cd::Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, cd::Matrix::IDENTITY, Some(cd::Color::Gray(1.0)), None);
let hidden = cd::Flags { hidden: true, locked: false };
let locked = cd::Flags { hidden: false, locked: true };
let objects = vec![
cd::Object::Shape(Box::new(cd::Shape { flags: hidden, ..square() })),
cd::Object::Group { objects: vec![cd::Object::Shape(Box::new(square()))], flags: locked },
cd::Object::Clip { container: Box::new(cd::Shape { flags: hidden, ..square() }), objects: vec![cd::Object::Shape(Box::new(square()))] },
];
let layer =
|flags: cd::Flags, objects: Vec<cd::Object>| cd::Layer { name: "L".into(), kind: cd::LayerKind::Drawing, flags, objects, guides: vec![] };
let drawing = |pages: Vec<Vec<cd::Layer>>| cd::Drawing {
version: 1300,
page_size: None,
pages: pages.into_iter().map(|layers| cd::Page { size: None, layers }).collect(),
master: vec![],
guides: vec![],
warnings: vec![],
};
let doc = Builder::new().document(&drawing(vec![vec![layer(cd::Flags::default(), objects)]]));
let kids = doc.layers[0].children().unwrap();
// Bottom to top: the clipping group, the group, the shape.
let states: Vec<(bool, bool)> = kids.iter().map(|n| (n.visible, n.locked)).collect();
assert_eq!(states, [(false, false), (true, true), (false, false)]);
assert!(doc.layers[0].visible && !doc.layers[0].locked);
// One name on two pages: hidden on the first only, then on both.
let one = || vec![cd::Object::Shape(Box::new(square()))];
let doc = Builder::new().document(&drawing(vec![vec![layer(hidden, one())], vec![layer(cd::Flags::default(), one())]]));
assert_eq!(doc.layers.len(), 1);
assert!(doc.layers[0].visible);
let states: Vec<bool> = doc.layers[0].children().unwrap().iter().map(|n| n.visible).collect();
assert_eq!(states, [false, true]);
let doc = Builder::new().document(&drawing(vec![vec![layer(cd::Flags { hidden: true, locked: true }, one())], vec![layer(hidden, one())]]));
assert!(!doc.layers[0].visible && !doc.layers[0].locked);
let states: Vec<(bool, bool)> = doc.layers[0].children().unwrap().iter().map(|n| (n.visible, n.locked)).collect();
assert_eq!(states, [(true, true), (true, false)]);
}
/// A corner rounded in the file stays on the same corner of the page, however the rectangle's
/// size points.
#[test]
+25
View File
@@ -546,6 +546,31 @@ fn lenses_and_transparency_are_named_in_the_warnings() {
assert_eq!(warnings, ["CDR lenses and object transparency were not applied, and the objects they are on show opaque"]);
}
/// A uniform transparency, a winding flag and hidden and locked flags of a drawing of version 16
/// open as the object's opacity, blend mode and fill rule and as hidden and locked nodes, without
/// a warning.
#[test]
fn transparency_winding_and_flags_open_on_the_art() {
let v = V(1600);
let args = vec![(30, v.rect(10.0, 10.0, 0.0)), synth::transparency(40.0, 29), (14001, vec![1, 0, 0, 0])];
let object = synth::flagged(synth::object(v, 1, &args, None), [0x10, 0, 0, 8]);
let layers = vec![
synth::layer(v, [0, 0, 0, 0x98], "Shown", vec![object]),
synth::layer(v, [0, 1, 0, 0x98], "Hidden", vec![synth::object(v, 1, &args[..1], None)]),
];
let file = synth::file_of(1600, vec![synth::page(false, layers)]);
let (doc, warnings) = super::cdr::import(&file).unwrap();
assert!(warnings.is_empty(), "{warnings:?}");
// Bottom to top: "Hidden", then "Shown".
let states: Vec<(String, bool)> = doc.layers.iter().map(|l| (l.name.clone().unwrap_or_default(), l.visible)).collect();
assert_eq!(states, [("Hidden".to_string(), false), ("Shown".to_string(), true)]);
let shown = doc.layers[1].children().unwrap();
let [n] = shown.as_slice() else { panic!("{shown:?}") };
assert!(matches!(n.kind, NodeKind::Path { rule: vectorcraft_doc::geom::FillRule::NonZero, .. }), "{:?}", n.kind);
assert!((n.opacity - 0.6).abs() < 1e-6 && n.blend == vectorcraft_color::BlendMode::Overlay, "{} {:?}", n.opacity, n.blend);
assert!(n.locked && n.visible);
}
#[test]
fn other_versions_and_damaged_drawings_say_why() {
let mut s = Session::new();
+1 -1
View File
@@ -301,7 +301,7 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors,
| PICT | open, place (legacy) | yes (versions 1 and 2: shapes, lines, regions, text, bitmaps, pixel maps and QuickTime JPEG images; placed as one group clipped to the picture's frame) | no | `.pct`, `.pic` and `.pict`; a version 2 picture also opens by its content; a two-color pattern fills with its average color; inverted shapes, transfer modes other than a copy and QuickTime images in other formats come back as warnings; a picture cut short keeps what came before it; tests in `crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs` and `crates/engine/tests/import_fuzz.rs` |
| Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` |
| FreeHand `.fh*` | open (legacy) | no | no | |
| `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, clipping containers, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses and object transparency are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies; version 3 envelopes are not applied, so the objects and groups under one keep their outlines and matrices, with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; record layouts and their sources in `crates/cdr/PROVENANCE.md`; synthetic test files only; tests in `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` |
| `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, clipping containers, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; hidden and locked layers, groups and objects; the winding flag as the nonzero fill rule; uniform transparency of version 13 on as opacity and blend mode; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses, other transparency and merge modes without a blend mode are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies; version 3 envelopes are not applied, so the objects and groups under one keep their outlines and matrices, with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; record layouts and their sources in `crates/cdr/PROVENANCE.md`; synthetic test files only; tests in `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` |
| Text `.txt` | place, export | place (Text Import Options) | yes | |
| RTF `.rtf` | place | place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only |
| Word `.docx` | place | place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out |
+10 -4
View File
@@ -8050,10 +8050,16 @@ included) become paths, and rectangles and ellipses become live shapes; a rectan
fills and outlines keep their colors, widths, caps, joins and dashes (an outline of width 0 becomes a 0.25 pt stroke),
an outline behind the fill becomes a stroke below the fill, and an object without a fill or outline of its own
takes its style's. A library color that the drawing stores with its
name and values (version 13 and later) becomes a spot swatch with its tint, and one stored only by its number opens as
a black spot color. Text, bitmaps, blends, contours, brush strokes, other objects the reader doesn't read yet,
fountain, pattern, texture and PostScript fills, and outline arrowheads are left out, and lenses and object
transparency are not applied. The `warnings` of
name and values (version 13 and later, in a fill or an outline) becomes a spot swatch with its tint, and one stored
only by its number opens as a black spot color. An object whose winding flag is set is filled with the nonzero rule, and
any other with even-odd. Hidden and locked layers, groups and objects open hidden and locked; when layers of one name
merge and only some of them are hidden or locked, their art is hidden or locked object by object. Hidden guidelines go
on a hidden layer named Hidden guides, and the other guides go on the top shown layer. A uniform
transparency (version 13 and later) becomes the object's opacity, and its merge mode the object's blend mode.
VectorCraft reads the stored value as the transparency in percent, 0 opaque and 100 clear, and a set winding flag as
the nonzero rule; both are VectorCraft's own readings. Text, bitmaps, blends, contours, brush strokes, other objects the
reader doesn't read yet, fountain, pattern, texture and PostScript fills, and outline arrowheads are left out, and
lenses, other transparency and merge modes without a VectorCraft blend mode are not applied. The `warnings` of
`document.open` name each of these kinds the drawing had, and say when damaged parts or parts past the import limits
were left out. Drawings of versions after 27 are refused with a message, and so are packages that are
encrypted, ZIP64 archives or split across files. VectorCraft doesn't write `.cdr` files.
+1 -1
View File
@@ -1757,7 +1757,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`).
- DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge.
- Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md).
- `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill, or scaled with the object's matrix, where the file says so), an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, object transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`).
- `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill, or scaled with the object's matrix, where the file says so), an object without a fill or outline of its own taking its style's, hidden and locked layers, groups and objects, the winding flag as the nonzero fill rule, and a uniform transparency of version 13 and later as the object's opacity and blend mode. A library color stored with its name and values (version 13 and later, in a fill or an outline) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, other transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`).
- Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it.
- Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`).
- Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. EPS and PostScript `.ai` files are still embedded (`crates/engine/src/tests/placed_document.rs`).