Preserve physical SVG scale independently of coordinate precision

This commit is contained in:
Taha-Mahmoodi
2026-11-11 19:37:00 +04:30
parent e2c19ffa55
commit b671c0bb8f
4 changed files with 56 additions and 30 deletions
+10 -10
View File
@@ -102,20 +102,20 @@ fn svg_export_writes_width_height_with_the_requested_unit() {
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 is the default, byte for byte");
for (unit, size) in [
("mm", "width=\"70.556mm\" height=\"35.278mm\""),
("cm", "width=\"7.056cm\" height=\"3.528cm\""),
("in", "width=\"2.778in\" height=\"1.389in\""),
("pt", "width=\"200pt\" height=\"100pt\""),
] {
for p in [json!({"units": unit}), json!({"svg": {"units": unit}})] {
let out = svg(&mut s, p);
assert!(out.contains(&format!(" {size} viewBox=\"0 0 200 100\"")), "{unit}:\n{out}");
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("width=\"70.6mm\" height=\"35.3mm\""));
assert!(svg(&mut s, json!({"units": "mm", "decimals": 1})).contains("x=\"10.1\""), "coordinate precision is unchanged");
}
#[test]
+16 -18
View File
@@ -184,7 +184,8 @@ impl Encoding {
/// The `viewBox` stays in user units (points) whatever is chosen.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SizeUnit {
/// Bare numbers, CSS pixels at one per point (72 per inch).
/// 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,
@@ -210,20 +211,14 @@ impl SizeUnit {
}
}
/// `points` as a length in this unit, rounded to `decimals` places, e.g. `70.556mm`. A
/// positive size never rounds to zero (a zero `width` disables rendering): in a unit with a
/// suffix it gets more places, up to 12, until a digit survives. `px` stays as [`fmt_num`]
/// writes it.
/// `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 {
const MAX_PLACES: u8 = 12;
let (scale, suffix) = self.per_point();
let v = points * scale;
let mut places = decimals;
if !suffix.is_empty() && v.is_finite() && v > 0.0 {
while places < MAX_PLACES && fmt_num(v, places) == "0" {
places += 1;
}
}
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))
}
}
@@ -783,12 +778,15 @@ mod tests {
}
#[test]
fn tiny_physical_sizes_never_format_as_zero() {
// 3 pt is 0.0417 in: one place would write `0in`, and a zero width disables rendering.
assert_eq!(SizeUnit::In.length(3.0, 1), "0.04in");
assert_eq!(SizeUnit::Mm.length(0.001, 1), "0.0004mm");
// Nothing to widen when a digit survives, or when the size really is zero.
assert_eq!(SizeUnit::In.length(72.0, 1), "1in");
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");
+26
View File
@@ -682,6 +682,32 @@ fn svg_in_physical_units_reopens_at_the_same_size() {
}
}
/// 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, 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);
File diff suppressed because one or more lines are too long