From 81d4dcc6eaf8a65a09acf196ed89936f538a7e38 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 17:14:37 -0800 Subject: [PATCH] File formats: export .cmx files document.export and Export As write .cmx exchange files with 32-bit coordinates through craft-cdr's write_cmx, in the layouts the .cmx reader reads. The chosen artboard is the file's page, or with Use Artboards each chosen artboard is a page of one file, and each layer with art on a page is a layer of that page. - vectorcraft-metafile gets painted_layers: the WMF writer's walk of the visible art, layer by layer, with each fill's and stroke's solid paint, its miter limit and the swatches of the document and of the documents it places. - The export keeps CMYK, RGB, gray, spot colors at their tints and Registration; type is written as outlines, and gradients and patterns as one color. The warnings name images, clipping masks, transparency, art past a page's edge, dash offsets, dashes aligned to corners, miter limits, and each loss the writer reports: nonzero fills written even-odd, long paths, rounded dashes, shortened names, low spot tints, and spot colors without a name or a known color. --- crates/engine/src/cmd/fileio.rs | 2 + crates/engine/src/cmd/fileio/cmx.rs | 284 +++++++++++++++++++++ crates/engine/src/cmd/fileio/commands.rs | 6 +- crates/engine/src/cmd/fileio/encode.rs | 5 +- crates/engine/src/cmd/fileio/formats.rs | 8 +- crates/engine/src/cmd/fileio/screens.rs | 2 +- crates/engine/src/cmd/fileio/tests.rs | 6 +- crates/engine/src/cmd/fileio/tests_cmx.rs | 181 ++++++++++++- crates/engine/src/tests/placed_document.rs | 27 ++ crates/mcp/src/tests/fileio.rs | 3 +- crates/mcp/src/tools/definitions.rs | 4 +- crates/metafile/src/encode.rs | 4 +- crates/metafile/src/lib.rs | 85 ++++++ crates/metafile/src/scene.rs | 45 +++- docs/file-format-parity.md | 2 +- docs/mcp.md | 28 +- docs/target-app-parity.md | 1 + 17 files changed, 665 insertions(+), 28 deletions(-) create mode 100644 crates/engine/src/cmd/fileio/cmx.rs diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 2c1ee412a6..e5515f0fe3 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -19,6 +19,7 @@ //! - `metafile`: EMF and WMF export, open and place; PICT open and place. //! - `cdr`: `.cdr` drawings of versions 1 to 27 and `.cdt` templates, and `.cmx` files with //! 32-bit coordinates, open and place. +//! - `cmx`: `.cmx` export (a page for each chosen artboard, a layer for each layer with art on it). //! - `hpgl`: HP-GL export options and plots. //! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no //! built-in format reads). @@ -31,6 +32,7 @@ mod action_batch; mod affinity; mod batch; mod cdr; +mod cmx; pub mod dxf; pub mod dxfimport; mod encode; diff --git a/crates/engine/src/cmd/fileio/cmx.rs b/crates/engine/src/cmd/fileio/cmx.rs new file mode 100644 index 0000000000..29e8a22696 --- /dev/null +++ b/crates/engine/src/cmd/fileio/cmx.rs @@ -0,0 +1,284 @@ +//! `.cmx` exchange files for every path that writes them (`craft_cdr::write_cmx`): +//! `document.export {format: cmx}` and Export As. The chosen artboard (default the first) is the +//! file's page; with Use Artboards each chosen artboard (default all) is a page of one file. Each +//! top-level layer with art over a page is a layer of that page, holding that art as +//! [`vectorcraft_metafile::painted_layers`] gives it: fills and strokes in their colors (CMYK, RGB, +//! gray, spot colors with their tints and Registration), type as glyph outlines, and gradients and +//! patterns as one color. What the file can't hold comes back in the warnings. + +use craft_cdr::Limits; +use craft_cdr::model as cd; +use kurbo::PathEl; +use serde_json::Value; +use vectorcraft_color::swatch::REGISTRATION; +use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_doc::{Document, LineCap, LineJoin, StrokeLayer}; +use vectorcraft_geom::{BezPath, FillRule, Point}; +use vectorcraft_metafile::Painted; + +use super::super::{Result, bad}; +use super::{ArtboardPick, Encoded, FormatOption}; + +const C: &str = "document.export"; + +/// The options `document.formats` lists for CMX. +pub(super) const OPTIONS: &[FormatOption] = &[super::ARTBOARD, super::ARTBOARDS, super::RANGE, super::USE_ARTBOARDS]; + +const IMAGES: &str = "placed images are left out of CMX files"; +const NONZERO: &str = "fills that use the nonzero fill rule are written even-odd: where a shape crosses itself, or parts of it that turn the same way overlap, they may leave holes"; +const SPLIT: &str = "paths with more than 7,281 points were written as several curves: their fills where their parts overlap, and their strokes where the curves meet, may draw differently"; +const PAST_PAGE: &str = "art that crosses the edge of a page is written whole, including the part past the edge"; +const DASHES: &str = "dash and gap lengths were rounded to whole stroke widths, the unit CMX files store them in"; +const CUT: &str = "filled shapes with a part of more than 7,281 points were written as open pieces of that part, so their fills draw differently"; +const ZERO_TINTS: &str = "spot colors at a low tint were written in the color they print at that tint, so their ink's color may open changed"; +const LONG_NAMES: &str = "layer and spot color names longer than 256 characters open again shortened"; +const UNNAMED_SPOTS: &str = "spot colors without a name were written as process colors"; +const UNKNOWN_LOOKS: &str = "spot colors whose color is not known were written as black at their tints"; +const MERGED_LOOKS: &str = "spot colors that share a name but not a color were all written in one of those colors"; +const LEFT_OUT: &str = "art the file can't hold was left out"; +const DASH_OFFSETS: &str = "dash offsets are left out: dashes start at the start of each path"; +const ALIGNED_DASHES: &str = "dashes aligned to corners and path ends are written as plain dashes"; +const MITER_LIMITS: &str = "miter limits are left out: mitered corners open again with a miter limit of 10"; + +/// Encode `doc` as CMX: one file with a page for the chosen artboard (default the first), or with +/// `use_artboards` a page for each chosen artboard (default all), in the order they are chosen. +pub(super) fn encode(doc: &Document, f: &super::Format, p: &Value, use_artboards: Option) -> Result { + let pick: ArtboardPick = super::encode::options(f, p)?; + let n = doc.artboards.len(); + let boards = match use_artboards { + Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()), + _ => vec![pick.one(n).map_err(|e| bad(C, e))?], + }; + if boards.is_empty() { + return Err(bad(C, "the document has no artboard")); + } + let rects = boards + .iter() + .map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))) + .collect::>>()?; + vectorcraft_metafile::check_regions(&rects).map_err(|e| bad(C, e))?; + let mut warnings = Vec::new(); + let mut note = |w: &str| { + if !warnings.iter().any(|x: &String| x == w) { + warnings.push(w.to_string()); + } + }; + let mut pages = Vec::with_capacity(rects.len()); + for r in &rects { + let art = vectorcraft_metafile::painted_layers(doc, *r).map_err(|e| bad(C, e))?; + art.warnings.iter().for_each(|w| note(w)); + if art.images { + note(IMAGES); + } + // The file has no clipping the reader reads, so art is not cut at the page's edge. + let edge = r.abs().inflate(PAGE_EDGE_TOLERANCE, PAGE_EDGE_TOLERANCE); + // A stroke reaches half its width past its path. + let past = |bp: &BezPath, reach: f64| { + let b = kurbo::Shape::bounding_box(bp).inflate(reach, reach); + !bp.elements().is_empty() && (b.x0 < edge.x0 || b.y0 < edge.y0 || b.x1 > edge.x1 || b.y1 > edge.y1) + }; + if art.layers.iter().flat_map(|(_, p)| p).any(|op| match op { + Painted::Fill { path, .. } => past(path, 0.0), + Painted::Stroke { path, width, .. } => past(path, width.max(0.0) / 2.0), + }) { + note(PAST_PAGE); + } + let page = Page { center: r.abs().center() }; + // The model lists layers and objects front to back; the document paints them back to front. + // A layer with nothing drawn on the page is left out, as the reader leaves out a layer that + // holds nothing. + let layers = art + .layers + .iter() + .rev() + .map(|(name, painted)| (name, page.objects(&art.swatches, painted, &mut note))) + .filter(|(_, objects)| !objects.is_empty()) + .map(|(name, objects)| cd::Layer { + name: name.clone(), + kind: cd::LayerKind::Drawing, + flags: cd::Flags::default(), + objects: objects.into_iter().rev().collect(), + guides: Vec::new(), + }) + .collect(); + pages.push(cd::Page { size: Some((r.width().abs(), r.height().abs())), layers }); + } + let drawing = cd::Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: Vec::new() }; + // The limits `document.open` reads `.cmx` files with, so the file opens whole again. + let written = craft_cdr::write_cmx(&drawing, Limits::default()).map_err(|e| bad(C, e.to_string()))?; + for (set, w) in [ + (written.nonzero_fills, NONZERO), + (written.split_paths, SPLIT), + (written.cut_subpaths, CUT), + (written.long_names, LONG_NAMES), + (written.zero_tints, ZERO_TINTS), + (written.rounded_dashes, DASHES), + (written.unnamed_spots, UNNAMED_SPOTS), + (written.unknown_looks, UNKNOWN_LOOKS), + (written.merged_looks, MERGED_LOOKS), + (written.left_out, LEFT_OUT), + ] { + if set { + note(w); + } + } + let mut enc = Encoded::one(written.bytes); + enc.warnings = warnings; + enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(&rects))); + Ok(enc) +} + +/// A page's placement: document space (y down) to the page's coordinates (from its center, y up). +struct Page { + center: Point, +} + +impl Page { + fn pt(&self, p: Point) -> cd::Pt { + cd::Pt { x: p.x - self.center.x, y: self.center.y - p.y } + } + + /// `bp` in the page's coordinates. A quadratic segment becomes the cubic that draws it. + fn path(&self, bp: &BezPath) -> cd::Path { + let mut subpaths: Vec = Vec::new(); + // The current point and the start of the current subpath, in document space. + let (mut last, mut start) = (Point::ZERO, Point::ZERO); + for el in bp.elements() { + match *el { + PathEl::MoveTo(p) => { + subpaths.push(cd::SubPath { start: self.pt(p), segments: Vec::new(), closed: false }); + (last, start) = (p, p); + } + PathEl::LineTo(p) => { + self.segment(&mut subpaths, last, cd::Segment::Line(self.pt(p))); + last = p; + } + PathEl::QuadTo(c, p) => { + let (c1, c2) = (last + (c - last) * (2.0 / 3.0), p + (c - p) * (2.0 / 3.0)); + self.segment(&mut subpaths, last, cd::Segment::Cubic(self.pt(c1), self.pt(c2), self.pt(p))); + last = p; + } + PathEl::CurveTo(c1, c2, p) => { + self.segment(&mut subpaths, last, cd::Segment::Cubic(self.pt(c1), self.pt(c2), self.pt(p))); + last = p; + } + PathEl::ClosePath => { + if let Some(s) = subpaths.last_mut() { + s.closed = true; + } + last = start; + } + } + } + // A subpath of a lone point draws nothing. + subpaths.retain(|s| !s.segments.is_empty()); + cd::Path { subpaths } + } + + /// Add `seg` to the open subpath, or to a new one from `from` after a close. + fn segment(&self, subpaths: &mut Vec, from: Point, seg: cd::Segment) { + match subpaths.last_mut() { + Some(s) if !s.closed => s.segments.push(seg), + _ => subpaths.push(cd::SubPath { start: self.pt(from), segments: vec![seg], closed: false }), + } + } + + /// The fills and strokes of one layer as shapes, in paint order. A fill followed by a stroke of + /// the same path is one shape with both. A path with no segments draws nothing and is left out. + fn objects(&self, swatches: &[Swatch], painted: &[Painted], note: &mut impl FnMut(&str)) -> Vec { + let mut out = Vec::with_capacity(painted.len()); + let mut i = 0; + while let Some(op) = painted.get(i) { + i += 1; + let shape = match op { + Painted::Fill { path, rule, rgb, paint } => { + let outline = match painted.get(i) { + Some(s @ Painted::Stroke { path: stroked, .. }) if stroked == path => { + i += 1; + outline(swatches, s, note) + } + _ => None, + }; + let fill = color(swatches, *rgb, paint.as_ref()); + let mut shape = cd::Shape::new(cd::Geometry::Path(self.path(path)), cd::Matrix::IDENTITY, Some(fill), outline); + shape.nonzero = *rule == FillRule::NonZero; + shape + } + Painted::Stroke { path, .. } => { + cd::Shape::new(cd::Geometry::Path(self.path(path)), cd::Matrix::IDENTITY, None, outline(swatches, op, note)) + } + }; + if matches!(&shape.geometry, cd::Geometry::Path(p) if p.subpaths.is_empty()) { + continue; + } + out.push(cd::Object::Shape(Box::new(shape))); + } + out + } +} + +/// How far (points) a path may reach past its page before the export says art crosses the edge. +const PAGE_EDGE_TOLERANCE: f64 = 0.01; + +/// The outline of a stroke: its width, color, cap, join and dashes in stroke widths. The file holds +/// no miter limit, so a mitered stroke with a limit other than the one a stroke opens with is +/// named in the warnings. +fn outline(swatches: &[Swatch], p: &Painted, note: &mut impl FnMut(&str)) -> Option { + let Painted::Stroke { rgb, paint, width, cap, join, miter, dash, .. } = p else { return None }; + if *join == LineJoin::Miter && *miter != StrokeLayer::new(Paint::None, *width).miter_limit { + note(MITER_LIMITS); + } + let dashes = match dash { + Some(d) if *width > 0.0 => { + if d.offset != 0.0 { + note(DASH_OFFSETS); + } + if d.align_corners { + note(ALIGNED_DASHES); + } + d.pattern.iter().map(|x| x / width).collect() + } + _ => Vec::new(), + }; + Some(cd::Outline { + width: *width, + color: color(swatches, *rgb, paint.as_ref()), + cap: match cap { + LineCap::Butt => cd::Cap::Butt, + LineCap::Round => cd::Cap::Round, + LineCap::Square => cd::Cap::Square, + }, + join: match join { + LineJoin::Miter => cd::Join::Miter, + LineJoin::Round => cd::Join::Round, + LineJoin::Bevel => cd::Join::Bevel, + }, + dashes, + behind_fill: false, + scale_with: false, + }) +} + +/// The color a fill or stroke is written in: Registration, a spot color at its tint with the look +/// of its swatch among `swatches`, or the solid color in its own model (Lab as RGB); `rgb` for the +/// one color of a gradient or pattern. +fn color(swatches: &[Swatch], rgb: [u8; 3], paint: Option<&Paint>) -> cd::Color { + let from_rgb = |[r, g, b]: [u8; 3]| cd::Color::Rgb([r, g, b].map(|v| f32::from(v) / 255.0)); + let Some(Paint::Solid { color, swatch, tint }) = paint else { return from_rgb(rgb) }; + if swatch.as_deref() == Some(REGISTRATION) { + return cd::Color::Registration; + } + if let Some(s) = swatch.as_deref().and_then(|name| swatches.iter().find(|s| s.name == name)).filter(|s| s.spot) { + let look = s.paint.color().map(|c| { + let [r, g, b, _] = c.to_rgba8(1.0); + [r, g, b].map(|v| f32::from(v) / 255.0) + }); + return cd::Color::Spot { name: s.name.clone(), tint: tint.clamp(0.0, 1.0), look }; + } + match *color { + Color::Rgb { r, g, b } => cd::Color::Rgb([r, g, b]), + Color::Cmyk { c, m, y, k } => cd::Color::Cmyk([c, m, y, k]), + Color::Gray { k } => cd::Color::Gray(k), + Color::Lab { .. } => from_rgb(rgb), + } +} diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 5e756623f0..a48ac3e85b 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Serialize Document", [], None, - "{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)", + "{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)", has_doc, export::serialize ), @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer for each layer with art on the page, holding the art's fills and strokes as curves in their colors: CMYK, RGB, gray, spot colors at their tints, Registration; type as outlines, gradients and patterns as one color, nonzero fills as even-odd, dashes in whole stroke widths, no miter limit, art across a page's edge written whole, without images, clipping masks or transparency; warnings name each of these losses), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", has_doc, export::export ), @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Export Selection…", ["File"], None, - "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})", + "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|cmx|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})", has_selection, export::export_selection ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index b308f874ab..a79ac295e5 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -1069,7 +1069,7 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result { } // Formats that draw type: missing fonts come out in the fallback font (PDF and SVG say so // themselves: SVG only when it outlines or embeds fonts). - if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl")) + if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl" | "cmx")) && let Some(w) = crate::cmd::fonts::substitution_warning(doc) { enc.warnings.push(w); @@ -1110,7 +1110,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { let doc = &*doc.without_edit_modes(); let n = doc.artboards.len(); // SVG reads its own `useArtboards` (an SVG option). - let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl") { use_artboards(C, p)? } else { None }; + let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None }; // `rect`: that area of the page, as if it were the only artboard (the document is not changed). if let Some(rect) = page_rect(f, p)? { let mut q = super::export::without_artboards(p); @@ -1156,6 +1156,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { "emf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Emf), "wmf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Wmf), "hpgl" => return super::hpgl::encode(doc, p, use_artboards), + "cmx" => return super::cmx::encode(doc, f, p, use_artboards), "ai" => return super::save::encode_ai(C, f, doc, p), "pdf" => { let (bytes, notes) = super::pdf::encode(C, doc, p)?; diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 2d6e459ece..6ee790d901 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -1,6 +1,6 @@ use super::super::unique_name; use super::{ - Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, dxf, eps, hpgl, json, metafile, native, pdf, screens, svg, text, + Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, cmx, dxf, eps, hpgl, json, metafile, native, pdf, screens, svg, text, unsupported, }; @@ -553,9 +553,9 @@ pub const FORMATS: &[Format] = &[ // them. reader("cdr", "CDR Drawing", &["cdr"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type reader("cdt", "CDR Template", &["cdt"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type - // `.cmx` exchange files with 32-bit coordinates, read by `craft-cdr`; exports don't write - // them. - reader("cmx", "CMX", &["cmx"], "image/x-cmx", false), + // `.cmx` exchange files with 32-bit coordinates, read and written by `craft-cdr`: a page for + // each chosen artboard, with the art's fills and strokes in their colors. + Format { id: "cmx", label: "CMX", extensions: &["cmx"], mime: "image/x-cmx", read: true, write: true, raster: false, options: cmx::OPTIONS }, // QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images. reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false), ]; diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 442f38e3cc..0fb1cc0860 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -196,7 +196,7 @@ pub(super) fn name_without_device(name: &str) -> String { pub(crate) const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"]; /// The writable formats a format row can't name. -pub(crate) const UNWRITTEN_FORMATS: [&str; 6] = ["template", "txt", "dxf", "emf", "wmf", "hpgl"]; +pub(crate) const UNWRITTEN_FORMATS: [&str; 7] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx"]; /// One format row: what to write, at which size, with which suffix, into which sub-folder. struct Row { diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index 56e2a12f30..cec025b69a 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -532,7 +532,8 @@ fn export_extensions_name_every_writable_format() { "wmf", "plt", "tga", - "psd" + "psd", + "cmx" ] ); for e in exts { @@ -568,7 +569,8 @@ fn formats_query_lists_readers_writers_and_options() { "wmf", "hpgl", "tga", - "psd" + "psd", + "cmx" ] ); assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string())); diff --git a/crates/engine/src/cmd/fileio/tests_cmx.rs b/crates/engine/src/cmd/fileio/tests_cmx.rs index f353caa008..bc9c38f226 100644 --- a/crates/engine/src/cmd/fileio/tests_cmx.rs +++ b/crates/engine/src/cmd/fileio/tests_cmx.rs @@ -1,5 +1,5 @@ //! `.cmx` files: Open and Place, by extension and by content, mapped to artboards, layers, groups, -//! paths, solid paint and strokes, with their warnings and refusals. +//! paths, solid paint and strokes, with their warnings and refusals; and export, read back. use super::*; use craft_cdr::synth_cmx::*; @@ -61,7 +61,7 @@ fn detection_by_content_and_place() { s.execute("file.place", &json!({"name":"art.cmx", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap(); assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty())); let f = format("cmx").unwrap(); - assert!(f.read && !f.write); + assert!(f.read && f.write); assert!(OPEN_EXTS.contains(&"cmx") && PLACE_EXTS.contains(&"cmx") && UNASSOCIATED_EXTS.contains(&"cmx")); assert!(!SAVE_FORMATS.contains(&"cmx")); } @@ -123,6 +123,183 @@ fn files_that_are_not_read_say_why() { assert!(e.contains("this CMX file can't be read (not a CMX file)"), "{e}"); } +fn b64(v: &serde_json::Value) -> Vec { + vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap() +} + +/// Two artboards of 200 x 100 pt. The first layer holds a CMYK rectangle with a dashed gray stroke on +/// the first; layer "Front" a 40 % tint of spot ink "Gold" on the first and an RGB stroke on the +/// second. +fn drawn() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2, "colorMode": "cmyk"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Gold", "color": {"model": "cmyk", "c": 0.0, "m": 0.2, "y": 0.8, "k": 0.1}, "spot": true})).unwrap(); + let second = s.doc().unwrap().doc.artboards[1].rect.x0; + s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 40, "height": 30})).unwrap(); + s.execute("paint.setFill", &json!({"color": {"model": "cmyk", "c": 0.6, "m": 0.1, "y": 0.0, "k": 0.2}})).unwrap(); + s.execute("paint.setStroke", &json!({"color": {"model": "gray", "k": 0.5}})).unwrap(); + s.execute("stroke.set", &json!({"weight": 2, "dash": [6, 2]})).unwrap(); + s.execute("layer.new", &json!({"name": "Front"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Gold", "tint": 40})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("shape.rectangle", &json!({"x": second + 5.0, "y": 5, "width": 10, "height": 10})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#3366cc"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 1})).unwrap(); + s +} + +/// Every path of a document with its bounds relative to the artboard it is on. +fn placed(s: &Session) -> Vec<(Node, vectorcraft_geom::Rect)> { + let doc = &s.doc().unwrap().doc; + let mut all = Vec::new(); + paths(&doc.layers, &mut all); + all.into_iter() + .map(|n| { + let b = doc.bounds_of(&[n.id], false).unwrap(); + let board = doc.artboards.iter().find(|a| a.rect.contains(b.center())).map_or(vectorcraft_geom::Rect::ZERO, |a| a.rect); + (n, b - board.origin().to_vec2()) + }) + .collect() +} + +#[test] +fn an_exported_cmx_file_opens_with_its_pages_layers_colors_and_strokes() { + let mut s = drawn(); + let r = s.execute("document.export", &json!({"format": "cmx", "useArtboards": true})).unwrap(); + assert_eq!(r["format"], "cmx"); + assert!(warnings(&r).is_empty(), "{r}"); + let bytes = b64(&r); + assert!(craft_cdr::is_cmx(&bytes), "one file holds both pages"); + let mut back = Session::new(); + let opened = open_bytes(&mut back, "drawing.cmx", &bytes, None).unwrap(); + assert!(warnings(&opened).is_empty(), "{opened}"); + let doc = &back.doc().unwrap().doc; + let sizes: Vec<(f64, f64)> = doc.artboards.iter().map(|a| (a.rect.width().round(), a.rect.height().round())).collect(); + assert_eq!(sizes, [(200.0, 100.0), (200.0, 100.0)]); + let names: Vec = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + let was: Vec = s.doc().unwrap().doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, was, "the layers keep their names and order"); + let was = placed(&s); + let now = placed(&back); + assert_eq!(was.len(), now.len()); + for ((_, a), (_, b)) in was.iter().zip(&now) { + assert!((a.x0 - b.x0).abs() < 0.01 && (a.y0 - b.y0).abs() < 0.01 && (a.x1 - b.x1).abs() < 0.01, "{a:?} {b:?}"); + } + let fill = |n: &Node| n.appearance.fill().map(|f| f.paint.clone()); + let stroke = |n: &Node| n.appearance.stroke().cloned(); + use vectorcraft_color::{Color, Paint}; + let cmyk = &now[0].0; + assert!(matches!(fill(cmyk).and_then(|p| p.color()), Some(Color::Cmyk { c, .. }) if (c - 0.6).abs() < 0.006), "{:?}", fill(cmyk)); + let st = stroke(cmyk).unwrap(); + assert!((st.width - 2.0).abs() < 1e-3 && matches!(st.paint.color(), Some(Color::Gray { k }) if (k - 0.5).abs() < 0.005)); + // Widths are stored to 0.1 µm. + let dash = st.dash.as_ref().map(|d| d.pattern.clone()).unwrap_or_default(); + assert!(dash.len() == 2 && (dash[0] - 6.0).abs() < 1e-3 && (dash[1] - 2.0).abs() < 1e-3, "{dash:?}"); + let gold = &now[1].0; + assert!(matches!(fill(gold), Some(Paint::Solid { swatch: Some(n), tint, .. }) if n == "Gold" && (tint - 0.4).abs() < 0.006), "{:?}", fill(gold)); + assert!(doc.swatch("Gold").is_some_and(|g| g.spot)); + let line = &now[2].0; + assert!(fill(line).is_none_or(|p| p == Paint::None)); + // The document converted the RGB color to its CMYK mode; the file keeps the CMYK values. + let (Some(Color::Cmyk { c, m, y, k }), Some(Color::Cmyk { c: c2, m: m2, y: y2, k: k2 })) = + (stroke(&was[2].0).unwrap().paint.color(), stroke(line).unwrap().paint.color()) + else { + panic!("not CMYK: {:?}", stroke(line)) + }; + assert!([c - c2, m - m2, y - y2, k - k2].iter().all(|d| d.abs() < 0.006)); +} + +#[test] +fn one_artboard_is_one_page_and_what_cmx_leaves_out_is_named() { + let mut s = drawn(); + let bytes = b64(&s.execute("document.export", &json!({"format": "cmx", "artboard": 1})).unwrap()); + let d = craft_cdr::read_cmx(&bytes, craft_cdr::Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + let shapes: usize = d.pages[0].layers.iter().map(|l| l.objects.len()).sum(); + assert_eq!(shapes, 1, "only the art over the second artboard"); + assert_eq!(b64(&s.execute("document.serialize", &json!({"format": "cmx", "artboard": 1})).unwrap()), bytes); + // A gradient is written as one color, and a placed image is left out. + s.execute("shape.rectangle", &json!({"x": 10, "y": 60, "width": 10, "height": 10})).unwrap(); + s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap(); + let png = vectorcraft_format::base64_encode(&tiny_png()); + s.execute("file.place", &json!({"name": "dot.png", "dataBase64": png, "x": 150, "y": 60})).unwrap(); + let w = warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap()); + assert!(w.iter().any(|w| w.contains("gradients are written as one colour")), "{w:?}"); + assert!(w.iter().any(|w| w == "placed images are left out of CMX files"), "{w:?}"); + assert!(w.iter().all(|w| !w.contains("edge of a page")), "{w:?}"); + // Art across the artboard's edge is written whole, and the warnings say so. + s.execute("shape.rectangle", &json!({"x": 190, "y": 90, "width": 20, "height": 20})).unwrap(); + let w = warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap()); + assert!(w.iter().any(|w| w.contains("edge of a page")), "{w:?}"); +} + +#[test] +fn a_nonzero_fill_that_would_fill_differently_even_odd_is_named() { + let nonzero = |w: &[String]| w.iter().any(|w| w.contains("nonzero")); + let export = |d: &str, rule: &str| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + s.execute("path.create", &json!({"d": d})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#cc3333"})).unwrap(); + s.execute("path.setFillRule", &json!({"rule": rule})).unwrap(); + let r = s.execute("document.export", &json!({"format": "cmx"})).unwrap(); + let shapes: Vec = craft_cdr::read_cmx(&b64(&r), craft_cdr::Limits::default()) + .unwrap() + .pages + .into_iter() + .flat_map(|p| p.layers) + .flat_map(|l| l.objects) + .filter_map(|o| match o { + craft_cdr::model::Object::Shape(s) => Some(*s), + _ => None, + }) + .collect(); + (warnings(&r), shapes) + }; + // Two squares that overlap and turn the same way leave a hole where they overlap even-odd. + let overlapping = "M10 10 L50 10 L50 50 L10 50 Z M30 30 L70 30 L70 70 L30 70 Z"; + let (w, shapes) = export(overlapping, "nonZero"); + assert!(nonzero(&w), "{w:?}"); + assert!(shapes.len() == 1 && shapes[0].fill.is_some(), "{shapes:?}"); + // The same shape filled even-odd is written as it fills. + assert!(!nonzero(&export(overlapping, "evenOdd").0)); + // A counter that turns the other way inside its shape fills the same either way. + let counter = "M10 10 L50 10 L50 50 L10 50 Z M20 20 L20 40 L40 40 L40 20 Z"; + assert!(!nonzero(&export(counter, "nonZero").0)); + // Type exported from a document gives no warning about the fill rule. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Bob 80"})).unwrap(); + let w = warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap()); + assert!(!nonzero(&w), "{w:?}"); +} + +#[test] +fn a_miter_limit_the_file_cannot_hold_is_named() { + let miter = |w: &[String]| w.iter().any(|w| w.contains("miter limit")); + let export = |join: &str, limit: f64| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 40, "height": 30})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#3366cc"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4, "join": join, "miterLimit": limit})).unwrap(); + warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap()) + }; + assert!(miter(&export("miter", 2.0))); + // The limit a stroke opens with again, and corners that are not mitered, lose nothing. + assert!(!miter(&export("miter", 10.0))); + assert!(!miter(&export("round", 2.0))); +} + +/// A 1 x 1 PNG. +fn tiny_png() -> Vec { + let mut out = Vec::new(); + image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + #[test] fn a_layer_without_a_name_is_named_by_its_place() { // An empty layer, which is left out, then a layer named only by spaces: it comes in unnamed, diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index e1b4f6aad0..3458c5ae37 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -181,6 +181,33 @@ fn a_placed_document_is_vectors_in_every_output() { assert!(info.to_string().contains("\"placedDocuments\""), "{info}"); } +#[test] +fn a_placed_documents_spot_color_stays_a_spot_color_in_a_cmx_file() { + let dir = Folder::new("placed-cmx-spot"); + let src = dir.file("logo.vectorcraft"); + let mut d = Document::new(100.0, 50.0); + let gold = Color::cmyk(0.0, 0.2, 0.8, 0.1); + d.swatches.push(vectorcraft_color::Swatch { name: "Gold".into(), paint: Paint::solid(gold), global: true, spot: true }); + let layer = d.layers[0].id; + let id = d.alloc_id(); + let paint = Paint::Solid { color: gold, swatch: Some("Gold".into()), tint: 1.0 }; + let look = Appearance::basic(paint, Paint::None, 0.0); + d.insert(Some(layer), 0, Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), look)).unwrap(); + write(&src, &vectorcraft_format::save_file(&d)); + let mut s = session(); + place(&mut s, &src); + assert!(s.doc().unwrap().doc.swatch("Gold").is_none(), "the placing document has no swatch of that name"); + let bytes = decode(&s.execute("document.serialize", &json!({"format": "cmx"})).unwrap()); + let drawing = craft_cdr::read_cmx(&bytes, craft_cdr::Limits::default()).unwrap(); + let mut fills = Vec::new(); + for o in drawing.pages.iter().flat_map(|p| &p.layers).flat_map(|l| &l.objects) { + if let craft_cdr::model::Object::Shape(shape) = o { + fills.extend(shape.fill.clone()); + } + } + assert!(fills.iter().any(|c| matches!(c, craft_cdr::model::Color::Spot { name, .. } if name == "Gold")), "{fills:?}"); +} + #[test] fn the_preview_is_saved_so_the_document_shows_it_without_its_file() { let dir = Folder::new("placed-saved"); diff --git a/crates/mcp/src/tests/fileio.rs b/crates/mcp/src/tests/fileio.rs index 50cebb4cbf..f8c3689f99 100644 --- a/crates/mcp/src/tests/fileio.rs +++ b/crates/mcp/src/tests/fileio.rs @@ -80,7 +80,8 @@ fn export_tool_lists_engine_formats_and_options() { "wmf", "hpgl", "tga", - "psd" + "psd", + "cmx" ]) ); for k in ["artboard", "range", "options"] { diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index d8d215b86e..d9bf1c8d98 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -400,14 +400,14 @@ pub fn tool_definitions() -> Vec { tool( "export", "Export", - "Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, emf, wmf, hpgl pen moves for plotters and cutters), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.", + "Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, emf, wmf, hpgl pen moves for plotters and cutters, cmx exchange files of fills and strokes), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.", obj( json!({ "format": {"type": "string", "enum": FORMATS.iter().filter(|f| f.write).map(|f| f.id).collect::>(), "description": "Default: from the path's extension"}, "path": string("Destination file (omit to get dataBase64)"), "scale": num("Raster pixels per point (without scale or options.ppi, uses the document's raster effects resolution; options.ppi wins)"), "artboard": {"type": "integer", "minimum": 0, "description": "0-based artboard (default: the first; PDF and .ai default: all)"}, - "range": string("1-based artboards such as \"1-3, 5\" (PDF and .ai: one page each; SVG and SVGZ: one file each; EPS: one file each, after a central file of the whole document when there are two or more and art shows; rasters, DXF, EMF, WMF and HP-GL: one, or one file each with options.useArtboards: true)"), + "range": string("1-based artboards such as \"1-3, 5\" (PDF and .ai: one page each; SVG and SVGZ: one file each; EPS: one file each, after a central file of the whole document when there are two or more and art shows; rasters, DXF, EMF, WMF and HP-GL: one, or one file each with options.useArtboards: true; CMX: one, or one page each in one file with options.useArtboards: true)"), "selection": {"type": "boolean", "description": "Export only the selection, cropped to it"}, "outlineText": {"type": "boolean", "description": "SVG/SVGZ: true writes text as outlines (viewable without the fonts). DXF takes it too (type outlined anyway unless preserve: editability). PDF uses options.advanced.outlineText instead (default false: live text)"}, "options": {"type": "object", "description": "More format options, passed through (see run_command document.formats), e.g. {\"quality\": 80} for jpg or {\"advanced\": {\"outlineText\": true}} for PDF text as outlines (default false: live text)"}, diff --git a/crates/metafile/src/encode.rs b/crates/metafile/src/encode.rs index 6eab34d886..708f386958 100644 --- a/crates/metafile/src/encode.rs +++ b/crates/metafile/src/encode.rs @@ -32,7 +32,7 @@ pub(crate) fn write(ops: Vec, region: Rect, kind: Kind, title: &str, fn convert(op: scene::Op, kind: Kind) -> Op { match op { - scene::Op::Fill { path, rule, rgb } => Op::Fill { path, even_odd: rule == FillRule::EvenOdd, rgb }, + scene::Op::Fill { path, rule, rgb, .. } => Op::Fill { path, even_odd: rule == FillRule::EvenOdd, rgb }, scene::Op::Stroke { mut path, pen } => { let dash = pen.dash.and_then(|dash| { let native = Dash { pattern: dash.pattern.clone(), offset: dash.offset }; @@ -78,7 +78,7 @@ mod tests { path.line_to((7.0, 45.0)); path.close_path(); let dash = vectorcraft_doc::Dash { pattern: vec![5.0, 3.0], offset: 1.25, align_corners: true }; - let plain = scene::Pen { rgb: [30, 60, 90], width: 1.0, cap: LineCap::Round, join: LineJoin::Round, miter: 4.0, dash: None }; + let plain = scene::Pen { rgb: [30, 60, 90], paint: None, width: 1.0, cap: LineCap::Round, join: LineJoin::Round, miter: 4.0, dash: None }; let with_dash = scene::Pen { dash: Some(dash.clone()), ..plain.clone() }; let segments = vectorcraft_effects::stroke::dash(&path, &dash).unwrap().path; let region = Rect::new(0.0, 0.0, 50.0, 50.0); diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 645eb30c11..df23cbb073 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -22,6 +22,9 @@ //! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of //! document. //! +//! [`painted_layers`] gives the same walk's fills and strokes, layer by layer, to writers of other +//! formats. +//! //! The app walks its document and maps its drawing operations to the shared writers. #[cfg(test)] @@ -111,6 +114,88 @@ pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result, + }, + Stroke { + path: vectorcraft_geom::BezPath, + rgb: [u8; 3], + /// The solid paint `rgb` comes from (`None`: the one colour of a gradient or pattern). + paint: Option, + /// Points. + width: f64, + cap: vectorcraft_doc::LineCap, + join: vectorcraft_doc::LineJoin, + /// The miter limit, as a multiple of the width. + miter: f64, + /// A dash pattern that draws dashes (points). + dash: Option, + }, +} + +/// The visible art of a document, layer by layer ([`painted_layers`]). +#[derive(Clone, Debug, Default)] +pub struct PaintedLayers { + /// Each top-level layer's name (empty when it has none) and its fills and strokes in + /// paint order, in the document's order of layers (the bottom layer first). + pub layers: Vec<(String, Vec)>, + /// What was approximated or left out, as the WMF writer reports it. + pub warnings: Vec, + /// Visible images that could be decoded were left out (one that can't be decoded has its own + /// warning). + pub images: bool, + /// The swatches the paints name: the document's, and those of the documents it places. + pub swatches: Vec, +} + +/// The visible art of `doc` over `region` as fills and strokes, one list for each top-level +/// layer, taken as the WMF writer takes it: live effects applied, type as glyph outlines, +/// gradients and patterns as one colour, clipping masks not applied, and strokes a pen can't draw +/// (aligned inside or outside, width profiles, arrowheads) as their filled outlines. Images are +/// left out. An empty region is an error. +pub fn painted_layers(doc: &Document, region: Rect) -> Result { + check_regions(&[region])?; + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers); + let doc = baked.as_ref().unwrap_or(doc); + let (by_layer, mut warnings) = scene::Scene::new(doc, region.abs(), false).run_by_layer(); + let mut out = PaintedLayers::default(); + for (layer, ops) in doc.layers.iter().zip(by_layer) { + let mut painted = Vec::with_capacity(ops.len()); + for op in ops { + match op { + scene::Op::Fill { path, rule, rgb, paint } => painted.push(Painted::Fill { path, rule, rgb, paint }), + scene::Op::Stroke { path, pen } => painted.push(Painted::Stroke { + path, + rgb: pen.rgb, + paint: pen.paint, + width: pen.width, + cap: pen.cap, + join: pen.join, + miter: pen.miter, + dash: pen.dash, + }), + scene::Op::Image { .. } => out.images = true, + scene::Op::Clip { .. } | scene::Op::Unclip => {} + } + } + out.layers.push((layer.name.clone().unwrap_or_default(), painted)); + } + // The images are left out, so how a distorted one would have been written does not apply. An + // image that can't be decoded keeps its warning: it is missing either way. + warnings.retain(|w| w != scene::DISTORTED_IMAGES_NOTE); + out.warnings = warnings; + out.swatches = doc.swatches_iter().cloned().collect(); + Ok(out) +} + /// A metafile read into a document. #[derive(Clone, Debug)] pub struct Imported { diff --git a/crates/metafile/src/scene.rs b/crates/metafile/src/scene.rs index 3c280822b3..8adbd5e9ed 100644 --- a/crates/metafile/src/scene.rs +++ b/crates/metafile/src/scene.rs @@ -44,11 +44,15 @@ const INSIDE_TOL: f64 = 1e-6; /// The warning for an image left out because it can't be decoded: the note raster exports give /// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`). const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; +/// The warning about how distorted images are written. +pub(crate) const DISTORTED_IMAGES_NOTE: &str = DISTORTED_IMAGES; /// A stroke as a pen draws it. #[derive(Clone, Debug, PartialEq)] pub(crate) struct Pen { pub rgb: [u8; 3], + /// The solid paint `rgb` comes from (`None`: a gradient's or pattern's one colour). + pub paint: Option, /// Points. pub width: f64, pub cap: LineCap, @@ -65,6 +69,8 @@ pub(crate) enum Op { path: BezPath, rule: FillRule, rgb: [u8; 3], + /// The solid paint `rgb` comes from (`None`: a gradient's or pattern's one colour). + paint: Option, }, Stroke { path: BezPath, @@ -104,6 +110,11 @@ fn first_solid(n: &Node) -> Option { own.or_else(|| n.children().into_iter().flatten().find_map(|c| first_solid(c))) } +/// `p` when it is a solid paint. +fn solid(p: &Paint) -> Option { + matches!(p, Paint::Solid { .. }).then(|| p.clone()) +} + fn q(v: f32) -> u8 { (v.clamp(0.0, 1.0) * 255.0).round() as u8 } @@ -169,6 +180,18 @@ impl<'a> Scene<'a> { (self.ops, self.warnings) } + /// The operations of each top-level layer of the document, in its paint order, and the + /// warnings. Unlike [`Scene::run`], nothing is clipped to the region. + pub fn run_by_layer(mut self) -> (Vec>, Vec) { + let doc = self.doc; + let mut layers = Vec::with_capacity(doc.layers.len()); + for l in &doc.layers { + self.node(l, false); + layers.push(std::mem::take(&mut self.ops)); + } + (layers, self.warnings) + } + fn warn(&mut self, w: &str) { if !self.warnings.iter().any(|x| x == w) { self.warnings.push(w.to_string()); @@ -397,7 +420,7 @@ impl<'a> Scene<'a> { fn flat_fill(&mut self, bp: &BezPath, rule: FillRule, paint: &Paint, opacity: f32) { let Some(rgb) = self.flat(paint) else { return }; self.check_opacity(opacity); - self.ops.push(Op::Fill { path: bp.clone(), rule, rgb }); + self.ops.push(Op::Fill { path: bp.clone(), rule, rgb, paint: solid(paint) }); } /// One colour for a paint: a solid colour, the average of a gradient's stops, or a pattern's @@ -485,7 +508,15 @@ impl<'a> Scene<'a> { } let Some(rgb) = self.flat(&st.paint) else { return }; self.check_opacity(st.opacity); - let pen = Pen { rgb, width: st.width, cap: st.cap, join: st.join, miter: st.miter_limit, dash: st.dash.clone().filter(|d| d.is_dashed()) }; + let pen = Pen { + rgb, + paint: solid(&st.paint), + width: st.width, + cap: st.cap, + join: st.join, + miter: st.miter_limit, + dash: st.dash.clone().filter(|d| d.is_dashed()), + }; self.ops.push(Op::Stroke { path: bp.clone(), pen }); } @@ -601,7 +632,7 @@ fn merge_tiles(ops: &mut Vec, starts: &[usize]) -> bool { if shape.is_empty() || !rest.iter().all(same) { return false; } - let mut merged: Vec = shape.iter().map(|(_, rule, rgb)| Op::Fill { path: BezPath::new(), rule: *rule, rgb: *rgb }).collect(); + let mut merged: Vec = shape.iter().map(|(_, rule, rgb)| Op::Fill { path: BezPath::new(), rule: *rule, rgb: *rgb, paint: None }).collect(); for tile in &tiles { for (op, (path, _, _)) in merged.iter_mut().zip(tile) { if let Op::Fill { path: all, .. } = op { @@ -630,7 +661,7 @@ fn plain_fills(ops: &[Op]) -> Option> { inner .iter() .map(|op| match op { - Op::Fill { path, rule, rgb } => Some((path.clone(), *rule, *rgb)), + Op::Fill { path, rule, rgb, .. } => Some((path.clone(), *rule, *rgb)), _ => None, }) .collect() @@ -741,9 +772,11 @@ mod merge_tests { #[test] fn a_clip_that_cuts_its_fill_is_kept() { let clip = Op::Clip { path: poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero }; - let past = Op::Fill { path: poly(&[(0.0, 0.0), (12.0, 0.0), (12.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero, rgb: [255, 0, 0] }; + let past = + Op::Fill { path: poly(&[(0.0, 0.0), (12.0, 0.0), (12.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero, rgb: [255, 0, 0], paint: None }; assert!(plain_fills(&[clip.clone(), past, Op::Unclip]).is_none()); - let within = Op::Fill { path: poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero, rgb: [255, 0, 0] }; + let within = + Op::Fill { path: poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]), rule: FillRule::NonZero, rgb: [255, 0, 0], paint: None }; assert_eq!(plain_fills(&[clip, within, Op::Unclip]).map(|f| f.len()), Some(1)); } } diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 0ed84c3f24..ccc082bab8 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -374,7 +374,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` | | FreeHand `.fh*` | open (legacy) | no | no | | | `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, clipping containers, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; hidden and locked layers, groups and objects; the winding flag as the nonzero fill rule; uniform transparency of version 13 on as opacity and blend mode; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses, other transparency and merge modes without a blend mode are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies; version 3 envelopes are not applied, so the objects and groups under one keep their outlines and matrices, with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; after an open with a warning, an export or Save As to the drawing's own path needs `acknowledgeLoss: true`; record layouts and their sources in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`); synthetic test files only; tests in `craft-cdr` `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` | -| `.cmx` exchange files | | yes (files with 32-bit coordinates: pages, layers, groups, curves, uniform fills and outlines with their width, color, caps, joins and dashes; text, images, rectangles, ellipses, clipping paths, other fills and arrowheads are left out with a warning, and lenses are not applied, with a warning; big-endian files and files with 16-bit coordinates are refused) | no | File › Place reads them too; after an open with a warning, an export or Save As to the file's own path needs `acknowledgeLoss: true`; layouts and their sources in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`, R53 to R63); synthetic test files only; tests in `craft-cdr` `crates/cdr/tests/it/cmx.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs` and `crates/engine/tests/import_fuzz.rs` | +| `.cmx` exchange files | | yes (files with 32-bit coordinates: pages, layers, groups, curves, uniform fills and outlines with their width, color, caps, joins and dashes; text, images, rectangles, ellipses, clipping paths, other fills and arrowheads are left out with a warning, and lenses are not applied, with a warning; big-endian files and files with 16-bit coordinates are refused) | yes (one file with a page for the artboard, or for each chosen artboard with Use Artboards, and a layer for each layer with art on the page: fills and strokes as curves in CMYK, RGB, gray, spot colors at their tints and Registration, with stroke widths, caps, joins and dashes in whole stroke widths; type as outlines, gradients and patterns as one color, nonzero fills as even-odd; images, clipping masks and transparency are left out with a warning) | File › Place reads them too; after an open with a warning, an export or Save As to the file's own path needs `acknowledgeLoss: true`; layouts and their sources in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`, R53 to R63; the writer's fields under Written fields at `storytold/craft-libs@51fcc3b041`); synthetic test files only; tests in `craft-cdr` `crates/cdr/tests/it/cmx.rs` and `crates/cdr/tests/it/cmx_write.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs` and `crates/engine/tests/import_fuzz.rs` | | Text `.txt` | place, export | place (Text Import Options) | yes | place reads Unicode and ANSI, and Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European through the WHATWG Encoding Standard's decoders (VectorCraft's own mapping); `tests/textimport.rs`, `place/text.rs`; fuzzed (`text_import_fuzz.rs`) | | RTF `.rtf` | place | place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only | | Word `.docx` | place | place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out | diff --git a/docs/mcp.md b/docs/mcp.md index 1bbe49574d..7b90cc0293 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11985,8 +11985,32 @@ rectangles, ellipses, clipping paths and other objects the reader doesn't read y outline arrowheads are left out, and lenses, canvases and containers are not applied. The objects a clipping path clips come in without it. The `warnings` of `document.open` name each of these kinds the file had, and say when damaged parts or parts past the import limits were left out. Files in big-endian byte order and files with 16-bit coordinates are refused with a -message. VectorCraft doesn't write `.cmx` files. After a file opens with warnings, an export or Save As to its own path -needs `acknowledgeLoss: true`. +message. After a file opens with warnings, an export or Save As to its own path needs `acknowledgeLoss: true`. + +## CMX export + +`document.export {format: "cmx"}` (and Export As, `.cmx`) writes one `.cmx` exchange file with 32-bit coordinates in +0.1 µm units, in the layouts the CMX import reads, through `craft-cdr`'s `write_cmx`. The file has a page for the +chosen artboard (`artboard`, default the first), or with `useArtboards: true` a page for each chosen artboard +(`artboards` or `range`, default all), in one file; `useArtboards: false` writes the bounds of the visible art. Each +page has a layer, with its name, for each top-level layer that has visible art over that page, holding that art as +curves in paint order. A fill and a stroke of one path are one curve. Colors keep their model: CMYK in whole +percents, RGB and gray in 8-bit values, a spot swatch's color as a named library color at its tint in whole percents +with the swatch's look, and Registration; Lab colors are written as RGB. Strokes keep their width, caps, joins and +dashes, and dash and gap lengths are rounded to whole stroke widths, the unit the file stores them in. Type is written +as its glyph outlines, gradients and patterns as one color, and strokes the file can't hold (aligned inside or +outside, width profiles, arrowheads) as their filled outlines. Clipping masks are not applied, and art that crosses +the edge of a page is written whole, including the part past the edge. Layer and spot color names are written up to +4,096 characters, and a name longer than 256 characters opens again shortened, as the CMX import reads it. Placed +images, transparency, blend modes and raster effects are left out. A fill that uses the nonzero rule is written +even-odd; the warnings say so when the shape crosses itself, or when parts of it that turn the same way overlap. A +path of more than 7,281 points is written as a group of curves (one part longer than that is cut into open pieces, so +a fill of it, and its stroke where the pieces meet, draw differently). Dash offsets and dashes aligned to corners and +path ends are written as plain dashes from the start of each path. The file holds no miter limit, so mitered +corners open again with VectorCraft's default limit of 10. A spot color at a low tint opens again with its +ink's color changed (at 0% as white), a spot swatch without a name opens as a process color, and one whose color is +not known is written as black at its tint. The `warnings` name each of these losses the document had. A coordinate +past the 32-bit range, and a file larger than the CMX import reads, are refused with a message. ## Printing diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a54102e675..75d0cffeb8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2483,6 +2483,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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. `craft-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 `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `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 (`craft-cdr` `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - `.cmx` exchange files with 32-bit coordinates open and place: `craft-cdr` reads their color, pen, line type, dash and outline tables and each page's instructions, and the importer maps pages, layers (a layer that holds nothing is left out), groups and curves, with uniform fills and outlines, as it maps a `.cdr` drawing's. Text, images, rectangles, ellipses, clipping paths, other fills, arrowheads and lenses are named in the warnings, and big-endian files and files with 16-bit coordinates are refused with a message (`craft-cdr` `storytold/craft-libs@9b28b56bc7` `crates/cdr/tests/it/cmx.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs`, `crates/engine/tests/import_fuzz.rs`). + - `.cmx` export: `document.export {format: "cmx"}` writes a page for the chosen artboard, or for each chosen artboard with Use Artboards, and a layer for each layer with art on the page, with the art's fills and strokes as curves in their CMYK, RGB, gray, spot and Registration colors, stroke widths, caps, joins and dashes, through `craft-cdr`'s `write_cmx` (`storytold/craft-libs@51fcc3b041`), in the layouts the CMX import reads; type is written as outlines and gradients and patterns as one color, and images, clipping masks, transparency and nonzero fills written even-odd are named in the warnings. Written files open again through the CMX import with the same pages, layers, colors and geometry (`craft-cdr` `crates/cdr/tests/it/cmx_write.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs`). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. An EPS file, a PostScript file or a PostScript `.ai` placed from a file with Link is a placed document the same way, showing the art placing it without Link gives (clipped to its bounding box, or its art's bounds with `crop: "bounding"`); Links lists it as `EPS` or `PostScript`, and a save, Package, Break Link and Object › Expand treat it as they treat a placed PDF page. Package also copies the files that the native document of an EPS file written by VectorCraft links, beside the EPS file's copy, which finds them there by name. Placing one keeps the file linked rather than embedding it, as [the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/eps-and-dcs-file-import-in-illustrator.html) describes; a DCS file stays a linked image (`crates/engine/src/tests/placed_document.rs`, `crates/engine/src/tests/package.rs`).