SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Insert SVG / DXF: place, size and turn the drawing before it is added (#2605, #3443) (#3542)
phanoob5622963b912c
diff --git a/assets/locales/pending/insert-drawing-place.json b/assets/locales/pending/insert-drawing-place.jsonnew file mode 100644index 0000000000..22884892bc--- /dev/null+++ b/assets/locales/pending/insert-drawing-place.json@@ -0,0 +1,11 @@+{+ "en": {+ "cmd.sketch_drawing_bounds": "Drawing Size"+ },+ "ja": {+ "cmd.sketch_drawing_bounds": "図面のサイズ"+ },+ "zh": {+ "cmd.sketch_drawing_bounds": "图纸尺寸"+ }+}diff --git a/crates/engine/src/cmd/sketch_import.rs b/crates/engine/src/cmd/sketch_import.rsindex e0ad13c3fd..e25be5c9ec 100644--- a/crates/engine/src/cmd/sketch_import.rs+++ b/crates/engine/src/cmd/sketch_import.rs@@ -16,11 +16,15 @@ pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("sketch.insert_dxf", "Insert DXF", insert_dxf).at("SKETCH", "INSERT").icon("sketch_dxf")- .params(concat!("path | text: ASCII DXF (blocks expanded); at?: [x,y] offset, scale?, tolerance?: mm within which ends join (default 0.0001); plane?: (when no sketch is active, a new sketch on it; default XY)", created_doc!())),+ .params(concat!("path | text: ASCII DXF (blocks expanded); at?: [x,y] offset, scale? | width? | height?: mm, the drawing's size before rotation, aspect kept (win over scale); angle?: degrees, about the drawing's origin (or its centre); align?: \"origin\" (default: `at` is where the file's origin goes) | \"center\" (`at` is where the drawing's middle goes and it turns and scales about it); tolerance?: mm within which ends join (default 0.0001); plane?: (when no sketch is active, a new sketch on it; default XY)", created_doc!())),CommandSpec::new("sketch.insert_svg", "Insert SVG", insert_svg).at("SKETCH", "INSERT").icon("svg")- .params(concat!("path | text: SVG; at?: [x,y] offset, scale?, tolerance?: mm within which ends join (default 0.0001); plane?: (when no sketch is active, a new sketch on it; default XY)", created_doc!())),+ .params(concat!("path | text: SVG; at?: [x,y] offset, scale? | width? | height?: mm, the drawing's size before rotation, aspect kept (win over scale); angle?: degrees, about the drawing's origin (or its centre); align?: \"origin\" (default: `at` is where the file's origin goes) | \"center\" (`at` is where the drawing's middle goes and it turns and scales about it); tolerance?: mm within which ends join (default 0.0001); plane?: (when no sketch is active, a new sketch on it; default XY)", created_doc!())),+ CommandSpec::new("sketch.drawing_bounds", "Drawing Size", drawing_bounds)+ .icon("svg")+ .noundo()+ .params("path | text: SVG or DXF (by `format`: \"svg\" | \"dxf\", default by the file name, else SVG); returns min, max, width and height in the file's own size"),CommandSpec::new("sketch.export_dxf", "Save As DXF", export_dxf).icon("sketch_dxf").noundo().params("sketch?: id|name (default active); path?: file to write (else the DXF text is returned)"),@@ -117,13 +121,92 @@ fn add_geometry(sk: &mut Sketch, geom: &[Geom2], f: &dyn Fn(Vec2) -> Vec2, k: f6Ok((curves, texts))}-fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result<Value> {+/// The box around a drawing's geometry (arcs, circles and curves by their extent).+fn bounds_of(geom: &[Geom2]) -> Option<(Vec2, Vec2)> {+ let mut pts: Vec<Vec2> = Vec::new();+ for g in geom {+ match g {+ Geom2::Point(p) => pts.push(*p),+ Geom2::Line(a, b) => pts.extend([*a, *b]),+ Geom2::Circle(c, r) => pts.extend([*c + Vec2::new(*r, *r), *c - Vec2::new(*r, *r)]),+ Geom2::Arc { c, a, b } => {+ let r = c.dist(*a);+ let (a0, mut a1) = ((*a - *c).angle(), (*b - *c).angle());+ while a1 <= a0 {+ a1 += std::f64::consts::TAU;+ }+ pts.extend([*a, *b]);+ // The four extreme directions that lie on the arc.+ for q in 0..4 {+ let mut d = f64::from(q) * std::f64::consts::FRAC_PI_2;+ while d < a0 {+ d += std::f64::consts::TAU;+ }+ if d < a1 {+ pts.push(*c + Vec2::from_angle(d) * r);+ }+ }+ }+ Geom2::Ellipse { c, major, minor } => {+ let r = c.dist(*major).max(*minor);+ pts.extend([*c + Vec2::new(r, r), *c - Vec2::new(r, r)]);+ }+ Geom2::Spline { pts: sp, .. } => pts.extend(sp.iter().copied()),+ Geom2::Conic { a, apex, b, .. } => pts.extend([*a, *apex, *b]),+ Geom2::Text { at, .. } => pts.push(*at),+ }+ }+ let first = *pts.first()?;+ let (lo, hi) = pts.iter().fold((first, first), |(lo, hi), p| (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y))));+ (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)?;- let geom = if svg { solidcraft_io::read_svg(&text) } else { solidcraft_io::read_dxf(&text) }.map_err(|e| bad(cmd, e.to_string()))?;+ if svg { solidcraft_io::read_svg(&text) } else { solidcraft_io::read_dxf(&text) }.map_err(|e| bad(cmd, e.to_string()))+}++/// How big a drawing is in its own file, to size it before it is inserted.+fn drawing_bounds(_s: &mut Session, p: &Value) -> Result<Value> {+ let cmd = "sketch.drawing_bounds";+ let name_is_dxf = str_(p, "path").is_some_and(|x| x.to_ascii_lowercase().ends_with(".dxf"));+ let svg = match str_(p, "format") {+ 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"))?;+ 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 k = num(p, "scale").filter(|k| *k > 1e-9 && *k < 1e6).unwrap_or(1.0);+ // 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 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")))?;+ Ok(Some(want / have))+ };+ let from_size = match sized("width", |n| n.0)? {+ Some(k) => Some(k),+ None => sized("height", |n| n.1)?,+ };+ let k = from_size.or_else(|| num(p, "scale")).filter(|k| *k > 1e-9 && *k < 1e6).unwrap_or(1.0);+ let angle = match p.get("angle") {+ Some(v) => v.as_f64().filter(|a| a.is_finite()).ok_or_else(|| bad(cmd, "`angle` must be a number (degrees)"))?.to_radians(),+ None => 0.0,+ };+ 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(_) => return Err(bad(cmd, "`align` must be \"origin\" or \"center\"")),+ };let off = p.get("at").and_then(vec2).unwrap_or(Vec2::ZERO);let mut created = None;if s.active_sketch.is_none() {@@ -135,7 +218,10 @@ fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result<Value> {created = r.get("sketch").and_then(Value::as_u64);}let tol = num(p, "tolerance").filter(|t| t.is_finite() && *t > 0.0).unwrap_or(1e-4).clamp(1e-9, 10.0);- let f = move |q: Vec2| q * k + off;+ let f = move |q: Vec2| {+ let v = (q - pivot) * k;+ Vec2::new(v.x * cos - v.y * sin, v.x * sin + v.y * cos) + off+ };let ((curves, texts), info) = edit(s, p, cmd, false, |sk, _| {let (cs, texts) = add_geometry(sk, &geom, &f, k, tol)?;Ok((ids_of(sk, &cs), texts))@@ -144,7 +230,7 @@ fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result<Value> {let id = s.active_sketch.ok_or_else(|| bad(cmd, "no sketch"))?;let mut n_text = 0;for t in texts {- if let Geom2::Text { text, at, height, angle } = t {+ if let Geom2::Text { text, at, height, angle: own } = t {let mut doc = (*s.doc).clone();let mut sk = doc.sketch(id)?.clone();if super::sketch_project::add_link(@@ -153,7 +239,7 @@ fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result<Value> {id,&mut sk,LinkKind::Text,- LinkSource::Text { text, at, height, angle, font: None, style: Default::default(), exprs: Default::default() },+ LinkSource::Text { text, at, height, angle: own + angle, font: None, style: Default::default(), exprs: Default::default() },).is_ok(){@@ -265,4 +351,54 @@ mod tests {s.execute("sketch.finish", &json!({})).unwrap();}}++ const PLATE: &str =+ r#"<svg xmlns="http://www.w3.org/2000/svg" width="20mm" height="10mm" viewBox="0 0 20 10"><rect x="0" y="0" width="20" height="10"/></svg>"#;++ fn span(s: &Session) -> (f64, f64, f64, f64) {+ let st = s.model.state();+ let sk = &st.sketch(s.active_sketch.unwrap()).unwrap().sketch;+ let (mut lo, mut hi) = ((f64::MAX, f64::MAX), (f64::MIN, f64::MIN));+ for p in (0..sk.curves.len()).flat_map(|i| sk.polyline(i)) {+ lo = (lo.0.min(p.x), lo.1.min(p.y));+ hi = (hi.0.max(p.x), hi.1.max(p.y));+ }+ (lo.0, lo.1, hi.0, hi.1)+ }++ fn inserted(params: serde_json::Value) -> (f64, f64, f64, f64) {+ let mut s = Session::default();+ s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();+ let mut p = json!({"text": PLATE});+ p.as_object_mut().unwrap().extend(params.as_object().unwrap().clone());+ s.execute("sketch.insert_svg", &p).unwrap();+ span(&s)+ }++ /// A drawing can be given a size in millimetres (its aspect kept), turned about its origin and+ /// placed; the size of the file itself is read without inserting anything.+ #[test]+ fn an_inserted_drawing_takes_a_width_a_height_and_an_angle() {+ let mut s = Session::default();+ let b = s.execute("sketch.drawing_bounds", &json!({"text": PLATE, "format": "svg"})).unwrap();+ assert_eq!((b["width"].as_f64(), b["height"].as_f64()), (Some(20.0), Some(10.0)));+ let near = |a: (f64, f64, f64, f64), e: (f64, f64, f64, f64)| {+ assert!((a.0 - e.0).abs() < 1e-6 && (a.1 - e.1).abs() < 1e-6 && (a.2 - e.2).abs() < 1e-6 && (a.3 - e.3).abs() < 1e-6, "{a:?} vs {e:?}")+ };+ near(inserted(json!({"width": 40})), (0.0, -20.0, 40.0, 0.0));+ near(inserted(json!({"height": 5, "at": [3, 4]})), (3.0, -1.0, 13.0, 4.0));+ near(inserted(json!({"width": 40, "scale": 9})), (0.0, -20.0, 40.0, 0.0));+ // Turned 90 degrees about the origin, then placed.+ near(inserted(json!({"angle": 90, "at": [100, 0]})), (100.0, 0.0, 110.0, 20.0));+ // About its centre: the middle lands on `at` whatever the size and angle.+ near(inserted(json!({"align": "center", "at": [50, 50]})), (40.0, 45.0, 60.0, 55.0));+ near(inserted(json!({"align": "center", "at": [50, 50], "width": 40})), (30.0, 40.0, 70.0, 60.0));+ near(inserted(json!({"align": "center", "at": [50, 50], "angle": 90})), (45.0, 40.0, 55.0, 60.0));+ for bad in [json!({"width": 0}), json!({"height": -1}), json!({"angle": "x"}), json!({"align": "left"})] {+ s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();+ let mut p = json!({"text": PLATE});+ p.as_object_mut().unwrap().extend(bad.as_object().unwrap().clone());+ assert!(s.execute("sketch.insert_svg", &p).is_err(), "{bad}");+ }+ }}diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 9ba41be17b..a1ebe41d43 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -362,6 +362,8 @@ crate::dialog_descriptor::dialog_descriptors! {dashed: bool,tolerance: f64,},+ /// Insert SVG / DXF: where the picked drawing goes (`dialogs_insert_drawing`).+ InsertDrawing(crate::dialogs_insert_drawing::Place),/// Plastic features (`dialogs_plastic`).Plastic(crate::dialogs_plastic::Pl),/// Frame members (`dialogs_frame`).@@ -1118,7 +1120,7 @@ impl Dialog {Kind::SketchModify(k) => return k.previews(),Kind::Plastic(k) => return k.previews(),Kind::Frame(_) => return true,- Kind::Part(_) | Kind::PartSize(_) => return true,+ Kind::Part(_) | Kind::PartSize(_) | Kind::InsertDrawing(_) => return true,// Web previews run synchronously; a modelled thread can take seconds.Kind::Thread { .. } => return !cfg!(target_arch = "wasm32") && self.extra.get("modeled").and_then(Value::as_bool).unwrap_or(false),_ => {}@@ -2022,6 +2024,7 @@ fn title(k: &Kind) -> &'static str {Kind::Surface(k) => k.title(),Kind::SaveMesh(_) => "SAVE AS MESH",Kind::ViewDxf { .. } => "Export Current View as DXF",+ Kind::InsertDrawing(p) => crate::dialogs_insert_drawing::title(p),Kind::Plastic(k) => k.title(),Kind::Frame(_) => "FRAME MEMBER",Kind::Appearance(_) => "APPEARANCE",@@ -4438,6 +4441,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>, SKind::SketchModify(k) => return crate::sketch_modify_ui::commands(app, k, &d.inputs, &d.extra),Kind::SaveMesh(k) => return crate::dialogs_save_mesh::commands(k, &d.inputs),Kind::ViewDxf { .. } => return Ok(Vec::new()),+ Kind::InsertDrawing(p) => return crate::dialogs_insert_drawing::commands(p),Kind::Plastic(k) => return crate::dialogs_plastic::commands(app, k, &d.inputs, &d.extra),Kind::Frame(k) => return crate::dialogs_frame::commands(app, k, &d.inputs, &d.extra),Kind::Appearance(k) => return Ok(crate::dialogs_appearance::commands(k, &d.inputs)),diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rsindex 46ce1470c8..0b0f957a8a 100644--- a/crates/ui-egui/src/dialogs_dense.rs+++ b/crates/ui-egui/src/dialogs_dense.rs@@ -17,6 +17,7 @@ pub(super) fn command(kind: &Kind) -> Option<&'static str> {Kind::PartSize(_) => Some("parts.resize"),Kind::SaveMesh(k) => Some(crate::dialogs_save_mesh::command_id(k)),Kind::ViewDxf { .. } => Some("file.export_view_dxf"),+ Kind::InsertDrawing(p) => Some(if p.command.ends_with("dxf") { "sketch.insert_dxf" } else { "sketch.insert_svg" }),Kind::Sketch => Some("sketch.create"),Kind::SketchModify(k) => Some(crate::sketch_modify_ui::command(k)),Kind::Text(_) => Some("sketch.edit_text"),@@ -197,6 +198,7 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui:Kind::PartSize(k) => enter |= crate::dialogs_part_size::rows(app, ui, k),Kind::SaveMesh(k) => enter |= crate::dialogs_save_mesh::rows(app, ui, k),Kind::ViewDxf { dashed, tolerance } => crate::dialogs_view_dxf::rows(app, ui, dashed, tolerance),+ Kind::InsertDrawing(p) => crate::dialogs_insert_drawing::rows(ui, p),Kind::Sketch => {if d.error.is_some() && matches!(d.inputs.first().and_then(|i| i.items.first()), Some(Sel::Face { .. })) {ui_kit::text(diff --git a/crates/ui-egui/src/dialogs_insert_drawing.rs b/crates/ui-egui/src/dialogs_insert_drawing.rsnew file mode 100644index 0000000000..2e59b94a3a--- /dev/null+++ b/crates/ui-egui/src/dialogs_insert_drawing.rs@@ -0,0 +1,226 @@+//! Insert SVG / Insert DXF: once the file is picked, the drawing is placed on the sketch (where+//! its middle goes, its size in millimetres or as a factor, and an angle) with a live preview,+//! and OK adds it (#2605, #3443).++use serde_json::{Value, json};++use crate::SolveApp;+use crate::dialogs::{Dialog, Kind, form_row};++/// Largest scale the insert commands take.+pub(crate) const MAX_SCALE: f64 = 1e5;++/// The drawing being placed: the insert command, its file, and where, how big and how turned+/// it goes. `x` and `y` are where the drawing's middle lands; it scales and turns about it.+#[derive(Clone, Debug, PartialEq)]+pub struct Place {+ pub command: String,+ pub path: String,+ pub x: f64,+ pub y: f64,+ pub scale: f64,+ /// Degrees, counter-clockwise.+ pub angle: f64,+ /// The drawing's own width and height in the file, when it could be read.+ pub natural: Option<(f64, f64)>,+}++/// Open the placement for `path`, picked for `command` (`sketch.insert_svg` / `_dxf`).+pub fn open(app: &mut SolveApp, command: &str, path: String) {+ let natural = app+ .session+ .execute("sketch.drawing_bounds", &json!({"path": path, "format": if command.ends_with("dxf") { "dxf" } else { "svg" }}))+ .ok()+ .and_then(|b| Some((b.get("width")?.as_f64()?, b.get("height")?.as_f64()?)))+ .filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 1e-9 && *h > 1e-9);+ app.dialog = Some(Dialog::new(+ Kind::InsertDrawing(Place { command: command.to_string(), path, x: 0.0, y: 0.0, scale: 1.0, angle: 0.0, natural }),+ Vec::new(),+ ));+}++pub fn title(p: &Place) -> &'static str {+ if p.command.ends_with("dxf") { "INSERT DXF" } else { "INSERT SVG" }+}++pub fn rows(ui: &mut egui::Ui, p: &mut Place) {+ let name = std::path::Path::new(&p.path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| p.path.clone());+ form_row(ui, "File", |ui| {+ ui.label(name).on_hover_text(&p.path);+ });+ for (label, v, handle) in [("X", &mut p.x, "dialog:insert:x"), ("Y", &mut p.y, "dialog:insert:y")] {+ form_row(ui, label, |ui| {+ let r = crate::ui_kit::number_field(ui, v, -1e9..=1e9, 0.5, " mm");+ crate::scenario::publish_handle(handle, r.rect.center());+ });+ }+ // The size in millimetres follows the scale and the other way round; the aspect is kept.+ if let Some((nw, nh)) = p.natural {+ for (label, natural, handle) in [("Width", nw, "dialog:insert:width"), ("Height", nh, "dialog:insert:height")] {+ form_row(ui, label, |ui| {+ let mut mm = natural * p.scale;+ let r = crate::ui_kit::number_field(ui, &mut mm, 0.001..=natural * MAX_SCALE, 0.5, " mm");+ if r.changed() && mm.is_finite() && mm > 0.0 {+ p.scale = (mm / natural).clamp(0.0001, MAX_SCALE);+ }+ crate::scenario::publish_handle(handle, r.rect.center());+ });+ }+ }+ form_row(ui, "Scale", |ui| {+ let r = crate::ui_kit::number_field(ui, &mut p.scale, 0.0001..=MAX_SCALE, 0.01, "");+ crate::scenario::publish_handle("dialog:insert:scale", r.rect.center());+ });+ form_row(ui, "Angle", |ui| {+ let r = crate::ui_kit::number_field(ui, &mut p.angle, -360.0..=360.0, 1.0, "\u{b0}");+ crate::scenario::publish_handle("dialog:insert:angle", r.rect.center());+ });+}++/// The command OK runs (and the preview shows).+pub fn commands(p: &Place) -> Result<Vec<(String, Value)>, String> {+ if !(p.x.is_finite() && p.y.is_finite()) {+ return Err("the position must be a number".into());+ }+ if !(p.scale.is_finite() && p.scale > 1e-9 && p.scale <= MAX_SCALE) {+ return Err("the scale must be above 0".into());+ }+ if !p.angle.is_finite() {+ return Err("the angle must be a number".into());+ }+ Ok(vec![(p.command.clone(), json!({"path": p.path, "at": [p.x, p.y], "scale": p.scale, "angle": p.angle, "align": "center"}))])+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::scenario::{Harness, handle_at};++ fn svg_file(name: &str) -> String {+ let dir = std::env::temp_dir().join(format!("solidcraft-insert-place-{}", std::process::id()));+ let _ = std::fs::create_dir_all(&dir);+ let path = dir.join(name);+ std::fs::write(&path, r#"<svg xmlns="http://www.w3.org/2000/svg" width="20mm" height="10mm" viewBox="0 0 20 10"><rect x="0" y="0" width="20" height="10"/></svg>"#).unwrap();+ path.to_string_lossy().to_string()+ }++ fn lines(h: &Harness) -> Vec<(solidcraft_engine::geom::Vec2, solidcraft_engine::geom::Vec2)> {+ let st = h.app.session.world_state();+ let sk = &st.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch;+ (0..sk.curves.len())+ .filter_map(|i| match sk.shape(i) {+ Some(solidcraft_engine::sketch::Shape::Line { a, b }) => Some((a, b)),+ _ => None,+ })+ .collect()+ }++ /// Insert SVG asks for the file, then places it: X, Y and Scale move and size the drawing+ /// before OK adds it, in one undo step.+ #[test]+ fn a_picked_svg_is_placed_and_scaled_before_it_is_added() {+ let mut h = Harness::new();+ let path = svg_file("plate.svg");+ let picked = path.clone();+ h.app.services.pick_open = Some(Box::new(move |_| Box::pin(std::future::ready(Some(picked.clone())))));+ h.app.run("sketch.create", json!({"plane": "XY"})).unwrap();+ h.settle();+ h.app.start("sketch.insert_svg");+ h.frames(3);+ let Some(Kind::InsertDrawing(p)) = h.app.dialog.as_ref().map(|d| d.kind.clone()) else { panic!("no placement: {:?}", h.app.status) };+ assert_eq!((p.path.as_str(), p.x, p.y, p.scale, p.angle, p.natural), (path.as_str(), 0.0, 0.0, 1.0, 0.0, Some((20.0, 10.0))));+ assert!(handle_at("dialog:insert:scale").is_some(), "the scale is drawn");+ assert!(lines(&h).is_empty(), "nothing is added before OK");+ // The drawing is previewed where it would go.+ h.step(&json!({"until": {"count": {"name": "sketch_preview_curves", "value": 4}}})).unwrap();+ if let Some(Kind::InsertDrawing(p)) = h.app.dialog.as_mut().map(|d| &mut d.kind) {+ (p.x, p.y, p.scale) = (5.0, -3.0, 2.0);+ }+ h.step(&json!({"key": "Enter"})).unwrap();+ h.settle();+ assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone()));+ let pts: Vec<_> = lines(&h).into_iter().flat_map(|(a, b)| [a, b]).collect();+ assert_eq!(pts.len(), 8, "the rectangle's four lines");+ let (lo_x, hi_x) = pts.iter().fold((f64::MAX, f64::MIN), |(l, u), p| (l.min(p.x), u.max(p.x)));+ let (lo_y, hi_y) = pts.iter().fold((f64::MAX, f64::MIN), |(l, u), p| (l.min(p.y), u.max(p.y)));+ assert!((hi_x - lo_x - 40.0).abs() < 1e-6 && (hi_y - lo_y - 20.0).abs() < 1e-6, "twice its size: {lo_x}..{hi_x} × {lo_y}..{hi_y}");+ assert!(((lo_x + hi_x) / 2.0 - 5.0).abs() < 1e-6, "its middle is at X: {lo_x}..{hi_x}");+ assert!(((lo_y + hi_y) / 2.0 + 3.0).abs() < 1e-6, "its middle is at Y: {lo_y}..{hi_y}");+ h.app.run("edit.undo", json!({})).unwrap();+ h.settle();+ assert!(lines(&h).is_empty(), "one undo removes the drawing");+ }++ /// The width in millimetres sets the scale, and the angle turns the drawing about its middle.+ #[test]+ fn a_width_and_an_angle_size_and_turn_the_drawing_about_its_middle() {+ let mut h = Harness::new();+ h.app.run("sketch.create", json!({"plane": "XY"})).unwrap();+ h.settle();+ open(&mut h.app, "sketch.insert_svg", svg_file("turned.svg"));+ h.frames(2);+ assert!(handle_at("dialog:insert:width").is_some() && handle_at("dialog:insert:angle").is_some(), "the new fields are drawn");+ if let Some(Kind::InsertDrawing(p)) = h.app.dialog.as_mut().map(|d| &mut d.kind) {+ let (nw, _) = p.natural.unwrap();+ // 40 mm wide, as the Width field sets it, turned a quarter, middle at (5, -3).+ p.scale = 40.0 / nw;+ (p.x, p.y, p.angle) = (5.0, -3.0, 90.0);+ }+ h.step(&json!({"key": "Enter"})).unwrap();+ h.settle();+ assert!(h.app.dialog.is_none());+ let pts: Vec<_> = lines(&h).into_iter().flat_map(|(a, b)| [a, b]).collect();+ let (lo_x, hi_x) = pts.iter().fold((f64::MAX, f64::MIN), |(l, u), p| (l.min(p.x), u.max(p.x)));+ let (lo_y, hi_y) = pts.iter().fold((f64::MAX, f64::MIN), |(l, u), p| (l.min(p.y), u.max(p.y)));+ assert!((hi_x - lo_x - 20.0).abs() < 1e-6 && (hi_y - lo_y - 40.0).abs() < 1e-6, "turned: {lo_x}..{hi_x} x {lo_y}..{hi_y}");+ assert!(((lo_x + hi_x) / 2.0 - 5.0).abs() < 1e-6 && ((lo_y + hi_y) / 2.0 + 3.0).abs() < 1e-6, "about its middle");+ }++ /// The drawing's handles in the viewport edit the same values: a corner scales about the+ /// opposite one, the box moves, and the knob turns.+ #[test]+ fn the_handles_in_the_viewport_scale_move_and_turn_the_drawing() {+ let mut h = Harness::new();+ h.app.run("sketch.create", json!({"plane": "XY"})).unwrap();+ h.step(&json!({"call": "ui.view", "params": {"view": "top"}})).unwrap();+ h.settle();+ open(&mut h.app, "sketch.insert_svg", svg_file("handles.svg"));+ h.frames(4);+ let place = |h: &Harness| match h.app.dialog.as_ref().map(|d| d.kind.clone()) {+ Some(Kind::InsertDrawing(p)) => p,+ other => panic!("no placement: {other:?}"),+ };+ // The corner at (+10, +5) dragged to (+30, +15): twice the size, the corner at (-10, -5) stays.+ h.step(&json!({"drag": [{"handle": "insert:handle:3"}, {"world": [30, 15, 0]}]})).unwrap();+ h.frames(3);+ let p = place(&h);+ assert!((p.scale - 2.0).abs() < 0.05, "scaled: {}", p.scale);+ assert!((p.x - 10.0).abs() < 0.5 && (p.y - 5.0).abs() < 0.5, "about the far corner: {}, {}", p.x, p.y);+ // The box dragged by its middle by (+5, -4).+ let (x, y) = (p.x, p.y);+ h.step(&json!({"drag": [{"world": [x, y, 0]}, {"world": [x + 5.0, y - 4.0, 0]}]})).unwrap();+ h.frames(3);+ let p = place(&h);+ assert!((p.x - x - 5.0).abs() < 0.5 && (p.y - y + 4.0).abs() < 0.5, "moved: {}, {}", p.x, p.y);+ // The knob above the box, dragged to the left of the middle: a quarter turn.+ h.step(&json!({"drag": [{"handle": "insert:handle:5"}, {"world": [p.x - 30.0, p.y, 0]}]})).unwrap();+ h.frames(3);+ assert!((place(&h).angle - 90.0).abs() < 2.0, "turned: {}", place(&h).angle);+ }++ /// Cancel adds nothing; a bad scale is refused.+ #[test]+ fn cancelling_the_placement_adds_nothing() {+ let mut h = Harness::new();+ h.app.run("sketch.create", json!({"plane": "XY"})).unwrap();+ h.settle();+ open(&mut h.app, "sketch.insert_svg", svg_file("cancel.svg"));+ h.frames(2);+ let bad = Place { command: "sketch.insert_svg".into(), path: "x.svg".into(), x: 0.0, y: 0.0, scale: 0.0, angle: 0.0, natural: None };+ assert!(commands(&bad).is_err());+ h.step(&json!({"key": "Escape"})).unwrap();+ h.settle();+ assert!(h.app.dialog.is_none());+ assert!(lines(&h).is_empty(), "nothing added");+ }+}diff --git a/crates/ui-egui/src/insert_handles.rs b/crates/ui-egui/src/insert_handles.rsnew file mode 100644index 0000000000..ff3e7616f4--- /dev/null+++ b/crates/ui-egui/src/insert_handles.rs@@ -0,0 +1,217 @@+//! Handles on the drawing being placed by Insert SVG / DXF: its box with a corner at each end+//! to scale (the opposite corner stays put, the aspect is kept), the box itself to move, and a+//! knob above it to turn (Shift snaps to 15 degrees). They change the same X, Y, Scale and Angle+//! the window shows.++use egui::{Pos2, Sense, Stroke, Vec2 as Screen, vec2};+use solidcraft_engine::geom::{Plane, Vec2};++use crate::SolveApp;+use crate::dialogs::Kind;+use crate::dialogs_insert_drawing::{MAX_SCALE, Place};+use crate::viewport::Proj;++/// Half the side of a corner handle, in screen points.+const HANDLE: f32 = 6.0;+/// How far above the box the turning knob sits, in screen points.+const KNOB_GAP: f32 = 28.0;+/// Smallest scale a drag makes.+const MIN_SCALE: f64 = 0.0001;++/// What a drag took hold of.+#[derive(Clone, Copy, Debug, PartialEq)]+enum Part {+ Move,+ /// A corner, by its signs in the box's own frame.+ Corner(f64, f64),+ Turn,+}++/// A drag in progress.+#[derive(Clone, Debug)]+pub struct Drag {+ part: Part,+ /// The pointer on the sketch where it began, and the placement then.+ from: Vec2,+ at: (f64, f64, f64, f64),+}++/// The box's half sizes (mm), unturned.+fn half(p: &Place) -> Option<Vec2> {+ let (w, h) = p.natural?;+ Some(Vec2::new(w * p.scale / 2.0, h * p.scale / 2.0))+}++fn turn(v: Vec2, degrees: f64) -> Vec2 {+ let (s, c) = degrees.to_radians().sin_cos();+ Vec2::new(v.x * c - v.y * s, v.x * s + v.y * c)+}++/// A spot of the box in its own frame (`u`, `v` in half sizes) on the sketch.+fn spot(p: &Place, u: f64, v: f64) -> Option<Vec2> {+ let h = half(p)?;+ Some(Vec2::new(p.x, p.y) + turn(Vec2::new(u * h.x, v * h.y), p.angle))+}++fn on_screen(plane: &Plane, proj: &Proj, q: Vec2) -> Option<Pos2> {+ proj.to_screen(plane.to_world(q))+}++fn pointer_on_sketch(plane: &Plane, proj: &Proj, at: Pos2) -> Option<Vec2> {+ let (o, d) = proj.ray(at);+ plane.intersect_ray(o, d).map(|w| plane.to_local(w))+}++fn place_of(app: &SolveApp) -> Option<Place> {+ match app.dialog.as_ref().map(|d| &d.kind) {+ Some(Kind::InsertDrawing(p)) => Some(p.clone()),+ _ => None,+ }+}++/// The placement window's drawing, with its handles. A drag on them edits the window's values.+pub fn show(app: &mut SolveApp, ui: &mut egui::Ui, proj: &Proj) {+ let Some(place) = place_of(app) else {+ app.viewport.insert_drag = None;+ return;+ };+ let Some(plane) = app.session.active_sketch.and_then(|id| crate::canvas::profile_plane(app, id)) else { return };+ let Some(corners) = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]+ .iter()+ .map(|(u, v)| spot(&place, *u, *v).and_then(|q| on_screen(&plane, proj, q)))+ .collect::<Option<Vec<_>>>()+ else {+ return;+ };+ let (Some(top), Some(knob_from)) =+ (spot(&place, 0.0, 1.0).and_then(|q| on_screen(&plane, proj, q)), spot(&place, 0.0, 0.0).and_then(|q| on_screen(&plane, proj, q)))+ else {+ return;+ };+ let away = (top - knob_from).normalized();+ let knob = top + if away.length() > 0.0 { away * KNOB_GAP } else { vec2(0.0, -KNOB_GAP) };+ let t = crate::theme::Tokens::get();+ let painter = ui.painter().clone();+ let stroke = Stroke::new(1.5, t.accent);+ painter.add(egui::Shape::closed_line(corners.clone(), stroke));+ painter.line_segment([top, knob], stroke);+ painter.circle(knob, HANDLE, t.overlay, stroke);++ // Whole box first, so the corners and the knob above it win where they overlap.+ let mut parts: Vec<(egui::Rect, Part, egui::CursorIcon)> = Vec::new();+ let bounds = egui::Rect::from_points(&corners);+ parts.push((bounds, Part::Move, egui::CursorIcon::Grab));+ for (c, (u, v)) in corners.iter().zip([(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]) {+ painter.rect(egui::Rect::from_center_size(*c, Screen::splat(HANDLE * 2.0)), 1.0, t.overlay, stroke, egui::StrokeKind::Inside);+ parts.push((egui::Rect::from_center_size(*c, Screen::splat(HANDLE * 3.0)), Part::Corner(u, v), egui::CursorIcon::ResizeNwSe));+ }+ parts.push((egui::Rect::from_center_size(knob, Screen::splat(HANDLE * 3.0)), Part::Turn, egui::CursorIcon::Crosshair));+ for (i, (rect, part, cursor)) in parts.into_iter().enumerate() {+ let response = ui.interact(rect, egui::Id::new(("sc_insert_handle", i)), Sense::drag()).on_hover_cursor(cursor);+ crate::scenario::publish_handle(&format!("insert:handle:{i}"), rect.center());+ if response.drag_started()+ && let Some(from) = response.interact_pointer_pos().and_then(|p| pointer_on_sketch(&plane, proj, p))+ {+ app.viewport.insert_drag = Some(Drag { part, from, at: (place.x, place.y, place.scale, place.angle) });+ }+ // The release frame carries the last move too: it counts, or a quick drag stops short.+ if (response.dragged() || response.drag_stopped())+ && let Some(drag) = app.viewport.insert_drag.clone()+ && drag.part == part+ && let Some(p) =+ response.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())).and_then(|p| pointer_on_sketch(&plane, proj, p))+ {+ let snap = ui.input(|i| i.modifiers.shift);+ if let Some(Kind::InsertDrawing(target)) = app.dialog.as_mut().map(|d| &mut d.kind) {+ apply(target, &drag, p, snap);+ }+ }+ if response.drag_stopped() {+ app.viewport.insert_drag = None;+ }+ }+}++/// The placement after the pointer has moved to `p`, from where `drag` began.+fn apply(target: &mut Place, drag: &Drag, p: Vec2, snap: bool) {+ let (x, y, scale, angle) = drag.at;+ let start = Place { x, y, scale, angle, ..target.clone() };+ match drag.part {+ Part::Move => {+ target.x = x + (p.x - drag.from.x);+ target.y = y + (p.y - drag.from.y);+ }+ Part::Turn => {+ let to = p - Vec2::new(x, y);+ if to.len() > 1e-9 {+ let a = to.angle().to_degrees() - 90.0;+ let a = if snap { (a / 15.0).round() * 15.0 } else { a };+ // Into -180..180, the range the field takes.+ target.angle = (a + 180.0).rem_euclid(360.0) - 180.0;+ }+ }+ Part::Corner(u, v) => {+ let (Some((nw, nh)), Some(fixed)) = (start.natural, spot(&start, -u, -v)) else { return };+ // The pointer in the box's own frame, measured from the corner that stays.+ let local = turn(p - fixed, -angle);+ let k = (local.x.abs() / nw).max(local.y.abs() / nh).clamp(MIN_SCALE, MAX_SCALE);+ if k.is_finite() {+ let reach = turn(Vec2::new(u * k * nw / 2.0, v * k * nh / 2.0), angle);+ target.scale = k;+ target.x = fixed.x + reach.x;+ target.y = fixed.y + reach.y;+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn place() -> Place {+ Place { command: "sketch.insert_svg".into(), path: "a.svg".into(), x: 10.0, y: 5.0, scale: 1.0, angle: 0.0, natural: Some((20.0, 10.0)) }+ }++ fn drag(part: Part, from: Vec2, p: &Place) -> Drag {+ Drag { part, from, at: (p.x, p.y, p.scale, p.angle) }+ }++ /// A corner drag scales about the opposite corner, which does not move.+ #[test]+ fn a_corner_scales_about_the_opposite_corner() {+ let mut p = place();+ let fixed = spot(&p, -1.0, -1.0).unwrap();+ let d = drag(Part::Corner(1.0, 1.0), spot(&p, 1.0, 1.0).unwrap(), &p);+ // The corner at (20, 10) goes to (40, 20) from the fixed one at (0, 0): twice the size.+ apply(&mut p, &d, Vec2::new(40.0, 20.0), false);+ assert!((p.scale - 2.0).abs() < 1e-9, "{}", p.scale);+ let now = spot(&p, -1.0, -1.0).unwrap();+ assert!(now.dist(fixed) < 1e-9, "the opposite corner stayed: {now:?} vs {fixed:?}");+ }++ #[test]+ fn a_turned_corner_keeps_its_opposite_corner_too() {+ let mut p = Place { angle: 30.0, ..place() };+ let fixed = spot(&p, 1.0, -1.0).unwrap();+ let d = drag(Part::Corner(-1.0, 1.0), spot(&p, -1.0, 1.0).unwrap(), &p);+ let pulled = spot(&p, -1.0, 1.0).unwrap() + turn(Vec2::new(-10.0, 5.0), 30.0);+ apply(&mut p, &d, pulled, false);+ assert!(p.scale > 1.0);+ assert!(spot(&p, 1.0, -1.0).unwrap().dist(fixed) < 1e-9);+ }++ #[test]+ fn dragging_the_box_moves_it_and_the_knob_turns_it() {+ let mut p = place();+ let d = drag(Part::Move, Vec2::new(10.0, 5.0), &p);+ apply(&mut p, &d, Vec2::new(14.0, 1.0), false);+ assert_eq!((p.x, p.y), (14.0, 1.0));+ // The knob is straight above the middle: dragging it to the left turns a quarter.+ let d = drag(Part::Turn, Vec2::new(14.0, 10.0), &p);+ apply(&mut p, &d, Vec2::new(4.0, 1.0), false);+ assert!((p.angle - 90.0).abs() < 1e-9, "{}", p.angle);+ apply(&mut p, &d, Vec2::new(4.0, 3.0), true);+ assert!(p.angle == 90.0 || (p.angle % 15.0).abs() < 1e-9, "snapped: {}", p.angle);+ }+}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 742dcdc155..6ee63053c2 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -38,6 +38,7 @@ pub mod dialogs_assembly;pub mod dialogs_coupling;pub mod dialogs_frame;mod dialogs_hole;+pub mod dialogs_insert_drawing;pub mod dialogs_library;pub mod dialogs_motion;pub mod dialogs_move;@@ -89,6 +90,7 @@ mod i18n_ui_tests;pub mod icon_svg;pub mod icons;pub mod inference;+pub mod insert_handles;pub mod install;pub mod issue_report;pub mod joint_drag;@@ -1261,8 +1263,14 @@ impl SolveApp {if dialogs_sheet::start_export(self, id) {return;}+ // The picked drawing is placed (position and scale, previewed) before OK adds it.if let Some(ext) = id.strip_prefix("sketch.insert_").filter(|e| matches!(*e, "dxf" | "svg")) {- self.pick_open_command(id, json!({}), &[ext]);+ let command = id.to_string();+ self.pick_open_for(&[ext], move |app, path| {+ if let Some(path) = path {+ dialogs_insert_drawing::open(app, &command, path);+ }+ });return;}if id == "component.update_links" && !self.session.doc.links.is_empty() {diff --git a/crates/ui-egui/src/preview.rs b/crates/ui-egui/src/preview.rsindex c2b6ba059b..53d980725e 100644--- a/crates/ui-egui/src/preview.rs+++ b/crates/ui-egui/src/preview.rs@@ -406,6 +406,8 @@ pub fn compute(s: &Session, cmds: &[(String, Value)], colors: Colors) -> Job {| "sketch.chamfer.equal_distance"| "sketch.chamfer.two_distance"| "sketch.chamfer.distance_angle"+ | "sketch.insert_svg"+ | "sketch.insert_dxf") || command == "construct.plane.along_path"|| params.get("command").and_then(Value::as_str) == Some("construct.plane.along_path")}) {@@ -820,7 +822,11 @@ pub fn paint_sketches(app: &SolveApp, painter: &egui::Painter, proj: &crate::vieif app.preview.rolled_back {return;}- if !app.dialog.as_ref().is_some_and(|d| matches!(d.kind, crate::dialogs::Kind::SketchModify(_)) && d.previews()) {+ if !app+ .dialog+ .as_ref()+ .is_some_and(|d| matches!(d.kind, crate::dialogs::Kind::SketchModify(_) | crate::dialogs::Kind::InsertDrawing(_)) && d.previews())+ {return;}let stroke = egui::Stroke::new(2.5, Tokens::get().preview_sketch);diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rsindex 8712f58d89..a039fa188e 100644--- a/crates/ui-egui/src/viewport.rs+++ b/crates/ui-egui/src/viewport.rs@@ -50,6 +50,8 @@ pub enum NavMode {#[derive(Default)]pub struct ViewportState {+ /// A drag on the handles of the drawing being placed (Insert SVG / DXF).+ pub(crate) insert_drag: Option<crate::insert_handles::Drag>,/// The arrow turning the view that is still down (`navigation::step_key_hold`).pub(crate) key_hold: Option<crate::navigation::KeyHold>,/// A two-point drawing tool's first point was placed by a press (here) that became a drag:@@ -3931,6 +3933,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {crate::sketch3d::show(app, &painter, &proj);crate::inference::show(app, &painter, &proj);crate::drag_snap::show(app, &painter, &proj);+ crate::insert_handles::show(app, ui, &proj);hover_highlight(app, &painter, &proj);crate::drag_extrude::tick(app);crate::drag_extrude::show(app, &painter);diff --git a/crates/ui-egui/tests/scenarios.rs b/crates/ui-egui/tests/scenarios.rsindex 95e7c18e94..2a72fcab6a 100644--- a/crates/ui-egui/tests/scenarios.rs+++ b/crates/ui-egui/tests/scenarios.rs@@ -181,6 +181,9 @@ fn sketch_toolbar_imports_use_file_picker() {{"call":"engine.execute","params":{"command":"sketch.create","params":{"plane":"XY"}}},{"choose_file":path},{"start":"sketch.insert_svg"},+ // The picked drawing is placed first (#2605): OK adds it.+ {"expect":{"dialog":"InsertDrawing","sketch_curves":{"own":0}}},+ {"key":"Enter"},{"expect":{"errors":0,"sketch_curves":{"own":4}}}])).unwrap();