fix(svg): preserve document units in legacy save dialogs

- Keep missing legacy Save and SaveCopy units as Document/None, without changing engine serialization.
- Preserve explicit saved units and Export/Export for Screens pixel defaults.
- Cover captured SVG output for legacy saves, explicit overrides and Export defaults.
This commit is contained in:
Taha-Mahmoodi committed 2026-11-28 16:51:19 +04:30
1 parent 398f641768
commit 4f404feb3f
3 files changed
+70 -9

No files matched your search

+1 -1
View File
@@ -509,7 +509,7 @@ pub(crate) fn settings(ui: &mut Ui, fields: &mut Map<String, Value>, 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),
};
+68 -7
View File
@@ -56,7 +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); 5] = [("px", "Pixels"), ("pt", "Points"), ("mm", "Millimeters"), ("cm", "Centimeters"), ("in", "Inches")];
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"];
@@ -73,9 +74,9 @@ pub(crate) struct SvgCodeKey {
selected: Option<Vec<vectorcraft_doc::NodeId>>,
}
/// The options a first SVG Options dialog starts from: the engine's defaults with Pixels,
/// 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<String, Value> {
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();
@@ -111,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 {
@@ -148,7 +153,7 @@ fn pairs(key: &str, label: &'static str, choices: &[(&str, &'static str)]) -> Pa
/// responsive, `<tspan>`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<Param> {
pub(crate) fn svg_params(mode: Mode, screens: bool, tiny: bool) -> Vec<Param> {
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);
@@ -164,7 +169,8 @@ pub(crate) fn svg_params(screens: bool, tiny: bool) -> Vec<Param> {
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.
rows.push(pairs("units", tl!("Units:"), &UNITS).enabled_when("responsive", false));
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.
@@ -193,7 +199,7 @@ fn artboard_rows(count: usize) -> Vec<Param> {
/// 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<Param> {
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 => {}
@@ -215,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) {
@@ -686,6 +695,58 @@ mod tests {
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]
+1 -1
View File
@@ -2,7 +2,7 @@
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row meLine truncated
>
> SVG Options can write physical dimensions with Responsive off and a physical unit selected (#4462); pixel output remains bare numbers.
> 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).
>