PICT: Export As writes QuickDraw pictures

File › Export As and document.export {format: "pict"} write a version 2
QuickDraw picture (.pct) of an artboard, or one per artboard with Use
Artboards, with the extended header at up to 16 device units a point.

- Fills are PaintPoly polygons. A path of several figures is one
  polygon that runs back along the line between its figures, so the
  even-odd fill QuickDraw gives polygons keeps its holes. Non-zero fills
  are first resolved into figures that don't overlap, and art is cut to
  the picture's frame so every coordinate fits 16 bits. A fill too
  complex to resolve is written as it is, with a warning.
- Strokes are written as their filled outlines (line_outline, with
  dashes, caps, joins and miter limit).
- Images are DirectBitsRect pixel maps in tiles of at most 1,024
  pixels, rows packed with PackBits, composited over white. Mirrored and
  quarter-turned images keep their placement, and an image reaching far
  past the frame keeps its columns in place.
- Clipping masks, gradients, patterns and transparency are written as
  WMF writes them, with the same warnings. Artboards over 32,767 points
  on a side are refused.

The writer follows the opcode tables of Inside Macintosh: Imaging With
QuickDraw, and the tests read every picture back through the PICT
reader.
This commit is contained in:
dotCooCoo committed 2026-12-05 05:52:10 -08:00
1 parent 9bdfcf7347
commit ca2c567f74
22 files changed
+1104 -48

No files matched your search

Generated
+1
View File
@@ -9008,6 +9008,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom 0.25.1",
"vectorcraft-pathops 0.25.1",
"vectorcraft-text",
]
@@ -572,6 +572,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def
| "dxf"
| "emf"
| "wmf"
| "pict"
| "hpgl"
| "ai"
)
+3 -3
View File
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Serialize Document",
[],
None,
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)",
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|pict|hpgl|tiff|bmp|tga|psd|cmx (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)",
has_doc,
export::serialize
),
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Document",
[],
None,
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), embedIcc?: true (webp: the sRGB profile in an ICCP chunk), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, units, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chos Line truncated
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|pict|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), embedIcc?: true (webp: the sRGB profile in an ICCP chunk), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, units, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …pict writes a QuickDraw version 2 picture (.pct) of the artboard as emf and wmf do (up to 16 device units a point; at most 32,767 points on a side; fills as polygons, strokes as their filled outlines and images over white; what it leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alik Line truncated
has_doc,
export::export
),
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Selection…",
["File"],
None,
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|cmx|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})",
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|pict|hpgl|cmx|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})",
has_selection,
export::export_selection
),
+4 -2
View File
@@ -1073,7 +1073,7 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
}
// Formats that draw type: missing fonts come out in the fallback font (PDF and SVG say so
// themselves: SVG only when it outlines or embeds fonts).
if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl" | "cmx"))
if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "pict" | "hpgl" | "cmx"))
&& let Some(w) = crate::cmd::fonts::substitution_warning(doc)
{
enc.warnings.push(w);
@@ -1114,7 +1114,8 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
let doc = &*doc.without_edit_modes();
let n = doc.artboards.len();
// SVG reads its own `useArtboards` (an SVG option).
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None };
let use_artboards =
if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "pict" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None };
// `rect`: that area of the page, as if it were the only artboard (the document is not changed).
if let Some(rect) = page_rect(f, p)? {
let mut q = super::export::without_artboards(p);
@@ -1159,6 +1160,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
"eps" => return super::eps::encode(doc, p),
"emf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Emf),
"wmf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Wmf),
"pict" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Pict),
"hpgl" => return super::hpgl::encode(doc, p, use_artboards),
"cmx" => return super::cmx::encode(doc, f, p, use_artboards),
"ai" => return super::save::encode_ai(C, f, doc, p),
+12 -2
View File
@@ -575,8 +575,18 @@ pub const FORMATS: &[Format] = &[
// `.cmx` exchange files with 32-bit coordinates, read and written by `craft-cdr`: a page for
// each chosen artboard, with the art's fills and strokes in their colors.
Format { id: "cmx", label: "CMX", extensions: &["cmx"], mime: "image/x-cmx", read: true, write: true, raster: false, options: cmx::OPTIONS },
// QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images.
reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false),
// QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images,
// and written by `vectorcraft_metafile::export` as version 2 pictures (`.pct`).
Format {
id: "pict",
label: "PICT",
extensions: &["pct", "pic", "pict"],
mime: "image/x-pict",
read: true,
write: true,
raster: false,
options: metafile::OPTIONS,
},
// 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),
+3 -3
View File
@@ -2,7 +2,7 @@
//! `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) are written (`format: pict`) and open and place the same way.
use serde_json::Value;
use vectorcraft_doc::Document;
@@ -13,7 +13,7 @@ use super::{ArtboardPick, Encoded, FormatOption};
const C: &str = "document.export";
/// The options `document.formats` lists for EMF and WMF.
/// The options `document.formats` lists for EMF, WMF and PICT.
pub(super) const OPTIONS: &[FormatOption] = &[super::ARTBOARD, super::ARTBOARDS, super::RANGE, super::USE_ARTBOARDS];
/// Encode `doc` as `kind`: the chosen artboard (default the first), or with `use_artboards` one
@@ -45,7 +45,7 @@ pub(super) fn encode_flattening(
.iter()
.map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))))
.collect::<Result<Vec<_>>>()?;
vectorcraft_metafile::check_regions(&rects).map_err(|e| bad(C, e))?;
vectorcraft_metafile::check_regions_for(&rects, kind).map_err(|e| bad(C, e))?;
// Raster effects (shadows, glows, blurs) as images, as PDF export does.
let flat = flatten(doc);
let src = flat.as_ref().unwrap_or(doc);
+1 -1
View File
@@ -196,7 +196,7 @@ pub(super) fn name_without_device(name: &str) -> String {
pub(crate) const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"];
/// The writable formats a format row can't name.
pub(crate) const UNWRITTEN_FORMATS: [&str; 7] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx"];
pub(crate) const UNWRITTEN_FORMATS: [&str; 8] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx", "pict"];
/// One format row: what to write, at which size, with which suffix, into which sub-folder.
struct Row {
+4 -2
View File
@@ -533,7 +533,8 @@ fn export_extensions_name_every_writable_format() {
"plt",
"tga",
"psd",
"cmx"
"cmx",
"pct"
]
);
for e in exts {
@@ -570,7 +571,8 @@ fn formats_query_lists_readers_writers_and_options() {
"hpgl",
"tga",
"psd",
"cmx"
"cmx",
"pict"
]
);
assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string()));
+3 -3
View File
@@ -326,9 +326,9 @@ fn dwg_and_pagemaker_say_what_to_use_instead() {
let e = s.execute("document.export", &p).unwrap_err().to_string();
assert!(e.contains("DWG files open but can't be written") && e.contains("export DXF instead"), "{p}: {e}");
}
// PICT opens; it isn't written.
let e = s.execute("document.export", &json!({"format": "pict"})).unwrap_err().to_string();
assert!(e.contains("PICT files can be opened but not written"), "{e}");
// PCX opens; it isn't written.
let e = s.execute("document.export", &json!({"format": "pcx"})).unwrap_err().to_string();
assert!(e.contains("PCX files can be opened but not written"), "{e}");
let e = s
.execute("document.open", &json!({"name": "old.pct", "dataBase64": vectorcraft_format::base64_encode(&[0u8; 600])}))
.unwrap_err()
+44 -6
View File
@@ -1,6 +1,6 @@
//! PICT pictures 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 pictures, or a PICT export, refused with a message.
//! one group clipped to the picture's frame, `document.export` of one artboard or each, the dialogs'
//! filters and the format list, and files that aren't pictures refused with a message.
use serde_json::json;
use vectorcraft_doc::NodeKind;
@@ -83,8 +83,47 @@ fn files_that_are_not_pictures_are_refused() {
let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
png.extend(&picture()[8..]);
assert!(detect("x.png", &png).is_none_or(|f| f.id != "pict"));
let e = s.execute("document.export", &json!({"format": "pict"})).expect_err("refused").to_string();
assert!(e.contains("PICT files can be opened but not written"), "{e}");
}
fn data(r: &serde_json::Value) -> Vec<u8> {
vectorcraft_format::base64_decode(r["dataBase64"].as_str().expect("dataBase64")).unwrap()
}
#[test]
fn document_export_writes_a_picture_that_opens_again() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap();
let second = s.doc().unwrap().doc.artboards[1].rect.x0;
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("shape.rectangle", &json!({"x": second + 50.0, "y": 5, "width": 20, "height": 10})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap();
let r = s.execute("document.export", &json!({"format": "pict"})).unwrap();
assert_eq!((r["format"].as_str(), &r["warnings"]), (Some("pict"), &json!([])), "{r}");
let bytes = data(&r);
assert_eq!(detect("x.bin", &bytes).map(|f| f.id), Some("pict"));
assert_eq!(writable_format(None, Some("x/logo.pct")).unwrap().id, "pict");
// The first artboard: its red rectangle, in place.
let mut back = Session::new();
back.execute("document.open", &json!({"name": "logo.pct", "dataBase64": b64(&bytes)})).unwrap();
let doc = &back.doc().unwrap().doc;
assert_eq!(doc.artboards[0].rect.size(), (100.0, 100.0).into());
let mut paths = vec![];
doc.walk(|n| {
if let NodeKind::Path { .. } = n.kind {
paths.push(n.clone());
}
});
assert_eq!(paths.len(), 1);
let b = paths[0].geometric_bounds().unwrap();
let want = vectorcraft_geom::Rect::new(10.0, 20.0, 40.0, 60.0);
assert!([b.x0 - want.x0, b.y0 - want.y0, b.x1 - want.x1, b.y1 - want.y1].iter().all(|d| d.abs() < 0.07), "{b:?}");
assert_eq!(paths[0].appearance.fill().and_then(|f| f.paint.color()).map(|c| c.to_rgba8(1.0)), Some([255, 0, 0, 255]));
// Use Artboards: one picture each.
let r = s.execute("document.export", &json!({"format": "pict", "useArtboards": true})).unwrap();
let files = r["files"].as_array().unwrap();
assert_eq!(files.len(), 2);
assert!(files[1]["name"].as_str().unwrap().ends_with("-Artboard-2.pct"), "{files:?}");
}
#[test]
@@ -98,7 +137,6 @@ fn the_dialogs_and_the_format_list_name_pict() {
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"] == "pict").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["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(true), Some(false)), "{f}");
assert_eq!(f["mime"], "image/x-pict");
assert!(writable_format(None, Some("x/logo.pct")).is_err());
}
+2 -1
View File
@@ -81,7 +81,8 @@ fn export_tool_lists_engine_formats_and_options() {
"hpgl",
"tga",
"psd",
"cmx"
"cmx",
"pict"
])
);
for k in ["artboard", "range", "options"] {
+1 -1
View File
@@ -400,7 +400,7 @@ pub fn tool_definitions() -> Vec<Value> {
tool(
"export",
"Export",
"Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, emf, wmf, hpgl pen moves for plotters and cutters, cmx exchange files of fills and strokes), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.",
"Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, emf, wmf, hpgl pen moves for plotters and cutters, cmx exchange files of fills and strokes, pict QuickDraw pictures as .pct), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.",
obj(
json!({
"format": {"type": "string", "enum": FORMATS.iter().filter(|f| f.write).map(|f| f.id).collect::<Vec<_>>(), "description": "Default: from the path's extension"},
+2 -1
View File
@@ -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, WMF and QuickDraw PICT export and EMF, EMF+, WMF and PICT import through craft-metafile"
[lints]
workspace = true
@@ -13,6 +13,7 @@ vectorcraft-geom = { workspace = true }
vectorcraft-color = { workspace = true }
vectorcraft-doc = { workspace = true }
vectorcraft-effects = { workspace = true }
vectorcraft-pathops = { workspace = true }
vectorcraft-brush = { workspace = true }
vectorcraft-text = { workspace = true }
craft-metafile = { workspace = true, features = ["write"] }
+24 -6
View File
@@ -1,4 +1,5 @@
//! Translate VectorCraft's drawing operations to the shared metafile writers.
//! Translate VectorCraft's drawing operations to the shared metafile writers (EMF, WMF) and to
//! the PICT writer.
use craft_metafile::{
Cap, Join,
write::{self, Dash, Op, Pen},
@@ -9,11 +10,30 @@ use vectorcraft_geom::{FillRule, Rect};
use crate::{Kind, scene};
pub(crate) fn write(ops: Vec<scene::Op>, region: Rect, kind: Kind, title: &str, warnings: &mut Vec<String>) -> Result<Vec<u8>, String> {
let ops: Vec<_> = ops.into_iter().map(|op| convert(op, kind)).collect();
let invalid = || "the export region is empty".to_string();
let mut note = |lost: bool, warning: &str| {
if lost && !warnings.iter().any(|w| w == warning) {
warnings.push(warning.to_string());
}
};
match kind {
Kind::Emf => write::emf(&ops, region, "VectorCraft", title).ok_or_else(invalid),
Kind::Pict => {
crate::pict::check_region(region)?;
let out = crate::pict::write(&ops, region);
note(out.translucent_images, "PICT has no transparency: images are written over white");
note(out.turned_images, "PICT turns images only by quarter turns: other turns and skews are written upright, filling their bounds");
note(out.split_fills, "fills with more than 16,381 points are written as several polygons, which may fill their holes");
note(out.thinned_fills, "outlines with more than 16,379 points are written with fewer points");
note(out.unresolved_fills, "non-zero fills too complex to resolve are written even-odd, which may leave overlaps unfilled");
note(out.uncut_fills, "fills too complex to cut to the artboard that reach far outside it may be written distorted");
Ok(out.bytes)
}
Kind::Emf => {
let ops: Vec<_> = ops.into_iter().map(|op| convert(op, kind)).collect();
write::emf(&ops, region, "VectorCraft", title).ok_or_else(invalid)
}
Kind::Wmf => {
let ops: Vec<_> = ops.into_iter().map(|op| convert(op, kind)).collect();
let out = write::wmf(&ops, region).ok_or_else(invalid)?;
for (lost, warning) in [
(out.translucent_images, "WMF has no transparency: images are written over white"),
@@ -21,9 +41,7 @@ pub(crate) fn write(ops: Vec<scene::Op>, region: Rect, kind: Kind, title: &str,
(out.clips_ignored, "clipping masks are not applied: the art they clip is written whole"),
(out.oversized_images, "WMF images with a side over 32,767 pixels were left out"),
] {
if lost && !warnings.iter().any(|w| w == warning) {
warnings.push(warning.to_string());
}
note(lost, warning);
}
Ok(out.bytes)
}
+5 -5
View File
@@ -1088,7 +1088,11 @@ fn retracked(t: &TextObject, laid: &vectorcraft_text::TextLayout, dx: &[f64]) ->
/// Read an EMF or WMF file.
pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
let kind = crate::sniff(bytes).ok_or("not an EMF or WMF file")?;
let wire_kind = craft_metafile::sniff(bytes).ok_or("not an EMF or WMF file")?;
let kind = match wire_kind {
craft_metafile::Kind::Emf => Kind::Emf,
craft_metafile::Kind::Wmf => Kind::Wmf,
};
let pic = craft_metafile::parse(bytes).map_err(|e| match e {
craft_metafile::Error::NotMetafile | craft_metafile::Error::NotPict => "not an EMF or WMF file".to_string(),
craft_metafile::Error::BadHeader => format!("the {} header is damaged", kind.id().to_uppercase()),
@@ -1096,10 +1100,6 @@ pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
})?;
let k = unit(bytes);
let mut m = Mapper::new(f64::from(pic.width), f64::from(pic.height), k);
let wire_kind = match kind {
Kind::Emf => craft_metafile::Kind::Emf,
Kind::Wmf => craft_metafile::Kind::Wmf,
};
if craft_metafile::ends_early(bytes, wire_kind) {
m.warn(ENDS_EARLY);
}
+24 -5
View File
@@ -1,4 +1,5 @@
//! Windows metafiles: hand-written EMF and WMF writers and readers.
//! Windows metafiles: hand-written EMF and WMF writers and readers, and a QuickDraw picture (PICT)
//! writer and reader.
//!
//! [`export`] writes the visible art over one region of a document (an artboard) as a metafile,
//! and [`export_regions`] one metafile per region:
@@ -13,6 +14,9 @@
//! placeable header that gives the size; WMF has no clipping paths, transparency, dashes on wide
//! lines or gradients, so clipped art is written whole, images over white, dashes as separate
//! lines and gradients and patterns as one colour (each loss comes back as a warning).
//! - **PICT**: the art WMF gets, as a QuickDraw version 2 picture in device units of up to 16 to a
//! point: fills are polygons cut to the picture's frame, strokes their filled outlines, and images
//! 24-bit pixel maps over white (see `pict`).
//!
//! [`import`] reads either format (an EMF with its EMF+ records too, through `craft_metafile`)
//! into a document of one artboard (the picture's frame) and one layer: paths with fills and
@@ -33,26 +37,31 @@ mod bytes;
mod dib;
mod encode;
mod import;
mod pict;
mod scene;
use vectorcraft_doc::Document;
use vectorcraft_geom::Rect;
/// A Windows metafile format.
/// A metafile format: the Windows metafiles, and QuickDraw pictures, which [`export`] writes and
/// [`is_pict`] and [`import_pict`] read ([`sniff`] and [`import`] read only the Windows formats).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
/// Enhanced Metafile (32-bit coordinates, Bézier curves, paths and clipping).
Emf,
/// Windows Metafile with a placeable header (16-bit coordinates, polygons).
Wmf,
/// QuickDraw picture, version 2, in a PICT file (16-bit coordinates, polygons).
Pict,
}
impl Kind {
/// The format id (`emf`, `wmf`).
/// The format id (`emf`, `wmf`, `pict`).
pub fn id(self) -> &'static str {
match self {
Self::Emf => "emf",
Self::Wmf => "wmf",
Self::Pict => "pict",
}
}
}
@@ -93,11 +102,21 @@ pub fn check_regions(regions: &[Rect]) -> Result<(), String> {
Ok(())
}
/// [`check_regions`] for `kind`: a PICT picture's frame is also at most 32,767 points on a side.
pub fn check_regions_for(regions: &[Rect], kind: Kind) -> Result<(), String> {
check_regions(regions)?;
if kind == Kind::Pict {
regions.iter().try_for_each(|r| pict::check_region(r.abs()))?;
}
Ok(())
}
/// Write the visible art of `doc` over each of `regions` as `kind`, one metafile per region in the
/// same order, each as [`export`] writes it over that region. The live effects are applied once
/// for all of them. When any region is empty, nothing is written and the result is an error.
/// for all of them. When any region is empty (or, for PICT, over 32,767 points on a side),
/// nothing is written and the result is an error.
pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result<Vec<Output>, String> {
check_regions(regions)?;
check_regions_for(regions, kind)?;
let regions: Vec<Rect> = regions.iter().map(|r| r.abs()).collect();
if regions.is_empty() {
return Ok(Vec::new());
+537
View File
@@ -0,0 +1,537 @@
//! The PICT writer: a QuickDraw version 2 picture with the extended header, behind a PICT file's
//! 512 bytes of application data, by the opcodes and data layouts of Apple's *Imaging With
//! QuickDraw*, appendix A.
//!
//! The picture frame is the region in points; the drawing is in device units of up to 16 to a
//! point (the header's resolution, at most 1,152 dpi), as many as keep the frame within 16-bit
//! coordinates. QuickDraw has no curves, Bézier paths or pens with joins, so:
//!
//! - fills are polygons (`PaintPoly`) in the fill's color, filled even-odd as QuickDraw fills
//! polygons: a path of several figures is one polygon that runs back along the line between its
//! figures, and a non-zero fill is first resolved into figures that do not overlap. Art is cut
//! to the frame first, which keeps every coordinate within 16 bits.
//! - strokes are their outlines (dashes cut first), filled the same way.
//! - images are `DirectBitsRect` records of 24-bit pixels in tiles of at most 1,024 pixels on a
//! side, packed by rows with PackBits; transparency is composited over white, and images that
//! are turned or skewed by other than a quarter turn are written upright, filling their bounds.
use std::sync::Arc;
use craft_metafile::write::Image;
use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape};
use vectorcraft_color::Paint;
use vectorcraft_doc::StrokeLayer;
use vectorcraft_geom::{FillRule, PathData};
use crate::scene::{Op, Pen};
/// The application data before the picture in a PICT file.
const FILE_HEADER: usize = 512;
/// The largest 16-bit coordinate.
const MAX_I16: f64 = 32767.0;
/// Most device units a point (16, 1,152 dpi).
const MAX_SCALE: f64 = 16.0;
/// Most points a polygon holds: its size, in bytes with its 10-byte head, is a signed 16-bit count.
const MAX_POLY_POINTS: usize = (i16::MAX as usize - 10) / 4;
/// Curves are flattened to within this many device units.
const FLATNESS: f64 = 0.25;
/// Times the flatness is raised (four-fold each time) for a fill with too many points before it
/// is split into several polygons.
const COARSER: u32 = 3;
/// Most pixels along a side of one image record.
const TILE: usize = 1024;
/// Opacity at or above this is written as opaque.
const OPAQUE: f32 = 0.998;
// Opcodes (*Imaging With QuickDraw*, table A-2).
const CLIP: u16 = 0x0001;
const PN_MODE: u16 = 0x0008;
const PN_PAT: u16 = 0x0009;
const VERSION: u16 = 0x0011;
const RGB_FG_COL: u16 = 0x001A;
const PAINT_POLY: u16 = 0x0071;
const DIRECT_BITS_RECT: u16 = 0x009A;
const OP_END_PIC: u16 = 0x00FF;
const HEADER_OP: u16 = 0x0C00;
/// The `patCopy` transfer mode.
const PAT_COPY: u16 = 8;
/// A written picture and what it could not hold.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct Pict {
pub bytes: Vec<u8>,
/// Images with transparency were written over white.
pub translucent_images: bool,
/// Turned or skewed images were written upright, filling their bounds.
pub turned_images: bool,
/// A fill with more points than one polygon holds was written as several polygons, so its
/// holes may be filled.
pub split_fills: bool,
/// A figure with more points than one polygon holds was written with fewer.
pub thinned_fills: bool,
/// A non-zero fill too complex to resolve into figures that don't overlap was written even-odd.
pub unresolved_fills: bool,
/// A fill too complex to cut to the frame was written with its points past 16 bits moved in.
pub uncut_fills: bool,
}
/// The device units a point for a picture `w` × `h` points: the most, up to [`MAX_SCALE`], that
/// keep its size within 16 bits.
fn units_per_point(w: f64, h: f64) -> f64 {
let side = w.max(h);
if side > 0.0 { (MAX_I16 / side).floor().clamp(1.0, MAX_SCALE) } else { MAX_SCALE }
}
/// The error for a region the picture frame can't hold: a side over 32,767 points.
pub(crate) fn check_region(region: Rect) -> Result<(), String> {
if region.width().round() > MAX_I16 || region.height().round() > MAX_I16 {
return Err("PICT pictures are at most 32,767 points on a side".into());
}
Ok(())
}
/// Big-endian bytes being written.
struct Out(Vec<u8>);
impl Out {
fn u8(&mut self, v: u8) {
self.0.push(v);
}
fn u16(&mut self, v: u16) {
self.0.extend_from_slice(&v.to_be_bytes());
}
fn i16(&mut self, v: i16) {
self.0.extend_from_slice(&v.to_be_bytes());
}
fn u32(&mut self, v: u32) {
self.0.extend_from_slice(&v.to_be_bytes());
}
fn bytes(&mut self, b: &[u8]) {
self.0.extend_from_slice(b);
}
/// A rectangle as QuickDraw stores one: top, left, bottom, right.
fn rect(&mut self, [left, top, right, bottom]: [i16; 4]) {
self.i16(top);
self.i16(left);
self.i16(bottom);
self.i16(right);
}
/// A zero up to the next even length: every version 2 opcode starts on a word.
fn align(&mut self) {
if self.0.len() % 2 == 1 {
self.0.push(0);
}
}
}
/// `v` rounded into 16 bits.
fn i16_of(v: f64) -> i16 {
v.round().clamp(-MAX_I16, MAX_I16) as i16
}
struct Writer {
out: Out,
/// Document space to device units.
to_dev: Affine,
/// Device units a point.
k: f64,
/// The frame in document space, a little larger: art is cut to it.
cut: Rect,
/// The frame in device units.
frame: Rect,
fg: Option<[u8; 3]>,
lost: Pict,
}
/// Write `ops` (no clips: [`crate::scene::Scene`] gives none for this format) as a PICT file of
/// `region` (corners in order, finite, with an area, within [`check_region`]).
pub(crate) fn write(ops: &[Op], region: Rect) -> Pict {
let k = units_per_point(region.width(), region.height());
let size = |v: f64| (v.round()).clamp(1.0, MAX_I16) as i16;
let (w, h) = (size(region.width()), size(region.height()));
let dev = |v: f64| (v * k).round().clamp(1.0, MAX_I16) as i16;
let (dw, dh) = (dev(region.width()), dev(region.height()));
let mut wr = Writer {
out: Out(vec![0; FILE_HEADER]),
to_dev: Affine::scale(k) * Affine::translate(-region.origin().to_vec2()),
k,
cut: region.inflate(1.0, 1.0),
frame: Rect::new(0.0, 0.0, f64::from(dw), f64::from(dh)),
fg: None,
lost: Pict::default(),
};
let o = &mut wr.out;
// picSize (its low 16 bits, set at the end) and the frame at 72 dpi.
o.u16(0);
o.rect([0, 0, w, h]);
o.u16(VERSION);
o.u16(0x02FF);
// The extended version 2 header: the device resolution and the frame in device units.
let dpi = ((72.0 * k) as u32) << 16;
o.u16(HEADER_OP);
o.i16(-2);
o.u16(0);
o.u32(dpi);
o.u32(dpi);
o.rect([0, 0, dw, dh]);
o.u32(0);
o.u16(CLIP);
o.u16(10);
o.rect([0, 0, dw, dh]);
// Shapes are painted with a solid pen in the foreground color.
o.u16(PN_MODE);
o.u16(PAT_COPY);
o.u16(PN_PAT);
o.bytes(&[0xFF; 8]);
for op in ops {
match op {
Op::Fill { path, rule, rgb, .. } => wr.fill(path, *rule, *rgb),
Op::Stroke { path, pen } => wr.stroke(path, pen),
Op::Image { image, xf, opacity } => wr.image(image, *xf, *opacity),
Op::Clip { .. } | Op::Unclip => {}
}
}
wr.out.align();
wr.out.u16(OP_END_PIC);
let mut bytes = wr.out.0;
let len = (bytes.len() - FILE_HEADER) as u16;
bytes[FILE_HEADER..FILE_HEADER + 2].copy_from_slice(&len.to_be_bytes());
Pict { bytes, ..wr.lost }
}
impl Writer {
fn color(&mut self, rgb: [u8; 3]) {
if self.fg != Some(rgb) {
self.out.u16(RGB_FG_COL);
for c in rgb {
self.out.u16(u16::from(c) * 257);
}
self.fg = Some(rgb);
}
}
/// `path` filled by `rule`, as polygons QuickDraw fills even-odd: cut to the frame (which also
/// resolves a non-zero fill into figures that don't overlap) unless it is an even-odd fill
/// inside the frame already.
fn fill(&mut self, path: &BezPath, rule: FillRule, rgb: [u8; 3]) {
let b = path.bounding_box();
let c = self.cut;
if ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) || b.x0 >= c.x1 || c.x0 >= b.x1 || b.y0 >= c.y1 || c.y0 >= b.y1 {
return;
}
let inside = self.cut.contains(b.origin()) && self.cut.contains(Point::new(b.x1, b.y1));
let clean = if rule == FillRule::EvenOdd && inside {
path.clone()
} else {
let cut = PathData::from_bezpath(&self.cut.to_path(0.1));
match vectorcraft_pathops::try_boolean(
&PathData::from_bezpath(path),
rule,
&cut,
FillRule::NonZero,
vectorcraft_pathops::BoolOp::Intersect,
vectorcraft_pathops::DEFAULT_PRECISION,
) {
Ok(p) => p.to_bezpath(),
// Too complex to resolve: written as it is, filled even-odd, its coordinates kept
// within 16 bits.
Err(_) => {
self.lost.unresolved_fills |= rule == FillRule::NonZero;
let d = self.to_dev.transform_rect_bbox(b);
self.lost.uncut_fills |= [d.x0, d.y0, d.x1, d.y1].iter().any(|v| v.abs() > MAX_I16);
path.clone()
}
}
};
self.polygons(&clean, rgb);
}
/// A stroke's outline (`vectorcraft_effects::stroke::line_outline`, with its dashes, caps,
/// joins and miter limit), filled non-zero in its color as [`Writer::fill`] fills. A stroke
/// thinner than a device unit is written one unit wide.
fn stroke(&mut self, path: &BezPath, pen: &Pen) {
if !(pen.width.is_finite() && pen.width > 0.0) {
return;
}
let width = pen.width.max(1.0 / self.k);
let mut st = StrokeLayer::new(Paint::None, width);
st.cap = pen.cap;
st.join = pen.join;
st.miter_limit = pen.miter;
st.dash = pen.dash.clone();
let outline = vectorcraft_effects::stroke::line_outline(path, &st, width, FLATNESS / self.k);
self.fill(&outline, FillRule::NonZero, pen.rgb);
}
/// The figures of `path` (document space) in device units, flattened to within `flatness`
/// device units, each without repeated points and with three or more.
fn figures(&self, path: &BezPath, flatness: f64) -> Vec<Vec<[i16; 2]>> {
let mut figs: Vec<Vec<[i16; 2]>> = vec![];
let mut cur: Vec<[i16; 2]> = vec![];
let mut done = |cur: &mut Vec<[i16; 2]>| {
if cur.len() > 1 && cur.first() == cur.last() {
cur.pop();
}
if cur.len() > 2 {
figs.push(std::mem::take(cur));
}
cur.clear();
};
let dev = self.to_dev * path.clone();
vectorcraft_geom::flatten(dev.iter(), flatness, |el| match el {
PathEl::MoveTo(p) => {
done(&mut cur);
cur.push([i16_of(p.x), i16_of(p.y)]);
}
PathEl::LineTo(p) => {
let q = [i16_of(p.x), i16_of(p.y)];
if cur.last() != Some(&q) {
cur.push(q);
}
}
PathEl::ClosePath => done(&mut cur),
_ => {}
});
done(&mut cur);
figs
}
/// `path` painted as polygons. All its figures go into one polygon, which returns along the
/// lines between them: each such line is crossed twice and changes nothing in an even-odd
/// fill. A path with more points than a polygon holds is flattened more coarsely, and past
/// that split into several polygons.
fn polygons(&mut self, path: &BezPath, rgb: [u8; 3]) {
let count = |figs: &[Vec<[i16; 2]>]| figs.iter().map(|f| f.len() + 2).sum::<usize>();
let mut flatness = FLATNESS;
let mut figs = self.figures(path, flatness);
for _ in 0..COARSER {
if count(&figs) <= MAX_POLY_POINTS {
break;
}
flatness *= 4.0;
figs = self.figures(path, flatness);
}
if figs.is_empty() {
return;
}
self.color(rgb);
let mut group: Vec<&[[i16; 2]]> = vec![];
let mut points = 0;
let thinned: Vec<Vec<[i16; 2]>> = figs
.iter()
.map(|fig| {
// A figure no polygon holds keeps evenly spaced points, as many as one holds.
let n = fig.len();
if n + 2 <= MAX_POLY_POINTS {
return fig.clone();
}
self.lost.thinned_fills = true;
let keep = MAX_POLY_POINTS - 2;
(0..keep).map(|i| fig[i * n / keep]).collect()
})
.collect();
for fig in &thinned {
if !group.is_empty() && points + fig.len() + 2 > MAX_POLY_POINTS {
self.lost.split_fills = true;
self.poly(&group);
group.clear();
points = 0;
}
points += fig.len() + 2;
group.push(fig);
}
self.poly(&group);
}
/// One `PaintPoly` of `figs`: each figure back to its start, then the next; after the last,
/// back through the starts to the first.
fn poly(&mut self, figs: &[&[[i16; 2]]]) {
let mut pts: Vec<[i16; 2]> = Vec::with_capacity(figs.iter().map(|f| f.len() + 2).sum());
for f in figs {
pts.extend_from_slice(f);
pts.push(f[0]);
}
pts.extend(figs.iter().rev().skip(1).map(|f| f[0]));
let (mut l, mut t, mut r, mut b) = (i16::MAX, i16::MAX, i16::MIN, i16::MIN);
for p in &pts {
(l, t, r, b) = (l.min(p[0]), t.min(p[1]), r.max(p[0]), b.max(p[1]));
}
self.out.u16(PAINT_POLY);
self.out.u16((10 + 4 * pts.len()) as u16);
self.out.rect([l, t, r, b]);
for p in &pts {
self.out.i16(p[1]);
self.out.i16(p[0]);
}
}
/// An image placed by `xf`, over white. Mirrored and quarter-turned images keep their
/// placement; other turns and skews are written upright, filling their bounds.
fn image(&mut self, img: &Arc<Image>, xf: Affine, opacity: f32) {
let (w, h) = (img.width as usize, img.height as usize);
if w == 0 || h == 0 || opacity <= 0.0 || img.rgba.len() < w * h * 4 {
return;
}
let m = self.to_dev * xf;
let [a, b, c, d, e, f] = m.as_coeffs();
if ![a, b, c, d, e, f].iter().all(|v| v.is_finite()) {
return;
}
let tiny = |v: f64| v.abs() < 1e-9;
// Output pixel (x, y) shows source pixel `src(x, y)`, in an output `ow` × `oh`.
let swapped = tiny(a) && tiny(d) && !tiny(b) && !tiny(c);
let upright = tiny(b) && tiny(c) && !tiny(a) && !tiny(d);
if !(upright || swapped) {
self.lost.turned_images = true;
}
let (ow, oh) = if swapped { (h, w) } else { (w, h) };
let (flip_x, flip_y) = if swapped { (c < 0.0, b < 0.0) } else { (upright && a < 0.0, upright && d < 0.0) };
let src = |x: usize, y: usize| {
let (x, y) = (if flip_x { ow - 1 - x } else { x }, if flip_y { oh - 1 - y } else { y });
if swapped { (y, x) } else { (x, y) }
};
let dst = m.transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64));
// The device edges of output columns and rows, and the ones that reach into the frame.
let edge = |from: f64, to: f64, n: usize, i: usize| from + (to - from) * i as f64 / n as f64;
let span = |from: f64, to: f64, n: usize, lo: f64, hi: f64| {
let first = (0..n).find(|&i| edge(from, to, n, i + 1) > lo);
let last = (0..n).rev().find(|&i| edge(from, to, n, i) < hi);
match (first, last) {
(Some(f), Some(l)) if f <= l => Some((f, l + 1)),
_ => None,
}
};
let (Some((x0, x1)), Some((y0, y1))) =
(span(dst.x0, dst.x1, ow, self.frame.x0, self.frame.x1), span(dst.y0, dst.y1, oh, self.frame.y0, self.frame.y1))
else {
return;
};
let alpha = opacity.clamp(0.0, 1.0);
let mut translucent = false;
let mut pixel = |x: usize, y: usize| {
let (sx, sy) = src(x, y);
let i = (sy * w + sx) * 4;
let p = &img.rgba[i..i + 4];
let a = f32::from(p[3]) / 255.0 * alpha;
if a < OPAQUE {
translucent = true;
}
[0, 1, 2].map(|c| (f32::from(p[c]) * a + 255.0 * (1.0 - a)).round() as u8)
};
// Tiles of up to `TILE` columns (rows). The edges between the visible columns lie in the
// frame; an outer edge past 16 bits is moved in, so its column (row) is a tile of its own,
// one color however far it is stretched.
let tiles = |from: f64, to: f64, n: usize, first: usize, end: usize| {
let far = |i: usize| edge(from, to, n, i).abs() > MAX_I16;
let mut cuts = vec![];
let (mut i, mut stop) = (first, end);
if far(i) && i + 1 < stop {
cuts.push((i, i + 1));
i += 1;
}
let last = (far(stop) && i + 1 < stop).then(|| {
stop -= 1;
(stop, stop + 1)
});
while i < stop {
let next = (i + TILE).min(stop);
cuts.push((i, next));
i = next;
}
cuts.extend(last);
cuts
};
for (ty, ty1) in tiles(dst.y0, dst.y1, oh, y0, y1) {
for (tx, tx1) in tiles(dst.x0, dst.x1, ow, x0, x1) {
let rect = [
i16_of(edge(dst.x0, dst.x1, ow, tx)),
i16_of(edge(dst.y0, dst.y1, oh, ty)),
i16_of(edge(dst.x0, dst.x1, ow, tx1)),
i16_of(edge(dst.y0, dst.y1, oh, ty1)),
];
if rect[2] > rect[0] && rect[3] > rect[1] {
let rows: Vec<Vec<[u8; 3]>> = (ty..ty1).map(|y| (tx..tx1).map(|x| pixel(x, y)).collect()).collect();
self.bits(&rows, tx1 - tx, ty1 - ty, rect);
}
}
}
self.lost.translucent_images |= translucent;
}
/// One `DirectBitsRect` of `rows` (`tw` × `th` pixels) into `dst` (left, top, right, bottom),
/// 32-bit pixels: rows of a red, a green and a blue plane, each row packed with PackBits; a
/// pixel map narrower than two pixels has unpacked rows of `0RGB` pixels.
fn bits(&mut self, rows: &[Vec<[u8; 3]>], tw: usize, th: usize, dst: [i16; 4]) {
let row_bytes = 4 * tw;
let o = &mut self.out;
o.align();
o.u16(DIRECT_BITS_RECT);
o.u32(0xFF);
o.u16(row_bytes as u16 | 0x8000);
o.rect([0, 0, tw as i16, th as i16]);
// pmVersion, packType 4 (component planes), packSize, 72 dpi.
o.u16(0);
o.u16(4);
o.u32(0);
o.u32(72 << 16);
o.u32(72 << 16);
// RGBDirect, 32 bits a pixel, 3 components of 8 bits, no plane bytes, table or reserve.
o.u16(16);
o.u16(32);
o.u16(3);
o.u16(8);
o.u32(0);
o.u32(0);
o.u32(0);
o.rect([0, 0, tw as i16, th as i16]);
o.rect(dst);
// srcCopy.
o.u16(0);
let mut plane = Vec::with_capacity(3 * tw);
let mut packed = Vec::with_capacity(3 * tw + 3 * tw / 128 + 2);
for row in rows {
if row_bytes < 8 {
for p in row {
o.u8(0);
o.bytes(p);
}
continue;
}
plane.clear();
for c in 0..3 {
plane.extend(row.iter().map(|p| p[c]));
}
packed.clear();
packbits(&plane, &mut packed);
if row_bytes > 250 {
o.u16(packed.len() as u16);
} else {
o.u8(packed.len() as u8);
}
o.bytes(&packed);
}
o.align();
}
}
/// `src` packed with PackBits: runs of two to 128 equal bytes as a count byte `1 - n` and the
/// byte, other bytes in literal runs of up to 128 behind a count byte `n - 1`.
fn packbits(src: &[u8], out: &mut Vec<u8>) {
let run_at = |i: usize| src[i..].iter().take(128).take_while(|&&b| b == src[i]).count();
let mut i = 0;
while i < src.len() {
let run = run_at(i);
if run >= 2 {
out.push((1 - run as i16) as u8);
out.push(src[i]);
i += run;
continue;
}
let start = i;
while i < src.len() && i - start < 128 && (i == start || run_at(i) < 3) {
i += 1;
}
out.push((i - start - 1) as u8);
out.extend_from_slice(&src[start..i]);
}
}
+1
View File
@@ -13,6 +13,7 @@ use crate::*;
mod import;
mod pict;
mod pict_export;
/// Add `n` (with a fresh id) on top of `d`'s first layer.
pub(crate) fn add(d: &mut Document, mut n: Node) {
+394
View File
@@ -0,0 +1,394 @@
//! PICT output read back through `craft_metafile`'s QuickDraw reader: the frame and resolution,
//! fills and their fill rules, strokes, images and their placement, and what the format leaves
//! out.
use craft_metafile::{Item, Seg};
use vectorcraft_geom::{BezPath, FillRule, Shape};
use super::*;
fn pict(d: &Document) -> Output {
export(d, d.artboards[0].rect, Kind::Pict).unwrap()
}
fn read(out: &Output) -> craft_metafile::Picture {
let pic = craft_metafile::parse_pict(&out.bytes).unwrap();
assert!(!pic.truncated && pic.skipped_records == 0 && pic.dropped_images == 0, "{pic:?}");
pic
}
fn bez(segs: &[Seg]) -> BezPath {
let mut bp = BezPath::new();
for s in segs {
match *s {
Seg::Move(x, y) => bp.move_to((f64::from(x), f64::from(y))),
Seg::Line(x, y) => bp.line_to((f64::from(x), f64::from(y))),
Seg::Cubic(a, b, c, d, e, f) => bp.curve_to((f64::from(a), f64::from(b)), (f64::from(c), f64::from(d)), (f64::from(e), f64::from(f))),
Seg::Close => bp.close_path(),
}
}
bp
}
/// The filled paths of `pic`: their outline and their color.
fn fills(pic: &craft_metafile::Picture) -> Vec<(BezPath, [u8; 4])> {
pic.items
.iter()
.filter_map(|i| match i {
Item::Path { segs, fill: Some(c), stroke: None, .. } => Some((bez(segs), *c)),
_ => None,
})
.collect()
}
/// Is `p` painted by one of `pic`'s fills, each filled even-odd as QuickDraw fills polygons?
fn painted(pic: &craft_metafile::Picture, p: (f64, f64)) -> bool {
fills(pic).iter().any(|(bp, _)| bp.winding(p.into()) % 2 != 0)
}
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(|d| d.abs() <= tol)
}
fn compound(parts: &[BezPath], rule: FillRule) -> Node {
let mut bp = BezPath::new();
parts.iter().for_each(|p| bp.extend(p.iter()));
let mut n = path(PathData::from_bezpath(&bp), red(), Paint::None, 0.0);
if let NodeKind::Path { rule: r, .. } = &mut n.kind {
*r = rule;
}
n
}
fn square(x0: f64, y0: f64, x1: f64, y1: f64, clockwise: bool) -> BezPath {
let mut pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)];
if !clockwise {
pts.reverse();
}
let mut bp = BezPath::new();
bp.move_to(pts[0]);
pts[1..].iter().for_each(|p| bp.line_to(*p));
bp.close_path();
bp
}
/// Walk the writer's version 2 opcodes and collect their PaintPoly data.
fn paint_polys(bytes: &[u8]) -> Vec<&[u8]> {
let word = |at: usize| u16::from_be_bytes(bytes[at..at + 2].try_into().unwrap());
let mut at = 522; // Application data, picSize, and frame.
let mut polys = vec![];
loop {
at += at % 2;
let opcode = word(at);
at += 2;
let len = match opcode {
0x0011 => {
assert_eq!(word(at), 0x02FF);
2
}
0x0C00 => 24,
0x0001 => usize::from(word(at)),
0x0008 => 2,
0x0009 => 8,
0x001A => 6,
0x0071 => {
let len = usize::from(word(at));
polys.push(&bytes[at..at + len]);
len
}
0x009A => {
let row_bytes = usize::from(word(at + 4) & 0x3FFF);
let rows = usize::from(word(at + 10) - word(at + 6));
let mut end = at + 68; // PixMap, source and destination rectangles, mode.
for _ in 0..rows {
if row_bytes < 8 {
end += row_bytes;
} else if row_bytes > 250 {
end += 2 + usize::from(word(end));
} else {
end += 1 + usize::from(bytes[end]);
}
}
end - at
}
0x00FF => {
assert_eq!(at, bytes.len());
return polys;
}
_ => panic!("unexpected PICT opcode {opcode:#06X}"),
};
at += len;
}
}
#[test]
fn pict_frame_is_the_region_in_points_and_art_lands_within_a_sixteenth_of_a_point() {
let r = Rect::new(10.5, 20.25, 100.0, 50.0);
let d = doc_with(612.0, 792.0, vec![path(shapes::rectangle(r), red(), Paint::None, 0.0)]);
let out = pict(&d);
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
// 512 bytes of application data, then the frame (top, left, bottom, right) at 72 dpi and the
// version 2 opcodes.
assert_eq!(out.bytes[514..522], [0, 0, 0, 0, 3, 24, 2, 100]);
assert_eq!(out.bytes[522..528], [0x00, 0x11, 0x02, 0xFF, 0x0C, 0x00]);
let pic = read(&out);
assert_eq!((pic.width, pic.height), (612.0, 792.0));
let f = fills(&pic);
assert_eq!(f.len(), 1, "{f:?}");
assert_eq!(f[0].1, [255, 0, 0, 255]);
assert!(near(f[0].0.bounding_box(), r, 1.0 / 16.0), "{:?}", f[0].0.bounding_box());
}
#[test]
fn fills_keep_their_holes_and_non_zero_overlaps() {
let even_odd = compound(&[square(10.0, 10.0, 90.0, 90.0, true), square(30.0, 30.0, 70.0, 70.0, true)], FillRule::EvenOdd);
let mut d = doc_with(300.0, 100.0, vec![even_odd]);
// Two overlapping squares drawn the same way round: non-zero fills where they overlap.
add(&mut d, compound(&[square(110.0, 10.0, 150.0, 50.0, true), square(130.0, 30.0, 170.0, 70.0, true)], FillRule::NonZero));
// A square with a hole drawn the other way round.
add(&mut d, compound(&[square(210.0, 10.0, 290.0, 90.0, true), square(230.0, 30.0, 270.0, 70.0, false)], FillRule::NonZero));
let pic = read(&pict(&d));
for (p, filled) in [
((20.0, 20.0), true),
((50.0, 50.0), false),
((120.0, 20.0), true),
((140.0, 40.0), true),
((160.0, 60.0), true),
((120.0, 60.0), false),
((220.0, 20.0), true),
((250.0, 50.0), false),
] {
assert_eq!(painted(&pic, p), filled, "{p:?}");
}
}
#[test]
fn art_off_the_frame_is_cut_to_it() {
// Far enough out that its device coordinates would not fit 16 bits.
let wide = path(shapes::rectangle(Rect::new(-5000.0, 10.0, 5000.0, 20.0)), red(), Paint::None, 0.0);
let away = path(shapes::rectangle(Rect::new(400.0, 10.0, 410.0, 20.0)), blue(), Paint::None, 0.0);
let pic = read(&pict(&doc_with(100.0, 100.0, vec![wide, away])));
let f = fills(&pic);
assert_eq!(f.len(), 1, "{f:?}");
let b = f[0].0.bounding_box();
assert!(b.x0 >= -1.0 && b.x1 <= 101.0 && near(Rect::new(0.0, b.y0, 100.0, b.y1), Rect::new(0.0, 10.0, 100.0, 20.0), 1.0 / 16.0), "{b:?}");
assert!(painted(&pic, (1.0, 15.0)) && painted(&pic, (99.0, 15.0)));
}
#[test]
fn strokes_are_written_as_their_outlines() {
let line = |y: f64| {
let mut bp = BezPath::new();
bp.move_to((10.0, y));
bp.line_to((50.0, y));
path(PathData::from_bezpath(&bp), Paint::None, blue(), 4.0)
};
let butt = line(20.0);
let mut round = line(60.0);
if let Some(s) = round.appearance.stroke_mut() {
s.cap = LineCap::Round;
}
let pic = read(&pict(&doc_with(100.0, 100.0, vec![butt, round])));
let f = fills(&pic);
assert_eq!(f.len(), 2, "{f:?}");
assert!(f.iter().all(|(_, c)| *c == [0, 0, 255, 255]));
let tol = 1.0 / 8.0;
assert!(near(f[0].0.bounding_box(), Rect::new(10.0, 18.0, 50.0, 22.0), tol), "{:?}", f[0].0.bounding_box());
assert!(near(f[1].0.bounding_box(), Rect::new(8.0, 58.0, 52.0, 62.0), tol), "{:?}", f[1].0.bounding_box());
// A stroke wider than the shape covers its interior.
let dot = path(shapes::ellipse(Rect::new(45.0, 45.0, 55.0, 55.0)), Paint::None, blue(), 40.0);
let pic = read(&pict(&doc_with(100.0, 100.0, vec![dot])));
assert!(painted(&pic, (50.0, 50.0)) && painted(&pic, (50.0, 32.0)) && !painted(&pic, (50.0, 20.0)));
}
/// A PNG of `w` × `h` pixels, `rgba` row by row.
fn png_of(w: u32, h: u32, rgba: Vec<u8>) -> Vec<u8> {
let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).unwrap();
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap()
}
/// A bitmap read back: where it goes (`[x, y, w, h]`), its width and height in pixels, and its
/// RGB pixels.
type Bitmap = ([f32; 4], u32, u32, Vec<[u8; 3]>);
/// The bitmaps of `pic`.
fn bitmaps(pic: &craft_metafile::Picture) -> Vec<Bitmap> {
pic.items
.iter()
.filter_map(|i| match i {
Item::Bitmap { rect, width, height, rgba, .. } => {
Some((*rect, *width, *height, rgba.as_chunks::<4>().0.iter().map(|p| [p[0], p[1], p[2]]).collect()))
}
_ => None,
})
.collect()
}
/// Each pixel of a bitmap read back shows the pixel of `src` (`w` × `h`) that `xf` places under
/// its center.
fn shows(bitmap: &Bitmap, src: &[[u8; 3]], w: usize, xf: Affine) {
let (rect, bw, bh, px) = bitmap;
let inv = xf.inverse();
let (cw, ch) = (f64::from(rect[2]) / f64::from(*bw), f64::from(rect[3]) / f64::from(*bh));
for y in 0..*bh as usize {
for x in 0..*bw as usize {
let at = Point::new(f64::from(rect[0]) + (x as f64 + 0.5) * cw, f64::from(rect[1]) + (y as f64 + 0.5) * ch);
let s = inv * at;
let want = src[s.y.floor() as usize * w + s.x.floor() as usize];
assert_eq!(px[y * *bw as usize + x], want, "pixel ({x}, {y}) at {at:?}");
}
}
}
#[test]
fn images_keep_their_pixels_mirrored_and_quarter_turned() {
let src: Vec<[u8; 3]> = vec![[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0], [0, 255, 255], [255, 0, 255]];
let bytes = png_of(3, 2, src.iter().flat_map(|p| [p[0], p[1], p[2], 255]).collect());
let places = [
Affine::translate((10.0, 10.0)) * Affine::scale(4.0),
Affine::translate((40.0, 10.0)) * Affine::scale_non_uniform(-4.0, 4.0),
Affine::translate((60.0, 10.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::scale(4.0),
Affine::translate((70.0, 60.0)) * Affine::rotate(-std::f64::consts::FRAC_PI_2) * Affine::scale_non_uniform(4.0, -4.0),
];
let mut d = doc_with(100.0, 100.0, vec![]);
for xf in places {
let n = image_node(&mut d, bytes.clone(), 3, 2, xf);
add(&mut d, n);
}
let out = pict(&d);
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
let bm = bitmaps(&read(&out));
assert_eq!(bm.len(), places.len());
for (b, xf) in bm.iter().zip(places) {
let want = xf.transform_rect_bbox(Rect::new(0.0, 0.0, 3.0, 2.0));
let got = Rect::new(f64::from(b.0[0]), f64::from(b.0[1]), f64::from(b.0[0] + b.0[2]), f64::from(b.0[1] + b.0[3]));
assert!(near(got, want, 1.0 / 16.0), "{got:?} {want:?}");
shows(b, &src, 3, xf);
}
}
#[test]
fn turned_and_translucent_images_are_reported() {
let mut d = doc_with(100.0, 100.0, vec![]);
// One pixel: a row narrower than two pixels is stored unpacked.
let half = image_node(&mut d, png(1, 1, [0, 0, 0, 128]), 1, 1, Affine::translate((10.0, 10.0)) * Affine::scale(10.0));
add(&mut d, half);
let out = pict(&d);
assert_eq!(out.warnings, ["PICT has no transparency: images are written over white"]);
let bm = bitmaps(&read(&out));
assert_eq!(bm.len(), 1);
assert_eq!(bm[0].3, [[127, 127, 127]]);
let turned = image_node(&mut d, png(2, 2, [0, 0, 0, 255]), 2, 2, Affine::translate((50.0, 50.0)) * Affine::rotate(0.5));
add(&mut d, turned);
assert!(pict(&d).warnings.iter().any(|w| w.contains("quarter turns")));
}
#[test]
fn large_images_are_written_in_tiles() {
let (w, h) = (1500usize, 3usize);
// Red changes along each row and green stays the same over long runs: both literal and
// repeated bytes are packed, in rows longer than 250 bytes.
let src: Vec<[u8; 3]> = (0..w * h).map(|i| [(i % w % 256) as u8, (i % w / 256) as u8, (i / w * 60) as u8]).collect();
let mut d = doc_with(100.0, 100.0, vec![]);
// A pixel a device unit (a sixteenth of a point) wide.
let xf = Affine::translate((5.0, 5.0)) * Affine::scale(0.0625);
let n = image_node(&mut d, png_of(w as u32, h as u32, src.iter().flat_map(|p| [p[0], p[1], p[2], 255]).collect()), w as u32, h as u32, xf);
add(&mut d, n);
let bm = bitmaps(&read(&pict(&d)));
assert_eq!(bm.iter().map(|b| (b.1, b.2)).collect::<Vec<_>>(), [(1024, 3), (476, 3)]);
for b in &bm {
shows(b, &src, w, xf);
}
}
#[test]
fn pict_polygon_sizes_fit_a_signed_word() {
// 8,800 figure points, plus closing points and bridges, fit the old unsigned limit.
let squares: Vec<BezPath> = (0..2200)
.map(|i| (f64::from(i % 50) * 1.5 + 1.0, f64::from(i / 50) * 1.5 + 1.0))
.map(|(x, y)| square(x, y, x + 1.0, y + 1.0, true))
.collect();
let out = pict(&doc_with(100.0, 100.0, vec![compound(&squares, FillRule::EvenOdd)]));
let polys = paint_polys(&out.bytes);
assert!(!polys.is_empty());
for poly in polys {
let size = i16::from_be_bytes(poly[..2].try_into().unwrap());
assert!(size > 0, "polySize must be a positive signed byte count: {size}");
let (points, remainder) = poly[10..].as_chunks::<4>();
assert!(remainder.is_empty());
assert!(!points.is_empty());
assert_eq!(size as usize, 10 + 4 * points.len());
}
}
#[test]
fn a_fill_past_one_polygon_is_split_or_thinned() {
// 3,000 separate squares: more points than one polygon holds.
let squares: Vec<BezPath> = (0..3000)
.map(|i| (f64::from(i % 60) * 1.5 + 1.0, f64::from(i / 60) * 1.5 + 1.0))
.map(|(x, y)| square(x, y, x + 1.0, y + 1.0, true))
.collect();
let out = pict(&doc_with(100.0, 100.0, vec![compound(&squares, FillRule::EvenOdd)]));
assert!(out.warnings.iter().any(|w| w.contains("several polygons")), "{:?}", out.warnings);
let pic = read(&out);
assert!(fills(&pic).len() > 1);
assert!(painted(&pic, (1.5, 1.5)) && painted(&pic, (59.0 * 1.5 + 1.5, 49.0 * 1.5 + 1.5)));
// One outline of 20,000 points.
let mut star = BezPath::new();
for i in 0..20_000 {
let t = f64::from(i) / 20_000.0 * std::f64::consts::TAU;
let r = if i % 2 == 0 { 45.0 } else { 40.0 };
let p = (50.0 + r * t.cos(), 50.0 + r * t.sin());
if i == 0 { star.move_to(p) } else { star.line_to(p) }
}
star.close_path();
let out = pict(&doc_with(100.0, 100.0, vec![compound(&[star], FillRule::EvenOdd)]));
assert!(out.warnings.iter().any(|w| w.contains("fewer points")), "{:?}", out.warnings);
let pic = read(&out);
assert!(painted(&pic, (50.0, 50.0)) && !painted(&pic, (2.0, 2.0)));
}
#[test]
fn an_image_reaching_far_past_the_frame_keeps_its_columns_in_place() {
// Two columns, each 2,550 pt wide: red ends at x = 50, well inside the frame, while the outer
// edges lie past 16-bit device coordinates.
let mut d = doc_with(100.0, 100.0, vec![]);
let bytes = png_of(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 255]);
let n = image_node(&mut d, bytes, 2, 1, Affine::translate((-2500.0, 10.0)) * Affine::scale_non_uniform(2550.0, 10.0));
add(&mut d, n);
let bm = bitmaps(&read(&pict(&d)));
let color_at = |x: f64| {
bm.iter().find_map(|(r, bw, _, px)| {
let (x0, w) = (f64::from(r[0]), f64::from(r[2]));
(x0..x0 + w).contains(&x).then(|| px[((x - x0) / w * f64::from(*bw)) as usize])
})
};
assert_eq!(color_at(25.0), Some([255, 0, 0]), "{bm:?}");
assert_eq!(color_at(49.0), Some([255, 0, 0]), "{bm:?}");
assert_eq!(color_at(51.0), Some([0, 0, 255]), "{bm:?}");
}
#[test]
fn a_non_zero_fill_too_complex_to_resolve_is_reported() {
let squares: Vec<BezPath> = (0..1000).map(|_| square(10.0, 10.0, 50.0, 50.0, true)).collect();
let out = pict(&doc_with(100.0, 100.0, vec![compound(&squares, FillRule::NonZero)]));
assert!(out.warnings.iter().any(|w| w.contains("written even-odd")), "{:?}", out.warnings);
// The same for a stroke whose outline can't be resolved: it is still written, not left out.
let mut lines = BezPath::new();
for _ in 0..1000 {
lines.move_to((10.0, 50.0));
lines.line_to((90.0, 50.0));
}
let out = pict(&doc_with(100.0, 100.0, vec![path(PathData::from_bezpath(&lines), Paint::None, blue(), 4.0)]));
assert!(out.warnings.iter().any(|w| w.contains("written even-odd")), "{:?}", out.warnings);
assert!(!fills(&read(&out)).is_empty());
}
#[test]
fn pict_regions_over_32767_points_are_refused() {
let d = doc_with(100.0, 100.0, vec![]);
assert!(export(&d, Rect::new(0.0, 0.0, 40_000.0, 10.0), Kind::Pict).is_err());
assert!(check_regions_for(&[Rect::new(0.0, 0.0, 40_000.0, 10.0)], Kind::Pict).is_err());
assert!(check_regions_for(&[Rect::new(0.0, 0.0, 40_000.0, 10.0)], Kind::Emf).is_ok());
assert!(export(&d, Rect::new(0.0, 0.0, 32_000.0, 10.0), Kind::Pict).is_ok());
}
+4 -3
View File
@@ -982,9 +982,10 @@ artboard. OK is disabled with none checked. Save As to an EPS file opens the sam
a pick writes the option's value (`"tiffColor"`, `"preserve"`, a built-in preset's id such as `"medium"` or a saved
preset's name, the level as a number), and a value none of them names shows as it is.
EMF and WMF: Export As… lists both formats (`file.exportAs {format: "emf"}` or `"wmf"`); they have no options
dialog, so `ui.dialog.confirm` asks for the path and writes the file (one per artboard with Use Artboards). Open and
Place read `.emf` and `.wmf`; a paste of `image/emf` from a system clipboard service runs `clipboard.importEmf`.
EMF, WMF and PICT: Export As… lists the three formats (`file.exportAs {format: "emf"}`, `"wmf"` or `"pict"`); they
have no options dialog, so `ui.dialog.confirm` asks for the path and writes the file (one per artboard with Use
Artboards). Open and Place read `.emf` and `.wmf`; a paste of `image/emf` from a system clipboard service runs
`clipboard.importEmf`.
HP-GL Options: Export As… with the HP-GL format (`file.exportAs {format: "hpgl"}`, then the save dialog), or
`ui.hpglOptionsDialog {path?, …HP-GL options}` for agents, opens the `hpglOptions` dialog. Its fields are
+1 -1
View File
@@ -384,7 +384,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's
| Layered raster `.pcraft` | open, place | yes (as one image: the full-size composite when the file has one; else the layers combined at the canvas size when the document is RGB at 8 or 16 bits and every visible layer is a Normal raster layer without clipping, layer effects, a vector mask, a frame, advanced blending or a feathered layer mask; else the composite preview, with a warning when it is smaller than the canvas) | no | read with craft-doc; sized by the document's resolution, the preview at the canvas's size (at least 1 ppi); a linked file is read the same way again when it is updated; a missing or damaged full-size composite or preview is an error; `tests_pcraftread.rs` |
| 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` |
| 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) | yes (a version 2 `.pct` of an artboard, or one per artboard: fills as polygons cut to the frame, strokes as their outlines, images as 24-bit pixel maps over white, at up to 16 device units a point) | `.pct`, `.pic` and `.pict`; a version 2 picture also opens by its content; export writes clipping masks, gradients, patterns and transparency as WMF does and reports each loss, and `crates/metafile/src/tests/pict_export.rs` reads its pictures back through the reader; 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` |
| 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` |
+33 -3
View File
@@ -882,7 +882,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions
| `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 (`.jpg`/`.jpeg`/`.jpe`), 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), DWG drawings (`.dwg`, `.dws`, `.dwt`). Templates (`.vctemplate`, `.ait`, `.cdt`, `.dwt`) 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.<id>"` 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 `<name>_<artboard>.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: <reason>` 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. |
| `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`, `pict` (a QuickDraw `.pct` picture), `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, PICT 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. |
| `apply_effect` | `{effect?, params?, ids?}` | Appends a live effect. Without `effect`, returns the effect catalogue with parameters and defaults. |
| `pathfinder` | `{operation, ids?}` | `unite`, `minusFront`, `intersect`, `exclude`, `divide`, `trim`, `merge`, `crop`, `outline`, `minusBack`. For a live version, apply the `pathfinder.*` effect to a group (`effect.apply` groups several loose selected objects first). In remote desktop mode, `run_command` and `invoke_menu` can both call `pathfinder.repeat` with `{}`. Successful panel operations, direct `object.pathfinder.*` commands, and `command.batch` steps (including Actions panel playback) set its history. Repeat applies it to the current selection using current Pathfinder Options. Trap, compound-shape edits, live effects and `action.batch` do not set history. With no history it returns "no Pathfinder operation applied yet". |
@@ -13564,13 +13564,43 @@ under any name. Opcodes and their data lengths follow Apple's
inverted shapes, transfer modes other than a copy (drawn as a copy), QuickTime images in formats other than JPEG, and
regions or images past the reader's limits. A picture cut short keeps what came before it with a warning, and one that
draws nothing VectorCraft reads opens empty with a warning. A file that holds no picture is refused with
"not a PICT file". PICT can't be written: `document.export` to it is refused with "PICT files can be opened but not
written".
"not a PICT file".
```json
{"name":"run_command","arguments":{"command":"file.place","params":{"path":"/tmp/logo.pct","at":[300,200]}}}
```
## PICT export
`document.export` (and `export`) with format `pict`, or a path ending in `.pct`, `.pic` or `.pict`, writes a QuickDraw
version 2 picture of the first artboard (or `artboard`): 512 bytes of application data, then the picture. Export As
offers it as PICT with the `.pct` extension. `useArtboards: true` writes one file per chosen artboard (`{stem}-{artboard}.pct`), `false` the bounds of the
visible art. The picture's frame is the artboard in points, at most 32,767 points on a side (a larger artboard is
refused). The drawing uses the extended version 2 header at up to 16 device units a point (1,152 dpi), as many as keep
the frame within 16-bit coordinates. The writer follows the opcodes and data layouts of Apple's
[Opcodes in Pictures](https://dev.os9.ca/techpubs/mac/QuickDraw/QuickDraw-461.html) and
[Version and Header Opcodes](https://dev.os9.ca/techpubs/mac/QuickDraw/QuickDraw-459.html):
- Fills are polygons (`PaintPoly`) in their color, with curves flattened. QuickDraw fills a polygon even-odd, so a path of
several figures is one polygon that runs back along the line between its figures, and a non-zero fill is first
resolved into figures that don't overlap. Art is cut to the frame. A fill too complex to resolve or cut is written
as it is, filled even-odd. A fill of more than 16,381 points is written as several polygons, and a single outline of
more than 16,379 points keeps that many points, evenly spaced. Each of these adds a warning.
- Strokes are their filled outlines, with their caps, joins, miter limit and dashes; a stroke thinner than a device unit
is written one unit wide.
- Images are `DirectBitsRect` pixel maps of 24-bit color in tiles of at most 1,024 pixels on a side, each row packed
with PackBits. Mirrored images and images turned by quarter turns keep their placement; other turns and skews are
written upright, filling their bounds, with a warning. PICT has no transparency: images are written over white, with
a warning.
- Type is written as outlines. Clipping masks, gradients, patterns, transparency and blending are written as WMF writes
them (clipped art whole, gradients and patterns as one color), each with its warning.
`document.open` reads a written picture back with the reader above.
```json
{"name":"run_command","arguments":{"command":"document.export","params":{"format":"pict","useArtboards":true,"path":"/tmp/icons.pct"}}}
```
## HP-GL import
`document.open` and `file.place` read HP-GL/2 plot files (`.plt`, `.hpgl`, `.hgl`, `.hpg`) into one layer, with the