From 9ef408dbd8921354a7422088a82eb5161faa3d5a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 16:20:39 -0800 Subject: [PATCH] File formats: CGM files open and place File > Open and File > Place read Computer Graphics Metafiles in the binary encoding of ISO/IEC 8632-3 (.cgm), and a binary CGM also opens by its content. The first picture comes in on one artboard, its VDC extent at its metric scale or 576 pt on its longer side, with the extent's first corner at the bottom left. - Polylines, disjoint polylines, polybeziers and open arcs are stroked with the line width, color, type, caps and joins, and line types the picture defines take their dashes from it. - Polygons, polygon sets, rectangles, circles, ellipses, closed arcs and figures are filled by the interior style and outlined with the edge attributes while edges are visible. - Markers become small paths, text becomes point type in the font the font list names, and cell arrays become images. - The clip rectangle clips what follows it. craft-metafile's CGM reader (craft-libs#5410) plays the picture into the same model as the PICT reader, so it becomes document objects the same way; craft-metafile is pinned at that pull request's head until it merges. Place puts the picture in one group clipped to its frame. What isn't read comes back as warnings, a picture cut short keeps what came before it, and clear text and character encoded files are refused with a message. CGM is not written. Docs: docs/mcp.md, docs/file-format-parity.md, docs/target-app-parity.md. --- Cargo.lock | 2 +- Cargo.toml | 4 +- crates/engine/src/cmd/fileio.rs | 4 +- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/formats.rs | 11 +- crates/engine/src/cmd/fileio/load.rs | 7 + crates/engine/src/cmd/fileio/metafile.rs | 9 +- crates/engine/src/cmd/fileio/tests_cgm.rs | 118 ++++++ crates/engine/src/cmd/place.rs | 4 +- crates/engine/tests/import_fuzz.rs | 114 +++++- crates/metafile/Cargo.toml | 2 +- crates/metafile/src/import.rs | 32 +- crates/metafile/src/lib.rs | 15 +- crates/metafile/src/tests.rs | 1 + crates/metafile/src/tests/cgm.rs | 441 ++++++++++++++++++++++ docs/file-format-parity.md | 3 +- docs/mcp.md | 41 +- docs/target-app-parity.md | 1 + 18 files changed, 793 insertions(+), 18 deletions(-) create mode 100644 crates/engine/src/cmd/fileio/tests_cgm.rs create mode 100644 crates/metafile/src/tests/cgm.rs diff --git a/Cargo.lock b/Cargo.lock index b53df9115b..2a7ac2cb80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1852,7 +1852,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=800ea5b587058832ed118c680cdba16b36789340#800ea5b587058832ed118c680cdba16b36789340" dependencies = [ "encoding_rs", "image", diff --git a/Cargo.toml b/Cargo.toml index 89a8feda76..fe8a7213b0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,8 +36,8 @@ craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "77ade5 craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified). craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -# WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +# WMF, EMF and EMF+ reader (craft-libs#778), and the binary CGM reader (craft-libs#5410). +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "800ea5b587058832ed118c680cdba16b36789340" } craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 1a24bf623b..22d4f28333 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,8 @@ mod tests_svgimport; #[cfg(test)] mod tests_eps; +#[cfg(test)] +mod tests_cgm; #[cfg(test)] mod tests_dwgimport; #[cfg(test)] diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 94565b3ce8..9e0cb072fa 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a file with that PieceInfo key: its trim box when no box is named, its crop box with cropTo: crop or crop: crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; 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), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a file with that PieceInfo key: its trim box when no box is named, its crop box with cropTo: crop or crop: crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; 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), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), binary CGM .cgm (the first picture: one artboard, its VDC extent at its metric scale, else 576 pt on its longer side; lines, shapes and markers as paths, text as point type, cell arrays as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index f8da5b941c..1d362fd1e6 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -558,6 +558,9 @@ 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. + 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), @@ -611,6 +614,7 @@ pub const OPEN_EXTS: &[&str] = &[ "pct", "pic", "pict", + "cgm", "plt", "hpgl", "hgl", @@ -633,11 +637,11 @@ pub const OPEN_EXTS: &[&str] = &[ /// `.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, PICT pictures, layered raster `.pcraft` -/// documents or DWG drawings either. +/// The packaging declares no type for HP-GL plot files, PICT pictures, CGM files, layered raster +/// `.pcraft` documents or DWG drawings 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", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", + "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "cgm", "pcraft", "dwg", ]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares @@ -714,6 +718,7 @@ pub const PLACE_EXTS: &[&str] = &[ "pct", "pic", "pict", + "cgm", "plt", "hpgl", "hgl", diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index f152132c69..557352ae86 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -131,6 +131,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" }); } @@ -576,6 +579,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 9d145853b9..4f2a1ec854 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 @@ -88,7 +88,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; an image changed by Perspective Distort or Free Distort keeps its corners, which a raster image or a DCS file's image fills, with its file's clipping path drawn through them, and other files but text are refused; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, from the bottom layer upward in each layer's listed order (returned object order without layers), embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; an image changed by Perspective Distort or Free Distort keeps its corners, which a raster image or a DCS file's image fills, with its file's clipping path drawn through them, and other files but text are refused; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, from the bottom layer upward in each layer's listed order (returned object order without layers), embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF, PICT (.pct, .pic, .pict) and binary CGM (.cgm, its first picture) (clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index c6f02b9240..5938ad0e14 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 @@ -4022,6 +4023,117 @@ proptest! { } } +// ---------- Binary CGM files: opened and placed ---------- + +/// One CGM element, in the long form past 30 bytes, padded to an even length. +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`. +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. +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. +#[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. +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, +]; + +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..5afc04a19a 100644 --- a/crates/metafile/Cargo.toml +++ b/crates/metafile/Cargo.toml @@ -3,7 +3,7 @@ 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 diff --git a/crates/metafile/src/import.rs b/crates/metafile/src/import.rs index 63ba902cef..d2e3f99de2 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,32 @@ 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). +const CGM_SIDE: f64 = 576.0; + +/// Read the first picture of a binary CGM (ISO/IEC 8632-3) through `craft_metafile`. +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..1394a75bb0 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,18 @@ pub fn import_pict(bytes: &[u8]) -> Result { Ok(p) } +/// Do `bytes` start like a binary CGM: BEGIN METAFILE, then METAFILE VERSION? +pub fn is_cgm(bytes: &[u8]) -> bool { + craft_metafile::is_cgm(bytes) +} + +/// 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. +pub fn import_cgm(bytes: &[u8]) -> Result { + let mut p = import::import_cgm(bytes)?; + p.document.limit_depth_noting(&mut p.warnings); + Ok(p) +} + #[cfg(test)] mod tests; diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index eeb30ec846..2bce1ded94 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -11,6 +11,7 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, shapes}; use crate::*; +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); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 31f0da4316..52acb9b572 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -61,7 +61,7 @@ Ordinary File > Save offers Save As when its own location refuses writes with a | | Illustrator | VectorCraft | Notes | |---|---:|---:|---| -| Formats opened or placed | ~30 | 37 | missing: FreeHand | +| Formats opened or placed | ~30 | 38 | missing: FreeHand | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, gradients, patterns, images, type, symbols, artboards, transparency, opacity masks, clipping, text wrap options) or as legacy version 7 (layers and groups, one artboard per file) | | Formats exported | ~16 | 20 | missing: DWG; extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | | **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting | @@ -385,6 +385,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | PCX | open, place | yes (1 bit in the header palette's first two colors, black and white without them; 1 bit in two to four planes and 4 bits with up to 16 colors; 2 bits in the CGA colors the header's CGA palette settings pick; 8 bits with the 256-color palette, gray without one; 24-bit color in three planes) | no | the header's HDpi and VDpi size the image; a file of another depth or plane count, cut short or past the pixel allowance is refused with a message; tests in `crates/engine/src/cmd/fileio/tests_pcxread.rs` and `crates/engine/tests/import_fuzz.rs` | | JPEG 2000 | open, place | yes (JP2 and raw codestream images; multiple codestreams and JPX composition or layers are refused) | no | `.jpf`, `.jpx`, `.jp2`, `.j2k`, `.j2c`, `.jpc`; resolution uses the valid `resd` (display) value on each axis, or else the valid `resc` (capture) value, or 72 ppi; bounded decoding; `tests_jp2read.rs` | | PICT | open, place (legacy) | yes (versions 1 and 2: shapes, lines, regions, text, bitmaps, pixel maps and QuickTime JPEG images; placed as one group clipped to the picture's frame) | no | `.pct`, `.pic` and `.pict`; a version 2 picture also opens by its content; a two-color pattern fills with its average color; inverted shapes, transfer modes other than a copy and QuickTime images in other formats come back as warnings; a picture cut short keeps what came before it; tests in `crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs` and `crates/engine/tests/import_fuzz.rs` | +| CGM `.cgm` | open, place | yes (the binary encoding, ISO/IEC 8632-3: the first picture's polylines, polygons, polygon sets, rectangles, circles, ellipses, arcs, polybeziers, figures, markers, text and cell arrays, with line, edge and fill attributes, the color table and the clip rectangle; placed as one group clipped to the picture's frame) | no | also opens by its content; clear text and character encoded files are refused with a message; hatch, pattern and interpolated fills fill with their fill color; B-splines, hyperbolic and parabolic arcs, symbols, tiles and segment copies are skipped with a warning; a picture cut short keeps what came before it; tests in `crates/metafile/src/tests/cgm.rs`, `crates/engine/src/cmd/fileio/tests_cgm.rs` and `crates/engine/tests/import_fuzz.rs` | | Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` | | FreeHand `.fh*` | open (legacy) | no | no | | | `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, clipping containers, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; 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` | diff --git a/docs/mcp.md b/docs/mcp.md index 2fd8648262..50681987da 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -866,7 +866,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. UI commands such as `view.*` and `window.*` are in `command_list` with `ui: true`; running them needs the desktop app (`--connect`). The app refuses `attributes.openUrl`, `file.export.svg.browser`, `file.saveForWeb.browser` and `file.showPackage` for every control and MCP request, since each opens another app, so the headless error for them does not suggest `--connect`. | | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | | `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. An app that does not send the image back writes a window capture without `path` to a file in a new folder inside the system's temporary folder (on Unix only the user can open it); the server reads the file and then removes the folder, also when the capture or the read fails. | -| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`), layered raster `.pcraft` documents (as one image at the canvas size; a warning says when only the smaller preview could be read). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | +| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), binary CGM (`.cgm`, and a binary CGM of any extension; its first picture), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`), layered raster `.pcraft` documents (as one image at the canvas size; a warning says when only the smaller preview could be read). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | | `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `_.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error; versions 1 to 3 get each live star as a plain path of its outline, without its point count and ratio), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a PDF-compatible `.ai` file reads `compress` but not `version`, `preview`, `precision`, `outlineText`, `hiddenObjects`, `transparentImages` or `preserveEditing`, and a legacy `.ai` file reads only its own options). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for each key given beside the path or in `options` that the file doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). In the desktop app, a save that runs in the background shows in the progress window after 0.4 s with a moving bar. `file.cancelSave` stops every such save before it replaces its file → `{cancelled: n}`: the file stays as it was, and the document keeps its file and format and stays modified. A save whose file was already being replaced finishes and is reported as saved. `file.saveInBackground` closes the window while the saves go on → `{hidden: n}`. | | `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` for type on a path (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning). An invalid effect is rejected before editing. `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | @@ -12672,7 +12672,7 @@ images. DWG drawings open and place (see DXF import) but can't be written: `document.formats` lists `dwg` as readable and not writable, and exporting to it answers with the hint to export DXF. PICT files open and place (see PICT -import) but can't be written. +import) but can't be written, and so do CGM files (see CGM import). ```json {"name":"run_command","arguments":{"command":"document.exportDxf","params":{"path":"/tmp/plan.dxf","version":"2013","unit":"mm","scale":10,"preserve":"editability"}}} @@ -13301,6 +13301,43 @@ written". {"name":"run_command","arguments":{"command":"file.place","params":{"path":"/tmp/logo.pct","at":[300,200]}}} ``` +## CGM import + +`document.open` and `file.place` read Computer Graphics Metafiles in the binary encoding of ISO/IEC 8632-3 (`.cgm`), +the encoding [WebCGM 2.1](https://www.w3.org/TR/webcgm21/) profiles, into one artboard and one layer. A CGM also opens by +its content under any name. Only the first picture is read; a file that holds more adds a warning. + +- The artboard is the picture's VDC extent, with the extent's first corner at its bottom left. A picture with a metric + scale keeps its size in millimeters; any other picture is scaled so that its longer side is 576 pt. +- Polylines, disjoint polylines, polybeziers and open arcs are stroked with the line width, color, type, caps and joins. + Line types 2 to 5 are dashes and dots at multiples of the line's width, and a type that LINE AND EDGE TYPE DEFINITION + defines takes its dashes from there. +- Polygons, polygon sets, rectangles, circles, ellipses and closed arcs are filled by the interior style with the odd-even + rule, and outlined with the edge attributes while edges are visible. A polygon set leaves out its hidden edges. A hollow + interior is outlined in the fill color. Lines and arcs between BEGIN FIGURE and END FIGURE fill as one shape. +- Markers become small paths at their points. Text, restricted text and appended text become point type in the font the + font list names, along the character orientation, with the character height as the cap height (0.7 of the type size). +- Cell arrays (packed or run-length encoded, indexed or direct color) become images placed by their three corners. +- The clip rectangle clips what follows it while the clip indicator is on. + +VectorCraft's own values where the file leaves them to the reader: a nominal line or edge width is 1/1000 of the +picture's longer side, a nominal marker 1/100 of it, and colors 0 to 7 of the default color table are white, black, red, +green, blue, yellow, cyan and magenta. + +`file.place` places the picture as one group clipped to its frame. What isn't read comes back in `warnings`, once each: +hatch, pattern and interpolated fills (filled with their fill color), text that runs left, up or down (set to run right), +restricted text (set at its character height without fitting it to its box), character spacing (not applied), text past +16,384 characters in one string (cut), colors in a CIE color model (read as RGB), drawing elements whose parameters are +cut short or describe no shape (left out, with their count), and B-splines, hyperbolic and parabolic arcs, symbols, tiles +and segment copies (skipped). A picture cut short or past the reader's limits keeps what came before it with a warning. A file that isn't binary CGM is refused with +"not a CGM file", a clear text or character encoded CGM with "only binary CGM files can be read: this one uses the clear +text or character encoding", and a metafile without a picture with "the CGM file holds no picture". CGM can't be written: +`document.export` to it is refused with "CGM files can be opened but not written". + +```json +{"name":"run_command","arguments":{"command":"file.place","params":{"path":"/tmp/part.cgm","at":[300,200]}}} +``` + ## HP-GL import `document.open` and `file.place` read HP-GL/2 plot files (`.plt`, `.hpgl`, `.hgl`, `.hpg`) into one layer, with the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 99255fa880..1041576062 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2545,6 +2545,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - HEIC and HEIF images open and place from `.heic` and `.heif`, as the [supported file formats](https://helpx.adobe.com/illustrator/kb/supported-file-formats-illustrator.html) list High Efficiency Image under both Open and Place (and [Fix HEIF file import errors on Windows](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/fix-heif-file-import-errors-on-windows.html) covers both ways of bringing HEIF files in): HEVC-coded single pictures and grids of tiles, 8 to 10 bits, with an alpha image, decoded by heic-rs in the engine's default `heif` feature. The container's rotation, mirror and crop are applied. Without an `nclx` box, the HEVC stream's video signal type gives the samples' matrix and range. An RGB ICC profile, or Display P3 with the sRGB curve named by an `nclx` box or, without a color box, by the stream, is converted to sRGB; the EXIF resolution tags size the image, or 72 ppi. Image sequences, other codings and grids of cropped tiles are refused with a message, and so is every HEIF file in a build without the feature. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_heifread.rs`). - HP-GL/2 plot files (`.plt`, `.hpgl`, `.hgl`, `.hpg`, or a name no other format reads when the file starts with plotter instructions) open and place as paths on one layer, the artboard round the art: each line drawn with the pen down is a stroked path in its pen's color and width, line types become dash patterns, circles, arcs, wedges and Bézier curves are curves, filled and edged rectangles, wedges and polygons (polygon mode) are filled or stroked paths, and encoded polylines, scaling points, user units and rotation are read. Labels, symbol mode's symbols, raster images and hatching aren't drawn and are listed in the warnings (`crates/cad/src/hpgl/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - PICT pictures (`.pct`, `.pic`, and `.pict` as VectorCraft's own name) open and place, as [the help page](https://helpx.adobe.com/archive/illustrator/illustrator-cs5-5-troubleshooting.pdf) lists Macintosh PICT under both opening and placing: versions 1 and 2, with or without the file's 512 bytes of application data, read by the opcodes of Apple's [Opcodes in Pictures](https://dev.os9.ca/techpubs/mac/QuickDraw/QuickDraw-461.html). Lines, rectangles, rounded rectangles, ovals, arcs, polygons and regions become paths in their pen and pattern colors, text becomes point type in the font the picture names, bitmaps, pixel maps and QuickTime JPEG images become images, and the clip region clips what follows it; File › Place places the picture as one group clipped to its frame. Inverted shapes, other transfer modes and other QuickTime formats come back as warnings, and a picture cut short keeps what came before it (`crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs`). + - Computer Graphics Metafiles (`.cgm`) open and place, as [the supported file formats page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/supported-file-formats-in-illustrator.html) lists them under both opening and placing: the binary encoding of ISO/IEC 8632-3, as [WebCGM 2.1](https://www.w3.org/TR/webcgm21/) profiles it. The first picture's lines, shapes, arcs, figures, markers, text and cell arrays come in at the picture's metric scale (or 576 pt on its longer side), with their line, edge and fill attributes and the clip rectangle; File › Place places the picture as one group clipped to its frame. Hatch and pattern fills fill with their fill color, other primitives are skipped with a warning, and a picture cut short keeps what came before it (`crates/metafile/src/tests/cgm.rs`, `crates/engine/src/cmd/fileio/tests_cgm.rs`). - EMF and WMF type takes its size from the font's height, where a negative height is the em and a positive height is the character cell, and a font's average character width becomes Horizontal Scale against the face's own average width (OS/2 `xAvgCharWidth`) when the face gives one, as [LOGFONT](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-logfontw) and [MS-EMF 2.2.13](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-emf/1cd7cb7a-1a7c-48d2-b4a4-c218f9d12100) describe the two fields. VectorCraft's own rules are that the cell is the face's `usWinAscent` plus `usWinDescent` at a variable font's instance (its ascent plus descent without an OS/2 table), that a negative width is read as its absolute value, and that the width is ignored when the height is 0 (`a_font_width_becomes_horizontal_scale`, `a_positive_font_height_is_the_character_cell`, `a_font_the_system_lacks_is_measured_in_the_face_that_draws_it`, `wmf_font_width_becomes_horizontal_scale`). - EMF and WMF files are read by the shared `craft-metafile` reader and open, place and paste as editable paths, clipping groups, images and point type: an EMF drawn with EMF+ records (on their own, or beside plain records) is read from them instead of opening empty, and hatched and pattern brushes fill with their average color (`crates/metafile/src/tests/import.rs`). - EMF, WMF and EMF+ text keeps the character advances the file gives (ExtTextOut's `lpDx`, DrawDriverString positions) as tracking, with pair kerning off; on a single left to right line, an advance that tracking can't give (wider than its range, or a tab) starts a new point type object where the advance puts it, with an underline or strikethrough filled across the space between and on to the end of the last character's advance; type on more than one line is placed a line at a time, each line aligned by its own advances and split as a single line is (`text_is_spaced_by_its_advances`, `multiline_text_with_advances_aligns_each_line`, `wmf_text_is_spaced_by_its_advances`, `emf_plus_driver_strings_keep_their_positions`, `split_type_keeps_its_underline_and_right_to_left_order`).