From 2cd5ad52d1a08e5f889a45566a033374e2e16445 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 12:01:08 -0800 Subject: [PATCH] .cdr import: objects without their own fill or outline take their style's From version 7 a drawing keeps its styles in LIST stlt, and an object names its style in argument 200. An object without a fill (20) or outline (10) argument of its own now takes the fill and outline its style gives, through the style's parents where the style leaves one to them. Before, such objects came in without a fill or outline. The table is read only when it parses to the end of its list; a table that does not is damage when an object needs a style from it. Its entries and styles count toward the chunk limit. PROVENANCE.md row R45 gives the layout and the sample files it was checked against. --- crates/cdr/PROVENANCE.md | 1 + crates/cdr/README.md | 1 + crates/cdr/src/build.rs | 55 ++++++++- crates/cdr/src/lib.rs | 1 + crates/cdr/src/limits.rs | 9 +- crates/cdr/src/riff.rs | 2 +- crates/cdr/src/styles.rs | 241 ++++++++++++++++++++++++++++++++++++++ crates/cdr/src/synth.rs | 101 ++++++++++++++++ crates/cdr/tests/read.rs | 70 +++++++++++ docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 11 files changed, 475 insertions(+), 11 deletions(-) create mode 100644 crates/cdr/src/styles.rs diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index c9a96f1206..6d050ce00d 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -90,3 +90,4 @@ file is committed. | R42 | The records of a file of version 1 or 2 run from the front of the stacking order to the back. Every record starts with the u32 24. A group or layer record is 28 bytes, and bit 0x40 of its flags byte at 26 is clear. A drawn object has that bit set (0x40 in files with the markers `e` and `m`, 0xc0 with `l`) and a u16 body size at byte 28; it is the body size plus 32 bytes long. A drawn object of another type than those of R43 gives its length otherwise, and the records after it are not read | S: TP `WI.CDR`, `FLAG.CDR`, `MENU.CDR` and `DRINKS.CDR`; the order checked against the picture of `MENU.CDR` | sample | | R43 | A drawn object of version 1 or 2: a point (two i16) at byte 32; six i32 in 16.16 fixed point at 36, `a b tx c d ty`, with x' = a x + b y + tx + the point's x and y' = c x + d y + ty + the point's y; the object type at 60 (0 rectangle, 1 ellipse, 2 curve, 3 text); a byte at 67 that is not 0 when the object is outlined, the outline's width (u16) at 68 and its color at 74; the fill type (0 none, 1 uniform) and its color after it, at 94 and 95 with the marker `e` and at 105 and 106 with `l` and `m`; the shape from byte 114 with `e` and 136 with `l` and `m`. Colors are as R36 | S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`) and `MENU.CDR` (`l`), checked against the pictures of `FLAG.CDR` and `MENU.CDR` | sample | | R44 | Shapes of version 1 or 2: a rectangle's width and height (i16), then a corner radius; an ellipse's width and height, then two angles; a curve's point list as R39 and R16 | S: rectangles in TP `FLAG.CDR`, ellipses and curves in TP `WI.CDR`, curves in TP `MENU.CDR` | sample (the radius of files with the marker `e`, which no sample shows, and how the angles make an arc: unconfirmed; a radius is kept only when it is at most half the shorter side, and an ellipse whose angles differ is left out with a warning) | +| R45 | `LIST stlt` from version 7: a u32 style count, and when it is not 0: the fill table (a u32 count, entries of a table id, 4 bytes and a `fild` id, 12 bytes each, 60 from version 13), the outline table (12-byte entries laid out the same way, naming `outl` ids), the text tables (fonts of 44 bytes, 60 from version 10; alignments of 12; spacings of 52; tables of 152 and 784; bullets whose length a u32 inside them sets; indents of 28; hyphenation of 32, 36 from 13; drop caps of 28; from 8.01 a table of 12), then the styles: kind (u32), id, parent id, 8 bytes, name length and name (bytes before 12, UTF-16 units from it), the fill and outline table ids, then 16 bytes (20 from 8.01) for kinds above 1 and 20 more for kinds above 2. An object names its style in argument 200 (u32). An object without argument 20 or 10 takes the fill or outline of its style; a style whose table id is 0 takes its parent's | K L593-L600, L852, L1926-L2198; S: UC `corel_rounded_rect_cdr7.cdr`, whose rectangles carry argument 200 and neither 10 nor 20, and name the style whose outline is a black hairline and whose fill is none, as the file's picture shows; the table parses exactly to the end of the list in each of the 498 sample files of versions 7 to 15 that has one, and every object with argument 200 in them names a style whose table ids are in the tables | public-spec (what the table ids name, and that an object takes its style's fill and outline: sample; a style taking its parent's entry: unconfirmed, as only text styles in the samples leave theirs to the parent, and a wrong guess draws a shape without that fill or outline) | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index d5cf86ef54..d1a7c8fc21 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -21,6 +21,7 @@ with each object's transform. It does not write `.cdr` files. | Polygons and stars (a base side copied for each side) | paths | | Uniform fills: CMYK, CMY, RGB, gray, registration, library colors | colors, spot colors with their tints | | Outlines: width, caps, joins, dashes, the no-outline flag | outlines | +| Styles (`LIST stlt`, versions 7 to 15) that objects name | the fill and outline of an object that has none of its own | Text, bitmaps, linked groups (blends, contours, brush strokes), B-spline curves, fountain, pattern, texture and PostScript fills and outline arrowheads are not read; the drawing's diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs index b78474136b..0eb6bf29df 100644 --- a/crates/cdr/src/build.rs +++ b/crates/cdr/src/build.rs @@ -11,6 +11,7 @@ use crate::limits::Budget; use crate::model::{Color, Drawing, Geometry, Guideline, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape}; use crate::records::{self, Loda}; use crate::riff::{Chunk, Index, push}; +use crate::styles::Styles; use crate::{Error, Warning}; /// Object types (R6). @@ -25,6 +26,7 @@ const ARG_OUTLINE: u32 = 10; const ARG_FILL: u32 = 20; const ARG_COORDS: u32 = 30; const ARG_TRANSFORMS: u32 = 100; +const ARG_STYLE: u32 = 200; const ARG_NAME: u32 = 1000; const ARG_POLYGON: u32 = 11000; const ARG_GUIDE: u32 = 16000; @@ -44,6 +46,9 @@ struct Ctx<'a, 'b> { outline_chunks: HashMap, fills: HashMap>, outlines: HashMap>, + /// The styles objects name in argument 200 (R45): `Err` when the file's style table doesn't + /// parse. + styles: Result, } pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec) -> Result { @@ -62,8 +67,22 @@ pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec) let mut found = Found::default(); collect(ix, root, &mut found); let page_size = found.mcfg.and_then(|c| page_size(ix.data(c), &p)); - let mut cx = - Ctx { ix, p, budget, warn, fill_chunks: HashMap::new(), outline_chunks: HashMap::new(), fills: HashMap::new(), outlines: HashMap::new() }; + // Before version 7 a `LIST stlt` holds chunks, not the style table (R4). + let styles = match found.stlt { + Some(c) if version >= 700 => Styles::read(ix.data(c), version, budget)?.ok_or(()), + _ => Ok(Styles::default()), + }; + let mut cx = Ctx { + ix, + p, + budget, + warn, + fill_chunks: HashMap::new(), + outline_chunks: HashMap::new(), + fills: HashMap::new(), + outlines: HashMap::new(), + styles, + }; for c in &found.fills { if let Some(id) = Rd::new(ix.data(c)).u32() { cx.fill_chunks.entry(id).or_insert(ix.data(c)); @@ -118,11 +137,12 @@ struct Found<'i> { outlines: Vec<&'i Chunk>, mcfg: Option<&'i Chunk>, guid: Option<&'i Chunk>, + stlt: Option<&'i Chunk>, pages: Vec<&'i Chunk>, } -/// Every fill, outline and page in file order, and the first `mcfg` and `guid`; pages are not -/// looked into. +/// Every fill, outline and page in file order, and the first `mcfg`, `guid` and `LIST stlt`; +/// pages are not looked into. fn collect<'i>(ix: &'i Index, root: &'i Chunk, found: &mut Found<'i>) { let mut stack: Vec<&Chunk> = ix.children(root).iter().rev().collect(); while let Some(c) = stack.pop() { @@ -131,6 +151,7 @@ fn collect<'i>(ix: &'i Index, root: &'i Chunk, found: &mut Found<'i>) { b"outl" => found.outlines.push(c), b"mcfg" => found.mcfg = found.mcfg.or(Some(c)), b"guid" => found.guid = found.guid.or(Some(c)), + _ if c.is_list(b"stlt") => found.stlt = found.stlt.or(Some(c)), _ if c.is_list(b"page") => found.pages.push(c), _ => stack.extend(ix.children(c).iter().rev()), } @@ -414,11 +435,33 @@ impl<'a, 'b> Ctx<'a, 'b> { Matrix::IDENTITY }), }; - let fill = loda.arg(ARG_FILL).and_then(id_of).and_then(|id| self.fill(id)); - let outline = loda.arg(ARG_OUTLINE).and_then(id_of).and_then(|id| self.outline(id)); + // Without a fill or outline argument of its own, an object takes its style's (R45). + let style = loda.arg(ARG_STYLE).and_then(id_of); + let fill_id = match loda.arg(ARG_FILL) { + Some(b) => id_of(b), + None => style.and_then(|s| self.style_entry(s, Styles::fill)), + }; + let outline_id = match loda.arg(ARG_OUTLINE) { + Some(b) => id_of(b), + None => style.and_then(|s| self.style_entry(s, Styles::outline)), + }; + let fill = fill_id.and_then(|id| self.fill(id)); + let outline = outline_id.and_then(|id| self.outline(id)); Some(Object::Shape(Box::new(Shape { geometry, matrix, fill, outline }))) } + /// The fill or outline record that style `id` names; a style table that doesn't parse is + /// damage, and the object is drawn without it. + fn style_entry(&mut self, id: u32, entry: fn(&Styles, u32) -> Option) -> Option { + match &self.styles { + Ok(s) => entry(s, id), + Err(()) => { + push(self.warn, Warning::Damaged); + None + } + } + } + /// A version 3 object, whose transforms, fill and outline are arguments of its own record /// (R33, R34, R35). A fill or an outline that is there but can't be read is damage. fn inline_object(&mut self, loda: &Loda, outer: &Matrix) -> Option { diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs index 847288b878..6d642cc2b7 100644 --- a/crates/cdr/src/lib.rs +++ b/crates/cdr/src/lib.rs @@ -21,6 +21,7 @@ pub mod model; mod package; mod records; mod riff; +mod styles; #[cfg(any(test, feature = "synth"))] pub mod synth; mod wl; diff --git a/crates/cdr/src/limits.rs b/crates/cdr/src/limits.rs index 34db782b4c..b3aadc23df 100644 --- a/crates/cdr/src/limits.rs +++ b/crates/cdr/src/limits.rs @@ -15,7 +15,7 @@ pub struct Limits { pub members: usize, /// Nested lists below the file's own. Deeper content is left out with a warning. pub depth: usize, - /// Chunks in the index, nested ones included. + /// Chunks in the index, nested ones included, and the entries and styles of the style table. pub chunks: usize, /// Objects mapped (shapes, groups and guidelines). pub objects: usize, @@ -92,7 +92,12 @@ impl Budget { } pub(crate) fn take_chunk(&mut self) -> Result<(), Error> { - self.chunks += 1; + self.take_chunks(1) + } + + /// `n` more chunks or style table entries. + pub(crate) fn take_chunks(&mut self, n: usize) -> Result<(), Error> { + self.chunks = self.chunks.saturating_add(n); if self.chunks > self.limits.chunks { Err(Error::Limit("chunk count")) } else { Ok(()) } } diff --git a/crates/cdr/src/riff.rs b/crates/cdr/src/riff.rs index 0298125e18..fcec80692b 100644 --- a/crates/cdr/src/riff.rs +++ b/crates/cdr/src/riff.rs @@ -228,7 +228,7 @@ impl<'a> Index<'a> { continue; } }; - // A `LIST stlt` holds the style tables, not chunks (R4); the reader doesn't use them. + // A `LIST stlt` holds the style tables, not chunks (R4); its body is read whole (R45). if chunk.id == LIST && chunk.form != *b"stlt" { lists.push(self.chunks.len()); } diff --git a/crates/cdr/src/styles.rs b/crates/cdr/src/styles.rs new file mode 100644 index 0000000000..b3a83b6c92 --- /dev/null +++ b/crates/cdr/src/styles.rs @@ -0,0 +1,241 @@ +//! The style table in a `LIST stlt` of versions 7 to 15 (R45): the fill and outline records that a +//! style gives the objects that name it and have no fill or outline argument of their own. + +use std::collections::{HashMap, HashSet}; + +use crate::Error; +use crate::bytes::{Rd, u32_at}; +use crate::limits::Budget; + +/// One style: its parent, and the fill and outline table entries it names (0: none). +#[derive(Clone, Copy)] +struct Style { + parent: u32, + fill: u32, + outline: u32, +} + +/// The styles of a drawing: for each style id, the fill and outline records it gives, its +/// parents' included. +#[derive(Default)] +pub(crate) struct Styles { + fills: HashMap, + outlines: HashMap, +} + +impl Styles { + /// The style table in body `b` of a `LIST stlt` of `version` (R45), or `None` when it doesn't + /// parse to its end. Its fill and outline entries and its styles count toward the chunks a + /// read takes. + pub(crate) fn read(b: &[u8], version: u16, budget: &mut Budget) -> Result, Error> { + let mut limit = None; + let styles = parse(b, version, &mut |n| match budget.take_chunks(n) { + Ok(()) => true, + Err(e) => { + limit = Some(e); + false + } + }); + match limit { + Some(e) => Err(e), + None => Ok(styles), + } + } + + /// The fill record that style `id` gives. + pub(crate) fn fill(&self, id: u32) -> Option { + self.fills.get(&id).copied() + } + + /// The outline record that style `id` gives. + pub(crate) fn outline(&self, id: u32) -> Option { + self.outlines.get(&id).copied() + } +} + +/// The style table in `b`. `take` is asked for each count of entries or styles before they are +/// read; a `false` stops the read. +fn parse(b: &[u8], version: u16, take: &mut dyn FnMut(usize) -> bool) -> Option { + let mut r = Rd::new(b); + let count = r.u32()? as usize; + if count == 0 { + return (r.left() == 0).then(Styles::default); + } + // Fill entries carry 48 more bytes from version 13. + let fills = table(&mut r, if version >= 1300 { 60 } else { 12 }, take)?; + let outlines = table(&mut r, 12, take)?; + // The text style tables: fonts, alignments, spacings, two tables of fixed records, bullets, + // indents, hyphenation and drop caps, and from version 8.01 one more. + skip_table(&mut r, if version >= 1000 { 60 } else { 44 })?; + skip_table(&mut r, 12)?; + skip_table(&mut r, 52)?; + skip_table(&mut r, 152)?; + skip_table(&mut r, 784)?; + let bullets = r.u32()?; + for _ in 0..bullets { + bullet(&mut r, version)?; + } + skip_table(&mut r, 28)?; + skip_table(&mut r, if version >= 1300 { 36 } else { 32 })?; + skip_table(&mut r, 28)?; + if version >= 801 { + skip_table(&mut r, 12)?; + } + // Each style is at least 32 bytes. + if count > r.left() / 32 || !take(count) { + return None; + } + let mut styles = HashMap::new(); + for _ in 0..count { + let (id, s) = style(&mut r, version)?; + styles.entry(id).or_insert(s); + } + if r.left() != 0 { + return None; + } + Some(Styles { fills: resolve(&styles, &fills, |s| s.fill), outlines: resolve(&styles, &outlines, |s| s.outline) }) +} + +/// For each style, the record of `table` that its own entry names, or the nearest parent's where +/// its entry is 0. Each style is resolved once, so a chain of any length takes time in proportion +/// to the styles; a chain that comes back to a style on it, or reaches a style that isn't there, +/// gives no record. +fn resolve(styles: &HashMap, table: &HashMap, entry: impl Fn(&Style) -> u32) -> HashMap { + // `None`: resolved to no record. + let mut done: HashMap> = HashMap::new(); + let mut path = Vec::new(); + let mut on_path = HashSet::new(); + for &start in styles.keys() { + let mut id = start; + let found = loop { + if let Some(&known) = done.get(&id) { + break known; + } + let Some(s) = styles.get(&id) else { break None }; + // Back at a style on this path: a cycle. + if !on_path.insert(id) { + break None; + } + path.push(id); + match entry(s) { + 0 => id = s.parent, + e => break table.get(&e).copied(), + } + }; + on_path.clear(); + for id in path.drain(..) { + done.insert(id, found); + } + } + done.into_iter().filter_map(|(id, r)| Some((id, r?))).collect() +} + +/// A table of a u32 count and entries of `size` bytes, each a table id, 4 bytes and a record id. +fn table(r: &mut Rd, size: usize, take: &mut dyn FnMut(usize) -> bool) -> Option> { + let n = r.u32()? as usize; + if n > r.left() / size || !take(n) { + return None; + } + let mut out = HashMap::new(); + for _ in 0..n { + let e = r.bytes(size)?; + out.entry(u32_at(e, 0)?).or_insert(u32_at(e, 8)?); + } + Some(out) +} + +/// A table of a u32 count and entries of `size` bytes, passed over. +fn skip_table(r: &mut Rd, size: usize) -> Option<()> { + let n = r.u32()? as usize; + r.skip(n.checked_mul(size)?) +} + +/// A bullet record, passed over: its length depends on a u32 inside it. +fn bullet(r: &mut Rd, version: u16) -> Option<()> { + r.skip(40)?; + if version >= 1300 { + if version >= 1400 { + r.skip(4)?; + } + let more = r.u32()?; + return r.skip(if more != 0 { 68 } else { 12 }); + } + r.skip(if version >= 1000 { 28 } else { 20 })?; + let more = r.u32()?; + if more != 0 { + r.skip(8)?; + } + r.skip(8) +} + +/// A style record: its kind (u32), id, parent, 8 bytes, a name length and the name (bytes before +/// version 12, UTF-16 units from it), the fill and outline entries, then the entries of text +/// styles (kinds 2 and 3). +fn style(r: &mut Rd, version: u16) -> Option<(u32, Style)> { + let kind = r.u32()?; + let (id, parent) = (r.u32()?, r.u32()?); + r.skip(8)?; + let len = r.u32()? as usize; + r.skip(len.checked_mul(if version >= 1200 { 2 } else { 1 })?)?; + let (fill, outline) = (r.u32()?, r.u32()?); + if kind > 1 { + r.skip(if version >= 801 { 20 } else { 16 })?; + } + if kind > 2 { + r.skip(20)?; + } + Some((id, Style { parent, fill, outline })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Limits; + use crate::synth::{self, V}; + + fn read(b: &[u8], version: u16) -> Option { + Styles::read(b, version, &mut Budget::new(Limits::default())).unwrap() + } + + #[test] + fn styles_that_name_each_other_as_parents_end() { + let looped = [synth::Style { id: 0x10, parent: 0x11, fill: 0, outline: 0 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + let s = read(&synth::stlt_body(V(700), &[(0x100, 1)], &[], &looped, false), 700).unwrap(); + assert_eq!((s.fill(0x10), s.outline(0x11), s.fill(0x12)), (None, None, None)); + } + + #[test] + fn a_long_chain_of_parents_reaches_the_style_that_names_an_entry() { + let mut chain = vec![synth::Style { id: 1, parent: 0, fill: 0x100, outline: 0 }]; + chain.extend((2..=500).map(|id| synth::Style { id, parent: id - 1, fill: 0, outline: 0 })); + let s = read(&synth::stlt_body(V(1100), &[(0x100, 7)], &[], &chain, false), 1100).unwrap(); + assert_eq!((s.fill(500), s.fill(250), s.outline(500)), (Some(7), Some(7), None)); + } + + #[test] + fn an_entry_missing_from_its_table_names_no_record() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x101, outline: 0x200 }]; + let s = read(&synth::stlt_body(V(1300), &[(0x100, 1)], &[(0x200, 2)], &styles, false), 1300).unwrap(); + assert_eq!((s.fill(0x10), s.outline(0x10)), (None, Some(2))); + } + + #[test] + fn counts_past_the_body_do_not_parse() { + let mut b = synth::stlt_body(V(900), &[], &[], &[], false); + b[..4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(read(&b, 900).is_none()); + let empty = 0u32.to_le_bytes(); + assert!(read(&empty, 900).is_some()); + assert!(read(&[], 900).is_none()); + } + + #[test] + fn entries_and_styles_count_toward_the_chunk_limit() { + let styles: Vec<_> = (1..=10).map(|id| synth::Style { id, parent: 0, fill: 0x100, outline: 0 }).collect(); + let b = synth::stlt_body(V(1000), &[(0x100, 1)], &[], &styles, false); + let mut budget = Budget::new(Limits { chunks: 10, ..Limits::default() }); + assert_eq!(Styles::read(&b, 1000, &mut budget).err(), Some(Error::Limit("chunk count"))); + let mut budget = Budget::new(Limits { chunks: 11, ..Limits::default() }); + assert!(Styles::read(&b, 1000, &mut budget).is_ok_and(|s| s.is_some())); + } +} diff --git a/crates/cdr/src/synth.rs b/crates/cdr/src/synth.rs index e78028b675..71847dd984 100644 --- a/crates/cdr/src/synth.rs +++ b/crates/cdr/src/synth.rs @@ -479,6 +479,107 @@ pub fn mcfg(v: V, w: f64, h: f64) -> Node { chunk(b"mcfg", b) } +/// A style of a [`stlt_body`]: its id, its parent's id, and its fill and outline table entries. +#[derive(Clone, Copy, Debug)] +pub struct Style { + pub id: u32, + pub parent: u32, + pub fill: u32, + pub outline: u32, +} + +/// The body of a `LIST stlt` of `v` (R45): the style count, the fill table (`(entry, fild id)`) and +/// the outline table (`(entry, outl id)`), the text style tables (each with one record when +/// `text`), then `styles` as styles of kind 1, and when `text` a style of kind 2 and one of kind 3. +pub fn stlt_body(v: V, fills: &[(u32, u32)], outlines: &[(u32, u32)], styles: &[Style], text: bool) -> Vec { + let version = v.0; + let u32s = |vals: &[u32]| -> Vec { vals.iter().flat_map(|x| x.to_le_bytes()).collect() }; + let count = styles.len() + if text { 2 } else { 0 }; + let mut b = u32s(&[count as u32]); + // A table without styles holds nothing else. + if count == 0 { + return b; + } + for (table, size) in [(fills, if version >= 1300 { 60 } else { 12 }), (outlines, 12)] { + b.extend(u32s(&[table.len() as u32])); + for (entry, record) in table { + let mut e = u32s(&[*entry, 0, *record]); + e.resize(size, 0); + b.extend(e); + } + } + let n = u32::from(text); + let fixed = |size: usize| -> Vec { + let mut t = n.to_le_bytes().to_vec(); + t.extend(vec![0x5a; size * n as usize]); + t + }; + // Fonts, alignments, spacings and two tables of fixed records. + for size in [if version >= 1000 { 60 } else { 44 }, 12, 52, 152, 784] { + b.extend(fixed(size)); + } + // One bullet, whose u32 inside asks for the longer form. + b.extend(n.to_le_bytes()); + if text { + b.extend([0x5a; 40]); + if version >= 1300 { + if version >= 1400 { + b.extend([0x5a; 4]); + } + b.extend(u32s(&[1])); + b.extend([0x5a; 68]); + } else { + b.extend(vec![0x5a; if version >= 1000 { 28 } else { 20 }]); + b.extend(u32s(&[1])); + b.extend([0x5a; 16]); + } + } + // Indents, hyphenation, drop caps, and from version 8.01 one more table. + for size in [28, if version >= 1300 { 36 } else { 32 }, 28] { + b.extend(fixed(size)); + } + if version >= 801 { + b.extend(fixed(12)); + } + let text_styles = [(2, Style { id: 0x7f02, parent: 0, fill: 0, outline: 0 }), (3, Style { id: 0x7f03, parent: 0x7f02, fill: 0, outline: 0 })]; + let all = styles.iter().map(|s| (1u32, *s)).chain(text_styles.into_iter().filter(|_| text)); + for (kind, s) in all { + b.extend(u32s(&[kind, s.id, s.parent, 1, 1])); + if version >= 1200 { + b.extend(u32s(&[7])); + b.extend("Graphic".encode_utf16().flat_map(u16::to_le_bytes)); + } else { + b.extend(u32s(&[8])); + b.extend(b"Graphic\0"); + } + b.extend(u32s(&[s.fill, s.outline])); + if kind > 1 { + b.extend(vec![0; if version >= 801 { 20 } else { 16 }]); + } + if kind > 2 { + b.extend([0; 20]); + } + } + b +} + +/// A `LIST stlt` of [`stlt_body`]. +pub fn stlt(v: V, fills: &[(u32, u32)], outlines: &[(u32, u32)], styles: &[Style], text: bool) -> Node { + Node::Chunk(*b"LIST", [b"stlt".to_vec(), stlt_body(v, fills, outlines, styles, text)].concat()) +} + +/// A file of `version` holding `content` as the program of that version saves it: a RIFF file +/// before 14, then a package (R25, R26). +pub fn file_of(version: u16, content: Vec) -> Vec { + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + body.extend(content); + match version { + ..1400 => riff(version, &body), + 1400..1600 => package14(riff(version, &body), false), + _ => package16(version, &body, false, &[]), + } +} + /// The document list and pages of the [`sample`] of `version`. pub fn sample_content(version: u16) -> Vec { let v = V(version); diff --git a/crates/cdr/tests/read.rs b/crates/cdr/tests/read.rs index 49d447c170..1df3b800be 100644 --- a/crates/cdr/tests/read.rs +++ b/crates/cdr/tests/read.rs @@ -1133,6 +1133,76 @@ fn a_style_table_list_is_not_read_as_chunks() { assert!(d.page_size.is_some_and(|(w, h)| (w - 100.0).abs() < 0.01 && (h - 50.0).abs() < 0.01)); } +/// The objects of a styled drawing: a rectangle with only its style (argument 200), one whose +/// style leaves the fill and outline to its parent, and one with an outline argument of its own. +fn graphic_style_drawing(version: u16, table: synth::Node) -> Vec { + let v = V(version); + let black = synth::color(2, [0, 0, 0, 100]); + let doc = list( + b"doc ", + vec![ + synth::mcfg(v, 612.0, 792.0), + list(b"filt", vec![chunk(if version >= 700 { b"fild" } else { b"fill" }, v.fill(1, &synth::color(5, [0, 0, 255, 0])))]), + list( + b"otlt", + vec![ + chunk(b"outl", v.outline(2, synth::Pen { line_type: 0, width: 2.0, cap: 1, join: 1 }, &black, &[])), + chunk(b"outl", v.outline(3, synth::Pen { line_type: 1, width: 1.0, cap: 0, join: 0 }, &black, &[])), + ], + ), + table, + ], + ); + let rect = (30, v.rect(20.0, 10.0, 0.0)); + let styled = |style: u32, own: &[(u32, Vec)]| { + let mut args = vec![(200, style.to_le_bytes().to_vec())]; + args.extend(own.iter().cloned()); + args.push(rect.clone()); + synth::object(v, 1, &args, None) + }; + let objects = vec![styled(0x10, &[]), styled(0x11, &[]), styled(0x10, &[(10, 3u32.to_le_bytes().to_vec())])]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)]); + synth::file_of(version, vec![doc, page]) +} + +/// From version 7 an object without a fill or outline argument of its own takes its style's +/// (argument 200, `LIST stlt`), through the style's parent where the style names none; its own +/// argument wins over the style's. +#[test] +fn objects_without_their_own_fill_or_outline_take_their_styles() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + for version in [700, 800, 801, 900, 1000, 1100, 1200, 1300, 1400, 1500] { + for text in [false, true] { + let table = synth::stlt(V(version), &[(0x100, 1)], &[(0x200, 2)], &styles, text); + let d = read(&graphic_style_drawing(version, table), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 3, "{version}"); + for shape in &s[..2] { + assert_eq!(shape.fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{version} {text}"); + assert!(shape.outline.as_ref().is_some_and(|o| (o.width - 2.0).abs() < 0.05), "{version} {text}: {:?}", shape.outline); + } + assert_eq!(s[2].fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{version} {text}"); + assert!(s[2].outline.is_none(), "{version} {text}"); + assert!(d.warnings.is_empty(), "{version} {text}: {:?}", d.warnings); + } + } +} + +/// A style table that doesn't parse to its end is damage when an object needs a style from it; +/// the object is drawn with what it holds itself. +#[test] +fn a_style_table_that_does_not_parse_is_damage_when_an_object_needs_it() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + let mut body = synth::stlt_body(V(1000), &[(0x100, 1)], &[(0x200, 2)], &styles, true); + body.push(0); + let table = chunk(b"LIST", [b"stlt".to_vec(), body].concat()); + let d = read(&graphic_style_drawing(1000, table), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 3); + assert!(s[0].fill.is_none() && s[0].outline.is_none()); + assert_eq!(d.warnings, vec![Warning::Damaged]); +} + #[test] fn linked_groups_are_left_out_with_a_warning() { let v = V(1100); diff --git a/docs/mcp.md b/docs/mcp.md index beac6b4b61..cc10b8e828 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6844,7 +6844,8 @@ place as editable art, the ZIP packages that versions 14 and later save included by side. Layers of the same name on different pages become one layer when the pages stack them in the same order, and the master page's guidelines become guides on every page. Groups stay groups. Curves, paths, arcs and polygons (stars included) become paths, and rectangles and ellipses become live shapes; a rectangle keeps each corner's radius. Uniform -fills and outlines keep their colors, widths, caps, joins and dashes. A library color that the drawing stores with its +fills and outlines keep their colors, widths, caps, joins and dashes, and an object without a fill or outline of its own +takes its style's. A library color that the drawing stores with its name and values (version 13 and later) becomes a spot swatch with its tint, and one stored only by its number opens as a black spot color. Text, bitmaps, blends, contours, brush strokes, other objects the reader doesn't read yet, fountain, pattern, texture and PostScript fills, and outline arrowheads are left out. The `warnings` of diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ae116dd6db..82b20aed3d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1542,7 +1542,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width, caps, joins and dashes. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). + - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `vectorcraft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width, caps, joins and dashes, an object without a fill or outline of its own taking its style's. A library color stored with its name and values (version 13 and later) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `crates/cdr/PROVENANCE.md`. Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`crates/cdr/tests/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. EPS and PostScript `.ai` files are still embedded (`crates/engine/src/tests/placed_document.rs`).