diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 426f374a5c..21618367b6 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -86,7 +86,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Live Paint"], Some("Cmd+Alt+X"), - "{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with the fill rows that draw (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge with the stroke rows that draw (also a weight above 0) of its source, in order with their settings and with that source's opacity and blending mode (on a path cut into several edges, dashes go on along the path with the lengths set, without the fit of dashes aligned to corners and path ends, arrowheads stay at its own ends, and a width profile or brush stays only on an edge that runs the whole path); a face or edge given no such row has one unpainted row; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}", + "{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with the fill rows that draw (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge with the stroke rows that draw (also a weight above 0) of its source, in order with their settings and with that source's opacity and blending mode (on a path cut into several edges, dashes go on along the path with the lengths set, without the fit of dashes aligned to corners and path ends, arrowheads stay at its own ends, and a width profile or brush stays only on an edge that runs the whole path); a face or edge given no such row has one unpainted row; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step). The command stops with an error and leaves the art unchanged when the paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. → {id, faces, edges}", has_selection_or_ids, lp_make ), @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Merge", ["Object", "Live Paint"], None, - "{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link); a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}", + "{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link); a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step). The command stops with an error and leaves the art unchanged when the paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. → {id, faces, edges}", has_multi_or_ids, lp_merge ), @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Gap Options", [], None, - "{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint; when every group already has the options and closeGaps finds no gap, nothing changes (no undo step) → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}", + "{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint; when every group already has the options and closeGaps finds no gap, nothing changes (no undo step). The command stops with an error and leaves the art unchanged when a group's paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. The paths include lines across the gaps when detect is on. → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}", has_selection_or_ids, lp_gap_options ), @@ -740,12 +740,13 @@ fn build_children(d: &mut Document, sources: Vec>, max_gap: Option { - let (regs, edges, _) = po::live_paint_with_gaps(&shapes, gap); + let (regs, edges, _) = po::try_live_paint_with_gaps(&shapes, gap).map_err(too_many)?; (regs, edges) } - None => po::live_paint(&shapes), + None => po::try_live_paint(&shapes).map_err(too_many)?, }; if regs.is_empty() && edges.is_empty() { return Err(EngineError::Other("Live Paint: these paths are too degenerate to paint".into())); diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index a48ac3e85b..e69ef7136e 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer for each layer with art on the page, holding the art's fills and strokes as curves in their colors: CMYK, RGB, gray, spot colors at their tints, Registration; type as outlines, gradients and patterns as one color, nonzero fills as even-odd, dashes in whole stroke widths, no miter limit, art across a page's edge written whole, without images, clipping masks or transparency; warnings name each of these losses), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, 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 chosen artboard, false the bounds of the visible art; a layer for each layer with art on the page, holding the art's fills and strokes as curves in their colors: CMYK, RGB, gray, spot colors at their tints, Registration; type as outlines, gradients and patterns as one color, nonzero fills as even-odd, dashes in whole stroke widths, no miter limit, art across a page's edge written whole, without images, clipping masks or transparency; warnings name each of these losses), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", has_doc, export::export ), diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index ac66cb8e65..7a6547890f 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -50,6 +50,12 @@ pub const OPTIONS: &[FormatOption] = &[ FormatOption { name: "decimals", ty: "integer", default: "3", description: "coordinate precision, 1–7 decimal places" }, FormatOption { name: "minify", ty: "boolean", default: "false", description: "no XML declaration, indentation or line breaks" }, FormatOption { name: "responsive", ty: "boolean", default: "false", description: "no width/height: the SVG scales to its container" }, + FormatOption { + name: "units", + ty: "string", + default: "null", + description: "override the document unit for width and height: px (bare numbers, one per point) | pt | mm | cm | in; omit to follow the document unit, not null (the viewBox stays in points; not with responsive)", + }, FormatOption { name: "preserveEditing", ty: "boolean", @@ -121,7 +127,7 @@ pub fn options_map(p: &Value) -> Result, String> { let mut m = Map::new(); let Some(o) = p.as_object() else { return Ok(m) }; for opt in OPTIONS.iter().filter(|opt| opt.name != "svg") { - if let Some(v) = o.get(opt.name).filter(|v| !v.is_null()) { + if let Some(v) = o.get(opt.name).filter(|v| opt.name == "units" || !v.is_null()) { m.insert(opt.name.into(), v.clone()); } } diff --git a/crates/engine/src/cmd/fileio/tests_svg.rs b/crates/engine/src/cmd/fileio/tests_svg.rs index 7b5545ddca..2790a1350c 100644 --- a/crates/engine/src/cmd/fileio/tests_svg.rs +++ b/crates/engine/src/cmd/fileio/tests_svg.rs @@ -115,6 +115,10 @@ fn junk_options_are_rejected() { json!({"svg": "css"}), json!({"images": "inline"}), json!({"useArtboards": "yes"}), + json!({"units": "furlong"}), + json!({"units": 7}), + json!({"units": null}), + json!({"svg": {"units": null}}), ] { let mut q = p.clone(); q["format"] = json!("svg"); @@ -124,6 +128,39 @@ fn junk_options_are_rejected() { assert!(s.execute("document.export", &json!({"format": "png", "styling": "fancy"})).is_ok()); } +/// #4462: width and height carry the chosen unit (the document is 200 × 100 pt, the viewBox stays +/// in points), px is today's bare numbers, and Responsive leaves the size out whatever the unit. +#[test] +fn svg_export_writes_width_height_with_the_requested_unit() { + let mut s = session(1); + let plain = svg(&mut s, json!({})); + assert!(plain.contains(" width=\"200\" height=\"100\" viewBox=\"0 0 200 100\""), "{plain}"); + assert_eq!(svg(&mut s, json!({"units": "px"})), plain, "px keeps bare point coordinates"); + for unit in ["mm", "cm", "in", "pt"] { + for decimals in [1, 3] { + for p in [json!({"units": unit, "decimals": decimals}), json!({"svg": {"units": unit, "decimals": decimals}})] { + let out = svg(&mut s, p); + assert!(out.contains(&format!("{unit}\"")) && out.contains("viewBox=\"0 0 200 100\""), "{unit}:\n{out}"); + let back = vectorcraft_svg::import(&out).unwrap(); + let rect = back.artboards[0].rect; + assert!((rect.width() - 200.0).abs() < 0.001 && (rect.height() - 100.0).abs() < 0.001, "{unit}: {rect:?}\n{out}"); + } + } + } + let out = svg(&mut s, json!({"units": "mm", "responsive": true})); + assert!(!out.contains("mm\"") && !out.contains("height=\"100\" viewBox") && out.contains("viewBox=\"0 0 200 100\""), "{out}"); + assert!(svg(&mut s, json!({"units": "mm", "decimals": 1})).contains("x=\"10.1\""), "coordinate precision is unchanged"); + // Omitted units retain main's document-unit save behavior, including serialized defaults. + s.execute("document.setUnits", &json!({"units": "millimeters"})).unwrap(); + let defaults = serde_json::to_value(vectorcraft_svg::ExportOptions::default()).unwrap(); + assert!(svg(&mut s, json!({"svg": defaults})).contains("mm\"")); + for p in [json!({"units": "px"}), json!({"svg": {"units": "px"}})] { + assert_eq!(svg(&mut s, p), plain, "explicit pixels override physical document units"); + } + assert_eq!(svg(&mut s, json!({"units": "mm", "svg": {"units": "px"}})), plain, "nested units override flat units"); + assert_eq!(svg(&mut s, json!({"units": null, "svg": {"units": "px"}})), plain, "nested units override flat null"); +} + #[test] fn several_artboards_write_one_file_each() { let mut s = session(3); diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 9b498f1ca8..8264d2f27e 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -956,11 +956,10 @@ fn option_trees() -> Value { let mut trees = pdf_option_tree(); if let Some(tree) = trees.as_object_mut() { tree.insert("flattener".into(), serde_json::to_value(super::flatten::FlattenOptions::default()).unwrap_or_default()); - let mut svg = serde_json::to_value(vectorcraft_svg::ExportOptions::default()).unwrap_or_default(); - if let Some(svg) = svg.as_object_mut() { - svg.extend(super::fileio::ARTBOARD_PARAMS.iter().chain(&["useArtboards"]).map(|k| (k.to_string(), Value::Null))); - } - tree.insert("svg".into(), svg); + // Serialized defaults omit optional overrides such as units; the registry lists every key. + let svg = super::fileio::FORMATS.iter().find(|f| f.id == "svg").into_iter().flat_map(|f| f.options); + let svg = svg.filter(|o| o.name != "svg").map(|o| (o.name.to_string(), Value::Null)).collect(); + tree.insert("svg".into(), Value::Object(svg)); } trees } diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 61406fdc61..2132375a44 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -63,7 +63,7 @@ pub fn specs() -> Vec { "Divide", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front). When open paths are among them, the command stops with an error and leaves the art unchanged if the paths are too many or too complex to map. This happens when the paths it maps, as it prepares them from the selection, have more than 65,536 segments, have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. → {ids}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Divide) ), @@ -823,7 +823,8 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result { if shapes.iter().any(|s| s.path.subpaths.iter().any(|sp| sp.anchors.iter().any(|a| !(a.p.x.is_finite() && a.p.y.is_finite())))) { return Err(EngineError::Other("paths contain invalid coordinates".into())); } - let mut results = po::pathfinder_with(op, &shapes, options.precision); + let mut results = po::try_pathfinder_with(op, &shapes, options.precision) + .map_err(|e| EngineError::Other(format!("{label}: {e} to cut with the open paths; select fewer paths")))?; if options.remove_unpainted && matches!(op, PathfinderOp::Divide | PathfinderOp::Outline) { // Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork: the pieces // of objects with no fill (or only hidden ones) go. diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index fecd16ed2a..2ac70f800d 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -1160,9 +1160,10 @@ fn a_blend_mode_over_art_of_several_colors_has_no_one_answer() { assert!((ratio(&r) - 21.0).abs() < 1e-3, "white minus white is black: {r}"); } -/// A Difference square over a white square in a 50 % group that isolates its blending, over the -/// edge between black and white art: the square blends only with the white inside the group, so +/// A Difference square over a 50 % white square in a 50 % group that isolates its blending, over +/// the edge between black and white art: the square blends only with the white inside the group, so /// the art of two colors outside it, which the group draws over in Normal mode, leaves one answer. +/// Without isolation the blend also reaches that art, and there is no one answer. #[test] fn a_blend_mode_inside_an_isolating_group_answers_over_art_of_several_colors() { let mut s = session(); @@ -1177,14 +1178,33 @@ fn a_blend_mode_inside_an_isolating_group_answers_over_art_of_several_colors() { let back = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + // Translucent, so that a blend that is not isolated also reaches the art behind the group. + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); let square = id(s.execute("shape.rectangle", &json!({"x": 70, "y": 70, "width": 60, "height": 60})).unwrap()); s.execute("paint.setStroke", &json!({"none": true})).unwrap(); s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); s.execute("transparency.set", &json!({"blend": "difference"})).unwrap(); - s.execute("object.group", &json!({"ids": [back, square]})).unwrap(); + let group = id(s.execute("object.group", &json!({"ids": [back, square]})).unwrap()); s.execute("transparency.set", &json!({"opacity": 50, "isolate": true})).unwrap(); s.execute("select.set", &json!({"ids": [square]})).unwrap(); - s.execute("color.contrast", &json!({})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let isolated = ratio(&r); + assert!(isolated > 1.0, "{r}"); + assert!(r["against"].as_str().is_some_and(|h| vectorcraft_color::Color::from_hex(h).is_some()), "{r}"); + // Without isolation the square also blends with the black and white art, so there is no one answer. + let set_isolate = |s: &mut Session, on: bool| { + s.execute("select.set", &json!({"ids": [group]})).unwrap(); + s.execute("transparency.set", &json!({"isolate": on})).unwrap(); + s.execute("select.set", &json!({"ids": [square]})).unwrap(); + }; + set_isolate(&mut s, false); + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("is not one color where it is read"), "{e}"); + set_isolate(&mut s, true); + // The Difference mode is applied: in Normal mode the same square gives another answer. + s.execute("transparency.set", &json!({"blend": "normal"})).unwrap(); + let normal = ratio(&s.execute("color.contrast", &json!({})).unwrap()); + assert!((isolated - normal).abs() > 0.1, "difference {isolated} against normal {normal}"); } /// With a fill of None, what a pick would be measured against is still read: the Color Wheel's diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 08c4240597..346df8ab64 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -2214,7 +2214,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.livePaintGapOptions", "Gap Options…", "", - "{} open Gap Options (Object › Live Paint › Gap Options…; dialog `livePaintGapOptions`: detect, size small|medium|large|custom, custom (pt), color (#rrggbb or a layer color's name), closeGaps, preview) on the selected Live Paint groups, filled in from the first; with preview on, the options apply live and the gaps found draw on the canvas in the preview color: OK runs livePaint.gapOptions as one undo step; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing, and with preview on a #rrggbbaa color is not previewed: the groups keep their own color and the gaps draw in black", + "{} open Gap Options (Object › Live Paint › Gap Options…; dialog `livePaintGapOptions`: detect, size small|medium|large|custom, custom (pt), color (#rrggbb or a layer color's name), closeGaps, preview) on the selected Live Paint groups, filled in from the first; with preview on, the options apply live and the gaps found draw on the canvas in the preview color: OK runs livePaint.gapOptions as one undo step; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing, and with preview on a #rrggbbaa color is not previewed: the groups keep their own color and the gaps draw in black; a preview that fails shows its error in the status bar, puts the groups back as they were and stops drawing the dialog's preview of the gaps (View › Show Live Paint Gaps still draws the restored groups' own gaps)", ), ( "ui.perspectivePlane", diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index 61d03ecbc1..da7960af0f 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -31,11 +31,12 @@ pub use fit::{fit_cubics, fit_cubics_through}; pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path}; pub use pathfinder::{ FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_with, regions_within, + try_pathfinder_with, }; pub use planar::{ Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS, - adjacency, cut_out, encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, - shape_builder_with_gap, + TooManyPieces, adjacency, cut_out, encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, + shape_builder, shape_builder_with_gap, try_live_paint, try_live_paint_with_gaps, }; pub use thickness::{MAX_DOCUMENT_THICKNESS_WORK, MAX_THICKNESS_PIECES, ThicknessBudget, thinner_than, thinner_than_within}; pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band}; diff --git a/crates/pathops/src/pathfinder.rs b/crates/pathops/src/pathfinder.rs index 3caddb4bc0..8389fd2dbb 100644 --- a/crates/pathops/src/pathfinder.rs +++ b/crates/pathops/src/pathfinder.rs @@ -109,6 +109,36 @@ pub fn pathfinder(op: PathfinderOp, shapes: &[Shape]) -> Vec { pathfinder_with(op, shapes, DEFAULT_PRECISION) } +/// [`pathfinder_with`], or [`TooManyPieces`](crate::TooManyPieces) when Divide's open paths and the +/// shapes they cut have more than [`SHAPE_BUILDER_MAX_SEGMENTS`](crate::SHAPE_BUILDER_MAX_SEGMENTS) +/// segments, or the sweep cuts them into more than +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`](crate::SHAPE_BUILDER_MAX_MAP_EDGES) pieces, or they exceed the +/// sweep's work budget. [`pathfinder_with`] then divides only the filled areas and leaves the open +/// paths out. +pub fn try_pathfinder_with(op: PathfinderOp, shapes: &[Shape], precision: f64) -> Result, crate::TooManyPieces> { + if op == PathfinderOp::Divide && crate::has_open_path(shapes) { + let precision = if precision.is_finite() && precision > 0.0 { precision } else { DEFAULT_PRECISION }; + let (faces, capped) = divide_with_open_paths(shapes, precision, false); + return if capped { Err(crate::TooManyPieces) } else { Ok(faces) }; + } + Ok(pathfinder_with(op, shapes, precision)) +} + +/// Divide with open paths as cutting edges, through the Shape Builder's bounded planar map (and, +/// with `fallback`, its filled-area fallback), and whether that map was skipped for its size. +fn divide_with_open_paths(shapes: &[Shape], precision: f64, fallback: bool) -> (Vec, bool) { + let (arrangement, capped) = crate::planar::builder_capped(shapes, false, 0.0, precision, fallback); + let faces = arrangement + .regions + .into_iter() + .filter_map(|r| { + let key = shapes.get(r.top()?)?.key; + Some(Shape::new(r.path, FillRule::NonZero, key)) + }) + .collect(); + (faces, capped) +} + /// [`pathfinder`] at Pathfinder Options › Precision: results are refit to within `precision` /// (document units) and pieces thinner than it are dropped. A smaller value follows the inputs more /// closely. A value that isn't positive and finite is [`DEFAULT_PRECISION`]. @@ -130,14 +160,7 @@ pub fn pathfinder_with(op: PathfinderOp, shapes: &[Shape], precision: f64) -> Ve // Open paths are cutting edges for Divide; the filled-only operations keep their // implicit closure. Reuse Shape Builder's bounded planar map and its fallback. if op == PathfinderOp::Divide && crate::has_open_path(shapes) { - return crate::planar::builder(shapes, false, 0.0, precision) - .regions - .into_iter() - .filter_map(|r| { - let key = shapes.get(r.top()?)?.key; - Some(Shape::new(r.path, FillRule::NonZero, key)) - }) - .collect(); + return divide_with_open_paths(shapes, precision, true).0; } let Some(arr) = arrangement(shapes, precision) else { return Vec::new() }; let p = &arr.tidy; @@ -1645,6 +1668,8 @@ mod tests { assert_eq!(faces.len(), 1, "a segment past the cap falls back to filled areas"); assert_eq!(faces[0].key, 7); assert!((crate::area(&faces[0].path, faces[0].rule) - 10000.0).abs() < 1e-6); + // The checked Divide reports that it left the lines out. + assert_eq!(try_pathfinder_with(PathfinderOp::Divide, &inputs, DEFAULT_PRECISION), Err(crate::TooManyPieces)); } fn old_trim(shapes: &[Shape], precision: f64) -> Vec { diff --git a/crates/pathops/src/planar.rs b/crates/pathops/src/planar.rs index ca473dd839..2d1eee08c9 100644 --- a/crates/pathops/src/planar.rs +++ b/crates/pathops/src/planar.rs @@ -37,14 +37,14 @@ pub use adjacency::{Adjacency, MapEdge, MapFace, MapOutline, adjacency}; pub(crate) use graph::pin_ends; #[cfg(test)] use index::{Crossings, RectIndex, reference_budget, segment_footprint, work_done}; -pub use live_paint::{find_gaps, live_paint, live_paint_with_gaps}; +pub use live_paint::{find_gaps, live_paint, live_paint_with_gaps, try_live_paint, try_live_paint_with_gaps}; pub use map::interior_point; pub(crate) use map::{Map, Rest, map}; pub use shape_builder::{ - BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, has_open_path, - run_around, shape_builder, shape_builder_with_gap, + BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS, TooManyPieces, cut_out, encloses_area, + has_open_path, run_around, shape_builder, shape_builder_with_gap, }; -pub(crate) use shape_builder::{builder, gap_inputs}; +pub(crate) use shape_builder::{builder_capped, gap_inputs}; #[cfg(test)] mod tests; diff --git a/crates/pathops/src/planar/live_paint.rs b/crates/pathops/src/planar/live_paint.rs index 1b9d5b6177..a98449dd0a 100644 --- a/crates/pathops/src/planar/live_paint.rs +++ b/crates/pathops/src/planar/live_paint.rs @@ -6,26 +6,72 @@ use super::*; /// Faces are the bounded areas the paths enclose, holes included, each with the inputs whose fill /// covers it (ascending; empty for an area only enclosed by paths). Edges are the paths split /// wherever they meet another path, keyed by the input they came from (the front-most where -/// inputs share one). Empty when the paths can't be swept (non-finite or too degenerate). +/// inputs share one). Empty when the paths can't be swept (non-finite or too degenerate), or when +/// the sweep cuts them into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces or the inputs exceed +/// the sweep's work budget ([`try_live_paint`] reports either limit). pub fn live_paint(shapes: &[Shape]) -> (Vec, Vec) { - build(shapes, DEFAULT_PRECISION).map(|(faces, edges, _)| (faces, edges)).unwrap_or_default() + try_live_paint(shapes).unwrap_or_default() } +/// [`live_paint`], or [`TooManyPieces`] when the sweep cuts the paths into more than +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces or the inputs exceed the sweep's work budget. +/// No faces or edges are built in either case. +pub fn try_live_paint(shapes: &[Shape]) -> Result<(Vec, Vec), TooManyPieces> { + Ok(build(shapes, DEFAULT_PRECISION)?.map(|(faces, edges, _)| (faces, edges)).unwrap_or_default()) +} + +/// Faces, edges and gaps, as [`live_paint_with_gaps`] gives them. +type WithGaps = (Vec, Vec, Vec<[Point; 2]>); + +type Capped = Result; + +type CappedWithGaps = (Capped>, Capped>, Vec<[Point; 2]>); + /// [`live_paint`] with Gap Detection: the faces are those of `shapes` with a line across each gap /// [`find_gaps`] finds up to `max_gap`, so paint stops at the gaps, and the edges are those of /// `shapes` alone (the lines add none). Also returns the gaps. pub fn live_paint_with_gaps(shapes: &[Shape], max_gap: f64) -> (Vec, Vec, Vec<[Point; 2]>) { + let (faces, edges, gaps) = faces_and_edges_with_gaps(shapes, max_gap); + (faces.unwrap_or_default(), edges.unwrap_or_default(), gaps) +} + +/// [`live_paint_with_gaps`], or [`TooManyPieces`] when the sweep cuts the paths, or the paths with +/// the lines across their gaps, into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces, or either +/// set of paths exceeds the sweep's work budget. +pub fn try_live_paint_with_gaps(shapes: &[Shape], max_gap: f64) -> Result { let gaps = find_gaps(shapes, max_gap); + let Some(closed) = with_gap_lines(shapes, &gaps) else { + let (faces, edges) = try_live_paint(shapes)?; + return Ok((faces, edges, gaps)); + }; + let (faces, _) = try_live_paint(&closed)?; + let (_, edges) = try_live_paint(shapes)?; + Ok((faces, edges, gaps)) +} + +/// The faces and the edges of [`live_paint_with_gaps`], each built on its own, and the gaps. +fn faces_and_edges_with_gaps(shapes: &[Shape], max_gap: f64) -> CappedWithGaps { + let gaps = find_gaps(shapes, max_gap); + let Some(closed) = with_gap_lines(shapes, &gaps) else { + return match try_live_paint(shapes) { + Ok((faces, edges)) => (Ok(faces), Ok(edges), gaps), + Err(e) => (Err(e), Err(e), gaps), + }; + }; + let faces = try_live_paint(&closed).map(|(faces, _)| faces); + let edges = try_live_paint(shapes).map(|(_, edges)| edges); + (faces, edges, gaps) +} + +/// `shapes` with a line across each of `gaps`, or `None` when there are none. +fn with_gap_lines(shapes: &[Shape], gaps: &[[Point; 2]]) -> Option> { if gaps.is_empty() { - let (faces, edges) = live_paint(shapes); - return (faces, edges, gaps); + return None; } let mut closed = shapes.to_vec(); let lines = PathData::new(gaps.iter().map(|g| SubPath::polyline(g, false)).collect()); closed.push(Shape::new(lines, FillRule::NonZero, u64::MAX)); - let (faces, _) = live_paint(&closed); - let (_, edges) = live_paint(shapes); - (faces, edges, gaps) + Some(closed) } /// How many times longer than a gap the way between its two ends along the paths must be for it to diff --git a/crates/pathops/src/planar/map.rs b/crates/pathops/src/planar/map.rs index 051a341e1a..f2114a6ceb 100644 --- a/crates/pathops/src/planar/map.rs +++ b/crates/pathops/src/planar/map.rs @@ -42,11 +42,18 @@ pub(crate) fn map(shapes: &[Shape], cover: bool) -> Option { /// [`map`] whose faces and pieces are refit to `precision`, and whose slivers thinner than it are dropped. pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option { - map_within(shapes, cover, precision, usize::MAX) + map_within(shapes, cover, precision, usize::MAX).ok().flatten() } -/// [`map_with`], or `None` when the sweep cuts the paths into more than `max_edges` pieces. -pub(super) fn map_within(shapes: &[Shape], cover: bool, precision: f64, max_edges: usize) -> Option { +/// [`map_with`], or [`TooManyPieces`] when the sweep cuts the paths into more than `max_edges` pieces +/// or the inputs exceed the sweep's work budget. +pub(super) fn map_within(shapes: &[Shape], cover: bool, precision: f64, max_edges: usize) -> Result, TooManyPieces> { + let mut capped = false; + let map = map_capped(shapes, cover, precision, max_edges, &mut capped); + if capped { Err(TooManyPieces) } else { Ok(map) } +} + +fn map_capped(shapes: &[Shape], cover: bool, precision: f64, max_edges: usize, capped: &mut bool) -> Option { let mut inputs: Vec<(BezPath, usize)> = Vec::new(); for (i, s) in shapes.iter().enumerate() { let mut bp = BezPath::new(); @@ -71,10 +78,11 @@ pub(super) fn map_within(shapes: &[Shape], cover: bool, precision: f64, max_edge snap_horizontals(&mut inputs.iter_mut().map(|p| &mut p.0).collect::>(), eps); // Counted on the snapped geometry, which is what the sweep sees: snapping can bring boxes into contact. if !crate::budget::sweep_fits(inputs.iter().map(|p| &p.0)) { + *capped = true; return None; } let tidy = Tidy::keeping(precision, inputs.iter().map(|p| &p.0)); - let (points, edges) = sweep_graph(&inputs, eps, precision, max_edges)?; + let (points, edges) = sweep_graph(&inputs, eps, precision, max_edges, capped)?; let nv = points.len(); // Half-edges leaving each vertex, sorted by direction; walking a face, the next half-edge is @@ -193,7 +201,7 @@ pub(super) fn map_within(shapes: &[Shape], cover: bool, precision: f64, max_edge Some(Map { edges, around, slot_of, faces, face_index, slivers, holes, face_holes, tidy, anchors, snap }) } -fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64, max_edges: usize) -> Option<(Vec, Vec)> { +fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64, max_edges: usize, capped: &mut bool) -> Option<(Vec, Vec)> { // The sweep can panic on rare near-degenerate input; that must never take the app down. let sweep = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Topology::::from_paths(inputs.iter().map(|(p, i)| (p, *i)), eps))); @@ -202,6 +210,7 @@ fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64, max_edges: // the paths into, and paths that cross many times are cut into far more pieces than they have // segments. if top.segment_indices().nth(max_edges).is_some() { + *capped = true; return None; } // The planar graph: vertices are the sweep's points, edges its segments. Points closer than @@ -437,10 +446,17 @@ impl Map { /// Faces and edges of `shapes`, and the pieces of the open paths (those with no closed subpath) /// that lie under another path in front of them, whose edges are that path's: under a closed /// path's outline, or along an open path in front. -/// `None` when the sweep cuts the paths into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces. -pub(super) fn build(shapes: &[Shape], precision: f64) -> Option<(Vec, Vec, Vec)> { - let m = map_within(shapes, false, precision, SHAPE_BUILDER_MAX_MAP_EDGES)?; - let Map { edges, around, faces, holes, face_holes, tidy, anchors, snap, .. } = &m; +/// This returns [`TooManyPieces`] when the sweep cuts the paths into more than +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces or the inputs exceed the sweep's work budget. +pub(super) fn build(shapes: &[Shape], precision: f64) -> Result, TooManyPieces> { + Ok(map_within(shapes, false, precision, SHAPE_BUILDER_MAX_MAP_EDGES)?.and_then(|m| build_from(&m, shapes, precision))) +} + +/// Faces, edges and the open paths' pieces under another path, as [`build`] gives them. +pub(super) type Built = (Vec, Vec, Vec); + +fn build_from(m: &Map, shapes: &[Shape], precision: f64) -> Option { + let Map { edges, around, faces, holes, face_holes, tidy, anchors, snap, .. } = m; let snap = *snap; let fills: Vec = shapes.iter().map(Fill::new).collect(); let subpath = |cycle: &[usize]| { diff --git a/crates/pathops/src/planar/shape_builder.rs b/crates/pathops/src/planar/shape_builder.rs index 4ddd10495a..86a2fc5f36 100644 --- a/crates/pathops/src/planar/shape_builder.rs +++ b/crates/pathops/src/planar/shape_builder.rs @@ -19,6 +19,20 @@ pub const SHAPE_BUILDER_MAX_SEGMENTS: usize = 65_536; /// from them still has its region. pub const SHAPE_BUILDER_MAX_MAP_EDGES: usize = 2 * SHAPE_BUILDER_MAX_SEGMENTS; +/// The paths have more than [`SHAPE_BUILDER_MAX_SEGMENTS`] segments, or the sweep cut them into +/// more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces, or they exceed the sweep's work budget. +/// Their planar map was not built. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TooManyPieces; + +impl std::fmt::Display for TooManyPieces { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("the paths have too many segments or pieces") + } +} + +impl std::error::Error for TooManyPieces {} + /// The Shape Builder's arrangement: see [`shape_builder`]. #[derive(Clone, Debug, Default, PartialEq)] pub struct BuilderArrangement { @@ -86,23 +100,43 @@ pub fn shape_builder_with_gap(shapes: &[Shape], edges: bool, gap: f64) -> Builde /// [`shape_builder_with_gap`] refitting its results to `precision` (Pathfinder Options › Precision). pub(crate) fn builder(shapes: &[Shape], edges: bool, gap: f64, precision: f64) -> BuilderArrangement { + builder_capped(shapes, edges, gap, precision, true).0 +} + +/// [`builder`], and whether its full map was skipped because the paths have more than +/// [`SHAPE_BUILDER_MAX_SEGMENTS`] segments or the sweep cut them into more than +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces, or the inputs exceed the sweep's work budget. +/// The regions are then the filled areas', or, without `fallback`, there are none and the filled +/// areas are not swept. +pub(crate) fn builder_capped(shapes: &[Shape], edges: bool, gap: f64, precision: f64, fallback: bool) -> (BuilderArrangement, bool) { let has_open = has_open_path(shapes); let segments: usize = shapes.iter().flat_map(|s| &s.path.subpaths).map(|sp| sp.segment_count()).sum(); + let mut capped = segments > SHAPE_BUILDER_MAX_SEGMENTS; + let mut built = |shapes: &[Shape]| match build(shapes, precision) { + Ok(b) => b.unwrap_or_default(), + Err(TooManyPieces) => { + capped = true; + Default::default() + } + }; let planar = (segments <= SHAPE_BUILDER_MAX_SEGMENTS) .then(|| { let keyed: Vec = shapes.iter().enumerate().map(|(i, s)| Shape::new(s.path.clone(), s.rule, i as u64)).collect(); if has_open && gap.is_finite() && gap > 0.0 { - let (faces, pieces, under) = build(&gap_inputs(&keyed, gap), precision).unwrap_or_default(); + let (faces, pieces, under) = built(&gap_inputs(&keyed, gap)); // Gap targets split original outlines too, but the bridges themselves aren't art. let art = |p: &Shape| p.key < shapes.len() as u64; (faces, pieces.into_iter().filter(art).collect(), under.into_iter().filter(art).collect()) } else { - build(&keyed, precision).unwrap_or_default() + built(&keyed) } }) .filter(|(faces, pieces, _)| !faces.is_empty() || !pieces.is_empty()); let Some((faces, pieces, under)) = planar else { - return BuilderArrangement { regions: filled_regions(shapes, precision), ..Default::default() }; + if capped && !fallback { + return (BuilderArrangement::default(), true); + } + return (BuilderArrangement { regions: filled_regions(shapes, precision), ..Default::default() }, capped); }; let is_line = |i: u64| shapes.get(i as usize).is_some_and(|s| !s.path.subpaths.iter().any(|sp| sp.closed)); let (lines, outline): (Vec, Vec) = pieces.into_iter().partition(|e| is_line(e.key)); @@ -114,12 +148,13 @@ pub(crate) fn builder(shapes: &[Shape], edges: bool, gap: f64, precision: f64) - regions.extend(faces.into_iter().filter(|f| f.sources.is_empty())); regions }; - BuilderArrangement { + let arrangement = BuilderArrangement { regions, lines: if has_open { lines } else { Vec::new() }, edges: if edges { outline } else { Vec::new() }, lines_under: if has_open { under } else { Vec::new() }, - } + }; + (arrangement, false) } /// The regions of the shapes' filled areas. A shape that fills nothing (open paths that enclose no diff --git a/crates/pathops/src/planar/tests.rs b/crates/pathops/src/planar/tests.rs index 130d381bfa..99045828f6 100644 --- a/crates/pathops/src/planar/tests.rs +++ b/crates/pathops/src/planar/tests.rs @@ -623,13 +623,39 @@ fn bar_grid(n: usize) -> Vec { fn a_map_past_its_edge_cap_is_not_built() { // 20 lines each way: each line is cut into 21 pieces, 840 in all. let s = line_grid(20); - assert!(map::map_within(&s, false, DEFAULT_PRECISION, 1000).is_some()); - assert!(map::map_within(&s, false, DEFAULT_PRECISION, 500).is_none()); + assert!(map::map_within(&s, false, DEFAULT_PRECISION, 1000).is_ok_and(|m| m.is_some())); + assert!(map::map_within(&s, false, DEFAULT_PRECISION, 500).is_err()); let bars = bar_grid(20); assert!(crate::pathfinder::regions_capped(&bars, DEFAULT_PRECISION, 100_000).is_some_and(|r| r.len() > 400)); assert!(crate::pathfinder::regions_capped(&bars, DEFAULT_PRECISION, 1000).is_none()); } +#[test] +fn divide_and_live_paint_report_the_edge_cap() { + // A filled square under 300 lines each way: the lines cross past the cap. + let mut s = vec![rect(100.0, 100.0, 900.0, 900.0, 7)]; + s.extend(line_grid(300).into_iter().map(|l| Shape::new(l.path, l.rule, l.key + 1))); + assert_eq!(crate::try_pathfinder_with(crate::PathfinderOp::Divide, &s, DEFAULT_PRECISION), Err(TooManyPieces)); + // Without the report, Divide gives back the square alone, uncut. + assert_eq!(crate::pathfinder_with(crate::PathfinderOp::Divide, &s, DEFAULT_PRECISION).len(), 1); + assert_eq!(try_live_paint(&s), Err(TooManyPieces)); + assert_eq!(try_live_paint_with_gaps(&s, 10.0), Err(TooManyPieces)); + // Overlapping lines exceed the sweep's work budget before any pieces are cut. + let mut overlapping = vec![rect(100.0, 100.0, 900.0, 900.0, 7)]; + overlapping.extend((0..1500).map(|i| line((0.0, 0.0), (1000.0, 1000.0), i + 8))); + assert_eq!(crate::try_pathfinder_with(crate::PathfinderOp::Divide, &overlapping, DEFAULT_PRECISION), Err(TooManyPieces)); + assert_eq!(crate::pathfinder_with(crate::PathfinderOp::Divide, &overlapping, DEFAULT_PRECISION).len(), 1); + assert_eq!(try_live_paint(&overlapping), Err(TooManyPieces)); + assert_eq!(try_live_paint_with_gaps(&overlapping, 10.0), Err(TooManyPieces)); + let (faces, edges) = live_paint(&overlapping); + assert!(faces.is_empty() && edges.is_empty()); + // Under the cap, both build as before. + let mut small = vec![rect(100.0, 100.0, 900.0, 900.0, 7)]; + small.extend(line_grid(20).into_iter().map(|l| Shape::new(l.path, l.rule, l.key + 1))); + assert!(crate::try_pathfinder_with(crate::PathfinderOp::Divide, &small, DEFAULT_PRECISION).is_ok_and(|f| f.len() > 1)); + assert!(try_live_paint(&small).is_ok_and(|(faces, _)| faces.len() > 1)); +} + #[test] fn shape_builder_builds_no_regions_past_its_edge_cap() { // 300 lines each way cross 90,000 times with 600 segments: the sweep cuts them into about diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index e0f5540b7d..e8c84530d5 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -195,7 +195,11 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: root = root.attr("version", "1.2").attr("baseProfile", "tiny"); } if !opts.responsive { - if let Some((unit, suffix)) = doc.units.svg_unit().and_then(|u| Some((u, u.svg_suffix()?))) { + // Explicit SVG Options override the document unit; absence keeps its native save behavior. + if let Some(unit) = opts.units { + let (width, height) = (unit.length(rect.width(), opts.decimals), unit.length(rect.height(), opts.decimals)); + root = root.attr("width", &width).attr("height", &height); + } else if let Some((unit, suffix)) = doc.units.svg_unit().and_then(|u| Some((u, u.svg_suffix()?))) { let w_val = physical_num(unit.from_pt(rect.width())); let h_val = physical_num(unit.from_pt(rect.height())); root = root.attr("width", format_args!("{w_val}{suffix}")).attr("height", format_args!("{h_val}{suffix}")); diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 0bcd5999b7..222b90b25c 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -185,6 +185,53 @@ impl Encoding { } } +/// The unit of the `width` and `height` an export writes (SVG Options → Units, off Responsive). +/// The `viewBox` stays in user units (points) whatever is chosen. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SizeUnit { + /// Legacy bare numbers, unchanged: one per document point. CSS pixels are 96 per inch; + /// choose an explicit physical unit to preserve the document's physical size. + #[default] + #[serde(rename = "px")] + Px, + #[serde(rename = "pt")] + Pt, + #[serde(rename = "mm")] + Mm, + #[serde(rename = "cm")] + Cm, + #[serde(rename = "in")] + In, +} + +impl SizeUnit { + /// This unit's size in points, and the suffix a length in it carries (`px` is written bare). + fn per_point(self) -> (f64, &'static str) { + match self { + Self::Px => (1.0, ""), + Self::Pt => (1.0, "pt"), + Self::Mm => (25.4 / 72.0, "mm"), + Self::Cm => (2.54 / 72.0, "cm"), + Self::In => (1.0 / 72.0, "in"), + } + } + + /// `points` as a length in this unit. Physical sizes use at least six decimal places and + /// six significant digits, independent of coordinate precision, so rounding does not change + /// the viewBox's rendered scale. `px` keeps [`fmt_num`]'s selected `decimals`. + pub fn length(self, points: f64, decimals: u8) -> String { + let (scale, suffix) = self.per_point(); + let v = points * scale; + let places = + if !suffix.is_empty() && v.is_finite() && v != 0.0 { decimals.max(6).max((5.0 - v.abs().log10().floor()) as u8) } else { decimals }; + format!("{}{suffix}", fmt_num(v, places)) + } +} + +fn explicit_size_unit<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + SizeUnit::deserialize(d).map(Some) +} + /// The SVG profile written (SVG Options → SVG Profile). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum Profile { @@ -231,6 +278,10 @@ pub struct ExportOptions { pub minify: bool, /// Omit `width`/`height` so the SVG scales to its container. pub responsive: bool, + /// Override the document's unit for `width` and `height` (ignored when `responsive`). + /// Absent follows the document; explicit `px` writes bare numbers. Null is invalid. + #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "explicit_size_unit")] + pub units: Option, /// Fonts → Convert to Outlines: text becomes paths (portable, no font needed to view it). pub outline_text: bool, /// Embed the native document (passed to [`export_full`]) in `` so VectorCraft @@ -268,6 +319,7 @@ impl Default for ExportOptions { images: ImageMode::Embed, minify: false, responsive: false, + units: None, outline_text: false, preserve_editing: false, metadata: false, @@ -721,6 +773,22 @@ mod tests { assert_eq!(fmt_num(100.0, 0), "100"); } + #[test] + fn tiny_physical_sizes_keep_their_scale() { + for unit in [SizeUnit::Pt, SizeUnit::Mm, SizeUnit::Cm, SizeUnit::In] { + let (scale, suffix) = unit.per_point(); + for points in [200.0, 10.0, 3.0, 0.001, 1e-14, 1e-30] { + let written = unit.length(points, 1); + let value: f64 = written.strip_suffix(suffix).unwrap().parse().unwrap(); + assert!((value / scale / points - 1.0).abs() < 1e-5, "{points}pt: {written}"); + } + } + assert_eq!(SizeUnit::In.length(0.0, 1), "0in"); + // `px` is written exactly as `fmt_num` does. + assert_eq!(SizeUnit::Px.length(3.0, 1), "3"); + assert_eq!(SizeUnit::Px.length(0.01, 1), "0"); + } + #[test] fn escaping() { assert_eq!(xml_escape("a&\"'"), "a<b>&"'"); diff --git a/crates/svg/tests/it/roundtrip.rs b/crates/svg/tests/it/roundtrip.rs index ce28085b8b..261bdb5d9f 100644 --- a/crates/svg/tests/it/roundtrip.rs +++ b/crates/svg/tests/it/roundtrip.rs @@ -6,7 +6,7 @@ use vectorcraft_doc::{ StrokeLayer, TextKind, TextObject, }; use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect, shapes}; -use vectorcraft_svg::{ExportOptions, ObjectIds, Styling, export, import, import_with_report}; +use vectorcraft_svg::{ExportOptions, ObjectIds, SizeUnit, Styling, export, import, import_with_report}; fn doc_with(nodes: Vec) -> Document { let mut d = Document::new(200.0, 200.0); @@ -698,6 +698,48 @@ fn options_decimals_minify_responsive_artboard() { assert!(!s.contains("id=\"Layer_1\"")); } +/// An SVG written with a physical width and height (#4462) reopens at the artboard it was written from. +#[test] +fn svg_in_physical_units_reopens_at_the_same_size() { + let mut d = Document::new(200.0, 100.0); + d.units = vectorcraft_doc::Unit::Millimeters; + let n = rect_node(&mut d, Rect::new(10.0, 10.0, 60.0, 50.0), Appearance::default_art()); + let l = d.layers[0].id; + d.insert(Some(l), usize::MAX, n).unwrap(); + for units in [SizeUnit::Mm, SizeUnit::Cm, SizeUnit::In, SizeUnit::Pt] { + let s = export(&d, &ExportOptions { units: Some(units), ..Default::default() }); + let back = import(&s).unwrap_or_else(|e| panic!("{units:?}: {e}\n{s}")); + let r = back.artboards[0].rect; + assert!((r.width() - 200.0).abs() < 0.1 && (r.height() - 100.0).abs() < 0.1, "{units:?}: {r:?}\n{s}"); + } +} + +/// A viewer's default `meet` scaling must preserve the artwork's physical extent, not just +/// reopen an artboard with roughly the right width and height. +#[test] +fn physical_units_preserve_rendered_extent_at_low_coordinate_precision() { + for (width, height, decimals) in [(200.0, 10.0, 1), (10.0, 200.0, 1), (0.2, 0.1, 1), (0.002, 0.001, 3)] { + let mut d = Document::new(width, height); + let n = rect_node(&mut d, Rect::new(0.0, 0.0, width, height), Appearance::basic(solid("#000000"), Paint::None, 0.0)); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, n).unwrap(); + for units in [SizeUnit::Mm, SizeUnit::Cm, SizeUnit::In, SizeUnit::Pt] { + let svg = export(&d, &ExportOptions { units: Some(units), decimals, ..Default::default() }); + let tree = usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap(); + let extent = tree.root().abs_bounding_box(); + // CSS consumers render physical lengths at 96 px/in, document geometry is 72 pt/in. + for (actual, expected) in [ + (tree.size().width(), width * 96.0 / 72.0), + (tree.size().height(), height * 96.0 / 72.0), + (extent.width(), width * 96.0 / 72.0), + (extent.height(), height * 96.0 / 72.0), + ] { + assert!((f64::from(actual) / expected - 1.0).abs() < 2e-5, "{units:?}: {actual} != {expected}\n{svg}"); + } + } + } +} + #[test] fn unique_sanitized_ids() { let mut d = Document::new(200.0, 200.0); diff --git a/crates/ui-egui/src/dialogs/live_paint_gaps.rs b/crates/ui-egui/src/dialogs/live_paint_gaps.rs index 388ded4a68..69e5e0ceed 100644 --- a/crates/ui-egui/src/dialogs/live_paint_gaps.rs +++ b/crates/ui-egui/src/dialogs/live_paint_gaps.rs @@ -198,7 +198,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { Some(Ok(done)) => Some(done["gaps"].clone()), Some(Err(e)) => { app.status(e); - None + // The failed preview rolled the groups back, so the gaps an earlier one found are gone too. + Some(Value::Null) } None => None, }; @@ -519,6 +520,23 @@ mod tests { assert!(!drawn(&mut app), "no preview, no gap"); } + /// A preview that fails after one that found gaps leaves no gaps drawn from the earlier one. + #[test] + fn a_failed_preview_draws_no_earlier_gaps() { + let mut app = app(); + gapped_group(&mut app); + app.run("ui.livePaintGapOptions", json!({})).unwrap(); + set(&app, "detect", json!(true)).unwrap(); + set(&app, "preview", json!(true)).unwrap(); + pump_all(&mut app); + assert_eq!(overlays(&app).len(), 1, "the gap is previewed"); + // A custom size past 72 pt is refused, and the preview with it fails. + set(&app, "size", json!("custom")).unwrap(); + set(&app, "custom", json!(100.0)).unwrap(); + pump_all(&mut app); + assert!(overlays(&app).is_empty(), "{:?}", overlays(&app)); + } + /// With Preview on, a Gap Preview Color with an alpha part is not previewed: the group keeps /// its own color, the gaps draw in black, OK refuses the color and Cancel rolls the preview back. #[test] diff --git a/crates/ui-egui/src/dialogs/screen_formats.rs b/crates/ui-egui/src/dialogs/screen_formats.rs index fae58f693d..221807dade 100644 --- a/crates/ui-egui/src/dialogs/screen_formats.rs +++ b/crates/ui-egui/src/dialogs/screen_formats.rs @@ -497,7 +497,7 @@ pub(crate) fn settings(ui: &mut Ui, fields: &mut Map, presets: &[ let mine = fields.get("settings").and_then(|all| all.get(id)).and_then(Value::as_object).cloned().unwrap_or_default(); let tiny = mine.get("profile").and_then(Value::as_str) == Some("tiny12"); let params = match id { - "svg" => svg_options::svg_params(true, tiny), + "svg" => svg_options::svg_params(svg_options::Mode::Export, true, tiny), "pdf" => Vec::new(), _ => png_options::raster_params(id, true, None), }; diff --git a/crates/ui-egui/src/dialogs/svg_options.rs b/crates/ui-egui/src/dialogs/svg_options.rs index a19a5160fc..e9fc5a9794 100644 --- a/crates/ui-egui/src/dialogs/svg_options.rs +++ b/crates/ui-egui/src/dialogs/svg_options.rs @@ -1,5 +1,5 @@ //! SVG Options (Export As SVG, Save As / Save a Copy to .svg): profile, styling, fonts, images, -//! object ids, decimals, encoding, minify, responsive, embedded fonts, artboards (export) or +//! object ids, decimals, encoding, units, minify, responsive, embedded fonts, artboards (export) or //! editing data (save), and a read-only view of the code. OK remembers the choices for next time and runs the export or save command with //! them as `svg: {…}`. Show in Browser (`file.export.svg.browser`) writes the SVG the choices give //! to a temporary folder and opens it in the default browser, leaving the dialog open. @@ -56,6 +56,8 @@ const IMAGES: [(&str, &str); 2] = [("embed", "Embed"), ("link", "Link")]; const OBJECT_IDS: [(&str, &str); 3] = [("layerNames", "Layer Names"), ("minimal", "Minimal"), ("unique", "Unique")]; const PROFILES: [(&str, &str); 2] = [("svg11", "SVG 1.1"), ("tiny12", "SVG Tiny 1.2")]; const ENCODINGS: [(&str, &str); 3] = [("utf8", "Unicode (UTF-8)"), ("utf16", "Unicode (UTF-16)"), ("latin1", "ISO 8859-1")]; +const UNITS: [(&str, &str); 6] = + [("document", "Document"), ("px", "Pixels"), ("pt", "Points"), ("mm", "Millimeters"), ("cm", "Centimeters"), ("in", "Inches")]; /// Dialog fields that are not SVG options. const UI_KEYS: [&str; 5] = ["mode", "path", "showCode", "allArtboards", "range"]; @@ -72,11 +74,12 @@ pub(crate) struct SvgCodeKey { selected: Option>, } -/// The options a first SVG Options dialog starts from: the engine's defaults with Internal CSS -/// and Responsive on (as the reference app's Export As starts). Hidden layers are left to the -/// command (Save keeps them, Export leaves them out). +/// The options a first SVG export starts from: the engine's defaults with Pixels, +/// Internal CSS and Responsive on. Saves choose Document unless a remembered unit overrides it. +/// Hidden layers are left to the command (Save keeps them, Export leaves them out). pub(super) fn first_use() -> Map { - let mut m = serde_json::to_value(vectorcraft_svg::ExportOptions::default()).ok().and_then(|v| v.as_object().cloned()).unwrap_or_default(); + let opts = vectorcraft_svg::ExportOptions { units: Some(vectorcraft_svg::SizeUnit::Px), ..Default::default() }; + let mut m = serde_json::to_value(opts).ok().and_then(|v| v.as_object().cloned()).unwrap_or_default(); m.remove("hiddenLayers"); m.insert("styling".into(), json!("css")); m.insert("responsive".into(), json!(true)); @@ -109,6 +112,10 @@ pub(crate) fn open_with(app: &mut VectorcraftApp, mode: Mode, path: Option<&str> fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone()))); } } + if mode != Mode::Export && saved.as_ref().unwrap_or(&app.ui.svg_options).get("units").is_none() { + // A document's legacy SVG options must not inherit Pixels from the last export. + fields.insert("units".into(), json!("document")); + } fields.insert("allArtboards".into(), json!(true)); fields.insert("range".into(), json!("")); if let Some(p) = path { @@ -146,7 +153,7 @@ fn pairs(key: &str, label: &'static str, choices: &[(&str, &'static str)]) -> Pa /// responsive, ``s and metadata. `screens` (Export for Screens' Format Settings) leaves out /// Images and Variable Data: a linked image is another file. `tiny`: SVG Tiny has presentation /// attributes alone and no web fonts. -pub(crate) fn svg_params(screens: bool, tiny: bool) -> Vec { +pub(crate) fn svg_params(mode: Mode, screens: bool, tiny: bool) -> Vec { let styling = pairs("styling", tl!("Styling:"), &STYLING); let fonts = ParamKind::radio(FONTS.iter().map(|(v, l)| ((*v).to_string(), tl!(*l).into())).collect(), Some("false".into())); let (lo, hi) = (*vectorcraft_svg::DECIMALS.start() as f64, *vectorcraft_svg::DECIMALS.end() as f64); @@ -161,6 +168,9 @@ pub(crate) fn svg_params(screens: bool, tiny: bool) -> Vec { rows.push(pairs("objectIds", tl!("Object IDs:"), &OBJECT_IDS)); rows.push(Param::number("decimals", tl!("Decimal:"), 3.0, 1.0, 0).bounds(Some(lo), Some(hi))); rows.push(pairs("encoding", tl!("Encoding:"), &ENCODINGS)); + // Responsive omits width and height, so the unit has nothing to act on. + let units = if mode == Mode::Export { &UNITS[1..] } else { &UNITS[..] }; + rows.push(pairs("units", tl!("Units:"), units).enabled_when("responsive", false)); rows.push(check("minify", tl!("Minify"), false)); rows.push(check("responsive", tl!("Responsive"), true)); // Embedded fonts need SVG 1.1 and text that stays text. @@ -189,7 +199,7 @@ fn artboard_rows(count: usize) -> Vec { /// Every row of the dialog for `mode`. Export Selection writes the selection's crop, without /// artboards to choose. fn dialog_params(mode: Mode, selection: bool, count: usize, tiny: bool) -> Vec { - let mut rows = svg_params(false, tiny); + let mut rows = svg_params(mode, false, tiny); match mode { Mode::Export if !selection => rows.extend(artboard_rows(count)), Mode::Export => {} @@ -211,6 +221,9 @@ fn options(mode: Mode, f: &DialogFields) -> Value { let tiny = f.text("profile") == Some("tiny12"); let mut o = json_of(&dialog_params(mode, false, 1, tiny), f); o.retain(|k, _| !UI_KEYS.contains(&k.as_str()) && !k.starts_with("__")); + if o.get("units").and_then(Value::as_str) == Some("document") { + o.remove("units"); + } if mode == Mode::Export { o.remove("preserveEditing"); if f.bool("useArtboards").unwrap_or(false) { @@ -663,6 +676,77 @@ mod tests { assert_eq!(fields(&app).number("decimals"), Some(1.0)); } + #[test] + fn svg_options_write_and_remember_units_and_decimals() { + let (mut app, written) = app(); + start(&mut app, Mode::Export, "/tmp/out.svg", false); + set(&mut app, "responsive", json!(false)); + set(&mut app, "units", json!("mm")); + set(&mut app, "decimals", json!(1)); + confirm(&mut app); + let svg = text(&written, 0); + assert!(svg.contains("mm\"") && svg.contains("viewBox=\"0 0 120 80\""), "{svg}"); + assert_eq!(app.ui.svg_options["decimals"], 1); + start(&mut app, Mode::Export, "/tmp/out.svg", false); + assert_eq!(fields(&app).text("units"), Some("mm")); + set(&mut app, "responsive", json!(true)); + confirm(&mut app); + let svg = text(&written, 2); + assert!(!svg.contains("mm\"") && svg.contains("viewBox=\"0 0 120 80\""), "{svg}"); + } + + #[test] + fn legacy_svg_saves_keep_document_units() { + for mode in [Mode::Save, Mode::SaveCopy] { + for last in [json!({"responsive": false}), json!({"responsive": false, "units": "px"})] { + let (mut app, written) = app(); + let original = std::env::temp_dir().join("vc-original.svg").to_string_lossy().replace('\\', "/"); + let path = std::env::temp_dir().join("vc-saved.svg").to_string_lossy().replace('\\', "/"); + app.run("document.setUnits", json!({"units": "millimeters"})).unwrap(); + app.run("file.saveAs", json!({"path": original, "svg": {"responsive": false}})).unwrap(); + let before = vectorcraft_svg::import(&text(&written, 0)).unwrap(); + app.ui.svg_options = last; + start(&mut app, mode, &path, false); + confirm(&mut app); + let after = vectorcraft_svg::import(&text(&written, 1)).unwrap(); + assert_eq!(after.units, vectorcraft_doc::Unit::Millimeters, "{mode:?}: {}", text(&written, 1)); + let (a, b) = (before.artboards[0].rect, after.artboards[0].rect); + assert!((a.width() - b.width()).abs() < 1e-6 && (a.height() - b.height()).abs() < 1e-6, "{mode:?}: {a:?} -> {b:?}"); + let expected = if mode == Mode::SaveCopy { &original } else { &path }; + assert_eq!(app.session.active().unwrap().path.as_deref(), Some(expected.as_str())); + } + } + } + + #[test] + fn svg_saves_keep_explicit_units_and_allow_pixel_overrides() { + for mode in [Mode::Save, Mode::SaveCopy] { + let (mut app, written) = app(); + let path = std::env::temp_dir().join("vc-explicit.svg").to_string_lossy().replace('\\', "/"); + app.run("document.setUnits", json!({"units": "millimeters"})).unwrap(); + app.run("file.saveAs", json!({"path": path, "svg": {"responsive": false, "units": "in"}})).unwrap(); + app.ui.svg_options = json!({"responsive": false, "units": "px"}); + start(&mut app, mode, &path, false); + confirm(&mut app); + assert_eq!(vectorcraft_svg::import(&text(&written, 1)).unwrap().units, vectorcraft_doc::Unit::Inches); + start(&mut app, mode, &path, false); + set(&mut app, "units", json!("px")); + confirm(&mut app); + assert_eq!(vectorcraft_svg::import(&text(&written, 2)).unwrap().units, vectorcraft_doc::Unit::Pixels); + } + } + + #[test] + fn svg_export_keeps_pixels_when_legacy_options_omit_units() { + let (mut app, written) = app(); + let path = std::env::temp_dir().join("vc-export.svg").to_string_lossy().replace('\\', "/"); + app.run("document.setUnits", json!({"units": "millimeters"})).unwrap(); + app.ui.svg_options = json!({"responsive": false}); + start(&mut app, Mode::Export, &path, false); + confirm(&mut app); + assert_eq!(vectorcraft_svg::import(&text(&written, 0)).unwrap().units, vectorcraft_doc::Unit::Pixels); + } + /// OK with a range the document lacks keeps the dialog open with the reason, writes nothing and /// remembers nothing. #[test] diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 26ae1ec4f1..fefe9f05aa 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -2215,7 +2215,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.livePaintGapOptions", "Gap Options…", "", - "{} open Gap Options (Object › Live Paint › Gap Options…; dialog `livePaintGapOptions`: detect, size small|medium|large|custom, custom (pt), color (#rrggbb or a layer color's name), closeGaps, preview) on the selected Live Paint groups, filled in from the first; with preview on, the options apply live and the gaps found draw on the canvas in the preview color: OK runs livePaint.gapOptions as one undo step; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing, and with preview on a #rrggbbaa color is not previewed: the groups keep their own color and the gaps draw in black", + "{} open Gap Options (Object › Live Paint › Gap Options…; dialog `livePaintGapOptions`: detect, size small|medium|large|custom, custom (pt), color (#rrggbb or a layer color's name), closeGaps, preview) on the selected Live Paint groups, filled in from the first; with preview on, the options apply live and the gaps found draw on the canvas in the preview color: OK runs livePaint.gapOptions as one undo step; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing, and with preview on a #rrggbbaa color is not previewed: the groups keep their own color and the gaps draw in black; a preview that fails shows its error in the status bar, puts the groups back as they were and stops drawing the dialog's preview of the gaps (View › Show Live Paint Gaps still draws the restored groups' own gaps)", ), ( "ui.perspectivePlane", diff --git a/crates/ui-egui/src/tests/quickpenwheel.rs b/crates/ui-egui/src/tests/quickpenwheel.rs index 8ea861c12a..66799faf6d 100644 --- a/crates/ui-egui/src/tests/quickpenwheel.rs +++ b/crates/ui-egui/src/tests/quickpenwheel.rs @@ -293,6 +293,7 @@ fn a_touchpad_steps_once_per_wheel_line() { // test-lint: allow never-run touchpad gesture phases reach the app only on macOS #[cfg(target_os = "macos")] #[test] +// test-lint: allow never-run egui reports touchpad gesture phases only on macOS fn keys_held_during_a_touchpad_gesture_count_until_it_ends() { let mut app = app(); on_canvas(&mut app, |rig| { diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 75f47d7a1c..a38623c2fe 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -2,6 +2,8 @@ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (`.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where several copies share its PostScript name, follows #6983; scores and estimates unchanged; previously: EPS import: images over 67 million pixels are read at a lower resolution; `.ai` import: a stroke's arrowheads, the symbols its style names, come in as custom arrowheads with their tip on, or past, the path's end, as the drawn art places it, and the line stopping where the symbol's sample of it ends, #8188; PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group instead of reading as nested clipping groups that clip nothing or stop the editing data from being read; previously: PDF import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF export writes the document language as the catalog's `/Lang`, #3644; PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) > +> SVG Options can write physical dimensions with Responsive off and a physical unit selected (#4462); pixel output remains bare numbers. +> > **File-font integration status (2026-11-19, #4569):** 56 focused PDF/native-reopen, file-font, stroked-text and font-binding tests passed on the current-main integration candidate. Full workspace CI and hardening paths outside those suites remain pending. Scores and estimates unchanged. > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). @@ -366,7 +368,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CIDFonts the file doesn't carry not drawn, but for those over a predefined CMap (`UniJIS-UCS2-H`, `90ms-RKSJ-H`, `GBK-EUC-H`, `KSCms-UHC-H`, `ETen-B5-H`), set as type in the font of the CIDFont's name, vertical over a `-V` CMap; a name that ends in the row-and-cell CMap `H` or `V` splits off the CMap only when the file defines the CIDFont of that name, the CIDFont is `Ryumin-Light` or `GothicBBB-Medium` (the Japanese CIDFonts a printer carries), or the name has a hyphen and an installed face that covers Japanese has it; name-keyed fonts in a FontSet set as type by name; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); an embedded Type 1 font's encrypted part is read for its glyphs, which space its type, outline it and draw glyphs without a character, in plain and composite fonts; a Type 42 font that carries its TrueType font gives each code its character by its glyph name or, for names that say nothing (`/g12`), by the glyph's entry in the font's own character map, spaces its type by its own widths and draws glyphs that stand for no character from its outlines; the show operators' spacing along the baseline (`ashow`, `widthshow`, `xshow`, `yshow`, `xyshow`, and the moves of `kshow`'s procedure, run between each two characters) is kept on live type as tracking, so type in a font that isn't installed keeps the file's line lengths (spacing that moves characters off the baseline, as `yshow`, `xyshow` or a `kshow` procedure can, places each character as its own text object); composite (Type 0) fonts with the 8/8 mapping, as PDF-to-PostScript converters write two-byte fonts, draw a Type 42 descendant's glyphs from the TrueType outlines it carries and an embedded Type 1 descendant's from its charstrings, and set other descendants' characters as type at the composite font's size (other mappings are still set as type in the font of their name); CID-keyed fonts (`composefont`, `FMapType` 9 over a CMap built with the CIDInit operators or `Identity-H`/`Identity-V`; `bfchar` and `bfrange` mappings give a base-font descendant its codes or glyph names) draw the glyphs of the Type 0 CIDFonts (Type 1 charstrings in their `StartData` binary data or `GlyphDirectory`) and Type 2 CIDFonts (TrueType glyphs through `CIDMap`) they carry, and the CID-keyed fonts of a FontSet's Compact Font Format data (Type 2 charstrings); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); an image of more than 2^26 pixels is read at a lower resolution (every second, third… sample of every second, third… row), not left out, with a note; when its data is more than the reader holds, Flate or LZW compressing it last (without a predictor) is decoded keeping only the rows read; sampled functions (type 0) interpolate between their samples, multilinearly or by cubics with `Order 3`, and a sampled axial or radial gradient has a stop at each sample; a gradient the page paints as a row of abutting one-colour strips (as Level 2 writers draw smooth shades) imports as one linear gradient, without the seams the strips leave when each is drawn alone; CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | DCS 1.0 / 2.0 | place linked | place linked only (one image of the plates; spot plates as spot swatches; the composite's clipping path; each plate on its own ink in Separations Preview and print separations) | no | `crates/eps/src/dcs/tests.rs`, `crates/engine/src/tests/dcs.rs` | -| SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as ``, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`); a masked group, or a knockout group's masked group, whose content has a shadow, glow, blur or feather starts with a hidden, unpainted rectangle over the mask's region, so readers that draw a masked group only inside the box of its shapes draw those effects too (`crates/svg/tests/it/blend_export.rs`); SVG Options › Include Variable Data writes the text variables, data sets and bound type objects, and opening the SVG reads them back (`tests::variables::an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings`) | +| SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as `<title>`, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`); a masked group, or a knockout group's masked group, whose content has a shadow, glow, blur or feather starts with a hidden, unpainted rectangle over the mask's region, so readers that draw a masked group only inside the box of its shapes draw those effects too (`crates/svg/tests/it/blend_export.rs`); SVG Options › Include Variable Data writes the text variables, data sets and bound type objects, and opening the SVG reads them back (`tests::variables::an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings`); SVG Options › Units writes `width` and `height` in px (bare numbers, the default), pt, mm, cm or in, the `viewBox` staying in points, for software that reads physical size such as LaserGRBL (#4462, `crates/svg/tests/it/roundtrip.rs`) | | DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open | | HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines; Export As opens HP-GL Options) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | | DWG | open, export | no | no | no open spec; DXF instead | @@ -465,6 +467,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | 2026-11-11 | minor | Native and Preserve Editing restores keep an existing File Info title exactly, including repeated spaces; imported-text fallback titles alone are normalized (#3626). | | 2026-11-07 | minor | EPS import: an image of more than 2^26 pixels (the reader's cap) was left out, so a page that is one large scan or photo came in empty. It is now read at a lower resolution: the least whole step that brings it within the cap, the middle sample of each step × step block, over the image's whole area, with the note *images of more than 67 million pixels were read at a lower resolution*. When its samples are more data than the reader holds (256 MB), an image whose last filter is Flate or LZW without a predictor is decoded a row at a time, keeping only the rows read (an 11903 × 8423 RGB page, 300 MB, comes in at 5952 × 4212). An image left out still has its data skipped (#6003), now also when a procedure reads it (called until it has given the image's data or ends) and when its first filter decompresses to more than the reader holds (the compressed data is measured without keeping it). Tests `an_image_over_the_pixel_cap_is_read_at_a_lower_resolution`, `an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads`, `the_data_of_an_image_too_large_to_hold_is_skipped`; scores unchanged | | 2026-11-03 | minor | An imported document's own title goes into File Info only (#3626): an SVG's root `<title>`, a PDF's, `.ai`'s or `.ait`'s XMP `dc:title` else its Info `Title` is File Info's title (`metadata.title` in the native format, left out when unset so other documents save unchanged and older versions ignore it; written by exports); the document's name, which the tab, Save As and the default export names use, stays the file's name. | +| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for the `width` and `height` an export writes, so laser and plotter software read the physical size (#4462; the `units` option, Pixels still bare numbers as before); scores and estimates unchanged | | 2026-11-11 | minor | `.ai` and EPS import, and what the canvas, every export and `.ai` save draw: type's strokes in an envelope (its characters' and those on its own appearance) paint along the bent glyph outlines at their own weight, Distort Appearance on or off, as the drawn art of users' `.ai` files strokes them (used locally, never committed: there the drawn art keeps those strokes as stroked paths at the type's own weights, and its ring is as wide wherever the grid squeezes or stretches the type). With Distort Appearance, VectorCraft bent them with the art, as their filled outlines, so an envelope of stroked type in a squeezed or stretched grid didn't draw as its drawn art and kept it. The same holds in an envelope inside an envelope. Paths' strokes, geometry effects, opacity masks, linear gradients and pattern fills bend as before. On 224 of our own files: envelopes of type that open live go from 135 in 37 files to 154 in 45, and no file loses one; no file changes whether it opens from its layers or its PDF part; renders at 40 ppi change in 31 files, by at most 2.3% of their pixels, 19 closer to the file's own page and 12 further, 11 of those where an envelope of type now opens live in place of its drawn art (the page's own art) and one by 4 pixels. Tests `envelope_distort::type_strokes_paint_at_their_own_weight_in_a_squeezed_envelope`, `a_stroke_on_types_appearance_paints_at_its_own_weight_in_a_squeezed_envelope`, `a_paths_stroke_still_bends_in_a_squeezed_envelope`, `tests_native::an_envelope_of_stroked_type_whose_drawn_art_strokes_the_bent_outlines_at_the_weight_opens_live` (#6644) | | 2026-11-11 | minor | Ordinary Save to a location refusing writes offers Save As (#6146); cancellation preserves the original path and modified state; automation receives READ_ONLY_LOCATION. Scores and estimates unchanged. Validation pending. | | 2026-11-11 | minor | `.ai` and EPS import, and what SVG export, PDF export and `.ai` save draw: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as a `.ai`'s own page aligns them (see type-parity.md, same date). In 224 users' files (used locally, never committed), 63 render differently: 54 closer to the page, 7 further, 1 alike and 1 that couldn't be compared; among them the median share of pixels that differ from the page went from 4.4% to 1.0%. Of the 7: one now opens from its layers instead of its PDF part (they differ from the page by less than the import's 5% limit now; type note 3.8%); one has a centred line whose spacing inside it differs from the page's, which now centres on the page's line while half of it no longer lies on the page's glyphs (type note 1.4% to 2.4%); five moved by less than 0.05 of a percentage point, in type the page draws in other glyphs. The type note shows a smaller share in 6 files; 2 more envelopes of type open live (129 to 131, none fewer in any file). SVG import: `text-anchor` aligns a line's advance, which ends after its last character's letter spacing, so a centred or right-aligned letter-spaced line moves back by half or all of it and stays where a reader draws it; SVG export, which anchors lines so, reads back unchanged (test `import_text::anchored_letter_spaced_lines_stay_where_a_reader_draws_them`). Affinity import: centred or right-aligned tracked artistic text moves by half or all of its last character's tracking, as layout now aligns it (unverified against Affinity, whose files we don't have), and differently aligned paragraphs line up by the widths layout aligns them by (`affinity_features::artistic_text_aligns_its_lines_within_the_longest`). Scores and estimates unchanged. (#6610) | diff --git a/docs/gaps.md b/docs/gaps.md index a98c869e44..d9c3209967 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -37,6 +37,8 @@ Actions panel item context menus (2026-11-20): Right-clicking an Action Set row Appearance panel row context menus (part of G12): right-clicking stroke and fill rows offers Duplicate Stroke / Duplicate Fill, Delete Stroke / Delete Fill, and Hide Stroke/Show Stroke / Hide Fill/Show Fill; effect rows offer Edit Effect…, Duplicate Effect, Delete Effect, and Hide Effect / Show Effect; the root object row offers Clear Appearance and Reduce to Basic Appearance. Right-clicking an unselected row targets that row before presenting the menu. Item actions run in one undo step. Evidence: `panels::tests_appearance::right_clicking_a_stroke_row_selects_it_and_exposes_context_menu`, `panels::tests_appearance::clicking_duplicate_stroke_duplicates_the_stroke_with_one_undo_step`, `panels::tests_appearance::clicking_delete_effect_removes_the_effect_from_appearance`, and `panels::tests_appearance::right_clicking_root_object_row_exposes_clear_and_reduce_appearance` in `crates/ui-egui/src/panels/tests_appearance.rs`. Scores and estimates unchanged. +> SVG Options can write physical dimensions with Responsive off and a physical unit selected (#4462); pixel output remains bare numbers. + Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. **2026-11-19 revision:** merged main while preserving the private raster-editor choice; no parity rescore. @@ -469,6 +471,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi such stubs into one vertex (within 4× the sweep's tolerance up and down its frame and 1/16 of the 0.01 pt precision along it, bounded by each cluster's extent so a run of tiny level segments keeps its length); regression tests in `crates/pathops/src/planar.rs`. Estimate unchanged. +- **Done (2026-11-03):** SVG Options › Units (`units`) explicitly overrides `width` and `height` with `px` + (bare numbers; CSS pixels are 96 per inch), `pt`, `mm`, `cm` or `in`, with the `viewBox` in points (#4462). + Responsive omits both dimensions; unknown units and explicit null are errors. Without an override, export + retains the document's physical units as below. Estimate unchanged. - **Done (#864):** SVG export writes physical unit suffixes on the root `<svg width="..." height="...">` for documents with physical units (`mm`, `cm`, `in`, `pc`; documents in feet and yards are written in `in`, in meters in `cm`, and in Q or Ha in `mm`, since SVG has no unit for them: `every_physical_document_unit_exports_its_printed_size`), so external vector tools (Inkscape, LightBurn) and browsers render drawings at their intended physical scale rather than scaling to 75% under point-based user-unit assumptions; unitless user coordinates in `viewBox` and path geometry remain in 1:1 internal points per SVG 1.1 coords §7.10. A round trip keeps `mm`, `cm`, `in` and `pc` documents in their unit (`export_physical_units_writes_unit_suffixes`, `svg_round_trip_preserves_document_units`); documents in feet, yards, meters, Q or Ha keep their printed size and open again in the SVG unit they were written in. General document unit preferences across restarts remain tracked under #864. - **Missing:** general document unit preference on restart (#864; SVG export physical units done). Shape Builder regions (#937, closed), PDF text placement (#722, above), the bezier drag preview (#834, #3065, #3729) and deleting an interior anchor of an open path (above) @@ -1116,6 +1122,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | 2026-11-05 | minor | G15: a document's first frame renders on the render worker (#4155); the longest UI-thread stall opening that file went from 8.7 s to 64 ms. Estimate unchanged. | | 2026-11-05 | minor | G15: a reduced image is shrunk before it is separated into ink planes (#4155); first frame 9.2 s → 1.6 s, sharp frame after a pan 3.9 s → 8 ms on that file. Estimate unchanged. | | 2026-11-05 | minor | G7: document tabs are dragged along the tab strip to reorder them (`document.move`, #5663). Estimate unchanged. | +| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for the `width` and `height` an export writes, so laser and plotter software read the physical size (#4462; the `units` option, Pixels still bare numbers as before; to export physical dimensions turn Responsive off and choose Points, Millimeters, Centimeters or Inches, since Responsive omits `width` and `height`); scores and estimates unchanged | | 2026-11-03 | minor | Symbol editing shows draggable 9-slice guides within the artwork (#5280). Guides outside the artwork remain unsupported. The G5 estimate remains 14–24 h. | | 2026-11-02 | minor | G15: the renderer keeps a compound path's assembled path between frames and drops unused geometry entries after a few frames however few there are. Estimate unchanged. | | 2026-11-02 | minor | G15: hit testing culls paths and compound paths by their control points' box and tests a compound path's outline and fill against only its members near the click; the same objects are hit. Estimate unchanged. | @@ -1326,4 +1333,4 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv ## EPS Save evidence (2026-10-26) Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transparent margins and the complete editable VectorCraft document. Existing import-loss confirmation and transparency warnings remain; the Save TIFF preview is capped at 1024 pixels, while Export retains 2048. See [file-format-parity.md](file-format-parity.md#eps-save-and-source-protection) for limits and regression evidence. This narrows G9 save-back workflow coverage; native Illustrator editing-data fidelity, parity scores and hour estimates are unchanged. Since 2026-11-12 the EPS Options of Save As show Use Artboards, unchecked by default: unchecked, the bounding box fits the visible art; checked, Save keeps the chosen page frame and margins described here. -> **Swatches status (2026-11-15):** Item context menus are implemented and covered by headless tests; full CI passed on the latest-main integration (all 13 gates), including the updated panel-view harness; parity scores and estimates are unchanged. +> **Historical Swatches proof (2026-11-15):** Item context menus were implemented and covered by headless tests; all 13 CI gates passed on the integration tested then, including the updated panel-view harness. This is not validation of the current merge; parity scores and estimates are unchanged. diff --git a/docs/mcp.md b/docs/mcp.md index b84a50c2b8..3c6f463196 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1355,7 +1355,7 @@ a script does the same with those commands. SVG Options: `export` to SVG takes them in `options`, flat or as `{"svg": {…}}`: `styling` (`presentation`, `style`, `entities`, `css`), `outlineText`, `images` (`embed`, or `link`: embedded images are written next to the SVG, or returned as `linked`), `objectIds` (`layerNames`, `minimal`, `unique`), `decimals` (1–7), `minify`, -`responsive`, `useArtboards`, `range: "all"` (one SVG per artboard, listed in `files`, each holding only the art over its artboard), `preserveEditing` (the SVG +`responsive`, `units` (`px`, `pt`, `mm`, `cm` or `in`: overrides the document unit for `width` and `height`; omit to retain the document unit, explicit null is rejected; `px` means bare numbers, the `viewBox` stays in points; ignored with `responsive`), `useArtboards`, `range: "all"` (one SVG per artboard, listed in `files`, each holding only the art over its artboard), `preserveEditing` (the SVG reopens as the full document), `metadata` and `fewerTspans` (one `<tspan>` per line of type). Unknown keys inside `svg` are rejected; `run_command document.formats` lists every option with its default. `encoding` is `utf8`, `utf16` (big-endian after a byte order mark) or `latin1` (ISO 8859-1, other characters as `&#x…;` references); `document.serialize` still answers `text`, plus `dataBase64` @@ -6162,7 +6162,9 @@ already walks Image Trace. Short agent entry points: When `livePaint.gapOptions` or `livePaint.merge` cuts an edge into pieces, each piece takes the edge's paint, with its rows fitted to its part of the edge in the same way. A face or edge given no such row has one unpainted row. Rows that do not draw stay with the stored sources, which `livePaint.release` returns unchanged. The source's object effects and the strokes' pen pressure are not carried. - Expand keeps those face fills. + Expand keeps those face fills. Make, Merge and Gap Options stop with an error and leave the art unchanged when the + paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where + they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. The paths include lines across the gaps when Gap Detection is on. `livePaint.expand` keeps each face and edge that draws, with all its fill and stroke rows: it is shown, its opacity is above 0, and a fill or stroke row is shown, has paint and an opacity above 0 (a stroke also a weight above 0), whichever row is on top. A painted lower row under an unpainted top row keeps the part; a part whose only painted @@ -6186,7 +6188,9 @@ already walks Image Trace. Short agent entry points: when another merged group has it on. When Gap Detection is off in every merged group, it stays off. The Gap Options dialog (`ui.livePaintGapOptions`) takes `color` as `#rrggbb` or a layer color's name; its OK gives an error for a `color` with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. With Preview on, a - `#rrggbbaa` color is not previewed: the groups keep their own color, and the previewed gaps draw in black. + `#rrggbbaa` color is not previewed: the groups keep their own color, and the previewed gaps draw in black. When a + preview fails, the status bar shows the error, the groups go back to how they were, and the dialog stops drawing its preview of the gaps. View › Show Live Paint Gaps still draws the restored + groups' own gaps. `view.livePaintGaps` (View › Show Live Paint Gaps, or Hide Live Paint Gaps while it is on) turns the drawing of those gaps on or off. While it is on and edges show, the canvas draws the gaps of each selected Live Paint group in that group's Gap Preview Color. The reply is the new state (`true` when on). @@ -7763,8 +7767,10 @@ Pathfinder command (`object.pathfinder.unite` … `minusBack`) also takes `preci whatever the options are then. Unite, Minus Front, Intersect, Exclude and Minus Back close open paths, so a straight line encloses no area and does not change the result's shape. When a selected object is or holds such a path, the reply's `warning` says so and names Object › Path › Outline Stroke. When such a path leaves the result empty (Intersect, a line -at the back in Minus Front, or a line in front in Minus Back), the error says so too. - +at the back in Minus Front, or a line in front in Minus Back), the error says so too. Divide with open paths among +the objects stops with an error and leaves the art unchanged when the paths are too many or too complex to map. +This happens when the paths Divide maps, as it prepares them from the selection, have more than 65,536 segments, have more than 131,072 pieces once cut where +they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. ```json {"name":"run_command","arguments":{"command":"object.pathfinder.options","params":{"precision":0.1,"removeUnpainted":true}}} ``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c9dfd4b596..aa49d934ac 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -15,6 +15,8 @@ Native saves on Unix flush the destination directory after writing or replacing > > Glyphs update (#5514): Alternates for Current Selection applies a variant's OpenType feature to that letter alone (`salt=2`) so an Arabic word stays joined; Entire Font lists unencoded glyphs. A positional variant no supported feature draws can be applied as a glyph choice (#6084). Entire Font uses the selection's font version and variable axes, and the default cell remains available after an unlisted choice even without GSUB alternates. Only Arabic presentation-form characters insert their joining base letter. Scores and estimates unchanged. > +> SVG physical dimensions update (#5450): explicit SVG Options write width and height in mm, cm, in or pt (#4462), retaining scale independently of coordinate precision, including tiny sizes. Commands accept flat `units` or nested `svg.units`; nested values win and explicit null is rejected. Without an override, export retains the document's units (#864). Responsive omits dimensions; explicit Pixels keeps bare numbers and CSS pixels are 96/in. Scores and estimates unchanged. +> > **File-font integration status (2026-11-19, #4569):** 56 focused integration tests passed, including wrapped carried-font paragraphs and conflicting glyphs through native reopen. Full workspace CI and other hardening paths remain pending. Type core and file-format scores and estimates unchanged. See [file-font ownership evidence](file-format-parity.md#file-font-ownership-hardening-4569). > > Live Paint Bucket update (2026-11-12): one drag fills the faces crossed in the same group (#6373). @@ -1828,7 +1830,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Outline Stroke, Expand's Stroke option and Flatten Transparency's Convert All Strokes to Outlines apply the object's visible geometry effects (Offset Path, Zig Zag and the others) to the path, and then apply each stroke's own geometry effects before outlining that stroke, as the canvas draws it. The filled outline of a stroke without a brush keeps the stroke's other effects, such as a drop shadow. Outline Stroke and Unite remove the overlaps of a long, low path with the sweep turned along it: when the estimated number of segments the sweep holds at once is under two thirds as large for the path turned a quarter turn (paths of 2,048 segments or more), the overlaps are removed on the turned path and the result is turned back, which moves no point by rounding. The lookups of the input curve that a piece of the result lies on, and of the input anchors that are kept, can search along y instead of x: once lookups with more than 64 candidates along x have counted 16 for each input curve or anchor, a lookup searches along y when it finds fewer candidates there (under a quarter as many for curves), and where that has rarely happened it measures along y in only one lookup of 32. On one open path of 200,000 anchors in rows of 1,000, Outline Stroke takes 17.3 s of processor time instead of 31.3 s and Unite 2.9 s instead of 6.5 s in a release build. A turned result has as many subpaths as the result without the turn, and the area where the two differ is no larger than the refit precision times the outline's length (`crates/pathops/src/sweep_axis.rs` tests). Offset Path turns the sweep the same way: when the estimate for its fill, the ring stroked around the fill and the outline of its open subpaths is under two thirds as large turned a quarter turn, the faces are found on the turned parts, the faces that lie within the offset distance of the path are dropped by testing their points turned back, and the result is turned back. On an open path of 10,000 anchors in rows of 1,000, offsetting by 2 pt takes 1.0 s of processor time instead of 1.8 s in a release build. The offset of a long, low path has as many subpaths as the offset of the same path stood on end, and the area where the two differ is no larger than the refit precision times the outline's length (`offset_path_sweeps_a_long_low_path_turned_with_the_result_of_the_path_on_end`). - - Divide uses open lines, bent paths and curves as cutting edges (#1307), preserving the frontmost filled face's appearance and holes. Engine tests cover implicit closure of filled open contours and unrelated objects; native automation confirms independent piece movement, one Undo/Redo, canvas/window captures and an exact saved-document read by a separate CLI process. The shared planar map keeps a segment cap (65,536 since #937, was 4,096) and its filled-area fallback; other Pathfinder operations are unchanged. + - Divide uses open lines, bent paths and curves as cutting edges (#1307), preserving the frontmost filled face's appearance and holes. Engine tests cover implicit closure of filled open contours and unrelated objects; native automation confirms independent piece movement, one Undo/Redo, canvas/window captures and an exact saved-document read by a separate CLI process. Divide with open paths stops with an error and leaves the art unchanged when the paths are too many or too complex to map. This happens when the paths it maps, as it prepares them from the selection, have more than 65,536 segments (since #937, the cap was 4,096), have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. Other Pathfinder operations are unchanged. - Type that Transform effects only move and copy (no scale, rotation, reflection or Random) exports as type in each place, and PDF export writes every copy as selectable, searchable text, when its characters are in solid colors without underline or strikethrough, the type object has no fills or strokes of its own, no inline graphics and no perspective, its transform does not scale or shear stroked characters, and the copies do not overlap. When the effect is on the type itself, the type can also have transparency, an opacity mask and raster effects. When the effect is on the group or layer holding the type, the type has no transparency or effects of its own and is not in a clipping path, the group or layer has no fill, stroke or Pathfinder effect of its own, and no group between them has a fill, stroke, Pathfinder or geometry effect. Type still exports as outlines when the effect stops its copies early, or when the copies would number more than 10,000 or take more than 20,000,000 bytes of document data, and so does other type under a geometry effect. - Extrude & Bevel and Inflate treat strokes as outlined: each visible stroke builds a solid from its outline in its own paint beside the top fill's ([three-d.md](three-d.md#fills-and-strokes)). - A 3D effect on one fill or stroke ([the help page](https://helpx.adobe.com/illustrator/using/effects.html)) leaves the object's other fills and strokes drawn with the path's or compound path's fill rule, so an even-odd compound path keeps its holes in them; this holds for Extrude & Bevel, Inflate, Rotate and Revolve, and for the Classic Extrude & Bevel, Rotate and Revolve. Tests: `solids::tests::a_fill_or_stroke_without_the_effect_keeps_the_even_odd_hole`, `revolve::tests::a_fill_without_the_revolve_keeps_the_even_odd_hole`. @@ -2108,7 +2110,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Live Paint Make preserves the front-most covering source's fill when compound paths share a curved boundary, and Expand keeps the face fills. Regression evidence: `planar::tests::coincident_curves_keep_their_source_faces` checks source order, winding, fill rules and nearby boundaries; `tests::build::live_paint_make_and_expand_keep_abutting_compound_colors` checks native compound paths, Make, Expand and Undo/Redo. This preserves VectorCraft's source-fill rule without changing arrangement precision. Object › Live Paint › Expand keeps the faces and edges that draw on the canvas, with all their fill and stroke rows, so the expanded paths look as the painted group did ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)). As VectorCraft's own rule, a face or edge draws when it is shown, its opacity is above 0, and any of its fill or stroke rows is shown, has paint and an opacity above 0 (a stroke also needs a weight above 0), whichever row is on top: a painted lower row under an unpainted top row is kept, and a part whose only painted row is hidden is removed. Merge copies the fill and stroke rows, visibility, opacity and blending mode of each face that draws by this rule, and of each edge, to the rebuilt parts, with their gradients kept at their fit on the old outline and without the strokes' pen pressure, tilt, bearing and rotation. Evidence: `tests::build::{live_paint_expand_keeps_the_faces_and_edges_that_draw, live_paint_merge_carries_the_faces_that_draw, live_paint_merge_leaves_pen_pressure_behind, live_paint_merge_keeps_the_fit_of_carried_gradients, live_paint_merge_keeps_the_visibility_opacity_and_blending_of_carried_parts}`. `livePaint.info` lists every fill and stroke row of each face and edge, bottom first, with its paint, opacity, visibility, weight for a stroke, and whether it draws by the rule above, beside the top fill, stroke and weight it already reported. Evidence: `tests::build::live_paint_info_lists_every_appearance_row`. - Live Paint Gap Options (Object › Live Paint › Gap Options…, `livePaint.gapOptions`): with Gap Detection on, paint stops at the gaps that run from a loose end of a path to the nearest path, up to Small (3 pt), Medium (6 pt), Large (12 pt) or a custom size; Close Gaps With Paths adds an unpainted path across each gap; Preview applies the options live and draws the gaps in the Gap Preview Color. The options are saved, copied and undone with the group, and Merge keeps the bottom group's options when its Gap Detection is on, or else turns Gap Detection on with Small when another merged group has it on. When Gap Detection is off in every merged group, it stays off. + Live Paint Gap Options (Object › Live Paint › Gap Options…, `livePaint.gapOptions`): with Gap Detection on, paint stops at the gaps that run from a loose end of a path to the nearest path, up to Small (3 pt), Medium (6 pt), Large (12 pt) or a custom size; Close Gaps With Paths adds an unpainted path across each gap; Preview applies the options live and draws the gaps in the Gap Preview Color, and a preview that fails puts the groups back and stops drawing the dialog's preview of the gaps. The options are saved, copied and undone with the group, and Merge keeps the bottom group's options when its Gap Detection is on, or else turns Gap Detection on with Small when another merged group has it on. When Gap Detection is off in every merged group, it stays off. View › Show Live Paint Gaps (`view.livePaintGaps`) draws the gaps of the selected Live Paint groups up to their Paint Stops At size, each in its group's Gap Preview Color, until Hide Live Paint Gaps or Hide Edges hides them ([Live Paint gaps](https://web.archive.org/web/20260105111201/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/find-and-close-gaps-in-live-paint-groups.html)). Double-clicking the Live Paint Selection tool opens its Tool Options ([Live Paint Selection tool options](https://web.archive.org/web/20250904012025/https://helpx.adobe.com/illustrator/using/selecting-objects.html)): with Select Fills off, a click selects an edge instead of a face; with Select Strokes off, Alt-click selects a face instead of an edge; Color and Width set the color and width of the highlight on the face or edge under the pointer (red and 4 px by default). The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintSelection"}`). As VectorCraft's own rule, OK in Live Paint Selection Tool Options, Live Paint Bucket Options, Gap Options and Tile Edge Color gives an error for a color with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. @@ -2387,6 +2389,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Save as Template always writes a file named with its template type's extension: `file.saveAsTemplate` saves a path ending in another format's extension (`card.png`) as `card.vctemplate` (or `card.ait`), the desktop save panel does the same with a Save As format's extension typed in it (`card.pdf` is saved as `card.vctemplate`), and `file.saveAs` and `document.save` refuse `ait` with an error that names `file.saveAsTemplate`. A `.ait` is PDF-compatible only: `aiVersion: "7"` is an error for it, and the web build's dialog shows no Version row for it. Exports refuse a `.ait` with an error that names `file.saveAsTemplate`, and `vectorcraft-cli convert in.pdf out.ait` and `run --export out.ait` write the template as `file.saveAsTemplate` does. - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs and the images in an `.ai` or EPS file's editing data, an alpha channel coming in as a grayscale opacity mask) to PDF export: a CMYK JPEG passes through with its compressed samples unchanged (its `ICC_PROFILE` segments are removed when `output.profiles` is `none` (except in PDF/A, and in PDF/X-3 and PDF/X-4 files that do not write CMYK colors as DeviceCMYK) and in PDF/X-3 and PDF/X-4 when they are the CMYK output intent's profile and CMYK colors are DeviceCMYK), others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4 when not in the output intent's profile) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. + - SVG Options › Units writes export `width` and `height` in px (bare numbers, the default), pt, mm, cm or in, with the `viewBox` in points (#4462). Physical dimensions require Responsive off and a physical unit; Responsive omits both dimensions. In imported PDF type, a space glyph the file draws between two words also keeps the next word where the file has it when the gap beside the space is wide, as VectorCraft's own export draws a tracked space: the space gets tracking of its own, and the wrapped lines of a justified paragraph still come back as one area type object when the word gaps on each line are alike (part of #2384). Letter-spaced PDF type, whether set with character spacing (`Tc`) or glyph by glyph, keeps its word spaces and gains none between its letters: the spacing a line's letters share is taken off each gap before a gap reads as a space. That holds on a line that also shows where its words break, with spaces the file draws or gaps wider than the rest; evenly spaced glyphs alone, which could be words of one letter, keep every gap as a space, as do glyphs set more than half an em apart, such as figures in columns. A function-based PDF shading (type 1) whose colour changes along one axis only, as a browser writes a repeating linear gradient, comes in as a linear gradient over its domain, each hard colour change two stops at one offset; one whose colour changes in two directions comes in as its average colour, with a warning. Either paints only over the shading's domain. Both came in as a flat grey that wasn't in the file (#3621). Each such shading is read once per import, and all of them within one budget of 200,000 function evaluations, so a file filling thousands of paths with long functions still opens in about a second (it took minutes); past the budget they come in as their average colour, then grey, with a warning. @@ -2401,6 +2404,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.svgz` file copied in a file manager pastes as its art, as a copied `.svg` file does. SVG export (Save As, Export As, Export for Screens, Asset Export and the clipboard share the writer) writes simple shapes as SVG basic shapes, as the reference app does (an ellipse is an `ellipse` tag until an anchor is added, [forum](https://community.adobe.com/t5/illustrator-discussions/trouble-exporting-shape-with-points-to-svg/td-p/10720325); rectangles come out as `<rect>` and `<polygon>`, [forum](https://community.adobe.com/t5/illustrator-discussions/force-svg-export-using-all-lt-rect-gt/td-p/11282378)): an axis-aligned rectangle as `<rect>`, a circle or ellipse drawn with four standard arcs as `<circle>`/`<ellipse>`, a straight line as `<line>`, and other straight-segment paths as `<polygon>`/`<polyline>`, at the written precision (#4652). A rectangle or ellipse with a dashed stroke, whose dashes would start elsewhere, a turned ellipse, curves and compound paths stay `<path>`. `crates/svg/tests/it/basic_shapes.rs` checks each element, that the picture renders as the canvas does and that the geometry reimports. At a precision of 9 decimals or fewer, SVG export writes each number from an integer when the integer rounds it as the decimal formatter does; the formatter still writes values halfway between two written numbers and values too large for the integer. Exporting one path of 200,000 anchors takes a median of 43.4 ms instead of 167.0 ms on Windows 11, and 20,000 rectangles 81.4 ms instead of 141.4 ms, with the same SVG (`crates/svg/src/lib.rs`). + Physical SVG sizes require both disabling SVG Options › Responsive and selecting Points, Millimeters, Centimeters or Inches under Units; Responsive omits `width` and `height`, so selecting a unit alone does not set physical size. Physical dimensions retain at least six decimal places and six significant digits independently of coordinate precision. Legacy Pixels output remains bare numbers, one per document point, rather than a physical-size guarantee: CSS pixels are 96 per inch. Regression coverage: `physical_units_preserve_rendered_extent_at_low_coordinate_precision` checks a consumer's viewport and drawn extent under default aspect-ratio scaling, including narrow and tiny artboards; `tiny_physical_sizes_keep_their_scale` covers smaller converted lengths. SVG import reads each `<circle>` and `<ellipse>` as the ellipse VectorCraft draws: four smooth anchors on the axes, starting at the right, with handles of the standard length, so an ellipse exported as `<ellipse>` comes back with the anchors it was written from and draws the same (`circles_and_ellipses_import_as_the_ellipse_drawn` in `crates/svg/tests/it/basic_shapes.rs`, `filled_ellipse_on_the_artboard_edge_survives_visually` in `prop_svg.rs`). SVG import keeps attributes in other applications' XML namespaces (`plotter:pen="2"`) on the objects and layers they belong to, as it keeps their `data-*` attributes: copies, duplicates and `.vectorcraft` files keep them, and SVG export writes them back with each namespace declared once on the root (the rest of #522; `crates/svg/tests/it/foreign_attributes.rs`, `tests/attributes.rs`). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps defines every symbol in its editing copy with its art, registration point and place in the Symbols panel's order, and writes its instances as symbol instances, which VectorCraft's `.ai` reader opens as symbols and instances again (`symbols_and_their_instances_are_read_back` in `crates/eps/src/ai_editing/tests.rs`; [file-format-parity.md](file-format-parity.md) lists the instances written as their art). @@ -3475,6 +3479,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-12 | minor | Type: kerning at the Type tool's caret at the start of a line (the text's, a paragraph's, or after a forced line break) sets the space before the character after it (`kerningBefore`), which moves it and the rest of its line; it did nothing at the text's start and kerned the invisible line break at a paragraph's (#5111). Scores and estimates unchanged. | | 2026-11-12 | minor | Live Paint Bucket fills faces crossed in one drag (#6373). Scores and estimates unchanged. | | 2026-11-12 | minor | Save refusal follow-up (#6146): changed format opens its Save options; unchanged format retains original options. Focused UI regressions passed, including the format-change case that failed before the fix; native panel acceptance pending. Scores and estimates unchanged. | +| 2026-11-11 | minor | SVG physical dimensions retain scale independently of coordinate precision, including tiny sizes (#5450 review); consumer-rendered extent regression added. Clarify that physical output requires Responsive off and a physical unit; legacy bare numeric output is unchanged and CSS pixels are 96/in. Scores and estimates unchanged. | | 2026-11-11 | minor | Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does (Smart Guides, Snap to Point and the ruler guides, pixels, the grid); evidence updated; scores unchanged. | | 2026-11-11 | minor | Interim macOS canvas cursor delivery (#2292): the tool's cursor stays after the pointer moves (#6362); tool cursors evidence updated; scores and hours unchanged. | | 2026-11-11 | minor | Eyedropper copies effective character dimensions between transformed text objects (#6404); scores and estimates unchanged. | @@ -3537,6 +3542,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-04 | minor | Contour add-on (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `addon.contour.set` is the command behind it. It is a built-in add-on: Object › Plug-ins › Contour, and its own heading in All Tools, with no default shortcut or toolbar slot. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-04 | minor | Contour tool (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `object.contour` is the command behind it. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-04 | minor | Area type vertical alignment buttons in the Properties panel's Paragraph section and the Control panel, off for columns, rows and threaded frames (#3759); evidence added; scores unchanged. | +| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for exported `width` and `height`. For physical size in laser and plotter software, disable Responsive and select a physical unit; Responsive omits both dimensions, so selecting a unit alone does not help (#4462; Pixels still bare numbers as before). Scores and estimates unchanged. | | 2026-11-03 | minor | Enclosing Lasso is an add-on with no default shortcut or Basic toolbar slot. Scores and estimates remain unchanged. | | 2026-11-03 | minor | The canvas context menu offers Outline Stroke for a stroked selection (#5267); scores and estimates unchanged. | | 2026-11-03 | minor | Find Font's replacement-source chooser offers Document, Recent and System (#5217); scores and estimates unchanged. | @@ -3878,4 +3884,4 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s ## EPS Save evidence (2026-10-26) Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transparent margins and the complete editable VectorCraft document. Existing import-loss confirmation and transparency warnings remain; the Save TIFF preview is capped at 1024 pixels, while Export retains 2048. See [file-format-parity.md](file-format-parity.md#eps-save-and-source-protection) for limits and regression evidence. This narrows G9 save-back workflow coverage; native Illustrator editing-data fidelity, parity scores and hour estimates are unchanged. Since 2026-11-12 the EPS Options of Save As show Use Artboards, unchecked by default: unchecked, the bounding box fits the visible art; checked, Save keeps the chosen page frame and margins described here. -> **Swatches status (2026-11-15):** Item context menus are implemented and covered by headless tests; full CI passed on the latest-main integration (all 13 gates), including the updated panel-view harness; parity scores and estimates are unchanged. +> **Historical Swatches proof (2026-11-15):** Item context menus were implemented and covered by headless tests; all 13 CI gates passed on the integration tested then, including the updated panel-view harness. This is not validation of the current merge; parity scores and estimates are unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f8e9a9467e..d613b4ccd2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -7,6 +7,8 @@ > > Outline Stroke is available in the canvas context menu when the selection has an outlinable stroke (#5267). A linked dimension selected with its source keeps its lines; those protected lines do not make a fill-only source eligible, including inside a group. Coincident-point paths with a plain butt-capped stroke do not make the selection eligible either; round and square caps still paint and can be outlined. Scores and estimates unchanged. > +> SVG Options can write physical dimensions with Responsive off and a physical unit selected (#4462); pixel output remains bare numbers. Save As and Save a Copy offer Document units and preserve an existing SVG's physical units when legacy saved options omit a unit; Export keeps its Pixels default. +> > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > > Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged. @@ -750,6 +752,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 2026-11-03 | minor | The canvas context menu offers Outline Stroke when the selection has a stroke to outline (#5267); scores and estimates unchanged. | | 2026-11-03 | minor | Enclosing Lasso selects fully enclosed objects with a freehand loop under Object › Plug-ins; scores and estimates unchanged. | | 2026-11-03 | minor | Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show); scores and estimates unchanged | +| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for the `width` and `height` an export writes, so laser and plotter software read the physical size (#4462; the `units` option, Pixels still bare numbers as before); scores and estimates unchanged | | 2026-11-03 | minor | Symbol editing draws and drags 9-slice guides on the canvas (#5280). Guides outside the artwork remain unsupported. Scores and hours remain unchanged. | | 2026-11-02 | minor | Font-family fields in Character, Properties and Control accept the wheel without opening the menu (#5253); scores and estimates unchanged. | | 2026-11-01 | minor | Object › Image Trace › Batch Trace Folder asks for a source and a destination folder and traces each image into it (#4921); scores and estimates unchanged | @@ -957,6 +960,6 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 2026-10-22 | minor | Tab-drag follow-up: reconcile upstream progress updates and document drag lifecycle, insertion behavior and regression contracts; behavior, scores and estimates unchanged. | | 2026-10-22 | minor | Artwork dragged with Selection switches visible document tabs after a 400 ms hover, then copies editable artwork on canvas release; source and clipboard stay intact; scores and hours unchanged | -> **Swatches status (2026-11-15):** Item context menus are implemented and covered by headless tests; full CI passed on the latest-main integration (all 13 gates), including the updated panel-view harness; parity scores and estimates are unchanged. +> **Historical Swatches proof (2026-11-15):** Item context menus were implemented and covered by headless tests; all 13 CI gates passed on the integration tested then, including the updated panel-view harness. This is not validation of the current merge; parity scores and estimates are unchanged. > **Text styles status (2026-11-19):** Character Styles and Paragraph Styles panels item context menus (Options…, Duplicate, Delete, Redefine, Clear Overrides) are implemented and covered by headless tests; parity scores and estimates are unchanged.