Skip to content

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

File: a command for each export format, so each can have a key (#10176) (#10177)

merik1cc90036fb20
diff --git a/assets/locales/pending/export-format-commands.json b/assets/locales/pending/export-format-commands.json
new file mode 100644
index 0000000000..463ef0815b
--- /dev/null
+++ b/assets/locales/pending/export-format-commands.json
@@ -0,0 +1,51 @@
+{
+ "en": {
+ "cmd.file.export_step": "Export STEP",
+ "cmd.file.export_stl": "Export STL",
+ "cmd.file.export_3mf": "Export 3MF",
+ "cmd.file.export_obj": "Export OBJ",
+ "cmd.file.export_urdf": "Export URDF"
+ },
+ "de": {
+ "cmd.file.export_step": "Als STEP exportieren",
+ "cmd.file.export_stl": "Als STL exportieren",
+ "cmd.file.export_3mf": "Als 3MF exportieren",
+ "cmd.file.export_obj": "Als OBJ exportieren",
+ "cmd.file.export_urdf": "Als URDF exportieren"
+ },
+ "ar": {
+ "cmd.file.export_step": "تصدير STEP",
+ "cmd.file.export_stl": "تصدير STL",
+ "cmd.file.export_3mf": "تصدير 3MF",
+ "cmd.file.export_obj": "تصدير OBJ",
+ "cmd.file.export_urdf": "تصدير URDF"
+ },
+ "he": {
+ "cmd.file.export_step": "ייצוא STEP",
+ "cmd.file.export_stl": "ייצוא STL",
+ "cmd.file.export_3mf": "ייצוא 3MF",
+ "cmd.file.export_obj": "ייצוא OBJ",
+ "cmd.file.export_urdf": "ייצוא URDF"
+ },
+ "ja": {
+ "cmd.file.export_step": "STEP をエクスポート",
+ "cmd.file.export_stl": "STL をエクスポート",
+ "cmd.file.export_3mf": "3MF をエクスポート",
+ "cmd.file.export_obj": "OBJ をエクスポート",
+ "cmd.file.export_urdf": "URDF をエクスポート"
+ },
+ "vi": {
+ "cmd.file.export_step": "Xuất tệp STEP",
+ "cmd.file.export_stl": "Xuất tệp STL",
+ "cmd.file.export_3mf": "Xuất tệp 3MF",
+ "cmd.file.export_obj": "Xuất tệp OBJ",
+ "cmd.file.export_urdf": "Xuất tệp URDF"
+ },
+ "zh": {
+ "cmd.file.export_step": "导出 STEP",
+ "cmd.file.export_stl": "导出 STL",
+ "cmd.file.export_3mf": "导出 3MF",
+ "cmd.file.export_obj": "导出 OBJ",
+ "cmd.file.export_urdf": "导出 URDF"
+ }
+}
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index 95100ebd4f..9b2df48fdc 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -61,6 +61,39 @@ pub static COMMANDS: &[CommandSpec] = &[
.icon("export")
.noundo()
.params("path; format?: stl|stla|obj|step|3mf|3mf-tagged|urdf|json (default from extension; 3mf-tagged: 3MF whose triangles carry their B-rep face, at full precision, for meshing and analysis tools; docs/formats/3mf-face-tags.md; obj: the colours of the bodies go in a material library (`.mtl`) written next to the mesh file; urdf: the whole assembly as a robot, with STL meshes written next to it; docs/urdf.md); bodies?: [names] (JSON and URDF export the complete design); urdf only: mesh_prefix? (before each mesh file name, e.g. package://robot/meshes/), effort? (default 1000), velocity? (default 10); quality?: standard|fine|finest (STL, OBJ and 3MF: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard); objects?: body|component (3MF only: one object per body, the default, or one object for each placed component with two or more bodies, with those bodies as its parts, so a slicer loads them as one object with parts)"),
+ // One command per format, so each File › Export item can have a key of its own; started
+ // from a key or command search, the app opens the save picker (the mesh dialog for STL and
+ // 3MF). Each takes `file.export`'s parameters for its format, without `format`.
+ CommandSpec::new("file.export_step", "Export STEP", crate::checked!("file.export_step", export_step))
+ .icon("export")
+ .noundo()
+ .contract(&EXPORT_STEP_CONTRACT)
+ .output(crate::schema::output_schema_for::<crate::schema::file::ExportResult>)
+ .params("path; bodies?: [names] (default: every body; a design with components then exports as a STEP assembly) → {path, bytes, format}: STEP, whatever the path's extension"),
+ CommandSpec::new("file.export_stl", "Export STL", crate::checked!("file.export_stl", export_stl))
+ .icon("mesh_export")
+ .noundo()
+ .contract(&EXPORT_STL_CONTRACT)
+ .output(crate::schema::output_schema_for::<crate::schema::file::ExportResult>)
+ .params("path; bodies?: [names] (default: every body); quality?: standard|fine|finest (default standard) → {path, bytes, format}: binary STL, whatever the path's extension"),
+ CommandSpec::new("file.export_3mf", "Export 3MF", crate::checked!("file.export_3mf", export_3mf))
+ .icon("mesh_export")
+ .noundo()
+ .contract(&EXPORT_3MF_CONTRACT)
+ .output(crate::schema::output_schema_for::<crate::schema::file::ExportResult>)
+ .params("path; bodies?: [names] (default: every body); quality?: standard|fine|finest (default standard); objects?: body|component (as file.export) → {path, bytes, format}: 3MF, whatever the path's extension"),
+ CommandSpec::new("file.export_obj", "Export OBJ", crate::checked!("file.export_obj", export_obj_cmd))
+ .icon("export")
+ .noundo()
+ .contract(&EXPORT_OBJ_CONTRACT)
+ .output(crate::schema::output_schema_for::<crate::schema::file::ExportResult>)
+ .params("path; bodies?: [names] (default: every body); quality?: standard|fine|finest (default standard) → {path, bytes, format, files}: OBJ, with the colours of the bodies in a material library (`.mtl`) next to it"),
+ CommandSpec::new("file.export_urdf", "Export URDF", crate::checked!("file.export_urdf", export_urdf_cmd))
+ .icon("export")
+ .noundo()
+ .contract(&EXPORT_URDF_CONTRACT)
+ .output(crate::schema::output_schema_for::<crate::schema::file::UrdfExportResult>)
+ .params("path; mesh_prefix?; effort? (default 1000); velocity? (default 10) → {path, format, files, links, joints, warnings}: the whole assembly as a robot, with STL meshes written next to it; docs/urdf.md"),
CommandSpec::new("file.save_mesh", "Save As Mesh", save_mesh)
.at("INSERT", "FILES")
.icon("mesh_export")
@@ -89,6 +122,12 @@ fn new_doc(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"name": name}))
}
+const EXPORT_STEP_CONTRACT: crate::schema::TypedContract<crate::schema::file::ExportStepParams> = crate::schema::TypedContract::new();
+const EXPORT_STL_CONTRACT: crate::schema::TypedContract<crate::schema::file::ExportMeshParams> = crate::schema::TypedContract::new();
+const EXPORT_3MF_CONTRACT: crate::schema::TypedContract<crate::schema::file::Export3mfParams> = crate::schema::TypedContract::new();
+const EXPORT_OBJ_CONTRACT: crate::schema::TypedContract<crate::schema::file::ExportMeshParams> = crate::schema::TypedContract::new();
+const EXPORT_URDF_CONTRACT: crate::schema::TypedContract<crate::schema::file::ExportUrdfParams> = crate::schema::TypedContract::new();
+
fn path_arg<'a>(p: &'a Value, cmd: &str) -> Result<&'a str> {
str_(p, "path").filter(|x| !x.trim().is_empty() && x.len() < 4096).ok_or_else(|| bad(cmd, "`path` is required"))
}
@@ -700,6 +739,7 @@ fn component_parts(s: &Session) -> Vec<(String, Vec<String>)> {
fn export_to(
s: &Session,
+ cmd: &str,
path: &str,
format: Format,
bodies: &[String],
@@ -714,7 +754,7 @@ fn export_to(
// A design with components exports as a STEP assembly; otherwise bodies as placed.
let bytes = if format == Format::Design {
if !bodies.is_empty() {
- return Err(bad("file.export", "design JSON exports the complete document; omit bodies"));
+ return Err(bad(cmd, "design JSON exports the complete document; omit bodies"));
}
solidcraft_io::write_design(&s.design())
} else if format == Format::Step && bodies.is_empty() && !s.doc.occurrences.is_empty() {
@@ -753,11 +793,44 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
let path = path_arg(p, cmd)?;
let format = Format::from_name(str_(p, "format").unwrap_or(path))?;
if format == Format::Urdf {
- return export_urdf(s, path, p);
+ if !string_list(cmd, p, "bodies")?.is_empty() {
+ return Err(bad(cmd, "urdf exports the whole assembly; omit bodies"));
+ }
+ return export_urdf(s, cmd, path, p);
}
let quality = mesh_quality(p, cmd)?;
let parts = mesh_parts(s, p, cmd, format)?;
- export_to(s, path, format, &string_list(cmd, p, "bodies")?, &parts, quality)
+ export_to(s, cmd, path, format, &string_list(cmd, p, "bodies")?, &parts, quality)
+}
+
+fn export_step(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.export_step";
+ let path = path_arg(p, cmd)?;
+ export_to(s, cmd, path, Format::Step, &string_list(cmd, p, "bodies")?, &[], solidcraft_io::MeshQuality::default())
+}
+
+fn export_stl(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.export_stl";
+ let path = path_arg(p, cmd)?;
+ export_to(s, cmd, path, Format::StlBinary, &string_list(cmd, p, "bodies")?, &[], mesh_quality(p, cmd)?)
+}
+
+fn export_3mf(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.export_3mf";
+ let path = path_arg(p, cmd)?;
+ let parts = mesh_parts(s, p, cmd, Format::ThreeMf)?;
+ export_to(s, cmd, path, Format::ThreeMf, &string_list(cmd, p, "bodies")?, &parts, mesh_quality(p, cmd)?)
+}
+
+fn export_obj_cmd(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.export_obj";
+ let path = path_arg(p, cmd)?;
+ export_to(s, cmd, path, Format::Obj, &string_list(cmd, p, "bodies")?, &[], mesh_quality(p, cmd)?)
+}
+
+fn export_urdf_cmd(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.export_urdf";
+ export_urdf(s, cmd, path_arg(p, cmd)?, p)
}
/// The OBJ export: the mesh file and the material library beside it, with the colours of the
@@ -788,11 +861,7 @@ fn export_obj(s: &Session, path: &str, bodies: &[String], quality: solidcraft_io
/// The assembly as a URDF and its meshes next to it (docs/urdf.md). Every path is checked before
/// anything is written; the meshes go first and the `.urdf` last.
-fn export_urdf(s: &Session, path: &str, p: &Value) -> Result<Value> {
- let cmd = "file.export";
- if !string_list(cmd, p, "bodies")?.is_empty() {
- return Err(bad(cmd, "urdf exports the whole assembly; omit bodies"));
- }
+fn export_urdf(s: &Session, cmd: &str, path: &str, p: &Value) -> Result<Value> {
let positive = |k: &str| match p.get(k) {
None | Some(Value::Null) => Ok(None),
Some(_) => num(p, k).filter(|x| *x > 0.0).map(Some).ok_or_else(|| bad(cmd, format!("`{k}` must be a positive number"))),
@@ -887,7 +956,7 @@ fn save_mesh(s: &mut Session, p: &Value) -> Result<Value> {
},
);
}
- export_to(s, path, format, &string_list(cmd, p, "bodies")?, &parts, quality)
+ export_to(s, cmd, path, format, &string_list(cmd, p, "bodies")?, &parts, quality)
}
/// The browser build can't start a program.
@@ -1050,6 +1119,43 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
+ /// Each format's own export command (one key each in Keyboard Shortcuts) writes that format
+ /// whatever the path's extension, as `file.export` does with `format`, and says so.
+ #[test]
+ fn each_format_has_an_export_command_of_its_own() {
+ let dir = std::env::temp_dir().join(format!("solidcraft-export-per-format-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let at = |n: &str| dir.join(n).to_string_lossy().to_string();
+ let mut s = Session::default();
+ s.execute("solid.box", &json!({"length": 20, "width": 10, "height": 5, "body_name": "Block"})).unwrap();
+ for (cmd, format, signature) in [
+ ("file.export_step", "Step", &b"ISO-10303-21;"[..]),
+ ("file.export_3mf", "ThreeMf", &b"PK"[..]),
+ ("file.export_obj", "Obj", &b""[..]),
+ ("file.export_stl", "StlBinary", &b""[..]),
+ ] {
+ // A name with another format's extension: the command, not the name, picks the format.
+ let path = at(&format!("{format}.txt"));
+ let r = s.execute(cmd, &json!({"path": path})).unwrap();
+ assert_eq!((r["path"].as_str(), r["format"].as_str()), (Some(path.as_str()), Some(format)), "{cmd}: {r}");
+ let bytes = std::fs::read(&path).unwrap();
+ assert_eq!(r["bytes"].as_u64(), Some(bytes.len() as u64), "{cmd}");
+ assert!(bytes.starts_with(signature), "{cmd}");
+ }
+ // The triangles `file.export` writes (the 80-byte header holds the file's name): a box is
+ // 12 triangles, 84 + 50 bytes each.
+ s.execute("file.export", &json!({"path": at("box.stl")})).unwrap();
+ assert_eq!(std::fs::read(at("StlBinary.txt")).unwrap()[80..], std::fs::read(at("box.stl")).unwrap()[80..]);
+ assert_eq!(std::fs::metadata(at("box.stl")).unwrap().len(), 84 + 50 * 12);
+ let obj = std::fs::read_to_string(at("Obj.txt")).unwrap();
+ assert_eq!(obj.lines().filter(|l| l.starts_with("f ")).count(), 12, "{obj}");
+ let r = s.execute("file.export_urdf", &json!({"path": at("robot.urdf")})).unwrap();
+ assert_eq!(r["format"], "Urdf");
+ assert!(std::fs::read_to_string(at("robot.urdf")).unwrap().contains("<robot"));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
/// #4747: a mesh export's `quality` follows curved faces more closely. A 3 mm hole in a
/// 200 mm plate gets more triangles at fine and more again at finest, in STL and 3MF alike
/// (Save As Mesh too); standard is what the export always gave; anything else is refused.
diff --git a/crates/engine/src/schema/file.rs b/crates/engine/src/schema/file.rs
new file mode 100644
index 0000000000..58754f627c
--- /dev/null
+++ b/crates/engine/src/schema/file.rs
@@ -0,0 +1,135 @@
+//! Contracts and result types for the commands in `cmd/file.rs`: so far the export command of
+//! each format (`file.export_step`, `file.export_stl`, `file.export_3mf`, `file.export_obj`,
+//! `file.export_urdf`), which take what `file.export` takes for that format, without `format`.
+
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+use super::types::StringList;
+
+/// How closely an exported mesh follows curved faces.
+#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)]
+#[serde(rename_all = "lowercase")]
+pub enum MeshQualityParam {
+ /// A chord tolerance of 2e-4 of each body's size.
+ Standard,
+ /// 5e-5 of each body's size.
+ Fine,
+ /// 1e-5 of each body's size.
+ Finest,
+}
+
+/// What each 3MF object holds.
+#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)]
+#[serde(rename_all = "lowercase")]
+pub enum ObjectsParam {
+ /// One object per body.
+ Body,
+ /// One object for each placed component with two or more bodies, with those bodies as its
+ /// parts, so a slicer loads them as one object with parts; other bodies stay objects of their own.
+ Component,
+}
+
+/// Export bodies as a STEP file. With no `bodies`, a design with components exports as a STEP
+/// assembly, otherwise its bodies as placed. The file is STEP whatever the path's extension.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct ExportStepParams {
+ /// The file to write.
+ pub path: String,
+ /// The bodies to export, by name. Default: every body.
+ #[serde(default)]
+ pub bodies: Option<StringList>,
+}
+
+/// Export bodies as a mesh file: binary STL for `file.export_stl`, OBJ for `file.export_obj`
+/// (the colours of the bodies go in a material library, `.mtl`, written next to it). The file
+/// has that format whatever the path's extension.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct ExportMeshParams {
+ /// The file to write.
+ pub path: String,
+ /// The bodies to export, by name. Default: every body.
+ #[serde(default)]
+ pub bodies: Option<StringList>,
+ /// How closely the mesh follows curved faces. Default: standard.
+ #[serde(default)]
+ pub quality: Option<MeshQualityParam>,
+}
+
+/// Export bodies as a 3MF file, whatever the path's extension.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct Export3mfParams {
+ /// The file to write.
+ pub path: String,
+ /// The bodies to export, by name. Default: every body.
+ #[serde(default)]
+ pub bodies: Option<StringList>,
+ /// How closely the mesh follows curved faces. Default: standard.
+ #[serde(default)]
+ pub quality: Option<MeshQualityParam>,
+ /// What each object in the file holds. Default: body.
+ #[serde(default)]
+ pub objects: Option<ObjectsParam>,
+}
+
+/// Export the whole assembly as a robot description (URDF), with an STL mesh for each link
+/// written next to it (docs/urdf.md).
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct ExportUrdfParams {
+ /// The `.urdf` file to write; the meshes go in its folder.
+ pub path: String,
+ /// Put before each mesh file name in the URDF, such as `package://robot/meshes/`. Default: none.
+ #[serde(default)]
+ pub mesh_prefix: Option<String>,
+ /// Each joint's effort limit, a positive number. Default: 1000.
+ #[serde(default)]
+ pub effort: Option<f64>,
+ /// Each joint's velocity limit, a positive number. Default: 10.
+ #[serde(default)]
+ pub velocity: Option<f64>,
+}
+
+/// What `file.export_step`, `file.export_stl`, `file.export_3mf` and `file.export_obj` return.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ExportResult {
+ /// The file written.
+ pub path: String,
+ /// Its size in bytes.
+ pub bytes: usize,
+ /// The format written: Step, StlBinary, ThreeMf or Obj.
+ pub format: String,
+ /// OBJ only: every file written, the material library first and the mesh file last.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub files: Vec<String>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What `file.export_urdf` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct UrdfExportResult {
+ /// The `.urdf` file written.
+ pub path: String,
+ /// Always Urdf.
+ pub format: String,
+ /// Every file written, the meshes first and the `.urdf` last.
+ pub files: Vec<String>,
+ /// How many links the robot has.
+ pub links: usize,
+ /// How many joints the robot has.
+ pub joints: usize,
+ /// What the export could not carry over as it is in the design.
+ pub warnings: Vec<String>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+#[cfg(test)]
+#[path = "file_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/file_tests.rs b/crates/engine/src/schema/file_tests.rs
new file mode 100644
index 0000000000..f040637bf8
--- /dev/null
+++ b/crates/engine/src/schema/file_tests.rs
@@ -0,0 +1,38 @@
+use serde_json::json;
+
+use super::{Export3mfParams, ExportMeshParams, ExportStepParams, ExportUrdfParams};
+use crate::Session;
+use crate::schema::tests::assert_keys;
+use crate::schema::{ParamCheck, input_schema_for};
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(input_schema_for::<ExportStepParams>(), &["bodies", "path"]);
+ assert_keys(input_schema_for::<ExportMeshParams>(), &["bodies", "path", "quality"]);
+ assert_keys(input_schema_for::<Export3mfParams>(), &["bodies", "objects", "path", "quality"]);
+ assert_keys(input_schema_for::<ExportUrdfParams>(), &["effort", "mesh_prefix", "path", "velocity"]);
+}
+
+#[test]
+fn bad_calls_say_what_is_wrong_and_write_nothing() {
+ let dir = std::env::temp_dir().join(format!("solidcraft-export-schemas-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap_or_else(|e| panic!("{e}"));
+ let mut s = Session::default();
+ s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap_or_else(|e| panic!("{e}"));
+ for cmd in ["file.export_step", "file.export_stl", "file.export_3mf", "file.export_obj", "file.export_urdf"] {
+ let e = s.execute(cmd, &json!({})).unwrap_err().to_string();
+ assert!(e.contains(cmd) && e.contains("path"), "{cmd}: {e}");
+ }
+ let at = dir.join("a.stl").to_string_lossy().to_string();
+ let e = s.execute("file.export_stl", &json!({"path": at, "quality": "rough"})).unwrap_err().to_string();
+ assert!(e.contains("quality"), "{e}");
+ s.param_check = ParamCheck::Strict;
+ let e = s.execute("file.export_stl", &json!({"path": at, "objects": "component"})).unwrap_err().to_string();
+ assert!(e.contains("objects"), "objects is for 3MF only: {e}");
+ s.param_check = ParamCheck::Off;
+ let e = s.execute("file.export_urdf", &json!({"path": at, "effort": -1})).unwrap_err().to_string();
+ assert!(e.contains("effort"), "{e}");
+ assert_eq!(std::fs::read_dir(&dir).map(|d| d.count()).unwrap_or(0), 0, "nothing written");
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index 4896d91e16..eeb03e5246 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -58,6 +58,7 @@ pub mod component;
pub mod construct;
pub mod edit;
pub mod features;
+pub mod file;
pub mod inspect;
pub mod joints;
pub mod mass_properties;
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index e689a8ff87..e2dfd5e392 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -889,8 +889,15 @@ fn hostile_params_never_panic() {
while let Some(&id) = ids.get(next.fetch_add(1, std::sync::atomic::Ordering::Relaxed)) {
for v in hostile_values() {
for k in keys {
- if k == "path" && (id.starts_with("parameters.") || id == "timeline.export_script") {
- continue; // parameter and script files: covered by their own tests (no stray files)
+ if k == "path"
+ && (id.starts_with("parameters.")
+ || id == "timeline.export_script"
+ || matches!(
+ id,
+ "file.export_3mf" | "file.export_obj" | "file.export_step" | "file.export_stl" | "file.export_urdf"
+ ))
+ {
+ continue; // parameter, script and export files: covered by their own tests (no stray files)
}
let mut s = Session::default();
// A model with a sketch, a body and an active sketch, so most commands get far.
diff --git a/crates/ui-egui/src/control_job.rs b/crates/ui-egui/src/control_job.rs
index 5b8f7bf71f..03b30c3276 100644
--- a/crates/ui-egui/src/control_job.rs
+++ b/crates/ui-egui/src/control_job.rs
@@ -67,7 +67,8 @@ const AHEAD_AREAS: &[&str] = &[
const NAMES_A_FILE: &[&str] = &["path", "paths", "file", "files", "dir", "folder", "url", "out"];
/// Commands that change nothing in the design and write a file: they run on a copy.
-const ANSWERED_ON_A_COPY: &[&str] = &["file.export", "file.save_mesh"];
+const ANSWERED_ON_A_COPY: &[&str] =
+ &["file.export", "file.export_3mf", "file.export_obj", "file.export_step", "file.export_stl", "file.export_urdf", "file.save_mesh"];
/// Commands that only read the design, which can take long on a large one (a measure of every
/// body, an inspection that measures them, #4604; a clearance or interference check of every pair
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 8dfdf51c05..e38f7ea7a3 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -1746,7 +1746,7 @@ impl SolveApp {
dim_view::cancel();
self.tool = None;
self.home.open = false;
- if dialogs_sheet::start_export(self, id) {
+ if dialogs_sheet::start_export(self, id) || toolbar::start_export(self, id) {
return;
}
if id == "component.finish_edit" {
diff --git a/crates/ui-egui/src/shortcut_box.rs b/crates/ui-egui/src/shortcut_box.rs
index 91afb68c50..d2276f0141 100644
--- a/crates/ui-egui/src/shortcut_box.rs
+++ b/crates/ui-egui/src/shortcut_box.rs
@@ -173,6 +173,10 @@ fn keywords(id: &str) -> &'static str {
match id {
"file.save_mesh" => "export stl 3mf mesh 3d print printing slicer",
"file.export" => "export stl 3mf obj step urdf mesh 3d print",
+ "file.export_step" => "stp cad",
+ "file.export_stl" | "file.export_3mf" => "mesh 3d print printing",
+ "file.export_obj" => "mesh",
+ "file.export_urdf" => "robot ros simulation",
_ => "",
}
}
diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs
index 07ba04b0e2..2a565528ea 100644
--- a/crates/ui-egui/src/toolbar.rs
+++ b/crates/ui-egui/src/toolbar.rs
@@ -703,32 +703,36 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) {
close = true;
}
ui.separator();
- if item_if(ui, "Export STL…", "", "mesh_export", shown) {
- FileAction::ExportMesh("stl").run(app);
+ // Each format's item runs its own command, so it shows that command's key.
+ let key = |id: &str| crate::keymap::effective(app, id).unwrap_or_default();
+ let (stl_key, mf_key, step_key, obj_key, urdf_key) =
+ (key("file.export_stl"), key("file.export_3mf"), key("file.export_step"), key("file.export_obj"), key("file.export_urdf"));
+ if item_if(ui, "Export STL…", &stl_key, "mesh_export", shown) {
+ FileAction::Command("file.export_stl").run(app);
close = true;
}
- if item_if(ui, "Export 3MF…", "", "mesh_export", shown) {
- FileAction::ExportMesh("3mf").run(app);
+ if item_if(ui, "Export 3MF…", &mf_key, "mesh_export", shown) {
+ FileAction::Command("file.export_3mf").run(app);
close = true;
}
if item_if(ui, "Send to Slicer", "", "mesh_export", shown && crate::dialogs_save_mesh::available(app)) {
app.start("file.send_to_slicer");
close = true;
}
- if item_if(ui, "Export STEP…", "", "export", shown) {
- FileAction::Export("step").run(app);
+ if item_if(ui, "Export STEP…", &step_key, "export", shown) {
+ FileAction::Command("file.export_step").run(app);
close = true;
}
if item_if(ui, app.tr_label("Export Current View as DXF…"), "", "export", shown) {
FileAction::Command("file.export_view_dxf").run(app);
close = true;
}
- if item_if(ui, "Export OBJ…", "", "export", shown) {
- FileAction::Export("obj").run(app);
+ if item_if(ui, "Export OBJ…", &obj_key, "export", shown) {
+ FileAction::Command("file.export_obj").run(app);
close = true;
}
- if item_if(ui, "Export URDF…", "", "export", shown) {
- FileAction::Export("urdf").run(app);
+ if item_if(ui, "Export URDF…", &urdf_key, "export", shown) {
+ FileAction::Command("file.export_urdf").run(app);
close = true;
}
if item(ui, "Export Design as JSON…", "", "export") {
@@ -838,6 +842,30 @@ pub(crate) fn export(app: &mut SolveApp, ext: &str) {
export_as(app, ext, None);
}
+/// Each format's own export command, started from its key, command search or the File menu,
+/// does what that File › Export item does: STEP, OBJ and URDF ask where to save, STL and 3MF
+/// open the mesh dialog with the format chosen. `false`: `id` is no such command.
+pub(crate) fn start_export(app: &mut SolveApp, id: &str) -> bool {
+ let (extension, mesh) = match id {
+ "file.export_step" => ("step", false),
+ "file.export_obj" => ("obj", false),
+ "file.export_urdf" => ("urdf", false),
+ "file.export_stl" => ("stl", true),
+ "file.export_3mf" => ("3mf", true),
+ _ => return false,
+ };
+ // As the File menu's items: not while a file is being picked or loaded, or behind a bug report.
+ if !FileAction::Export(extension).enabled(app) {
+ return true;
+ }
+ if mesh {
+ crate::dialogs_save_mesh::start_with_format(app, extension);
+ } else {
+ export(app, extension);
+ }
+ true
+}
+
/// Export to a file with extension `ext`, in `format` when the extension alone doesn't name it.
fn export_as(app: &mut SolveApp, ext: &str, format: Option<&str>) {
let name = format!("{}.{ext}", app.session.doc.name);
@@ -3466,6 +3494,36 @@ mod header_report_tests {
assert!(FileAction::Export("step").enabled(&h.app));
}
+ /// File › Export STEP…, STL…, 3MF…, OBJ… and URDF… each run a command of their own, so each
+ /// can be given a key in Keyboard Shortcuts: the key asks where to save the file as the menu
+ /// item does (STL and 3MF open Save As Mesh).
+ #[test]
+ fn each_export_format_has_a_key_that_starts_it() {
+ let mut h = crate::scenario::Harness::new();
+ let offered = std::rc::Rc::new(std::cell::RefCell::new(Vec::<(String, Vec<String>)>::new()));
+ let (seen, dir) = (offered.clone(), h.dir.clone());
+ h.app.services.pick_save = Some(Box::new(move |name, extensions| {
+ seen.borrow_mut().push((name.to_string(), extensions.iter().map(|e| e.to_string()).collect()));
+ Box::pin(std::future::ready(Some(dir.join(name).to_string_lossy().into_owned())))
+ }));
+ h.app.run("solid.box", json!({"length":2,"width":3,"height":4})).unwrap();
+ h.app.session.doc_mut().name = "Bracket".into();
+ for (id, key) in [("file.export_step", "Alt+Shift+F7"), ("file.export_stl", "Alt+Shift+F8")] {
+ crate::keymap::bind(&mut h.app, id, key, false).unwrap();
+ assert_eq!(crate::keymap::effective(&h.app, id).as_deref(), Some(key), "the File menu shows it");
+ }
+ crate::keymap::press(&mut h.app, "Alt+Shift+F7", false);
+ h.frames(3);
+ h.settle();
+ assert_eq!(offered.borrow().last().cloned(), Some(("Bracket.step".to_string(), vec!["step".to_string()])));
+ let step = std::fs::read(h.dir.join("Bracket.step")).unwrap();
+ assert!(step.starts_with(b"ISO-10303-21;"), "a STEP file is written");
+
+ crate::keymap::press(&mut h.app, "Alt+Shift+F8", false);
+ assert_eq!(h.app.dialog.as_ref().and_then(|d| d.command()), Some("file.save_mesh"), "STL opens Save As Mesh");
+ crate::dialogs::cancel(&mut h.app);
+ }
+
/// New designs are saved as `.sc`. A design opened from a `.solidcraft` file is saved back to
/// that file by Save (no rename behind the user's back); Save As offers `.sc` and leaves it.
#[test]