Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Open and insert a DXF outside a sketch (#2052) (#4635)

raykholo0344a41dc45b
diff --git a/apps/solidcraft-web/src/disk.rs b/apps/solidcraft-web/src/disk.rs
index c9aa086cf1..10e0ca596b 100644
--- a/apps/solidcraft-web/src/disk.rs
+++ b/apps/solidcraft-web/src/disk.rs
@@ -114,6 +114,46 @@ pub fn opens_design(extensions: &[&str]) -> bool {
extensions.is_empty() || extensions.iter().any(|e| solidcraft_engine::io::DESIGN_EXTS.contains(e))
}
+/// Where an Open for `extensions` (what the command reads; `&[]`: anything) is answered.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum OpenRoute {
+ /// The browser's open dialog for a design: the file keeps its handle, so Save writes back.
+ Disk,
+ /// The "Files in this browser" window, where the browser can't open a design from the disk.
+ Panel,
+ /// A plain file input that offers these types: the file is read into the engine's files and
+ /// the command runs on it (Insert DXF or SVG, images, meshes, imported settings).
+ Upload,
+}
+
+/// Choose how an Open for `extensions` asks for its file; `api`: the browser can open a file
+/// from the disk and keep its handle.
+pub fn open_route(api: bool, extensions: &[&str]) -> OpenRoute {
+ match (opens_design(extensions), api) {
+ (true, true) => OpenRoute::Disk,
+ (true, false) => OpenRoute::Panel,
+ (false, _) => OpenRoute::Upload,
+ }
+}
+
+/// The `accept` list of a file input for `extensions` (with or without their dot): ".dxf,.svg".
+pub fn accept_list(extensions: &[&str]) -> String {
+ let list: Vec<String> = extensions
+ .iter()
+ .map(|e| e.trim().trim_start_matches('.'))
+ .filter(|e| !e.is_empty())
+ .map(|e| format!(".{}", e.to_ascii_lowercase()))
+ .collect();
+ list.join(",")
+}
+
+/// The largest file an upload for `extensions` reads: images go into a canvas, which has a size
+/// limit, so a bigger one is refused before it is read. `None`: the importer checks the file.
+pub fn upload_limit(extensions: &[&str]) -> Option<usize> {
+ let image = |e: &&str| ["png", "jpg", "jpeg"].contains(&e.trim_start_matches('.').to_ascii_lowercase().as_str());
+ (!extensions.is_empty() && extensions.iter().all(image)).then_some(solidcraft_engine::doc::canvas::MAX_CANVAS_BYTES)
+}
+
/// The file type a Save As dialog offers for `name`: (description, MIME type, extension).
pub fn save_type(name: &str) -> (&'static str, &'static str, &'static str) {
let json = std::path::Path::new(name).extension().is_some_and(|e| e.eq_ignore_ascii_case("json"));
@@ -140,7 +180,7 @@ mod web {
use wasm_bindgen_futures::{JsFuture, spawn_local};
use web_sys::{FileSystemFileHandle, IdbDatabase, IdbObjectStore, IdbOpenDbRequest, IdbRequest, IdbTransactionMode};
- use super::{HANDLE_MAX_AGE_MS, is_abort, make_id, opens_design, parse, path, plan_prune, save_type};
+ use super::{HANDLE_MAX_AGE_MS, is_abort, make_id, parse, path, plan_prune, save_type};
use crate::files::{Files, err, read_handle};
const DB: &str = "solidcraft-disk-handles";
@@ -294,7 +334,7 @@ mod web {
let options = Object::new();
let _ = Reflect::set(&options, &"multiple".into(), &JsValue::FALSE);
let extensions = Array::new();
- for e in [".solidcraft", ".solvecraft", ".json", ".step", ".stp", ".3mf", ".stl", ".obj", ".glb", ".gltf", ".fcstd", ".3dm"] {
+ for e in [".solidcraft", ".solvecraft", ".json", ".step", ".stp", ".3mf", ".stl", ".obj", ".glb", ".gltf", ".fcstd", ".3dm", ".dxf", ".svg"] {
extensions.push(&e.into());
}
let accept = Object::new();
@@ -315,11 +355,6 @@ mod web {
p
}
- /// Does an Open for `extensions` use the browser's open dialog?
- pub fn handles_open(extensions: &[&str]) -> bool {
- supported() && opens_design(extensions)
- }
-
// ---- writing ------------------------------------------------------------------------
/// Queue what a command wrote to a disk path. Writes go one at a time; a newer write of the
@@ -621,6 +656,21 @@ mod tests {
assert!(!opens_design(&["json"]));
}
+ /// Insert DXF or SVG, images and other non-design files get a file input that offers their
+ /// types in every browser (#2052); designs keep the disk dialog or the browser's files.
+ #[test]
+ fn opens_of_other_files_use_a_file_input_for_their_types() {
+ assert_eq!(open_route(true, &["dxf"]), OpenRoute::Upload);
+ assert_eq!(open_route(false, &["png", "jpg", "jpeg"]), OpenRoute::Upload);
+ assert_eq!(open_route(true, &[]), OpenRoute::Disk);
+ assert_eq!(open_route(false, &["solidcraft"]), OpenRoute::Panel);
+ assert_eq!(accept_list(&["dxf"]), ".dxf");
+ assert_eq!(accept_list(&["png", ".JPG", "", "jpeg"]), ".png,.jpg,.jpeg");
+ assert_eq!(accept_list(&[]), "");
+ assert!(upload_limit(&["png", "jpg", "jpeg"]).is_some());
+ assert_eq!(upload_limit(&["dxf"]), None);
+ }
+
#[test]
fn the_save_dialog_offers_the_type_of_the_name() {
assert_eq!(save_type("Plate.solidcraft").2, ".solidcraft");
diff --git a/apps/solidcraft-web/src/files.rs b/apps/solidcraft-web/src/files.rs
index 5e7d67fcc0..a04aa543a1 100644
--- a/apps/solidcraft-web/src/files.rs
+++ b/apps/solidcraft-web/src/files.rs
@@ -500,8 +500,9 @@ fn input_picker(files: &Rc<Files>, intent: Intent) {
let Ok(input) = doc.create_element("input").map(|e| e.unchecked_into::<web_sys::HtmlInputElement>()) else { return };
input.set_type("file");
// Everything the browser build imports, from the format registry: cadmpeg is pure Rust, so
- // FreeCAD and Rhino files are part of it.
- let accept = solidcraft_engine::io::formats::open_extensions(true).iter().map(|e| format!(".{e}")).collect::<Vec<_>>().join(",");
+ // FreeCAD and Rhino files are part of it; plus the DXF and SVG drawings Open and Insert take.
+ let accept =
+ solidcraft_engine::io::formats::open_extensions(true).iter().chain(&["dxf", "svg"]).map(|e| format!(".{e}")).collect::<Vec<_>>().join(",");
input.set_accept(&accept);
// Attached (hidden) while it is open: some browsers ignore a click on a detached input.
let _ = input.set_attribute("style", "display:none");
@@ -527,6 +528,67 @@ fn input_picker(files: &Rc<Files>, intent: Intent) {
input.click();
}
+/// Ask for one file of these types (`extensions`, e.g. `["dxf"]`) with a plain file input, the
+/// dialog every browser has. The answer is the file's path in the engine's files (under
+/// [`UPLOAD`], as for a file picked in the disk dialog), so the command that asked runs on it;
+/// `None` when the dialog was closed or the file could not be read.
+pub fn pick_upload(files: &Rc<Files>, extensions: &[&str]) -> impl std::future::Future<Output = Option<String>> + use<> {
+ // Shown now, in the click: a file dialog needs the user's gesture.
+ let chosen = choose_file(&disk::accept_list(extensions));
+ let limit = disk::upload_limit(extensions);
+ let files = files.clone();
+ async move {
+ let read = async {
+ let value = JsFuture::from(chosen?).await.map_err(err)?;
+ // Closing the dialog answers no file: nothing to say.
+ let Ok(file) = value.dyn_into::<web_sys::File>() else { return Ok(None) };
+ let name = file.name();
+ if limit.is_some_and(|max| !file.size().is_finite() || file.size() > max as f64) {
+ return Err(format!("{name}: the file is too large"));
+ }
+ let bytes = blob_bytes(&file).await.map_err(|e| format!("{name}: {e}"))?;
+ let path = format!("{UPLOAD}{name}");
+ vfs::insert(&path, bytes);
+ Ok(Some(path))
+ };
+ match read.await {
+ Ok(path) => path,
+ Err(e) => {
+ files.say(format!("open: {e}"), true);
+ None
+ }
+ }
+ }
+}
+
+/// Show a hidden `<input type=file>` offering `accept` (call in the click). The promise answers
+/// the picked `File`, or `null` when the dialog is closed (the input's `cancel` event).
+fn choose_file(accept: &str) -> Result<js_sys::Promise, String> {
+ let doc = web_sys::window().and_then(|w| w.document()).ok_or("this page can't show a file dialog")?;
+ let input = doc.create_element("input").map_err(err)?.dyn_into::<web_sys::HtmlInputElement>().map_err(|_| "no file input".to_string())?;
+ input.set_type("file");
+ input.set_accept(accept);
+ // Attached (hidden) while it is open: some browsers ignore a click on a detached input.
+ input.set_attribute("style", "display:none").map_err(err)?;
+ doc.body().ok_or("this page has no body")?.append_child(&input).map_err(err)?;
+ let promise = js_sys::Promise::new(&mut |resolve: Function, _reject: Function| {
+ // One answer for a pick or a cancel; read from the event, so it does not keep the input.
+ let done = Closure::once_into_js(move |event: web_sys::Event| {
+ let file = event.target().and_then(|t| t.dyn_into::<web_sys::HtmlInputElement>().ok()).and_then(|input| {
+ input.set_onchange(None);
+ input.set_oncancel(None);
+ input.remove();
+ input.files().and_then(|list| list.get(0))
+ });
+ let _ = resolve.call1(&JsValue::UNDEFINED, &file.map_or(JsValue::NULL, JsValue::from));
+ });
+ input.set_onchange(Some(done.unchecked_ref()));
+ input.set_oncancel(Some(done.unchecked_ref()));
+ });
+ input.click();
+ Ok(promise)
+}
+
/// Read files dropped on the page.
pub fn take_drops(files: &Rc<Files>, raw: &mut egui::RawInput) {
for f in std::mem::take(&mut raw.dropped_files) {
diff --git a/apps/solidcraft-web/src/main.rs b/apps/solidcraft-web/src/main.rs
index 8631aa93f1..05ce3cc65b 100644
--- a/apps/solidcraft-web/src/main.rs
+++ b/apps/solidcraft-web/src/main.rs
@@ -330,7 +330,7 @@ mod web {
files::pick_from_disk(&self.files, Intent::Open);
}
if ui_kit::button(ui, "Insert from computer…", ui_kit::Button::Normal)
- .on_hover_text("STEP, 3MF or STL into the open design")
+ .on_hover_text(solidcraft_ui_egui::i18n::tr("web.files.insert_drawings_hint"))
.clicked()
{
files::pick_from_disk(&self.files, Intent::Insert);
@@ -383,7 +383,7 @@ mod web {
let design = solidcraft_engine::io::is_design_path(&e.name);
if !design
&& ui_kit::button(ui, "Insert", ui_kit::Button::Small)
- .on_hover_text("Into the open design (STEP, 3MF, STL)")
+ .on_hover_text(solidcraft_ui_egui::i18n::tr("web.files.insert_stored_drawings_hint"))
.clicked()
{
act = Some(("insert", e.name.clone()));
@@ -707,14 +707,17 @@ mod web {
let (restorable, restorer) = (files.clone(), files.clone());
let services = if launch.embed { Services::default() } else { Services {
// Open shows the browser's open dialog for a design where it has one
- // (the file keeps its handle, so Save writes back to it); otherwise,
- // and for inserting STEP or meshes, the browser's files window.
- pick_open: Some(Box::new(move |exts: &[&str]| {
- if disk::handles_open(exts) {
- return Box::pin(disk::pick_open(&opener));
+ // (the file keeps its handle, so Save writes back to it), else the
+ // browser's files window. A command that reads another kind of file
+ // (Insert DXF or SVG, an image, a mesh, settings) gets a file dialog
+ // offering that kind, and runs on the picked file.
+ pick_open: Some(Box::new(move |exts: &[&str]| match disk::open_route(disk::supported(), exts) {
+ disk::OpenRoute::Disk => Box::pin(disk::pick_open(&opener)),
+ disk::OpenRoute::Upload => Box::pin(files::pick_upload(&opener, exts)),
+ disk::OpenRoute::Panel => {
+ panel.panel.set(true);
+ Box::pin(std::future::ready(None))
}
- panel.panel.set(true);
- Box::pin(std::future::ready(None))
})),
// A design is saved to a file the user picks, or kept in the browser
// where the browser can't pick one; everything else is downloaded.
diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs
index a7e3b3755e..e84ba50bdc 100644
--- a/apps/solidcraft/src/main.rs
+++ b/apps/solidcraft/src/main.rs
@@ -292,7 +292,9 @@ fn services(cc: &eframe::CreationContext<'_>) -> Services {
dialog = dialog.add_filter(label, &case_variants(first));
}
// The groups come from the format registry, so a new format joins this dialog by itself.
- dialog = dialog.add_filter("Designs, CAD files and meshes", &case_variants(&io::formats::open_extensions(true)));
+ let mut everything = io::formats::open_extensions(true);
+ everything.extend(["dxf", "svg"]);
+ dialog = dialog.add_filter(solidcraft_ui_egui::i18n::tr("file.open.drawing_filter"), &case_variants(&everything));
for (label, exts) in io::formats::import_filters(true) {
dialog = dialog.add_filter(label, &case_variants(&exts));
}
diff --git a/assets/locales/pending/open-insert-drawings.json b/assets/locales/pending/open-insert-drawings.json
new file mode 100644
index 0000000000..0ff75dc074
--- /dev/null
+++ b/assets/locales/pending/open-insert-drawings.json
@@ -0,0 +1,17 @@
+{
+ "en": {
+ "file.open.drawing_filter": "Designs, CAD files, meshes and drawings",
+ "web.files.insert_drawings_hint": "CAD files, meshes, DXF or SVG into the open design",
+ "web.files.insert_stored_drawings_hint": "Into the open design (CAD files, meshes, DXF, SVG)"
+ },
+ "ja": {
+ "file.open.drawing_filter": "デザイン、CADファイル、メッシュ、図面",
+ "web.files.insert_drawings_hint": "CADファイル、メッシュ、DXF、SVGを開いているデザインに挿入",
+ "web.files.insert_stored_drawings_hint": "開いているデザインに挿入(CADファイル、メッシュ、DXF、SVG)"
+ },
+ "zh": {
+ "file.open.drawing_filter": "设计、CAD 文件、网格和图纸",
+ "web.files.insert_drawings_hint": "将 CAD 文件、网格、DXF 或 SVG 插入当前设计",
+ "web.files.insert_stored_drawings_hint": "插入当前设计(CAD 文件、网格、DXF、SVG)"
+ }
+}
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index 430a109cf9..acd5ff444b 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -1,4 +1,4 @@
-//! Documents and files: new, open (designs and STEP), insert STEP, save, export.
+//! Documents and files: new, open designs, CAD files and drawings, insert STEP, save, export.
#[path = "file_thumbnail.rs"]
mod thumbnail;
@@ -20,7 +20,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.icon("open")
.key("Ctrl+O")
.noundo()
- .params("path: .solidcraft design, or a .step/.stp/.igs/.fcstd/.3dm/.3mf/.stl/.obj/.glb/.gltf file (STEP, IGES, FreeCAD, Rhino, 3MF, STL, OBJ or glTF; opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make); up?: z|y for a STEP, IGES, FreeCAD, Rhino or glTF file (see file.insert_step and file.insert_mesh); names?: auto|solid|product|instance for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step); read_only?: bool (a design: saving to its own file is refused, file.save_as keeps the changes elsewhere) → open_elsewhere: {host, user, app, opened} when another SolidCraft has the design open (its lock file is fresh)"),
+ .params("path: .solidcraft design, .dxf/.svg drawing (opens as a new, unsaved design with an XY sketch, using sketch.insert_dxf/sketch.insert_svg units and defaults), or a .step/.stp/.igs/.fcstd/.3dm/.3mf/.stl/.obj/.glb/.gltf file (STEP, IGES, FreeCAD, Rhino, 3MF, STL, OBJ or glTF; opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make); up?: z|y for a STEP, IGES, FreeCAD, Rhino or glTF file (see file.insert_step and file.insert_mesh); names?: auto|solid|product|instance for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step); read_only?: bool (a design: saving to its own file is refused, file.save_as keeps the changes elsewhere) → open_elsewhere: {host, user, app, opened} when another SolidCraft has the design open (its lock file is fresh)"),
CommandSpec::new("file.insert_step", "Insert STEP", insert_step)
.at("SOLID", "INSERT")
.icon("import")
@@ -260,6 +260,18 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
if !solidcraft_io::is_step_path(path) && !solidcraft_io::is_gltf_path(path) && p.get("up").is_some_and(|v| !v.is_null()) {
return Err(bad("doc.open", "`up` applies to STEP, IGES and glTF files only"));
}
+ if let Some(command) = super::drawing_import_command(path) {
+ let stem = std::path::Path::new(path).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| "Untitled".into());
+ let mut fresh = Session::new(Document::new(&stem));
+ let mut out = fresh.execute(command, &json!({"path": path}))?;
+ fresh.undo.clear();
+ s.replace_design(fresh);
+ out["path"] = json!(path);
+ out["name"] = json!(s.doc.name);
+ out["features"] = json!(s.doc.features.len());
+ out["errors"] = json!(s.model.results.iter().filter(|r| r.error.is_some()).count());
+ return Ok(out);
+ }
if solidcraft_io::is_step_path(path) || solidcraft_io::is_mesh_path(path) {
// A new, unsaved design holding the file's bodies.
let stem = std::path::Path::new(path).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| "Untitled".into());
@@ -763,6 +775,35 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
+ #[test]
+ fn opening_drawing_files_creates_an_unsaved_xy_sketch() {
+ let dir = name_dir("drawing-open");
+ let dxf = "0\nSECTION\n2\nENTITIES\n0\nLINE\n10\n0\n20\n0\n11\n10\n21\n0\n0\nLINE\n10\n10\n20\n0\n11\n10\n21\n10\n0\nARC\n10\n0\n20\n0\n40\n5\n50\n0\n51\n90\n0\nENDSEC\n0\nEOF\n";
+ let svg = r#"<svg xmlns="http://www.w3.org/2000/svg"><path d="M0 0 L10 0 L10 10"/><circle cx="5" cy="5" r="2"/></svg>"#;
+ for (file, text) in [("outline.DXF", dxf), ("outline.SVG", svg)] {
+ let path = dir.join(file);
+ std::fs::write(&path, text).unwrap();
+ let mut s = Session::default();
+ s.execute("sketch.create", &json!({"plane":"YZ"})).unwrap();
+ let result = s.execute("doc.open", &json!({"path":path})).unwrap();
+ assert_eq!(result["errors"], 0);
+ assert_eq!(s.doc.features.len(), 1);
+ let id = s.active_sketch.unwrap();
+ let sketch = s.doc.sketch(id).unwrap();
+ assert_eq!(s.model.state().sketch(id).unwrap().plane, solidcraft_geom::Plane::XY);
+ assert_eq!(sketch.curves.len(), 3);
+ assert_eq!(s.doc.name, "outline");
+ assert!(s.path.is_none(), "Save must ask for a design path");
+ assert!(s.is_dirty());
+ assert!(s.undo.is_empty());
+ let before = s.doc.clone();
+ std::fs::write(&path, "invalid drawing").unwrap();
+ assert!(s.execute("doc.open", &json!({"path":path})).is_err());
+ assert_eq!(s.doc, before, "a failed open preserves the current design");
+ }
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
/// #3044: a save run on a scratch copy of the session (on a worker, so the window keeps
/// drawing) and taken up with `adopt_save` leaves the session as saving it directly does:
/// the design named after its first file, its file, and nothing unsaved; undo keeps the name.
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index 63f45ed101..316aa219f8 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -39,6 +39,7 @@ pub(crate) use face::{FaceRefForm, face_ref_form};
pub(crate) use features::profiles as feature_profiles;
pub(crate) use features::{EdgeRefForm, edge_ref_form, sketch_key};
pub use features::{auto_operation, extrude_reach};
+pub use sketch_import::drawing_import_command;
pub use sketch_modify::{extend_arc_preview, extend_preview, trim_piece};
pub use view_dxf::sketch::exportable as view_dxf_exportable;
pub use view_navigation::standard_view;
diff --git a/crates/engine/src/cmd/sketch_import.rs b/crates/engine/src/cmd/sketch_import.rs
index 22f8362a5c..e0ad13c3fd 100644
--- a/crates/engine/src/cmd/sketch_import.rs
+++ b/crates/engine/src/cmd/sketch_import.rs
@@ -26,6 +26,18 @@ pub static COMMANDS: &[CommandSpec] = &[
.params("sketch?: id|name (default active); path?: file to write (else the DXF text is returned)"),
];
+/// The sketch import command for a drawing file name, regardless of extension case.
+pub fn drawing_import_command(path: &str) -> Option<&'static str> {
+ let ext = std::path::Path::new(path).extension()?.to_str()?;
+ if ext.eq_ignore_ascii_case("dxf") {
+ Some("sketch.insert_dxf")
+ } else if ext.eq_ignore_ascii_case("svg") {
+ Some("sketch.insert_svg")
+ } else {
+ None
+ }
+}
+
fn source_text(p: &Value, cmd: &str) -> Result<String> {
if let Some(t) = str_(p, "text") {
if t.len() > MAX_DRAWING_BYTES {
diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs
index cf5113a23f..8dc8bc5b85 100644
--- a/crates/ui-egui/src/file_load.rs
+++ b/crates/ui-egui/src/file_load.rs
@@ -29,9 +29,9 @@ use crate::ui_kit;
/// What a file operation does with its file.
#[derive(Clone, Debug, PartialEq)]
pub enum Kind {
- /// Open the design (or a STEP/mesh file as a new design) in a tab of its own.
+ /// Open the design (or a CAD, mesh or drawing file as a new design) in a tab of its own.
Open,
- /// Insert a STEP or mesh file's bodies into the active design.
+ /// Insert CAD bodies, meshes or sketch drawing geometry into the active design.
Insert,
/// Open a design an earlier run autosaved before it closed.
Recover { id: String, dir: Option<String> },
@@ -71,7 +71,7 @@ impl Request {
match &self.kind {
Kind::Open => ("doc.open", self.params()),
Kind::Insert if solidcraft_engine::io::is_mesh_path(&self.path) => ("file.insert_mesh", self.params()),
- Kind::Insert => ("file.insert_step", self.params()),
+ Kind::Insert => (insert_command(&self.path), self.params()),
Kind::Recover { id, dir } => ("doc.recover", json!({"id": id, "dir": dir})),
Kind::ExportDxf => ("file.export_view_dxf", Value::Object(self.options.clone())),
Kind::UpdateLinks => ("component.update_links", json!({})),
@@ -87,6 +87,12 @@ impl Request {
}
}
+/// Route drawing files to the same commands as the sketch's Insert DXF and Insert SVG.
+pub(crate) fn insert_command(path: &str) -> &'static str {
+ solidcraft_engine::cmd::drawing_import_command(path)
+ .unwrap_or_else(|| if solidcraft_engine::io::is_mesh_path(path) { "file.insert_mesh" } else { "file.insert_step" })
+}
+
struct Made {
session: Session,
result: Value,
@@ -1064,6 +1070,58 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
mod tests {
use super::*;
+ #[test]
+ fn drawing_insert_and_drop_reuse_the_active_sketch_or_create_xy() {
+ let mut h = crate::scenario::Harness::new();
+ let dxf = solidcraft_engine::io::write_dxf(&[
+ solidcraft_engine::io::Geom2::Line(solidcraft_engine::geom::Vec2::ZERO, solidcraft_engine::geom::Vec2::new(10.0, 0.0)),
+ solidcraft_engine::io::Geom2::Arc {
+ c: solidcraft_engine::geom::Vec2::ZERO,
+ a: solidcraft_engine::geom::Vec2::new(5.0, 0.0),
+ b: solidcraft_engine::geom::Vec2::new(0.0, 5.0),
+ },
+ ]);
+ let svg = r#"<svg xmlns="http://www.w3.org/2000/svg"><path d="M0 0 L10 0 L10 10"/></svg>"#;
+ for (file, text) in [("outline.DXF", dxf.as_str()), ("outline.SVG", svg)] {
+ h.app.run("file.new", json!({})).unwrap();
+ h.app.run("sketch.create", json!({"plane":"YZ"})).unwrap();
+ h.app.run("sketch.finish", json!({})).unwrap();
+ let path = h.dir.join(file).to_string_lossy().into_owned();
+ std::fs::write(&path, text).unwrap();
+ h.app.insert_path_async(&path);
+ let wait = |h: &mut crate::scenario::Harness| {
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
+ while h.app.file_load.busy() && std::time::Instant::now() < deadline {
+ h.frames(1);
+ std::thread::yield_now();
+ }
+ assert!(!h.app.file_load.busy());
+ };
+ wait(&mut h);
+ assert_eq!(h.app.session.doc.features.len(), 2, "{:?}", h.app.status);
+ let id = h.app.session.active_sketch.unwrap();
+ assert_eq!(h.app.session.model.state().sketch(id).unwrap().plane, solidcraft_engine::geom::Plane::XY);
+ assert_eq!(h.app.session.doc.sketch(id).unwrap().curves.len(), 2);
+ h.app.cam.set_view(solidcraft_engine::render::StandardView::Top);
+ h.app.fit_view();
+ h.run(&json!([{ "shot": format!("insert-{file}") }])).unwrap();
+ h.app.drop_path(&path);
+ wait(&mut h);
+ assert_eq!(h.app.session.active_sketch, Some(id));
+ assert_eq!(h.app.session.doc.features.len(), 2);
+ assert_eq!(h.app.session.doc.sketch(id).unwrap().curves.len(), 4);
+ h.app.run("sketch.finish", json!({})).unwrap();
+ h.app.drop_path(&path);
+ wait(&mut h);
+ assert_eq!(h.app.session.doc.features.len(), 3);
+ let new_id = h.app.session.active_sketch.unwrap();
+ assert_ne!(id, new_id);
+ assert_eq!(h.app.session.doc.sketch(new_id).unwrap().curves.len(), 2);
+ h.app.insert_path(&path);
+ assert_eq!(h.app.session.doc.sketch(new_id).unwrap().curves.len(), 4);
+ }
+ }
+
#[test]
fn dxf_export_progress_keeps_frames_alive_and_never_adopts_a_worker_document() {
let mut h = crate::scenario::Harness::new();
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index bc84b4c3f9..6c94e78c9f 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -1429,10 +1429,9 @@ impl SolveApp {
file_load::begin(self, path, true);
}
- /// Insert a STEP file's bodies (an Import base feature) or a mesh file's meshes into the
- /// current design.
+ /// Insert CAD bodies, meshes or sketch drawing geometry into the current design.
pub fn insert_path(&mut self, path: &str) {
- let cmd = if solidcraft_engine::io::is_mesh_path(path) { "file.insert_mesh" } else { "file.insert_step" };
+ let cmd = file_load::insert_command(path);
let before: Vec<String> = self.session.world_state().bodies.iter().map(|b| b.name.clone()).collect();
if let Ok(r) = self.run(cmd, json!({ "path": path })) {
self.fit_view();
@@ -1443,10 +1442,11 @@ impl SolveApp {
}
}
- /// A dropped file: a STEP or mesh file (3MF, STL, OBJ, glTF) joins a design that has features, anything else
- /// opens.
+ /// A dropped CAD, mesh or drawing file joins a design that has features; otherwise it opens.
pub fn drop_path(&mut self, path: &str) {
- let import = solidcraft_engine::io::is_step_path(path) || solidcraft_engine::io::is_mesh_path(path);
+ let import = solidcraft_engine::io::is_step_path(path)
+ || solidcraft_engine::io::is_mesh_path(path)
+ || solidcraft_engine::cmd::drawing_import_command(path).is_some();
if import && !self.session.doc.features.is_empty() {
self.insert_path_async(path);
} else {