* claim: #9641 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Insert SVG: say why a drawing has nothing to import, and read UTF-16 files (#9641) An SVG with nothing SolidCraft draws (only an embedded picture, shapes pulled from another file with <use>, or not an SVG at all) was refused with "invalid parameters for sketch.insert_svg: the drawing has no geometry SolidCraft reads". It now names the file and says why, pointing pictures at Insert Canvas and Canvas to Sketch. SVG files with a byte-order mark or in UTF-16 now read, and a gzip-compressed (.svgz) file is refused clearly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Insert SVG: decode UTF-16 with as_chunks (clippy) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -43,7 +43,7 @@ pub fn drawing_import_command(path: &str) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
fn source_text(p: &Value, cmd: &str) -> Result<String> {
|
||||
fn source_text(p: &Value, cmd: &str, svg: bool) -> Result<String> {
|
||||
if let Some(t) = str_(p, "text") {
|
||||
if t.len() > MAX_DRAWING_BYTES {
|
||||
return Err(bad(cmd, "the drawing is too large"));
|
||||
@@ -52,9 +52,22 @@ fn source_text(p: &Value, cmd: &str) -> Result<String> {
|
||||
}
|
||||
let path = str_(p, "path").filter(|x| !x.trim().is_empty() && x.len() < 4096).ok_or_else(|| bad(cmd, "give `path` or `text`"))?;
|
||||
let bytes = solidcraft_io::vfs::read(path, MAX_DRAWING_BYTES).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
if svg {
|
||||
return solidcraft_io::decode_svg(&bytes).map_err(|e| drawing_error(p, svg, e.to_string()));
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&bytes).to_string())
|
||||
}
|
||||
|
||||
/// A problem with the drawing file's contents (not with the command's parameters), named after
|
||||
/// the file so the message says which drawing it is about (#9641).
|
||||
fn drawing_error(p: &Value, svg: bool, msg: String) -> EngineError {
|
||||
let name = str_(p, "path")
|
||||
.and_then(|x| std::path::Path::new(x).file_name())
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| if svg { "SVG" } else { "DXF" }.to_string());
|
||||
EngineError::Other(format!("{name}: {msg}"))
|
||||
}
|
||||
|
||||
/// Add imported geometry to a sketch, sharing end points that meet.
|
||||
/// Adds the geometry; end points closer than `q` (mm) become one point, so drawings whose
|
||||
/// ends almost meet still make closed profiles.
|
||||
@@ -168,9 +181,16 @@ fn bounds_of(geom: &[Geom2]) -> Option<(Vec2, Vec2)> {
|
||||
(lo.x.is_finite() && lo.y.is_finite() && hi.x.is_finite() && hi.y.is_finite()).then_some((lo, hi))
|
||||
}
|
||||
|
||||
fn read_drawing(p: &Value, cmd: &str, svg: bool) -> Result<Vec<Geom2>> {
|
||||
let text = source_text(p, cmd)?;
|
||||
if svg { solidcraft_io::read_svg(&text) } else { solidcraft_io::read_dxf(&text) }.map_err(|e| bad(cmd, e.to_string()))
|
||||
/// The drawing's geometry and the box around it; a drawing with none is an error that says why
|
||||
/// (#9641).
|
||||
fn read_drawing(p: &Value, cmd: &str, svg: bool) -> Result<(Vec<Geom2>, (Vec2, Vec2))> {
|
||||
let text = source_text(p, cmd, svg)?;
|
||||
let geom = if svg { solidcraft_io::read_svg(&text) } else { solidcraft_io::read_dxf(&text) }.map_err(|e| drawing_error(p, svg, e.to_string()))?;
|
||||
let Some(bounds) = bounds_of(&geom) else {
|
||||
let why = if svg { solidcraft_io::svg_nothing_to_import(&text) } else { "the DXF has no entities SolidCraft reads".to_string() };
|
||||
return Err(drawing_error(p, svg, why));
|
||||
};
|
||||
Ok((geom, bounds))
|
||||
}
|
||||
|
||||
/// How big a drawing is in its own file, to size it before it is inserted.
|
||||
@@ -181,22 +201,18 @@ fn drawing_bounds(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(f) => !f.eq_ignore_ascii_case("dxf"),
|
||||
None => !name_is_dxf,
|
||||
};
|
||||
let geom = read_drawing(p, cmd, svg)?;
|
||||
let (lo, hi) = bounds_of(&geom).ok_or_else(|| bad(cmd, "the drawing has no geometry SolidCraft reads"))?;
|
||||
let (_, (lo, hi)) = read_drawing(p, cmd, svg)?;
|
||||
Ok(json!({"min": [lo.x, lo.y], "max": [hi.x, hi.y], "width": hi.x - lo.x, "height": hi.y - lo.y}))
|
||||
}
|
||||
|
||||
fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result<Value> {
|
||||
let geom = read_drawing(p, cmd, svg)?;
|
||||
if geom.is_empty() {
|
||||
return Err(bad(cmd, "the drawing has no geometry SolidCraft reads"));
|
||||
}
|
||||
let (geom, (lo, hi)) = read_drawing(p, cmd, svg)?;
|
||||
// A size in millimetres wins over a factor; the aspect ratio is always kept.
|
||||
let natural = bounds_of(&geom).map(|(lo, hi)| (hi.x - lo.x, hi.y - lo.y));
|
||||
let natural = (hi.x - lo.x, hi.y - lo.y);
|
||||
let sized = |key: &str, of: fn(&(f64, f64)) -> f64| -> Result<Option<f64>> {
|
||||
let Some(v) = p.get(key) else { return Ok(None) };
|
||||
let want = v.as_f64().filter(|w| w.is_finite() && *w > 0.0).ok_or_else(|| bad(cmd, format!("`{key}` must be a positive number (mm)")))?;
|
||||
let have = natural.as_ref().map(of).filter(|h| *h > 1e-9).ok_or_else(|| bad(cmd, format!("the drawing has no {key} to size")))?;
|
||||
let have = Some(of(&natural)).filter(|h| *h > 1e-9).ok_or_else(|| bad(cmd, format!("the drawing has no {key} to size")))?;
|
||||
Ok(Some(want / have))
|
||||
};
|
||||
let from_size = match sized("width", |n| n.0)? {
|
||||
@@ -211,7 +227,7 @@ fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result<Value> {
|
||||
let (sin, cos) = angle.sin_cos();
|
||||
let pivot = match str_(p, "align") {
|
||||
None | Some("origin") => Vec2::ZERO,
|
||||
Some("center") => bounds_of(&geom).map(|(lo, hi)| (lo + hi) * 0.5).unwrap_or(Vec2::ZERO),
|
||||
Some("center") => (lo + hi) * 0.5,
|
||||
Some(_) => return Err(bad(cmd, "`align` must be \"origin\" or \"center\"")),
|
||||
};
|
||||
let off = p.get("at").and_then(vec2).unwrap_or(Vec2::ZERO);
|
||||
@@ -355,6 +371,33 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// #9641: an SVG with nothing SolidCraft can draw (here only an embedded picture) is refused
|
||||
/// with a message naming the file and saying why, not "invalid parameters … no geometry"; a
|
||||
/// UTF-16 SVG file inserts.
|
||||
#[test]
|
||||
fn an_svg_with_nothing_to_import_says_why() {
|
||||
let dir = std::env::temp_dir().join(format!("solidcraft-9641-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let picture = dir.join("logo.svg");
|
||||
std::fs::write(
|
||||
&picture,
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><image width="64" height="64" href="data:image/png;base64,iVBORw0KGgo="/></svg>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let mut s = Session::default();
|
||||
for cmd in ["sketch.insert_svg", "sketch.drawing_bounds"] {
|
||||
let e = s.execute(cmd, &json!({"path": picture.to_string_lossy(), "align": "center"})).unwrap_err().to_string();
|
||||
assert!(e.starts_with("logo.svg: ") && e.contains("embedded picture") && !e.contains("invalid parameters"), "{cmd}: {e}");
|
||||
}
|
||||
assert!(s.active_sketch.is_none(), "a refused insert leaves no empty sketch behind");
|
||||
let square = r#"<svg xmlns="http://www.w3.org/2000/svg" width="10mm" height="10mm" viewBox="0 0 10 10"><rect width="10" height="10"/></svg>"#;
|
||||
let utf16 = dir.join("square.svg");
|
||||
std::fs::write(&utf16, [0xFF, 0xFE].into_iter().chain(square.encode_utf16().flat_map(u16::to_le_bytes)).collect::<Vec<u8>>()).unwrap();
|
||||
let r = s.execute("sketch.insert_svg", &json!({"path": utf16.to_string_lossy()})).unwrap();
|
||||
assert_eq!(r["curves"], 4, "{r}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #8155: an elliptical arc of a DXF (as Fusion writes one) comes into the sketch as exact
|
||||
/// conics, and the drawing's size is the arc's own, not the box round the conics' apexes.
|
||||
#[test]
|
||||
|
||||
@@ -44,7 +44,7 @@ pub use dxf_out::{DxfEntity, DxfLayer, DxfLinetype, DxfShape, loop_shapes, seg_s
|
||||
pub use legacy_dir::{APP_ID, LEGACY_APP_ID, PREVIOUS_APP_IDS, adopt_legacy_dir, legacy_flatpak_paths};
|
||||
pub use safe_write::{backup_path, write_atomic};
|
||||
pub use sketch2d::{Geom2, MAX_DRAWING_BYTES};
|
||||
pub use svg::read_svg;
|
||||
pub use svg::{decode_svg, read_svg, svg_nothing_to_import};
|
||||
mod gltf_in;
|
||||
pub use gltf_in::{GltfImport, Loader, MAX_GLTF_BYTES, MeshPlan, PlanPlace, glb_container, is_gltf_path, read_gltf};
|
||||
mod obj;
|
||||
|
||||
@@ -525,6 +525,84 @@ pub fn read_svg(text: &str) -> Result<Vec<Geom2>> {
|
||||
Ok(out.g)
|
||||
}
|
||||
|
||||
/// The text of an SVG file's bytes: a UTF-8 byte-order mark is dropped and UTF-16 files (with
|
||||
/// their mark, as some Windows tools write them) are decoded. A gzip-compressed file (`.svgz`
|
||||
/// under any name) is refused with a clear error instead of being read as text (#9641).
|
||||
pub fn decode_svg(bytes: &[u8]) -> Result<String> {
|
||||
if bytes.len() > MAX_DRAWING_BYTES {
|
||||
return Err(IoError::Invalid("the SVG file is too large".into()));
|
||||
}
|
||||
if bytes.starts_with(&[0x1f, 0x8b]) {
|
||||
return Err(IoError::Invalid(
|
||||
"this SVG is gzip-compressed (an .svgz file); SolidCraft reads plain SVG only: save it as plain (uncompressed) SVG in a vector editor first"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
let utf16 = |rest: &[u8], le: bool| -> String {
|
||||
let units = rest.as_chunks::<2>().0.iter().map(|&pair| if le { u16::from_le_bytes(pair) } else { u16::from_be_bytes(pair) });
|
||||
char::decode_utf16(units).map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER)).collect()
|
||||
};
|
||||
Ok(match bytes {
|
||||
[0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(),
|
||||
[0xFF, 0xFE, rest @ ..] => utf16(rest, true),
|
||||
[0xFE, 0xFF, rest @ ..] => utf16(rest, false),
|
||||
_ => String::from_utf8_lossy(bytes).into_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Why [`read_svg`] found nothing to import in `text`, in words for the person inserting it
|
||||
/// (#9641): a picture embedded in an SVG, shapes drawn only from another file, or a file that is
|
||||
/// not an SVG drawing at all, rather than a bare "no geometry".
|
||||
pub fn svg_nothing_to_import(text: &str) -> String {
|
||||
let mut rd = Reader::from_reader(text.as_bytes());
|
||||
rd.config_mut().trim_text(true);
|
||||
let mut buf = Vec::new();
|
||||
let (mut svg, mut images, mut external_uses, mut elements) = (false, 0usize, 0usize, 0usize);
|
||||
let mut broken = None;
|
||||
while elements < MAX_ENTITIES {
|
||||
match rd.read_event_into(&mut buf) {
|
||||
Ok(Event::Start(e) | Event::Empty(e)) => {
|
||||
elements += 1;
|
||||
match e.local_name().as_ref() {
|
||||
b"svg" => svg = true,
|
||||
b"image" => images += 1,
|
||||
b"use" => {
|
||||
let a = attrs(&e);
|
||||
if attr(&a, "href").is_some_and(|h| !h.trim_start().starts_with('#')) {
|
||||
external_uses += 1;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Event::Eof) => break,
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
broken = Some(e.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
buf.clear();
|
||||
}
|
||||
if !svg {
|
||||
return match broken {
|
||||
Some(e) => format!("the file is not a readable SVG drawing ({e})"),
|
||||
None => "the file is not an SVG drawing: it has no <svg> element (it may be a picture or a web page saved with an .svg name)".into(),
|
||||
};
|
||||
}
|
||||
if images > 0 {
|
||||
return format!(
|
||||
"the SVG holds only {} embedded picture{} (<image>), not outlines, so there is nothing to draw in the sketch; trace the picture into paths in a vector editor, or save it as PNG/JPEG and use Insert > Canvas, then Canvas to Sketch",
|
||||
if images == 1 { "an" } else { "several" },
|
||||
if images == 1 { "" } else { "s" }
|
||||
);
|
||||
}
|
||||
if external_uses > 0 {
|
||||
return "the SVG's shapes are drawn with <use> from another file, which SolidCraft does not follow; save the drawing as a single self-contained SVG first".into();
|
||||
}
|
||||
"the SVG has no shapes SolidCraft reads (path, line, rect, circle, ellipse, polyline, polygon or text)".into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -589,6 +667,36 @@ mod tests {
|
||||
assert!(matches!(g[0], Geom2::Line(a, b) if (a.dist(b) - 25.4).abs() < 1e-9));
|
||||
}
|
||||
|
||||
/// #9641: a file with nothing to import says why (an embedded picture, shapes from another
|
||||
/// file, not an SVG at all), and SVG files saved as UTF-16 or with a byte-order mark read.
|
||||
#[test]
|
||||
fn a_drawing_with_nothing_to_import_says_why() {
|
||||
let picture = r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="64" height="64">
|
||||
<defs><pattern id="p"><use xlink:href="#i"/></pattern><image id="i" width="64" height="64" xlink:href="data:image/png;base64,iVBORw0KGgo="/></defs>
|
||||
<rect width="0" height="0" fill="url(#p)"/></svg>"##;
|
||||
assert!(read_svg(picture).unwrap().is_empty());
|
||||
let why = svg_nothing_to_import(picture);
|
||||
assert!(why.contains("embedded picture") && why.contains("Canvas"), "{why}");
|
||||
let external = r#"<svg xmlns="http://www.w3.org/2000/svg"><use href="shapes.svg#logo"/></svg>"#;
|
||||
assert!(svg_nothing_to_import(external).contains("another file"), "{}", svg_nothing_to_import(external));
|
||||
assert!(svg_nothing_to_import("<html><body>Not found</body></html>").contains("not an SVG drawing"));
|
||||
assert!(svg_nothing_to_import("<svg><g/></svg>").contains("no shapes"));
|
||||
|
||||
let square = r#"<?xml version="1.0" encoding="UTF-16"?><svg xmlns="http://www.w3.org/2000/svg"><rect width="10" height="10"/></svg>"#;
|
||||
let le: Vec<u8> = [0xFF, 0xFE].into_iter().chain(square.encode_utf16().flat_map(u16::to_le_bytes)).collect();
|
||||
let be: Vec<u8> = [0xFE, 0xFF].into_iter().chain(square.encode_utf16().flat_map(u16::to_be_bytes)).collect();
|
||||
let bom: Vec<u8> = [0xEF, 0xBB, 0xBF].into_iter().chain(square.bytes()).collect();
|
||||
for bytes in [le, be, bom, square.as_bytes().to_vec()] {
|
||||
let text = decode_svg(&bytes).unwrap();
|
||||
assert_eq!(read_svg(&text).unwrap().len(), 4, "{bytes:?}");
|
||||
}
|
||||
let gz = decode_svg(&[0x1f, 0x8b, 8, 0, 0, 0]).unwrap_err().to_string();
|
||||
assert!(gz.contains("gzip"), "{gz}");
|
||||
for bytes in [&[0xFF, 0xFE, 0x3C][..], &[0xFE, 0xFF, 0xD8, 0x00][..], &[][..]] {
|
||||
assert!(decode_svg(bytes).is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
/// A transform that scales a shape past the range of `f64` is refused with a clear error
|
||||
/// instead of handing the sketch an infinite curve (solidcraft#5020).
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user