diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 2487dcd01d..a06b163888 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -17,6 +17,11 @@ bundled-fonts = ["vectorcraft-text/bundled-fonts"] # feature still recognizes the files and refuses them with a message. The apps list it beside # `bundled-fonts`. heif = ["dep:heic-rs", "dep:rayon"] +# Binary CGM files open and place. Off until the craft-metafile CGM reader (craft-libs#5410) merges +# and the workspace pins it; the build fails with this feature on before then. Without it, `.cgm` +# is not listed as readable or placeable anywhere. Turning it on also needs `cgm` in +# `UNASSOCIATED_EXTS` (`src/cmd/fileio/formats.rs`). +cgm = ["vectorcraft-metafile/cgm"] [dependencies] craft-codepage = { workspace = true } diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index b57811b4ae..3a0bbe8b6c 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -16,7 +16,7 @@ //! - `dxf`: DXF export options, `document.exportDxf`, and the formats that can't be written (DWG, PageMaker). //! - `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. +//! - `metafile`: EMF and WMF export, open and place; PICT and CGM 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). @@ -246,6 +246,9 @@ mod tests_svgimport; #[cfg(test)] mod tests_eps; +// The CGM reader waits on craft-libs#5410 (the `cgm` feature). +#[cfg(all(test, feature = "cgm"))] +mod tests_cgm; #[cfg(test)] mod tests_dwgimport; #[cfg(test)] diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index ff20e5046a..b0809bfbad 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -577,6 +577,10 @@ pub const FORMATS: &[Format] = &[ 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), + // Binary Computer Graphics Metafiles, read by `vectorcraft_metafile::import_cgm` into paths, + // type and images. Behind the `cgm` feature until craft-libs#5410 merges. + #[cfg(feature = "cgm")] + reader("cgm", "CGM", &["cgm"], "image/cgm", false), // Layered raster `.pcraft` documents, read by `pcraftread` as one image: the full-size // composite, the layers combined, or the preview with a note. Exports don't write them. reader("pcraft", "PCRAFT", &["pcraft"], "application/x-pcraft", true), @@ -640,6 +644,8 @@ pub const OPEN_EXTS: &[&str] = &[ "pct", "pic", "pict", + #[cfg(feature = "cgm")] + "cgm", "plt", "hpgl", "hgl", @@ -666,7 +672,8 @@ pub const OPEN_EXTS: &[&str] = &[ /// entry's EPS and JPEG types (shared-mime-info's) also cover `.epsf` and `.jpe`, so file managers /// offer VectorCraft for them. /// The packaging declares no type for HP-GL plot files, PICT pictures, layered raster `.pcraft` -/// documents or DWG drawings (`.dwg`, `.dws` and `.dwt`) either. +/// documents or DWG drawings (`.dwg`, `.dws` and `.dwt`) either. CGM files are added here +/// when the `cgm` feature is turned on (craft-libs#5410). pub const UNASSOCIATED_EXTS: &[&str] = &[ "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "jpe", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc", "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", "dws", "dwt", @@ -747,6 +754,8 @@ pub const PLACE_EXTS: &[&str] = &[ "pct", "pic", "pict", + #[cfg(feature = "cgm")] + "cgm", "plt", "hpgl", "hgl", diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 76f793f302..46f65c414c 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -134,6 +134,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { if let Some(kind) = vectorcraft_metafile::sniff(bytes) { return format(kind.id()); } + if vectorcraft_metafile::is_cgm(bytes) { + return format("cgm"); + } if psdread::is_psd(bytes) { return format(if psdread::is_psb(bytes) { "psb" } else { "psd" }); } @@ -581,6 +584,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result let (doc, warnings) = super::metafile::import_pict(bytes)?; (doc, warnings, false) } + "cgm" => { + let (doc, warnings) = super::metafile::import_cgm(bytes)?; + (doc, warnings, false) + } "hpgl" => { let i = vectorcraft_cad::hpgl::import(bytes).map_err(err)?; (i.document, i.warnings, false) diff --git a/crates/engine/src/cmd/fileio/metafile.rs b/crates/engine/src/cmd/fileio/metafile.rs index 3012f7c238..23d4978218 100644 --- a/crates/engine/src/cmd/fileio/metafile.rs +++ b/crates/engine/src/cmd/fileio/metafile.rs @@ -2,7 +2,8 @@ //! `document.export {format: emf|wmf}` and Export As (one picture of an artboard, or one per //! artboard with Use Artboards; raster effects as images, rendered at the document's raster //! effects resolution), `document.open` and File → Place (one artboard, the picture's frame). -//! QuickDraw pictures (PICT) open and place the same way; they are never written. +//! QuickDraw pictures (PICT) and binary Computer Graphics Metafiles (CGM) open and place the same +//! way; they are never written. use serde_json::Value; use vectorcraft_doc::Document; @@ -78,3 +79,9 @@ pub(super) fn import_pict(bytes: &[u8]) -> Result<(Document, Vec)> { let p = vectorcraft_metafile::import_pict(bytes).map_err(super::err)?; Ok((p.document, p.warnings)) } + +/// A binary CGM's first picture as a document, and the import's warnings. +pub(super) fn import_cgm(bytes: &[u8]) -> Result<(Document, Vec)> { + let p = vectorcraft_metafile::import_cgm(bytes).map_err(super::err)?; + Ok((p.document, p.warnings)) +} diff --git a/crates/engine/src/cmd/fileio/tests_cgm.rs b/crates/engine/src/cmd/fileio/tests_cgm.rs new file mode 100644 index 0000000000..3317d66e5a --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_cgm.rs @@ -0,0 +1,118 @@ +//! Binary CGM files through the commands: `document.open` by extension or by content, File › Place +//! as one group clipped to the picture's frame, the dialogs' filters and the format list, and +//! files that aren't binary CGM, or a CGM export, refused with a message. + +use serde_json::json; +use vectorcraft_doc::NodeKind; + +use super::*; + +fn b64(bytes: &[u8]) -> String { + vectorcraft_format::base64_encode(bytes) +} + +/// One element, padded to an even length. +fn el(class: u16, id: u16, data: &[u8]) -> Vec { + let mut b = ((class << 12) | (id << 5) | data.len() as u16).to_be_bytes().to_vec(); + b.extend(data); + if data.len() % 2 == 1 { + b.push(0); + } + b +} + +fn words(v: &[i16]) -> Vec { + v.iter().flat_map(|x| x.to_be_bytes()).collect() +} + +/// A binary CGM whose picture is 1000 × 500 units at 0.2 mm a unit (200 × 100 mm): a solid +/// rectangle and a line. +fn picture() -> Vec { + let mut b = el(0, 1, b"\x04logo"); + b.extend(el(1, 1, &words(&[1]))); + b.extend(el(0, 3, b"\x01p")); + b.extend(el(2, 1, &[words(&[1]), 0.2f32.to_be_bytes().to_vec()].concat())); + b.extend(el(2, 6, &words(&[0, 0, 1000, 500]))); + b.extend(el(0, 4, &[])); + b.extend(el(5, 22, &words(&[1]))); + b.extend(el(4, 11, &words(&[100, 100, 400, 300]))); + b.extend(el(4, 1, &words(&[0, 450, 1000, 450]))); + b.extend(el(0, 5, &[])); + b.extend(el(0, 2, &[])); + b +} + +const MM: f64 = 72.0 / 25.4; + +#[test] +fn document_open_reads_a_picture() { + let mut s = Session::new(); + let r = s.execute("document.open", &json!({"name": "part.cgm", "dataBase64": b64(&picture())})).unwrap(); + assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("cgm"), Some("part.cgm")), "{r}"); + assert_eq!(r["warnings"], json!([])); + let st = s.doc().unwrap(); + let size = st.doc.artboards[0].rect.size(); + assert!((size.width - 200.0 * MM).abs() < 1e-3 && (size.height - 100.0 * MM).abs() < 1e-3, "{size:?}"); + let mut paths = vec![]; + st.doc.walk(|n| { + if let NodeKind::Path { .. } = n.kind { + paths.push(n.clone()); + } + }); + assert_eq!(paths.len(), 2); + let b = paths[0].geometric_bounds().unwrap(); + assert!((b.x0 - 20.0 * MM).abs() < 1e-3 && (b.width() - 60.0 * MM).abs() < 1e-3, "{b:?}"); + assert!(st.path.is_none(), "opened as artwork: Save asks for a name"); + + // A CGM opens by its content under a name no format reads. + for name in ["part.CGM", "part.bin", "part"] { + let r = Session::new().execute("document.open", &json!({"name": name, "dataBase64": b64(&picture())})).unwrap(); + assert_eq!(r["format"].as_str(), Some("cgm"), "{name}: {r}"); + } + assert_eq!(detect("part.dat", &picture()).map(|f| f.id), Some("cgm")); +} + +#[test] +fn file_place_places_a_picture_as_one_clipped_group() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let p = json!({"name": "part.cgm", "dataBase64": b64(&picture()), "at": [400, 400]}); + let info = s.execute("file.place.info", &p).unwrap(); + assert_eq!(info["format"], "cgm", "{info}"); + assert!((info["width"].as_f64().unwrap() - 200.0 * MM).abs() < 1e-3, "{info}"); + let r = s.execute("file.place", &p).unwrap(); + assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("cgm"), Some(1)), "{r}"); + let doc = &s.doc().unwrap().doc; + let group = doc.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); + assert_eq!(group.name.as_deref(), Some("part.cgm")); + let NodeKind::Group { clip: true, .. } = &group.kind else { panic!("a clipping group, got {:?}", group.kind) }; + let b = group.geometric_bounds().unwrap(); + assert!((b.width() - 200.0 * MM).abs() < 1e-3 && (b.height() - 100.0 * MM).abs() < 1e-3, "{b:?}"); +} + +#[test] +fn files_that_are_not_cgm_are_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let e = s.execute("document.open", &json!({"name": "old.cgm", "dataBase64": b64(&[0; 64])})).expect_err("refused"); + assert!(e.to_string().contains("not a CGM file"), "{e}"); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), (100.0, 50.0).into()); + assert!(s.execute("file.place", &json!({"name": "old.cgm", "dataBase64": b64(&[0; 64])})).is_err()); + let e = s.execute("document.open", &json!({"name": "text.cgm", "dataBase64": b64(b"BEGMF 'x';")})).expect_err("refused"); + assert!(e.to_string().contains("only binary CGM files"), "{e}"); + let e = s.execute("document.export", &json!({"format": "cgm"})).expect_err("refused").to_string(); + assert!(e.contains("CGM files can be opened but not written"), "{e}"); +} + +#[test] +fn the_dialogs_and_the_format_list_name_cgm() { + assert!(OPEN_EXTS.contains(&"cgm") && PLACE_EXTS.contains(&"cgm") && UNASSOCIATED_EXTS.contains(&"cgm")); + assert_eq!(format_for_name("a.cgm").map(|f| f.id), Some("cgm")); + let filter = ("CGM", &["cgm"][..]); + assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter)); + let r = Session::new().execute("document.formats", &json!({})).unwrap(); + let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "cgm").unwrap().clone(); + assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(false), Some(false)), "{f}"); + assert_eq!(f["mime"], "image/cgm"); + assert!(writable_format(None, Some("x/part.cgm")).is_err()); +} diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 95d48d106a..cb1ae23fbf 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -10,7 +10,7 @@ //! [`fileio::psd_slices`]). //! - An SVG becomes one group of its art; so does a DXF drawing, read with the DXF options //! (`dxf`, [`fileio::dxfimport`]), and an HP-GL plot file (`vectorcraft_cad::hpgl`). -//! - An EMF, WMF or PICT picture becomes one group, clipped to its frame (`crop: "crop"`) or +//! - An EMF, WMF, PICT or CGM picture becomes one group, clipped to its frame (`crop: "crop"`) or //! bounded by its art (`crop: "bounding"`). //! - An EPS file (or a PostScript .ai) becomes one group, clipped to its bounding box or bounded by //! its art: the document an EPS file of ours carries, else what its PostScript draws, else its diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index db08db87f8..edc89b319b 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -4,7 +4,8 @@ //! must load as an error or as a document that then renders and exports, without a panic; nor may //! bitmaps, PDF and text pasted from other apps, nor EMF and WMF pictures (damaged files, records //! of every kind with random contents) opened, placed or pasted, nor PICT pictures (damaged files, -//! opcodes with random contents) opened or placed, nor EPS and PostScript files +//! opcodes with random contents) opened or placed, nor binary CGM files (damaged files, elements +//! with random contents) opened or placed, nor EPS and PostScript files //! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of //! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor the widths a //! `.ai`'s PDF part gives its fonts' characters (hostile font dictionaries), nor Affinity documents @@ -4158,6 +4159,125 @@ proptest! { } } +// ---------- Binary CGM files: opened and placed ---------- + +// The CGM reader waits on craft-libs#5410: everything here is behind the `cgm` feature. + +/// One CGM element, in the long form past 30 bytes, padded to an even length. +#[cfg(feature = "cgm")] +fn cgm_el(class: u16, id: u16, data: &[u8]) -> Vec { + let mut b = Vec::new(); + if data.len() < 31 { + b.extend(((class << 12) | (id << 5) | data.len() as u16).to_be_bytes()); + } else { + b.extend(((class << 12) | (id << 5) | 31).to_be_bytes()); + b.extend((data.len() as u16).to_be_bytes()); + } + b.extend(data); + if data.len() % 2 == 1 { + b.push(0); + } + b +} + +/// A metafile of one picture holding `body`. +#[cfg(feature = "cgm")] +fn cgm_of(body: &[(u16, u16, Vec)]) -> Vec { + let mut b = cgm_el(0, 1, b"\x01x"); + b.extend(cgm_el(1, 1, &be16(&[3]))); + b.extend(cgm_el(1, 13, b"\x09Helvetica")); + b.extend(cgm_el(0, 3, b"\x01p")); + b.extend(cgm_el(2, 6, &be16(&[0, 0, 1000, 500]))); + b.extend(cgm_el(0, 4, &[])); + for (class, id, data) in body { + b.extend(cgm_el(*class, *id, data)); + } + b.extend(cgm_el(0, 5, &[])); + b.extend(cgm_el(0, 2, &[])); + b +} + +/// A picture with lines, shapes, arcs, a figure, markers, text, a cell array and a clip. +#[cfg(feature = "cgm")] +fn cgm_sample() -> Vec { + cgm_of(&[ + (5, 34, vec![8, 10, 20, 30, 40, 50, 60]), + (5, 3, be16(&[3])), + (5, 2, be16(&[2])), + (4, 1, be16(&[0, 0, 100, 100, 200, 0])), + (4, 2, be16(&[0, 10, 50, 10, 60, 10, 90, 10])), + (5, 22, be16(&[1])), + (5, 30, be16(&[1])), + (4, 7, be16(&[300, 0, 400, 0, 350, 80])), + (4, 8, be16(&[0, 200, 1, 100, 200, 1, 100, 300, 3])), + (4, 11, be16(&[500, 0, 600, 100])), + (4, 12, be16(&[700, 100, 50])), + (4, 14, be16(&[800, 0, 850, 50, 900, 0, 0])), + (4, 16, be16(&[100, 400, 1, 0, 0, 1, 50, 1])), + (4, 19, be16(&[300, 400, 350, 400, 300, 420, 1, 0, 0, 1, 0])), + (4, 26, be16(&[2, 0, 0, 10, 20, 30, 20, 40, 0])), + (0, 8, vec![]), + (4, 1, be16(&[500, 300, 600, 300])), + (4, 15, be16(&[600, 350, 0, -1, 0, 1, 50])), + (3, 10, vec![]), + (0, 9, vec![]), + (5, 6, be16(&[3])), + (4, 3, be16(&[900, 400, 950, 450])), + (3, 5, be16(&[0, 0, 500, 250])), + (5, 15, be16(&[40])), + (4, 4, [be16(&[100, 100, 0]), b"\x03abc".to_vec()].concat()), + (4, 6, [be16(&[1]), b"\x02de".to_vec()].concat()), + (4, 9, [be16(&[0, 0, 200, 100, 200, 0, 2, 2, 4, 1]), vec![0x12, 0, 0x34, 0]].concat()), + ]) +} + +/// The sample the mutations start from opens with art, type and an image. +#[cfg(feature = "cgm")] +#[test] +fn the_cgm_sample_opens() { + let l = vectorcraft_engine::cmd::fileio::load("x.cgm", &cgm_sample()).unwrap(); + assert_eq!(l.format.id, "cgm"); + let (mut paths, mut images, mut texts) = (0, 0, 0); + l.doc.walk(|n| match n.kind { + vectorcraft_doc::NodeKind::Path { .. } => paths += 1, + vectorcraft_doc::NodeKind::Image(_) => images += 1, + vectorcraft_doc::NodeKind::Text(_) => texts += 1, + _ => {} + }); + assert!(paths > 10 && images == 1 && texts == 1, "{paths} paths, {images} images, {texts} texts, warnings {:?}", l.warnings); +} + +/// CGM elements VectorCraft reads, and some it skips: the class in the high byte, the id in the +/// low one. +#[cfg(feature = "cgm")] +const CGM_ELEMENTS: [u16; 44] = [ + 0x0008, 0x0009, 0x0103, 0x0104, 0x0105, 0x0107, 0x010A, 0x010C, 0x010D, 0x0113, 0x0201, 0x0202, 0x0203, 0x0207, 0x0301, 0x0302, 0x0305, 0x0306, + 0x030A, 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0406, 0x0407, 0x0408, 0x0409, 0x040B, 0x040C, 0x040D, 0x040F, 0x0411, 0x0412, 0x0414, 0x0418, + 0x041A, 0x0503, 0x0504, 0x050F, 0x0510, 0x0512, 0x0522, 0x0801, +]; + +#[cfg(feature = "cgm")] +proptest! { + #![proptest_config(config())] + + #[test] + fn mutated_cgm_pictures_never_panic(cut in 0usize..4096, edits in prop::collection::vec((0usize..4096, any::()), 0..16)) { + let mut bytes = cgm_sample(); + let n = bytes.len(); + for &(at, b) in &edits { + bytes[at % n] = b; + } + bytes.truncate(cut); + survive_metafile("mutated CGM", "x.cgm", &bytes)?; + } + + #[test] + fn random_cgm_elements_never_panic(els in prop::collection::vec((prop::sample::select(CGM_ELEMENTS.to_vec()), arb_body()), 0..32)) { + let body: Vec<(u16, u16, Vec)> = els.into_iter().map(|(e, d)| (e >> 8, e & 0xFF, d)).collect(); + survive_metafile("CGM elements", "x.cgm", &cgm_of(&body))?; + } +} + // ---------- HP-GL plot files: opened and placed ---------- /// A plot file with every kind of instruction the reader plays, printer escapes around it. diff --git a/crates/metafile/Cargo.toml b/crates/metafile/Cargo.toml index 364f5c55d3..c561ffccf0 100644 --- a/crates/metafile/Cargo.toml +++ b/crates/metafile/Cargo.toml @@ -3,11 +3,16 @@ name = "vectorcraft-metafile" version.workspace = true edition.workspace = true license.workspace = true -description = "VectorCraft metafiles: EMF and WMF export and EMF, EMF+, WMF and QuickDraw PICT import through craft-metafile" +description = "VectorCraft metafiles: EMF and WMF export and EMF, EMF+, WMF, QuickDraw PICT and binary CGM import through craft-metafile" [lints] workspace = true +[features] +# The binary CGM reader (`import_cgm`). Off until the craft-metafile CGM reader (craft-libs#5410) +# merges and the workspace pins it; without it, `is_cgm` is false and `import_cgm` is refused. +cgm = [] + [dependencies] vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } diff --git a/crates/metafile/src/import.rs b/crates/metafile/src/import.rs index 63ba902cef..298d47f5d7 100644 --- a/crates/metafile/src/import.rs +++ b/crates/metafile/src/import.rs @@ -1,5 +1,6 @@ //! The metafile readers. EMF (with its EMF+ records) and WMF files, and QuickDraw pictures (PICT), -//! are read by `craft_metafile`, and `picture` turns what they draw into document objects. +//! and binary CGM files are read by `craft_metafile`, and `picture` turns what they draw into +//! document objects. //! //! Fills and strokes become paths with a fill and a stroke; lines drawn one after another with the //! same pen join into one path. Clips become clipping groups around what they clip. Images keep @@ -92,3 +93,35 @@ pub(crate) fn import_pict(bytes: &[u8]) -> Result { })?; Ok(picture::convert(pic)) } + +/// The longer side of a CGM picture without a metric scale, points (8 inches). +#[cfg(feature = "cgm")] +const CGM_SIDE: f64 = 576.0; + +/// Read the first picture of a binary CGM (ISO/IEC 8632-3) through `craft_metafile`. +/// `craft_metafile::parse_cgm` comes with craft-libs#5410, so this waits on the `cgm` feature. +#[cfg(feature = "cgm")] +pub(crate) fn import_cgm(bytes: &[u8]) -> Result { + let cgm = craft_metafile::parse_cgm(bytes, CGM_SIDE).map_err(|e| e.to_string())?; + let n = cgm.notes; + let mut p = picture::convert(cgm.picture); + let notes = [ + (n.fills_approximated, "hatch, pattern and interpolated fills were filled with their fill color"), + (n.more_pictures, "the file holds more than one picture: only the first was read"), + (n.cie_colors, "colors in a CIE color model were read as RGB"), + (n.text_path, "text set to run left, up or down was set to run right"), + (n.restricted_text, "restricted text was set at its character height without fitting it to its box"), + (n.character_spacing, "character spacing was not applied"), + (n.text_cut, "text past 16,384 characters in one string was cut"), + ]; + p.warnings.extend(notes.iter().filter(|(on, _)| *on).map(|(_, w)| (*w).to_string())); + if n.damaged_elements > 0 { + let k = n.damaged_elements; + p.warnings.push(format!( + "{k} drawing element{} cut short or describing no shape {} left out", + if k == 1 { "" } else { "s" }, + if k == 1 { "was" } else { "were" } + )); + } + Ok(p) +} diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 66f3c4327b..b602a5edab 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -20,7 +20,7 @@ //! A picture cut short by a reader limit, images and pattern brushes that can't be read, clips //! that can't be applied and raster operations other than a plain copy each add a warning. //! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of -//! document. +//! document, and [`import_cgm`] the first picture of a binary Computer Graphics Metafile (CGM). //! //! [`painted_layers`] gives the same walk's fills and strokes, layer by layer, to writers of other //! formats. @@ -236,5 +236,34 @@ pub fn import_pict(bytes: &[u8]) -> Result { Ok(p) } +/// Do `bytes` start like a binary CGM: BEGIN METAFILE, then METAFILE VERSION? Always false +/// without the `cgm` feature (craft-libs#5410). +pub fn is_cgm(bytes: &[u8]) -> bool { + #[cfg(feature = "cgm")] + return craft_metafile::is_cgm(bytes); + #[cfg(not(feature = "cgm"))] + { + let _ = bytes; + false + } +} + +/// Read the first picture of a binary Computer Graphics Metafile (CGM, ISO/IEC 8632-3) into a +/// document whose one artboard is the picture's VDC extent. Without the `cgm` feature +/// (craft-libs#5410), every file is refused. +pub fn import_cgm(bytes: &[u8]) -> Result { + #[cfg(feature = "cgm")] + { + let mut p = import::import_cgm(bytes)?; + p.document.limit_depth_noting(&mut p.warnings); + Ok(p) + } + #[cfg(not(feature = "cgm"))] + { + let _ = bytes; + Err("CGM files can't be read in this build".to_string()) + } +} + #[cfg(test)] mod tests; diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index eeb30ec846..420edeb077 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -11,6 +11,9 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, shapes}; use crate::*; +// The CGM reader waits on craft-libs#5410 (the `cgm` feature). +#[cfg(feature = "cgm")] +mod cgm; mod import; mod pict; diff --git a/crates/metafile/src/tests/cgm.rs b/crates/metafile/src/tests/cgm.rs new file mode 100644 index 0000000000..a9cbca18fc --- /dev/null +++ b/crates/metafile/src/tests/cgm.rs @@ -0,0 +1,441 @@ +//! Binary Computer Graphics Metafiles read from hand-built elements: the picture's frame and its +//! scale, lines, shapes, arcs, figures, markers, text, cell arrays and clips; elements written in +//! partitions; and files that aren't binary CGM, hold no picture, are cut short or hold more than +//! one picture. + +use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind}; +use vectorcraft_geom::{Point, Rect}; + +use crate::{import_cgm, is_cgm}; + +/// Big-endian 16-bit words. +fn be(v: &[i16]) -> Vec { + v.iter().flat_map(|x| x.to_be_bytes()).collect() +} + +/// One element in the short form (or the long form past 30 bytes, in one partition), padded to +/// an even length. +fn el(class: u16, id: u16, data: &[u8]) -> Vec { + let mut b = Vec::new(); + if data.len() < 31 { + b.extend(((class << 12) | (id << 5) | data.len() as u16).to_be_bytes()); + } else { + b.extend(((class << 12) | (id << 5) | 31).to_be_bytes()); + b.extend((data.len() as u16).to_be_bytes()); + } + b.extend(data); + if data.len() % 2 == 1 { + b.push(0); + } + b +} + +/// A string parameter. +fn s(text: &str) -> Vec { + [vec![text.len() as u8], text.as_bytes().to_vec()].concat() +} + +/// A metafile of one picture: `descriptor` after METAFILE VERSION, `picture` after BEGIN PICTURE +/// and `body` after BEGIN PICTURE BODY. +fn cgm(descriptor: &[Vec], picture: &[Vec], body: &[Vec]) -> Vec { + let mut b = el(0, 1, &s("test")); + b.extend(el(1, 1, &be(&[1]))); + descriptor.iter().for_each(|e| b.extend(e)); + b.extend(el(0, 3, &s("p1"))); + picture.iter().for_each(|e| b.extend(e)); + b.extend(el(0, 4, &[])); + body.iter().for_each(|e| b.extend(e)); + b.extend(el(0, 5, &[])); + b.extend(el(0, 2, &[])); + b +} + +/// A VDC extent of 1000 × 500 units: abstract, so 576 × 288 pt (0.576 pt a unit). +fn extent() -> Vec { + el(2, 6, &be(&[0, 0, 1000, 500])) +} + +/// Direct color selection: colors as 8-bit RGB. +fn direct() -> Vec { + el(2, 2, &be(&[1])) +} + +/// A VDC point (x, y) in points: y runs up from the bottom of the 1000 × 500 extent. +fn pt(x: f64, y: f64) -> Point { + Point::new(x * 0.576, (500.0 - y) * 0.576) +} + +fn all(d: &Document) -> Vec { + let mut v = vec![]; + for l in &d.layers { + for c in l.children().into_iter().flatten() { + c.walk(&mut |n| v.push(n.clone())); + } + } + v +} + +fn paths(d: &Document) -> Vec { + all(d).into_iter().filter(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })).collect() +} + +fn near(a: Rect, b: Rect, tol: f64) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() <= tol) +} + +fn fill_rgb(n: &Node) -> Option<[u8; 3]> { + n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) => f.paint.color().map(|c| { + let [r, g, b, _] = c.to_rgba8(1.0); + [r, g, b] + }), + _ => None, + }) +} + +fn stroke(n: &Node) -> Option<([u8; 3], f64)> { + n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Stroke(s) => s.paint.color().map(|c| { + let [r, g, b, _] = c.to_rgba8(1.0); + ([r, g, b], s.width) + }), + _ => None, + }) +} + +fn images(d: &Document) -> Vec<(Node, image::RgbaImage)> { + all(d) + .into_iter() + .filter_map(|n| match &n.kind { + NodeKind::Image(im) => { + let decoded = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap(); + Some((n.clone(), image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap())) + } + _ => None, + }) + .collect() +} + +#[test] +fn a_picture_opens_on_its_extent_with_the_first_corner_at_the_bottom_left() { + let bytes = cgm(&[], &[extent(), direct()], &[el(5, 22, &be(&[1])), el(5, 23, &[255, 0, 0]), el(4, 11, &be(&[100, 100, 300, 200]))]); + assert!(is_cgm(&bytes)); + let p = import_cgm(&bytes).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + assert!(near(p.document.artboards[0].rect, Rect::new(0.0, 0.0, 576.0, 288.0), 1e-9)); + let v = paths(&p.document); + assert_eq!(v.len(), 1, "{v:?}"); + assert_eq!(fill_rgb(&v[0]), Some([255, 0, 0])); + assert!(v[0].appearance.stroke().is_none(), "edges are off by default"); + let b = v[0].geometric_bounds().unwrap(); + assert!(near(b, Rect::from_points(pt(100.0, 100.0), pt(300.0, 200.0)), 1e-4), "{b:?}"); + + // An extent whose first corner is its top left turns the picture over: the same rectangle + // is then as far from the top as it was from the bottom. + let flipped = cgm(&[], &[el(2, 6, &be(&[0, 500, 1000, 0])), direct()], &[el(5, 22, &be(&[1])), el(4, 11, &be(&[100, 100, 300, 200]))]); + let b = paths(&import_cgm(&flipped).unwrap().document)[0].geometric_bounds().unwrap(); + assert!(near(b, Rect::new(57.6, 57.6, 172.8, 115.2), 1e-4), "{b:?}"); +} + +#[test] +fn a_metric_picture_keeps_its_size() { + // 0.1 mm a unit: 100 × 50 mm. + let metric = el(2, 1, &[be(&[1]), 0.1f32.to_be_bytes().to_vec()].concat()); + let p = import_cgm(&cgm(&[], &[metric, extent()], &[el(4, 1, &be(&[0, 0, 1000, 500]))])).unwrap(); + let size = p.document.artboards[0].rect.size(); + let mm = 72.0 / 25.4; + assert!((size.width - 100.0 * mm).abs() < 1e-3 && (size.height - 50.0 * mm).abs() < 1e-3, "{size:?}"); +} + +#[test] +fn lines_take_their_width_color_type_caps_and_joins() { + let bytes = cgm( + &[], + // Widths in VDC units. + &[extent(), el(2, 3, &be(&[0])), el(2, 17, &be(&[-1, 200, 1, 3]))], + &[ + // Color 9 from the color table: green. + el(5, 34, &[9, 0, 200, 0]), + el(5, 4, &[9]), + el(5, 3, &be(&[10])), + el(5, 2, &be(&[2])), + el(5, 37, &be(&[2, 2])), + el(5, 38, &be(&[4])), + el(4, 1, &be(&[0, 0, 500, 0, 500, 250])), + // Default color index 1 (black), a disjoint polyline: two separate lines. + el(5, 4, &[1]), + el(5, 2, &be(&[1])), + el(4, 2, &be(&[0, 400, 100, 400, 200, 400, 300, 400])), + // Line type -1 as the picture defines it: 200 units, a quarter on and three off. + el(5, 2, &be(&[-1])), + el(4, 1, &be(&[0, 450, 1000, 450])), + ], + ); + let p = import_cgm(&bytes).unwrap(); + let v = paths(&p.document); + assert_eq!(v.len(), 3, "{v:?}"); + let dash = v[2].appearance.stroke().unwrap().dash.clone().unwrap(); + assert!(dash.pattern.len() == 2 && (dash.pattern[0] - 28.8).abs() < 1e-3 && (dash.pattern[1] - 86.4).abs() < 1e-3, "{dash:?}"); + let (rgb, w) = stroke(&v[0]).unwrap(); + assert_eq!(rgb, [0, 200, 0]); + assert!((w - 5.76).abs() < 1e-4, "{w}"); + let st = v[0].appearance.stroke().unwrap(); + assert!(st.dash.as_ref().is_some_and(|d| d.is_dashed()), "line type 2 is dashed"); + assert_eq!((st.cap, st.join), (vectorcraft_doc::LineCap::Butt, vectorcraft_doc::LineJoin::Bevel)); + let NodeKind::Path { path, .. } = &v[1].kind else { panic!("a path") }; + assert_eq!(path.subpaths.len(), 2); + assert_eq!(stroke(&v[1]).unwrap().0, [0, 0, 0]); +} + +#[test] +fn circles_ellipses_and_arcs_are_curves_in_their_place() { + let bytes = cgm( + &[], + &[extent()], + &[ + el(5, 22, &be(&[1])), + // A circle of radius 100 at (500, 250). + el(4, 12, &be(&[500, 250, 100])), + // An ellipse 200 across and 50 high at (200, 100). + el(4, 17, &be(&[200, 100, 300, 100, 200, 125])), + // A half circle from (900, 250) through (800, 350) to (700, 250): the top half. + el(4, 13, &be(&[900, 250, 800, 350, 700, 250])), + // A quarter circle around (100, 400), from east to north, closed as a pie. + el(4, 16, &be(&[100, 400, 1, 0, 0, 1, 50, 0])), + ], + ); + let p = import_cgm(&bytes).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + let v = paths(&p.document); + assert_eq!(v.len(), 4, "{v:?}"); + // Cubic Béziers stand in for the curves: within 0.03% of the radius. + let tol = 0.05; + assert!(near(v[0].geometric_bounds().unwrap(), Rect::from_points(pt(400.0, 150.0), pt(600.0, 350.0)), tol)); + assert!(near(v[1].geometric_bounds().unwrap(), Rect::from_points(pt(100.0, 75.0), pt(300.0, 125.0)), tol)); + assert!(near(v[2].geometric_bounds().unwrap(), Rect::from_points(pt(700.0, 250.0), pt(900.0, 350.0)), tol)); + assert!(v[2].appearance.fill().is_none(), "an open arc is stroked"); + assert!(near(v[3].geometric_bounds().unwrap(), Rect::from_points(pt(100.0, 400.0), pt(150.0, 450.0)), tol)); + assert!(fill_rgb(&v[3]).is_some(), "a closed arc is filled"); +} + +#[test] +fn edges_outline_shapes_and_polygon_sets_skip_their_hidden_edges() { + let bytes = cgm( + &[], + &[extent(), direct()], + &[ + el(5, 22, &be(&[1])), + el(5, 30, &be(&[1])), + el(5, 29, &[0, 0, 255]), + // Two squares; the first one's left edge (from its last point) is hidden. + el(4, 8, &be(&[0, 0, 1, 100, 0, 1, 100, 100, 1, 0, 100, 2, 200, 0, 1, 300, 0, 1, 300, 100, 1, 200, 100, 3])), + ], + ); + let p = import_cgm(&bytes).unwrap(); + let v = paths(&p.document); + assert_eq!(v.len(), 2, "a fill and its edges: {v:?}"); + let NodeKind::Path { path, .. } = &v[0].kind else { panic!("a path") }; + assert_eq!(path.subpaths.len(), 2, "both squares fill"); + assert_eq!(stroke(&v[1]).unwrap().0, [0, 0, 255]); + let NodeKind::Path { path, .. } = &v[1].kind else { panic!("a path") }; + // The first square's three visible edges are one open line, and the second square is one + // closed outline. + assert_eq!(path.subpaths.len(), 2, "one outline for each square"); + assert_eq!(path.subpaths.iter().filter(|s| s.closed).count(), 1, "{:?}", path.subpaths); +} + +#[test] +fn a_figure_fills_its_lines_as_one_shape() { + let bytes = cgm( + &[], + &[extent()], + &[ + el(5, 22, &be(&[1])), + el(0, 8, &[]), + el(4, 1, &be(&[0, 0, 100, 0])), + el(4, 15, &be(&[100, 50, 0, -1, 0, 1, 50])), + el(4, 1, &be(&[100, 100, 0, 100])), + el(0, 9, &[]), + ], + ); + let p = import_cgm(&bytes).unwrap(); + let v = paths(&p.document); + assert_eq!(v.len(), 1, "{v:?}"); + assert!(fill_rgb(&v[0]).is_some() && v[0].appearance.stroke().is_none()); + let NodeKind::Path { path, .. } = &v[0].kind else { panic!("a path") }; + assert_eq!(path.subpaths.len(), 1); + assert!(near(v[0].geometric_bounds().unwrap(), Rect::from_points(pt(0.0, 0.0), pt(150.0, 100.0)), 0.05)); +} + +#[test] +fn text_comes_in_as_point_type_at_its_character_height() { + let bytes = cgm( + &[el(1, 13, &[s("Times-Roman"), s("Helvetica-BoldOblique")].concat())], + &[extent()], + &[ + el(5, 10, &be(&[2])), + el(5, 15, &be(&[70])), + // Not final: the rest of the string follows in APPEND TEXT. + el(4, 4, &[be(&[100, 200, 0]), s("Hel")].concat()), + el(4, 6, &[be(&[1]), s("lo")].concat()), + // Restricted text: its box is not applied, and a warning says so. + el(4, 5, &[be(&[300, 70, 100, 50, 1]), s("Box")].concat()), + ], + ); + let p = import_cgm(&bytes).unwrap(); + assert_eq!(p.warnings, ["restricted text was set at its character height without fitting it to its box"]); + let texts: Vec<_> = all(&p.document).into_iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).collect(); + assert_eq!(texts.len(), 2); + let NodeKind::Text(t) = &texts[0].kind else { panic!("text") }; + assert_eq!(t.plain_text(), "Hello"); + let st = &t.runs[0].style; + assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Helvetica", "Bold Italic")); + // The character height (70 units, 40.32 pt) is the cap height: 0.7 of the size. + assert!((st.size - 57.6).abs() < 1e-3, "{}", st.size); + assert!((t.xf.translation().to_point() - pt(100.0, 200.0)).hypot() < 1e-3, "{:?}", t.xf); +} + +#[test] +fn what_the_reader_left_out_or_set_differently_is_warned_about() { + let bytes = cgm( + &[], + &[extent()], + &[ + // Character spacing 0.5, then a rectangle with one corner and a circle without its radius. + el(5, 13, &[0, 0, 0x80, 0]), + el(4, 4, &[be(&[0, 0, 1]), s("spaced")].concat()), + el(4, 11, &be(&[0, 0])), + el(4, 12, &be(&[10, 10])), + el(4, 11, &be(&[0, 0, 10, 10])), + ], + ); + let p = import_cgm(&bytes).unwrap(); + assert!(p.warnings.iter().any(|w| w == "character spacing was not applied"), "{:?}", p.warnings); + assert!(p.warnings.iter().any(|w| w == "2 drawing elements cut short or describing no shape were left out"), "{:?}", p.warnings); + assert_eq!(paths(&p.document).len(), 1); +} + +#[test] +fn cell_arrays_become_images_packed_or_run_length() { + // 2 × 2 cells over (0, 0) to (200, 100), first row along the bottom: red, green, then blue, + // white. + let corners = be(&[0, 0, 200, 100, 200, 0]); + let packed = [corners.clone(), be(&[2, 2, 8, 1]), vec![255, 0, 0, 0, 255, 0], vec![0, 0, 255, 255, 255, 255]].concat(); + // Runs: a count (16 bits) and a color. + let run = |color: [u8; 3]| [be(&[1]), color.to_vec()].concat(); + let runs = [corners.clone(), be(&[2, 2, 8, 0]), run([255, 0, 0]), run([0, 255, 0]), run([0, 0, 255]), run([255, 255, 255])].concat(); + // 4-bit indexed cells: each row of two cells takes one byte and is padded to a word. + let indexed = [corners, be(&[2, 2, 4, 1]), vec![0x23, 0, 0x41, 0]].concat(); + for data in [packed, runs] { + let p = import_cgm(&cgm(&[], &[extent(), direct()], &[el(4, 9, &data)])).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + let imgs = images(&p.document); + assert_eq!(imgs.len(), 1); + let (n, px) = &imgs[0]; + assert_eq!(px.dimensions(), (2, 2)); + assert_eq!(px.get_pixel(0, 0).0, [255, 0, 0, 255]); + assert_eq!(px.get_pixel(1, 0).0, [0, 255, 0, 255]); + assert_eq!(px.get_pixel(0, 1).0, [0, 0, 255, 255]); + // The first row is at the bottom of the picture: drawn upward from P. + let b = n.geometric_bounds().unwrap(); + assert!(near(b, Rect::from_points(pt(0.0, 0.0), pt(200.0, 100.0)), 1e-3), "{b:?}"); + } + // Indexed cells through the default color table. + let p = import_cgm(&cgm(&[], &[extent()], &[el(4, 9, &indexed)])).unwrap(); + let px = &images(&p.document)[0].1; + let row = |y| [px.get_pixel(0, y).0, px.get_pixel(1, y).0]; + assert_eq!(row(0), [[255, 0, 0, 255], [0, 255, 0, 255]]); + assert_eq!(row(1), [[0, 0, 255, 255], [0, 0, 0, 255]]); +} + +#[test] +fn markers_are_drawn_at_their_points() { + let bytes = cgm(&[], &[extent()], &[el(5, 6, &be(&[4])), el(4, 3, &be(&[100, 100, 900, 400]))]); + let v = paths(&import_cgm(&bytes).unwrap().document); + assert_eq!(v.len(), 2); + // A nominal marker is 1/100 of the longer side across: 5.76 pt. + let b = v[1].geometric_bounds().unwrap(); + assert!((b.center() - pt(900.0, 400.0)).hypot() < 1e-3 && (b.width() - 5.76).abs() < 1e-2, "{b:?}"); +} + +#[test] +fn the_clip_rectangle_clips_what_follows() { + let bytes = cgm( + &[], + &[extent()], + &[el(5, 22, &be(&[1])), el(4, 11, &be(&[0, 0, 100, 100])), el(3, 5, &be(&[0, 0, 500, 250])), el(4, 11, &be(&[0, 0, 1000, 500]))], + ); + let p = import_cgm(&bytes).unwrap(); + let layer = p.document.layers[0].children().unwrap(); + assert!(matches!(layer[0].kind, NodeKind::Path { .. }), "the picture's own extent clips nothing"); + let NodeKind::Group { children, clip: true } = &layer[1].kind else { panic!("a clipping group: {:?}", layer[1].kind) }; + assert!(near(children[0].geometric_bounds().unwrap(), Rect::from_points(pt(0.0, 0.0), pt(500.0, 250.0)), 1e-3)); + // With the clip indicator off, nothing is clipped. + let off = [el(3, 5, &be(&[0, 0, 500, 250])), el(3, 6, &be(&[0])), el(5, 22, &be(&[1])), el(4, 11, &be(&[0, 0, 1000, 500]))]; + let off = cgm(&[], &[extent()], &off); + let p = import_cgm(&off).unwrap(); + assert!(matches!(p.document.layers[0].children().unwrap()[0].kind, NodeKind::Path { .. })); +} + +#[test] +fn precisions_real_coordinates_partitions_and_default_replacements() { + // Real VDC (fixed point 16.16), a line width set in the metafile's defaults, and a polyline + // in two partitions. + let fixed = |v: f64| ((v * 65536.0) as i32).to_be_bytes().to_vec(); + let mdr = el(1, 12, &[el(2, 3, &be(&[0])), el(5, 3, &fixed(100.0))].concat()); + let real_extent = el(2, 6, &[fixed(0.0), fixed(0.0), fixed(1000.0), fixed(500.0)].concat()); + let points: Vec = [0.0, 0.0, 500.0, 0.0, 500.0, 250.0, 1000.0, 500.0].iter().flat_map(|v| fixed(*v)).collect(); + let mut body = vec![]; + body.extend(((4u16 << 12) | (1 << 5) | 31).to_be_bytes()); + body.extend((0x8000u16 | 16).to_be_bytes()); + body.extend(&points[..16]); + body.extend(16u16.to_be_bytes()); + body.extend(&points[16..]); + let bytes = cgm(&[el(1, 3, &be(&[1])), mdr], &[real_extent], &[body]); + let p = import_cgm(&bytes).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + let v = paths(&p.document); + assert_eq!(v.len(), 1); + assert!(near(v[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 576.0, 288.0), 1e-3)); + assert!((stroke(&v[0]).unwrap().1 - 57.6).abs() < 1e-3, "{:?}", stroke(&v[0])); +} + +#[test] +fn files_that_are_not_binary_cgm_are_refused() { + assert_eq!(import_cgm(b"").unwrap_err(), "not a CGM file"); + assert_eq!(import_cgm(&[0; 64]).unwrap_err(), "not a CGM file"); + assert!(!is_cgm(&[0; 64])); + let clear = import_cgm(b"BEGMF 'drawing';\nmfversion 1;\n").unwrap_err(); + assert!(clear.contains("only binary CGM files"), "{clear}"); + // A metafile without a picture. + let mut b = el(0, 1, &s("empty")); + b.extend(el(1, 1, &be(&[1]))); + b.extend(el(0, 2, &[])); + assert!(is_cgm(&b)); + assert_eq!(import_cgm(&b).unwrap_err(), "the CGM file holds no picture"); +} + +#[test] +fn a_picture_cut_short_keeps_what_came_before() { + let full = cgm(&[], &[extent()], &[el(5, 22, &be(&[1])), el(4, 11, &be(&[0, 0, 100, 100])), el(4, 11, &be(&[200, 0, 300, 100]))]); + // Cut inside the second rectangle. + let cut = &full[..full.len() - 10]; + let p = import_cgm(cut).unwrap(); + assert_eq!(paths(&p.document).len(), 1); + assert!(p.warnings.iter().any(|w| w.contains("cut short")), "{:?}", p.warnings); +} + +#[test] +fn only_the_first_picture_is_read() { + let mut b = cgm(&[], &[extent()], &[el(5, 22, &be(&[1])), el(4, 11, &be(&[0, 0, 100, 100]))]); + // Drop END METAFILE and add a second picture. + b.truncate(b.len() - 2); + b.extend(el(0, 3, &s("p2"))); + b.extend(el(0, 4, &[])); + b.extend(el(4, 11, &be(&[0, 0, 500, 500]))); + b.extend(el(0, 5, &[])); + b.extend(el(0, 2, &[])); + let p = import_cgm(&b).unwrap(); + assert_eq!(paths(&p.document).len(), 1); + assert!(p.warnings.iter().any(|w| w.contains("only the first")), "{:?}", p.warnings); +}