mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 10:30:03 +00:00
File formats: open and place .cmx files
.cmx exchange files with 32-bit coordinates open and place as editable art. vectorcraft-cdr reads the RIFF form CMX1, its header, the color, pen, line type, dash, outline and arrowhead tables, and each page's instructions in drawing order, into the drawing model the .cdr reader uses, so the importer maps pages, layers, groups and curves with uniform fills and outlines the same way. A layer that holds nothing is left out. A page that gives no size of its own takes the size of the drawing's bounds, which the page header stores, and is centered on them. Text, images, rectangles, ellipses, clipping paths, fills other than uniform ones and arrowheads are left out, and lenses are not applied; the warnings name each kind, with rows in every complete catalog. Big-endian files and files with 16-bit coordinates are refused with a message. Layouts and their sources are rows R53 to R63 of crates/cdr/PROVENANCE.md; tests use synthetic files only.
This commit is contained in:
@@ -17,7 +17,8 @@
|
||||
//! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`.
|
||||
//! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`.
|
||||
//! - `metafile`: EMF and WMF export, open and place; PICT open and place.
|
||||
//! - `cdr`: `.cdr` drawings of versions 1 to 27 and `.cdt` templates, open and place.
|
||||
//! - `cdr`: `.cdr` drawings of versions 1 to 27 and `.cdt` templates, and `.cmx` files with
|
||||
//! 32-bit coordinates, open and place.
|
||||
//! - `hpgl`: HP-GL export options and plots.
|
||||
//! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no
|
||||
//! built-in format reads).
|
||||
@@ -179,6 +180,8 @@ mod tests_artboard_fill;
|
||||
#[cfg(test)]
|
||||
mod tests_cdr;
|
||||
#[cfg(test)]
|
||||
mod tests_cmx;
|
||||
#[cfg(test)]
|
||||
mod tests_pdf;
|
||||
#[cfg(test)]
|
||||
mod tests_pdfcolor;
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
//! `vectorcraft-cdr` reads, mapped to editable VectorCraft art. Pages become
|
||||
//! artboards side by side; layers of the same name on different pages become one layer where the
|
||||
//! pages stack them in the same order. What the
|
||||
//! reader leaves out is listed in the warnings, one line for each kind ([`note`]).
|
||||
//! reader leaves out is listed in the warnings, one line for each kind ([`note`]). `.cmx` exchange
|
||||
//! files with 32-bit coordinates are mapped the same way, with their own warnings ([`cmx_note`]).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -30,6 +31,15 @@ const TOO_DEEP: &str = "parts of the drawing nested too deeply, or past the impo
|
||||
const DAMAGED: &str = "damaged parts of the drawing were left out";
|
||||
const PAGES_CUT: &str = "CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard";
|
||||
|
||||
const CMX_UNSUPPORTED_OBJECTS: &str =
|
||||
"CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out";
|
||||
const CMX_UNSUPPORTED_FILLS: &str = "CMX fills other than uniform colors were left out";
|
||||
const CMX_UNKNOWN_COLORS: &str = "colors in CMX color models VectorCraft doesn't read were opened as black";
|
||||
const CMX_SPOT_LOOKS: &str = "CMX library colors that the file stores only by number were opened as black spot colors";
|
||||
const CMX_ARROWHEADS: &str = "CMX outline arrowheads were left out";
|
||||
const CMX_LENSES: &str = "CMX lenses were not applied";
|
||||
const CMX_PAGES_CUT: &str = "CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard";
|
||||
|
||||
/// What reading a drawing left out or changed, for each kind the reader reports.
|
||||
fn note(w: Warning) -> &'static str {
|
||||
match w {
|
||||
@@ -45,6 +55,20 @@ fn note(w: Warning) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// What reading a `.cmx` file left out or changed. The reader reports no envelopes in one.
|
||||
fn cmx_note(w: Warning) -> &'static str {
|
||||
match w {
|
||||
Warning::UnsupportedObjects | Warning::Envelopes => CMX_UNSUPPORTED_OBJECTS,
|
||||
Warning::UnsupportedFills => CMX_UNSUPPORTED_FILLS,
|
||||
Warning::UnknownColors => CMX_UNKNOWN_COLORS,
|
||||
Warning::SpotLooks => CMX_SPOT_LOOKS,
|
||||
Warning::Arrowheads => CMX_ARROWHEADS,
|
||||
Warning::Lenses => CMX_LENSES,
|
||||
Warning::TooDeep => TOO_DEEP,
|
||||
Warning::Damaged => DAMAGED,
|
||||
}
|
||||
}
|
||||
|
||||
/// The page size used when neither the page nor the document settings give one: US Letter,
|
||||
/// VectorCraft's own choice.
|
||||
const FALLBACK_PAGE: (f64, f64) = (612.0, 792.0);
|
||||
@@ -79,8 +103,25 @@ pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
|
||||
}
|
||||
why => err(format!("this CDR drawing can't be read ({why})")),
|
||||
})?;
|
||||
Ok(build(&d, note, PAGES_CUT))
|
||||
}
|
||||
|
||||
/// Is `bytes` a `.cmx` file, of any byte order or coordinate size?
|
||||
pub(super) fn is_cmx(bytes: &[u8]) -> bool {
|
||||
vectorcraft_cdr::is_cmx(bytes)
|
||||
}
|
||||
|
||||
/// A `.cmx` file with 32-bit coordinates: its pages, layers, groups and curves with uniform fills
|
||||
/// and outlines, mapped as a `.cdr` drawing's are.
|
||||
pub(super) fn import_cmx(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
|
||||
let d = vectorcraft_cdr::read_cmx(bytes, Limits::default()).map_err(|why| err(format!("this CMX file can't be read ({why})")))?;
|
||||
Ok(build(&d, cmx_note, CMX_PAGES_CUT))
|
||||
}
|
||||
|
||||
/// The document of `d`, and one warning for each kind of content left out or changed.
|
||||
fn build(d: &cd::Drawing, note: fn(Warning) -> &'static str, pages_cut: &str) -> (Document, Vec<String>) {
|
||||
let mut b = shapes::Builder::new();
|
||||
let mut doc = b.document(&d);
|
||||
let mut doc = b.document(d);
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
for w in d.warnings.iter().chain(&b.notes) {
|
||||
if !warnings.iter().any(|x| x == note(*w)) {
|
||||
@@ -88,10 +129,10 @@ pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
|
||||
}
|
||||
}
|
||||
if b.pages_cut {
|
||||
warnings.push(PAGES_CUT.to_string());
|
||||
warnings.push(pages_cut.to_string());
|
||||
}
|
||||
doc.limit_depth_noting(&mut warnings);
|
||||
Ok((doc, warnings))
|
||||
(doc, warnings)
|
||||
}
|
||||
|
||||
/// Where each page lies in the document: its artboard, and the map from its own space (points
|
||||
|
||||
@@ -537,6 +537,9 @@ pub const FORMATS: &[Format] = &[
|
||||
// them.
|
||||
reader("cdr", "CDR Drawing", &["cdr"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type
|
||||
reader("cdt", "CDR Template", &["cdt"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type
|
||||
// `.cmx` exchange files with 32-bit coordinates, read by `vectorcraft-cdr`; exports don't write
|
||||
// them.
|
||||
reader("cmx", "CMX", &["cmx"], "image/x-cmx", false),
|
||||
// QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images.
|
||||
reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false),
|
||||
];
|
||||
@@ -598,17 +601,18 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"afpub",
|
||||
"cdr",
|
||||
"cdt",
|
||||
"cmx",
|
||||
];
|
||||
|
||||
/// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to
|
||||
/// raster editors, so Finder and file managers don't offer a vector app for them, and there is no
|
||||
/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL or `.cdr` type, nor one for the `.pns`, `.dib` and `.rle` names of
|
||||
/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib` and `.rle` names of
|
||||
/// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS
|
||||
/// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it.
|
||||
/// The packaging declares no type for HP-GL plot files or PICT pictures either.
|
||||
pub const UNASSOCIATED_EXTS: &[&str] = &[
|
||||
"psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc",
|
||||
"heic", "heif", "jxl", "cdr", "cdt", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict",
|
||||
"heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict",
|
||||
];
|
||||
|
||||
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
|
||||
@@ -697,6 +701,7 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"afpub",
|
||||
"cdr",
|
||||
"cdt",
|
||||
"cmx",
|
||||
"txt",
|
||||
"rtf",
|
||||
"docx",
|
||||
|
||||
@@ -96,6 +96,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
|
||||
// A template keeps its meaning from the extension.
|
||||
return by_name.filter(|f| f.id == "cdt").or_else(|| format("cdr"));
|
||||
}
|
||||
if super::cdr::is_cmx(bytes) {
|
||||
return format("cmx");
|
||||
}
|
||||
if vectorcraft_format::sniff(bytes) {
|
||||
// A template keeps its meaning from the extension, like .ait.
|
||||
return by_name.filter(|f| f.id == "template").or_else(|| format("vectorcraft"));
|
||||
@@ -549,6 +552,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
let (doc, warnings) = super::cdr::import(bytes)?;
|
||||
(doc, warnings, false)
|
||||
}
|
||||
"cmx" => {
|
||||
let (doc, warnings) = super::cdr::import_cmx(bytes)?;
|
||||
(doc, warnings, false)
|
||||
}
|
||||
// A PSD or PSB file's layers become layers (`layers`, default on); without layers, or with
|
||||
// `layers: false`, its merged image opens. Layers that can't be read leave the merged image.
|
||||
"psd" | "psb" if opts.layers => match super::psdlayers::import_active(bytes, opts.hidden_layers) {
|
||||
@@ -800,12 +807,12 @@ fn open_loaded(
|
||||
loaded.with_grid_prefs(&s.prefs).with_unit_prefs(&s.prefs);
|
||||
// EPS now has an ordinary Save path. Its preview, partial-program and damaged-editing
|
||||
// fallbacks must ask before overwriting the richer source they could not fully read. Every
|
||||
// warning of a `.cdr` drawing names content the import left out or changed.
|
||||
// warning of a `.cdr` drawing or a `.cmx` file names content the import left out or changed.
|
||||
let losses: Vec<String> = warnings
|
||||
.iter()
|
||||
.filter(|w| {
|
||||
is_loss(w)
|
||||
|| matches!(format.id, "cdr" | "cdt")
|
||||
|| matches!(format.id, "cdr" | "cdt" | "cmx")
|
||||
|| (format.id == "eps"
|
||||
&& (matches!(w.as_str(), EDITING_DAMAGED | EDITING_STALE)
|
||||
|| w.starts_with("this file's PostScript couldn't be read")
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! `.cmx` files: Open and Place, by extension and by content, mapped to artboards, layers, groups,
|
||||
//! paths, solid paint and strokes, with their warnings and refusals.
|
||||
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use vectorcraft_cdr::synth_cmx::*;
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
|
||||
fn paths(nodes: &[std::sync::Arc<Node>], out: &mut Vec<Node>) {
|
||||
for n in nodes {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => paths(children, out),
|
||||
_ => out.push((**n).clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn warnings(r: &serde_json::Value) -> Vec<String> {
|
||||
r["warnings"].as_array().map(|w| w.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmx_file_opens_as_editable_art() {
|
||||
let mut s = Session::new();
|
||||
let r = open_bytes(&mut s, "drawing.cmx", &sample(), None).unwrap();
|
||||
assert_eq!(r["format"], "cmx");
|
||||
assert!(warnings(&r).is_empty(), "{r}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
// One 210 x 297 mm page.
|
||||
assert_eq!(doc.artboards.len(), 1);
|
||||
let ab = doc.artboards[0].rect;
|
||||
assert_eq!((ab.width().round(), ab.height().round()), (595.0, 842.0));
|
||||
// Bottom to top: the layer drawn first is at the bottom.
|
||||
let names: Vec<String> = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, ["Art", "Top"]);
|
||||
let art = doc.layers[0].children().unwrap();
|
||||
assert_eq!(art.len(), 2);
|
||||
assert!(matches!(art[1].kind, NodeKind::Group { .. }), "the group drawn after the red square is above it");
|
||||
let mut all = Vec::new();
|
||||
paths(&doc.layers, &mut all);
|
||||
assert_eq!(all.len(), 4);
|
||||
// The red square: 100 mm on a side, centered on the page, with a fill and a stroke.
|
||||
let red = &all[0];
|
||||
let b = doc.bounds_of(&[red.id], false).unwrap();
|
||||
let mm = 72.0 / 25.4;
|
||||
assert!((b.width() - 100.0 * mm).abs() < 0.01 && (b.center().x - ab.center().x).abs() < 0.01, "{b:?}");
|
||||
assert_eq!(red.appearance.items.len(), 2);
|
||||
// The square whose line type draws no outline has a fill only.
|
||||
assert_eq!(all[1].appearance.items.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detection_by_content_and_place() {
|
||||
let bytes = sample();
|
||||
let mut s = Session::new();
|
||||
// A renamed file is found by its content, and a .cmx extension alone reads it as one.
|
||||
assert_eq!(open_bytes(&mut s, "renamed.bin", &bytes, None).unwrap()["format"], "cmx");
|
||||
assert_eq!(detect("drawing.png", &bytes).map(|f| f.id), Some("cmx"));
|
||||
assert_eq!(detect("drawing.cmx", b"").map(|f| f.id), Some("cmx"));
|
||||
s.execute("file.new", &json!({"width":100,"height":100})).unwrap();
|
||||
s.execute("file.place", &json!({"name":"art.cmx", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty()));
|
||||
let f = format("cmx").unwrap();
|
||||
assert!(f.read && !f.write);
|
||||
assert!(OPEN_EXTS.contains(&"cmx") && PLACE_EXTS.contains(&"cmx") && UNASSOCIATED_EXTS.contains(&"cmx"));
|
||||
assert!(!SAVE_FORMATS.contains(&"cmx"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_left_out_is_named_in_the_warnings() {
|
||||
let mut children = vec![cont(b'4', 1e-7)];
|
||||
children.push(page(&[
|
||||
begin_page(None),
|
||||
begin_layer("L", None),
|
||||
instr(66, &fields(&[field(1, &[0; 8])])),
|
||||
square(&attrs_fill_type(2), 0, 0, 1000),
|
||||
square(&attrs(Some(1), Some(1), true), 0, 0, 1000),
|
||||
]));
|
||||
children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rota")));
|
||||
children.push(arrowheads(&[(1, 0)]));
|
||||
let mut s = Session::new();
|
||||
let w = warnings(&open_bytes(&mut s, "drawing.cmx", &riff(&children), None).unwrap());
|
||||
assert_eq!(
|
||||
w,
|
||||
[
|
||||
"CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out",
|
||||
"CMX fills other than uniform colors were left out",
|
||||
"CMX outline arrowheads were left out",
|
||||
"CMX lenses were not applied",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_the_open_left_things_out_of_is_not_written_over_unasked() {
|
||||
let d = std::env::temp_dir().join(format!("vc-cmx-loss-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let src = d.join("drawing.cmx");
|
||||
let mut children = vec![cont(b'4', 1e-7), page(&[begin_page(None), square(&attrs_fill_type(2), 0, 0, 1000)])];
|
||||
children.extend(tables());
|
||||
let original = riff(&children);
|
||||
std::fs::write(&src, &original).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({ "path": src.to_string_lossy() })).unwrap();
|
||||
let e = s.execute("document.export", &json!({ "path": src.to_string_lossy(), "format": "svg" })).unwrap_err().to_string();
|
||||
assert!(e.contains("acknowledgeLoss"), "{e}");
|
||||
assert_eq!(std::fs::read(&src).unwrap(), original);
|
||||
std::fs::remove_dir_all(d).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_that_are_not_read_say_why() {
|
||||
let mut s = Session::new();
|
||||
let mut rifx = sample();
|
||||
rifx[..4].copy_from_slice(b"RIFX");
|
||||
let e = open_bytes(&mut s, "a.cmx", &rifx, None).unwrap_err().to_string();
|
||||
assert!(e.contains("this CMX file can't be read (big-endian CMX files are not read)"), "{e}");
|
||||
let e = open_bytes(&mut s, "b.cmx", &riff(&[cont(b'2', 1e-3)]), None).unwrap_err().to_string();
|
||||
assert!(e.contains("this CMX file can't be read (CMX files with 16-bit coordinates are not read)"), "{e}");
|
||||
let e = open_bytes(&mut s, "c.cmx", &riff(&[]), None).unwrap_err().to_string();
|
||||
assert!(e.contains("this CMX file can't be read (damaged CMX header)"), "{e}");
|
||||
let e = open_bytes(&mut s, "d.cmx", b"not a cmx file", None).unwrap_err().to_string();
|
||||
assert!(e.contains("this CMX file can't be read (not a CMX file)"), "{e}");
|
||||
}
|
||||
Reference in New Issue
Block a user