diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index 7a6547890f..5369b34398 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -47,7 +47,12 @@ pub const OPTIONS: &[FormatOption] = &[ default: "\"layerNames\"", description: "layerNames (readable ids from names) | minimal (only referenced ids) | unique (content-hashed prefix on every id and class)", }, - FormatOption { name: "decimals", ty: "integer", default: "3", description: "coordinate precision, 1–7 decimal places" }, + FormatOption { + name: "decimals", + ty: "integer", + default: "3", + description: "coordinate precision, 1–7 decimal places; positive root width/height and viewBox size stay positive", + }, 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 { diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index e8c84530d5..140b94e183 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -85,9 +85,8 @@ fn physical_num(v: f64) -> String { return "0".into(); } let leading_zeros = (-v.log10().floor() as i32).max(0); - let decimals = (leading_zeros + 3).clamp(3, 14) as u8; - let s = fmt_num(v, decimals); - if s == "0" && v > 0.0 { format!("{v:.16}").trim_end_matches('0').trim_end_matches('.').to_string() } else { s } + let decimals = (leading_zeros + 3).max(3); + if decimals > 14 { format!("{v:e}") } else { fmt_num(v, decimals as u8) } } /// `doc` as SVG with `opts`, the native file `native` embedded for Preserve Editing, its generated @@ -186,7 +185,9 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: .join(nl); svg.doctype_internal("svg", &entities, nl); } - let (ww, hh) = (w.num(rect.width()), w.num(rect.height())); + // A positive pixel size that the chosen decimals round to 0 is written with enough digits to stay positive. + let nonzero = |v: f64, s: String| if v > 0.0 && s == "0" { physical_num(v) } else { s }; + let (ww, hh) = (nonzero(rect.width(), w.num(rect.width())), nonzero(rect.height(), w.num(rect.height()))); let mut root = svg.root().attr("xmlns:xlink", "http://www.w3.org/1999/xlink"); for (ns, prefix) in &w.foreign_ns { root = root.attr(&format!("xmlns:{prefix}"), ns); @@ -197,7 +198,9 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: if !opts.responsive { // 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)); + // Pixels are written bare at one per point. + let (width, height) = + (nonzero(rect.width(), unit.length(rect.width(), opts.decimals)), nonzero(rect.height(), 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())); @@ -207,9 +210,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: root = root.attr("width", &ww).attr("height", &hh); } } - let vb_w = if rect.width() > 0.0 && ww == "0" { physical_num(rect.width()) } else { ww.clone() }; - let vb_h = if rect.height() > 0.0 && hh == "0" { physical_num(rect.height()) } else { hh.clone() }; - root.attr("viewBox", format_args!("0 0 {vb_w} {vb_h}")).open(); + root.attr("viewBox", format_args!("0 0 {ww} {hh}")).open(); let mut out = svg.as_str().to_string(); out.push_str(nl); let css = opts.styling == Styling::InternalCss && !w.classes.is_empty(); diff --git a/crates/svg/tests/it/import_units.rs b/crates/svg/tests/it/import_units.rs index 91138d8a93..1c17c156fe 100644 --- a/crates/svg/tests/it/import_units.rs +++ b/crates/svg/tests/it/import_units.rs @@ -3,7 +3,7 @@ use vectorcraft_doc::{Document, Node, NodeKind, Unit}; use vectorcraft_geom::Rect; -use vectorcraft_svg::{ExportOptions, export, import}; +use vectorcraft_svg::{ExportOptions, SizeUnit, export, import}; fn art(d: &Document) -> Vec<&Node> { let mut v = Vec::new(); @@ -191,6 +191,28 @@ fn export_physical_units_writes_unit_suffixes() { // Re-importing preserved physical units let back = import(&s).unwrap(); assert_eq!(back.units, Unit::Millimeters); + + // A small positive size in pixels keeps a nonzero width and height, with the document unit + // and with Pixels chosen in the SVG options + for (w, h) in [(0.0004, 0.0002), (1e-17, 2e-17), (5.1e-17, 1e-17), (5.1e-15, 4.9e-15)] { + let mut d = Document::new(w, h); + d.units = Unit::Pixels; + for opts in [ExportOptions::default(), ExportOptions { units: Some(SizeUnit::Px), ..Default::default() }] { + let s = export(&d, &opts); + let num = |name: &str| -> f64 { root_attr(&s, name).and_then(|v| v.parse().ok()).unwrap_or_else(|| panic!("{name}: {s}")) }; + let view: Vec = root_attr(&s, "viewBox").unwrap_or_default().split(' ').filter_map(|v| v.parse().ok()).collect(); + for (got, want) in [(num("width"), w), (num("height"), h), (view[2], w), (view[3], h)] { + assert!((got - want).abs() <= want * 1e-3, "{got} for {want}: {s}"); + } + } + } +} + +/// The value of attribute `name` on `svg`'s root element. +fn root_attr<'a>(svg: &'a str, name: &str) -> Option<&'a str> { + let start = svg.find("').next()?; + tag.split(&format!(" {name}=\"")).nth(1)?.split('"').next() } /// The `width` of `svg`'s root as a length in points, read by the SVG and CSS absolute units diff --git a/docs/gaps.md b/docs/gaps.md index 671283d648..dee91c3fe7 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -474,7 +474,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **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. + retains the document's physical units as below; positive root `width`/`height` and `viewBox` dimensions that would round to 0 at the chosen decimals use enough digits to stay positive. Estimate unchanged. - **Done (#864):** SVG export writes physical unit suffixes on the root `` 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) diff --git a/docs/mcp.md b/docs/mcp.md index ccbe5eb0e8..a409c1bd48 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1357,7 +1357,7 @@ SVG Options: `export` to SVG takes them in `options`, flat or as `{"svg": {…}} SVG, or returned as `linked`), `objectIds` (`layerNames`, `minimal`, `unique`), `decimals` (1–7), `minify`, `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 `` 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` +lists every option with its default. If `decimals` would round a positive dimension to zero, root `width`/`height` values in unitless or px form and `viewBox` sizes use enough digits to stay positive, with scientific notation when more than 14 decimal places are needed. `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` (the file) when it isn't UTF-8, and such files open again. `profile: "tiny12"` writes a simplified SVG Tiny 1.2 (presentation attributes only; filters, masks, blend modes and embedded fonts left out, symbols as art, each with