Skip to content

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

Sketch Dimension: `name = value` defines a user parameter (#2916) (#3638)

Danielb289dc2421a8
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index ef77f1f524..9a52d36a1a 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -3227,10 +3227,11 @@ impl Document {
if name.len() > 64 {
return Some("parameter names are at most 64 characters".into());
}
- if expr::is_reserved(name) {
- return Some(format!("`{name}` is a unit, constant or function name"));
+ match expr::reserved_kind(name) {
+ Some("constant") => Some(format!("`{name}` is a constant, so it cannot be a parameter name")),
+ Some(kind) => Some(format!("`{name}` is a {kind} name, so it cannot be a parameter name")),
+ None => None,
}
- None
}
/// Add or change a parameter. Fails if the result would not evaluate. A new parameter
diff --git a/crates/doc/src/expr.rs b/crates/doc/src/expr.rs
index 694cbe72a4..d8419b1290 100644
--- a/crates/doc/src/expr.rs
+++ b/crates/doc/src/expr.rs
@@ -304,9 +304,23 @@ fn is_constant(id: &str) -> bool {
CONSTANTS.contains(&id)
}
+/// What kind of word the expression language reserves `name` as: `unit`, `constant` or
+/// `function` (None: free for a parameter).
+pub fn reserved_kind(name: &str) -> Option<&'static str> {
+ if unit(name).is_some() {
+ Some("unit")
+ } else if is_constant(name) {
+ Some("constant")
+ } else if FUNCTIONS.iter().any(|(f, _)| *f == name) {
+ Some("function")
+ } else {
+ None
+ }
+}
+
/// Is this a name the expression language reserves (unit, constant or function)?
pub fn is_reserved(name: &str) -> bool {
- unit(name).is_some() || is_constant(name) || FUNCTIONS.iter().any(|(f, _)| *f == name)
+ reserved_kind(name).is_some()
}
#[derive(Clone, Debug, PartialEq)]
@@ -535,6 +549,24 @@ pub fn is_bare_number(s: &str) -> bool {
is_literal(s) && s.trim().trim_start_matches(['-', '+']).trim().parse::<f64>().is_ok()
}
+/// Is `s` shaped like a parameter name: a letter or `_`, then letters, digits and `_`? The shape
+/// only; whether the name is free or reserved is `Document::param_name_problem`'s business.
+fn is_name_shaped(s: &str) -> bool {
+ let mut cs = s.chars();
+ matches!(cs.next(), Some(c) if c.is_alphabetic() || c == '_') && cs.all(|c| c.is_alphanumeric() || c == '_')
+}
+
+/// A value typed as a definition, `name = expression`: the name and the text after the first
+/// `=`, both trimmed (the text may be empty). `None` for anything else, including text whose
+/// left side is not shaped like a name (`2 = 3`), which stays an ordinary expression and fails
+/// to parse as before. The dimension input defines a user parameter this way (#2916); other
+/// value inputs can take the same form later.
+pub fn definition(s: &str) -> Option<(&str, &str)> {
+ let (name, rhs) = s.split_once('=')?;
+ let name = name.trim();
+ is_name_shaped(name).then(|| (name, rhs.trim()))
+}
+
/// The length unit of a design with these units: `mm` unless they name another length unit.
pub fn length_unit_or_mm(units: &str) -> &str {
let u = units.trim();
@@ -1204,4 +1236,49 @@ mod tests {
assert!(is_bare_number(" -1.5 ") && is_bare_number("+2") && !is_bare_number("20 mm") && !is_bare_number("(2)"));
assert_eq!((length_unit_or_mm(" in "), length_unit_or_mm("deg"), length_unit_or_mm("")), ("in", "mm", "mm"));
}
+
+ /// `name = expression` splits at the first `=` when the left side is shaped like a name; the
+ /// right side is any text, checked by whoever evaluates it.
+ #[test]
+ fn definitions_split_on_a_name_and_an_equals_sign() {
+ let splits = [
+ ("w = 20", "w", "20"),
+ ("w=20", "w", "20"),
+ (" w = 20 mm ", "w", "20 mm"),
+ ("w = (a + b) / 2", "w", "(a + b) / 2"),
+ ("w = 2 * (3 + sin(45 deg))", "w", "2 * (3 + sin(45 deg))"),
+ ("w = 1 in - 5.4 mm", "w", "1 in - 5.4 mm"),
+ ("_w1 = 1", "_w1", "1"),
+ ("szerokość = 20", "szerokość", "20"),
+ // Reserved names split too: the parameter check names the reason.
+ ("mm = 5", "mm", "5"),
+ // A second `=` stays in the expression, which then fails to evaluate.
+ ("w == 3", "w", "= 3"),
+ ("w = a = 3", "w", "a = 3"),
+ // An empty expression is the caller's error to report.
+ ("w =", "w", ""),
+ ("w = ", "w", ""),
+ ];
+ for (text, name, rhs) in splits {
+ assert_eq!(definition(text), Some((name, rhs)), "{text:?}");
+ }
+ for text in ["20", "20 mm", "width / 2", "= 20", "=", "", "2w = 3", "a b = 3", "a-b = 3", "w.x = 3", "(w) = 3", "-w = 3"] {
+ assert_eq!(definition(text), None, "{text:?}");
+ }
+ }
+
+ /// A reserved name is refused by saying what kind of word it is.
+ #[test]
+ fn a_reserved_name_is_refused_by_its_kind() {
+ assert_eq!(
+ (reserved_kind("mm"), reserved_kind("deg"), reserved_kind("pi"), reserved_kind("sin"), reserved_kind("width")),
+ (Some("unit"), Some("unit"), Some("constant"), Some("function"), None)
+ );
+ let problem = |n: &str| crate::Document::param_name_problem(n).unwrap_or_default();
+ assert_eq!(problem("mm"), "`mm` is a unit name, so it cannot be a parameter name");
+ assert_eq!(problem("sin"), "`sin` is a function name, so it cannot be a parameter name");
+ assert_eq!(problem("pi"), "`pi` is a constant, so it cannot be a parameter name");
+ assert_eq!(crate::Document::param_name_problem("width"), None);
+ assert!(problem("2w").contains("not a valid parameter name"));
+ }
}
diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs
index 6dbbc22189..ec1ff880d2 100644
--- a/crates/engine/src/cmd/sketch.rs
+++ b/crates/engine/src/cmd/sketch.rs
@@ -115,7 +115,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.params(concat!("p0, p1: overall ends, width", connect_doc!(), created_doc!())),
CommandSpec::new("sketch.point", "Point", draw_point).at("SKETCH", "CREATE").icon("point").enabled(in_sketch).params(concat!("point: [x,y] (each a number or an expression over the design's parameters: the point is then fixed where it comes to and follows them), id?", connect_doc!(), created_doc!())),
CommandSpec::new("sketch.dimension", "Sketch Dimension", dimension).at("SKETCH", "CREATE").icon("dimension").key("D").enabled(in_sketch).params(
- "entities: [refs], type?: auto|distance|horizontal|vertical|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override); text_at?: [x, y]. Two points or a line off the axes: with auto, text_at across from them is the distance between them, above or below them horizontal, beside them vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled",
+ "entities: [refs], type?: auto|distance|horizontal|vertical|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override), or `name = expression` (e.g. \"width = 40\"), which adds the user parameter `name` with that expression and dimensions with `name` (refused when the name is taken or reserved; the reply's `defined` names it); text_at?: [x, y]. Two points or a line off the axes: with auto, text_at across from them is the distance between them, above or below them horizontal, beside them vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled",
),
CommandSpec::new("sketch.constraint.horizontal_vertical", "Horizontal/Vertical", c_horizontal_vertical)
.at("SKETCH", "CONSTRAINTS")
@@ -2095,6 +2095,19 @@ fn dimension(s: &mut Session, p: &Value) -> Result<Value> {
let value = expr(p, "value");
let text_at = p.get("text_at").and_then(vec2);
let driven = bool_(p, "driven").unwrap_or(false);
+ // `name = expression` defines the user parameter `name` and dimensions with it (#2916).
+ let (defines, value) = match value.as_ref().and_then(|v| solidcraft_doc::expr::definition(v.as_str())) {
+ Some((name, rhs)) => {
+ if rhs.is_empty() {
+ return Err(bad(cmd, format!("value: `{name} =` needs a value after the `=`")));
+ }
+ if driven {
+ return Err(bad(cmd, format!("value: a driven dimension has no value, so it cannot define `{name}`")));
+ }
+ (Some((name.to_string(), rhs.to_string())), Some(solidcraft_doc::expr::Expr::new(name)))
+ }
+ None => (None, value),
+ };
let scale_sketch = bool_(p, "scale_sketch").unwrap_or(false);
let mut scaled = None;
let mut before = None;
@@ -2260,7 +2273,21 @@ fn dimension(s: &mut Session, p: &Value) -> Result<Value> {
}
let (unit, default_expr) =
if is_angle { ("deg", format!("{} deg", round6(cur.to_degrees()))) } else { ("mm", format!("{} mm", round6(cur))) };
- let e = value.as_ref().map(|e| doc.with_design_unit(e, if is_angle { Kind::Angle } else { Kind::Length })).unwrap_or(default_expr);
+ let kind = if is_angle { Kind::Angle } else { Kind::Length };
+ if let Some((name, rhs)) = &defines {
+ // The new user parameter reads a bare number as the dimension would (the design's
+ // unit for a length, degrees for an angle), and carries that unit.
+ if let Some(problem) = solidcraft_doc::Document::param_name_problem(name) {
+ return Err(bad(cmd, format!("value: {problem}")));
+ }
+ if doc.param(name).is_some() {
+ return Err(bad(cmd, format!("value: there is already a parameter `{name}`: type `{name}` to use it, or change it in Parameters")));
+ }
+ let rhs = doc.with_design_unit(rhs, kind);
+ let unit = if is_angle { "deg".to_string() } else { solidcraft_doc::expr::length_unit_or_mm(&doc.units).to_string() };
+ doc.add_user_param(name, &rhs, Some(&unit), None).map_err(|e| bad(cmd, format!("value: {e}")))?;
+ }
+ let e = value.as_ref().map(|e| doc.with_design_unit(e, kind)).unwrap_or(default_expr);
let pname = doc.new_model_param(&e, unit);
// The value must evaluate.
let (vals, errs) = doc.param_values();
@@ -2326,6 +2353,9 @@ fn dimension(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(factor) = scaled {
out["scaled"] = json!(round6(factor));
}
+ if let Some((name, _)) = defines {
+ out["defined"] = json!(name);
+ }
Ok(out)
}
diff --git a/crates/engine/src/cmd/sketch_constraints_tests.rs b/crates/engine/src/cmd/sketch_constraints_tests.rs
index 1e4c08746f..ace5abcaf4 100644
--- a/crates/engine/src/cmd/sketch_constraints_tests.rs
+++ b/crates/engine/src/cmd/sketch_constraints_tests.rs
@@ -735,3 +735,156 @@ fn midpoint_rejects_wrong_picks_without_changing_the_sketch() {
assert_eq!(s.undo.len(), undo, "{params}");
}
}
+
+/// A parameter's row in `parameters.list` (Null when there is none).
+fn param_row(s: &mut Session, name: &str) -> Value {
+ let l = run(s, "parameters.list", json!({}));
+ l["parameters"].as_array().and_then(|a| a.iter().find(|p| p["name"] == name)).cloned().unwrap_or(Value::Null)
+}
+
+/// The distance between a line's ends on the solved sketch.
+fn line_length(s: &Session, line: &str) -> f64 {
+ let sk = sketch(s);
+ let at = |r: &str| sk.point(sk.resolve_point(r).unwrap()).unwrap();
+ at(&format!("{line}.start")).dist(at(&format!("{line}.end")))
+}
+
+/// A session with the user parameter `len = 60 mm` and a sketch holding one 30 mm line `la`
+/// whose start is on the origin.
+fn sketch_with_len() -> Session {
+ let mut s = Session::default();
+ run(&mut s, "parameters.add", json!({"name": "len", "expression": "60 mm"}));
+ run(&mut s, "sketch.create", json!({"plane": "XY"}));
+ run(&mut s, "sketch.line", json!({"points": [[0, 0], [30, 0]], "ids": ["la"], "infer": false}));
+ run(&mut s, "sketch.constraint.coincident", json!({"a": "la.start", "b": "origin"}));
+ s
+}
+
+/// `name = expression` in a dimension's value adds the user parameter and dimensions with it
+/// (#2916): the expression may be anything the parameter editor takes (arithmetic, units,
+/// parentheses, functions, other parameters), and is stored as typed on the new parameter.
+#[test]
+fn a_dimension_value_can_define_a_user_parameter() {
+ let cases = [
+ ("w = 20", "20"),
+ ("w=40/2", "40/2"),
+ (" w = (10 + 30) / 2 ", "(10 + 30) / 2"),
+ ("w = 1 in - 5.4 mm", "1 in - 5.4 mm"),
+ ("w = len / 3", "len / 3"),
+ ("w = sqrt(400)", "sqrt(400)"),
+ ("w = 2 * (len / 6)", "2 * (len / 6)"),
+ ("w = min(len, 20 mm)", "min(len, 20 mm)"),
+ ];
+ for (value, stored) in cases {
+ let mut s = sketch_with_len();
+ let d = run(&mut s, "sketch.dimension", json!({"entities": ["la"], "value": value}));
+ assert_eq!(d["defined"], "w", "{value}: {d}");
+ assert_eq!(d["expression"], "w", "{value}: the dimension refers to the parameter: {d}");
+ assert!((d["measured"].as_f64().unwrap() - 20.0).abs() < 1e-6, "{value}: {d}");
+ assert!((line_length(&s, "la") - 20.0).abs() < 1e-6, "{value}");
+ let w = param_row(&mut s, "w");
+ assert_eq!(w["source"], "user", "{value}: {w}");
+ assert_eq!(w["expression"], stored, "{value}: {w}");
+ assert_eq!(w["unit"], "mm", "{value}: {w}");
+ assert!((w["value"].as_f64().unwrap() - 20.0).abs() < 1e-9, "{value}: {w}");
+ // The dimension follows the parameter from now on.
+ run(&mut s, "parameters.change", json!({"name": "w", "expression": "30 mm"}));
+ assert!((line_length(&s, "la") - 30.0).abs() < 1e-6, "{value}");
+ }
+}
+
+/// A bare right-hand side is in the design's unit, like a bare dimension value, and the new
+/// parameter carries that unit; an angle's parameter is in degrees.
+#[test]
+fn a_defined_parameter_takes_the_design_unit_or_degrees() {
+ let mut s = Session::default();
+ run(&mut s, "document.units", json!({"units": "in"}));
+ run(&mut s, "sketch.create", json!({"plane": "XY"}));
+ run(&mut s, "sketch.line", json!({"points": [[0, 0], [30, 0]], "ids": ["la"], "infer": false}));
+ let d = run(&mut s, "sketch.dimension", json!({"entities": ["la"], "value": "w = 2"}));
+ assert_eq!(d["defined"], "w", "{d}");
+ assert!((d["measured"].as_f64().unwrap() - 50.8).abs() < 1e-6, "{d}");
+ // Stored with the design's unit spelled out, as a bare dimension value is.
+ let w = param_row(&mut s, "w");
+ assert_eq!((w["unit"].as_str(), w["expression"].as_str()), (Some("in"), Some("2 in")), "{w}");
+ assert!((line_length(&s, "la") - 50.8).abs() < 1e-6);
+ // A unit in the expression wins over the design's.
+ run(&mut s, "sketch.line", json!({"points": [[0, 50], [30, 50]], "ids": ["lb"], "infer": false}));
+ let d = run(&mut s, "sketch.dimension", json!({"entities": ["lb"], "value": "h = 20 mm"}));
+ assert!((d["measured"].as_f64().unwrap() - 20.0).abs() < 1e-6, "{d}");
+ assert_eq!((param_row(&mut s, "h")["unit"].as_str(), param_row(&mut s, "h")["expression"].as_str()), (Some("in"), Some("20 mm")));
+
+ let mut s = new_sketch();
+ run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0]], "ids": ["a"], "infer": false}));
+ run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 10]], "ids": ["b"], "infer": false}));
+ let d = run(&mut s, "sketch.dimension", json!({"entities": ["a", "b"], "type": "angle", "value": "ang = 60"}));
+ assert_eq!((d["defined"].as_str(), d["unit"].as_str()), (Some("ang"), Some("deg")), "{d}");
+ assert!((d["measured"].as_f64().unwrap() - 60.0).abs() < 1e-6, "{d}");
+ let ang = param_row(&mut s, "ang");
+ assert_eq!((ang["unit"].as_str(), ang["expression"].as_str()), (Some("deg"), Some("60")), "{ang}");
+ assert!((line_angle(&s, "a", "b") - 60.0).abs() < 1e-6);
+}
+
+/// A definition that cannot be made is refused with the reason, and leaves no parameter behind:
+/// a taken or reserved name, no expression, a driven dimension, a left side that is not a name
+/// (which stays the old parse error), and a dimension the sketch refuses.
+#[test]
+fn a_definition_that_cannot_be_made_is_refused_and_leaves_nothing() {
+ let refused = [
+ ("w = 20", json!({"name": "w", "expression": "5 mm"}), "there is already a parameter `w`: type `w` to use it"),
+ ("len = 20", Value::Null, "there is already a parameter `len`"),
+ ("mm = 5", Value::Null, "`mm` is a unit name, so it cannot be a parameter name"),
+ ("sin = 5", Value::Null, "`sin` is a function name, so it cannot be a parameter name"),
+ ("pi = 5", Value::Null, "`pi` is a constant, so it cannot be a parameter name"),
+ ("w =", Value::Null, "`w =` needs a value after the `=`"),
+ ("w = ", Value::Null, "needs a value"),
+ ("2 = 3", Value::Null, "unexpected `=`"),
+ ("w == 3", Value::Null, "unexpected `=`"),
+ ("w = nope", Value::Null, "nope"),
+ ("w = 1 deg", Value::Null, ""),
+ ("w = w", Value::Null, ""),
+ ];
+ for (value, add, message) in refused {
+ let mut s = sketch_with_len();
+ if !add.is_null() {
+ run(&mut s, "parameters.add", add);
+ }
+ let before = run(&mut s, "parameters.list", json!({}))["count"].clone();
+ let e = s.execute("sketch.dimension", &json!({"entities": ["la"], "value": value})).unwrap_err().to_string();
+ assert!(e.contains(message), "{value}: {e}");
+ assert_eq!(run(&mut s, "parameters.list", json!({}))["count"], before, "{value}: a refused definition added a parameter");
+ assert_eq!(sketch(&s).constraints.iter().filter(|c| c.param.is_some()).count(), 0, "{value}: a refused definition added a dimension");
+ }
+ // A driven (reference) dimension has no value, so it defines nothing.
+ let mut s = sketch_with_len();
+ let e = s.execute("sketch.dimension", &json!({"entities": ["la"], "value": "w = 20", "driven": true})).unwrap_err().to_string();
+ assert!(e.contains("driven"), "{e}");
+ assert!(param_row(&mut s, "w").is_null());
+ // A dimension the sketch already determines is refused as before, and its parameter with it.
+ let mut s = sketch_with_len();
+ run(&mut s, "sketch.dimension", json!({"entities": ["la"], "value": 30}));
+ let e = s.execute("sketch.dimension", &json!({"entities": ["la.start", "la.end"], "value": "w = 30"})).unwrap_err().to_string();
+ assert!(e.contains("already determined"), "{e}");
+ assert!(param_row(&mut s, "w").is_null(), "the parameter of a refused dimension was kept");
+ // Placed as driven instead (`if_redundant`), it has no value and defines nothing.
+ let d = run(&mut s, "sketch.dimension", json!({"entities": ["la.start", "la.end"], "value": "w = 30", "if_redundant": "driven"}));
+ assert_eq!((d["driven"].as_bool(), d.get("defined")), (Some(true), None), "{d}");
+ assert!(param_row(&mut s, "w").is_null(), "a driven dimension kept the parameter");
+}
+
+/// The parameter and the dimension are one command, so one undo removes both and one redo
+/// brings both back.
+#[test]
+fn undoing_a_defining_dimension_removes_the_parameter_too() {
+ let mut s = sketch_with_len();
+ let params = run(&mut s, "parameters.list", json!({}))["count"].as_u64().unwrap();
+ run(&mut s, "sketch.dimension", json!({"entities": ["la"], "value": "w = 20"}));
+ assert_eq!(run(&mut s, "parameters.list", json!({}))["count"].as_u64().unwrap(), params + 2, "the user parameter and the dimension's own");
+ run(&mut s, "edit.undo", json!({}));
+ assert!(param_row(&mut s, "w").is_null());
+ assert_eq!(run(&mut s, "parameters.list", json!({}))["count"].as_u64().unwrap(), params);
+ assert!((line_length(&s, "la") - 30.0).abs() < 1e-6);
+ run(&mut s, "edit.redo", json!({}));
+ assert_eq!(param_row(&mut s, "w")["expression"], "20");
+ assert!((line_length(&s, "la") - 20.0).abs() < 1e-6);
+}
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index e9a6685d43..b92c4d83e4 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -682,6 +682,12 @@ pub(crate) fn hostile_values() -> Vec<Value> {
json!("nope"),
json!("1/0"),
json!("((((((((((1"),
+ json!("w = 20"),
+ json!("w ="),
+ json!("= 20"),
+ json!("mm = 5"),
+ json!("w = w"),
+ json!("w == 1/0"),
json!([]),
json!([1e308, -1e308]),
json!([0, 0, 0]),
diff --git a/crates/ui-egui/src/dim_view.rs b/crates/ui-egui/src/dim_view.rs
index 1fa26a3157..e0af566cc5 100644
--- a/crates/ui-egui/src/dim_view.rs
+++ b/crates/ui-egui/src/dim_view.rs
@@ -103,7 +103,7 @@ impl DimensionDraft {
}
fn evaluate(&self, app: &SolveApp, expr: &str) -> Result<solidcraft_engine::Session, String> {
let mut scratch = app.session.scratch();
- let result = scratch.execute("sketch.dimension", &self.params(expr)).map_err(|e| e.to_string())?;
+ let result = scratch.execute("sketch.dimension", &self.params(expr)).map_err(|e| shown_error("sketch.dimension", &e.to_string()))?;
let param = result.get("param").and_then(serde_json::Value::as_str).ok_or("The dimension value is unavailable")?;
let state = scratch.world_state();
let solved = state.sketch(self.sketch).ok_or("The dimension sketch is unavailable")?;
@@ -120,6 +120,14 @@ impl DimensionDraft {
}
}
+/// A command's error as the value box and the status line show it: the command's label instead
+/// of its id, and without the `value:` field tag, since the box is the value
+/// ("Sketch Dimension: `mm` is a unit name, so it cannot be a parameter name").
+fn shown_error(id: &str, e: &str) -> String {
+ let label = crate::i18n::tr_label(crate::command_label(id));
+ crate::friendly_error(id, e).replacen(&format!("{label}: value: "), &format!("{label}: "), 1)
+}
+
pub fn cancel() {
EDIT.with(|edit| *edit.borrow_mut() = None);
PLACEMENT.with(|preview| *preview.borrow_mut() = None);
@@ -764,7 +772,9 @@ fn edit_box(app: &mut SolveApp, ctx: &egui::Context) {
Some(true) => {
let result = if let Some(draft) = &e.draft {
if draft.valid(app) {
- draft.evaluate(app, &e.expr).and_then(|_| app.run("sketch.dimension", draft.params(&e.expr)))
+ draft
+ .evaluate(app, &e.expr)
+ .and_then(|_| app.run("sketch.dimension", draft.params(&e.expr)).map_err(|err| shown_error("sketch.dimension", &err)))
} else {
Err("The sketch changed; place the dimension again".into())
}
@@ -777,14 +787,20 @@ fn edit_box(app: &mut SolveApp, ctx: &egui::Context) {
.map(|(k, _)| k)
.unwrap_or(solidcraft_engine::doc::expr::Kind::Unitless);
let expression = app.session.doc.with_design_unit(&e.expr, kind);
- app.run("parameters.change", json!({"name": e.param, "expression": expression}))
+ app.run("parameters.change", json!({"name": e.param, "expression": expression})).map_err(|err| shown_error("parameters.change", &err))
};
- if let Err(err) = result {
- app.set_status(err, true);
- EDIT.with(|x| *x.borrow_mut() = Some(Edit { fresh: FRESH, ..e }));
- } else {
- clear_picks(app);
- app.set_status("Dimension applied", false);
+ match result {
+ Err(err) => {
+ app.set_status(err, true);
+ EDIT.with(|x| *x.borrow_mut() = Some(Edit { fresh: FRESH, ..e }));
+ }
+ Ok(reply) => {
+ clear_picks(app);
+ match reply.get("defined").and_then(serde_json::Value::as_str) {
+ Some(name) => app.set_status(format!("Dimension applied; parameter `{name}` defined"), false),
+ None => app.set_status("Dimension applied", false),
+ }
+ }
}
}
Some(false) if escaped => clear_picks(app),
@@ -872,6 +888,67 @@ mod tests {
cancel();
}
+ /// Typing `w = 20` into a new dimension's value defines the user parameter `w` and
+ /// dimensions with it, in one undo step, and the status line says so (#2916). A taken name
+ /// is refused and the editor stays open with the text to correct.
+ #[test]
+ fn typing_a_definition_adds_the_parameter_and_dimensions_with_it() {
+ cancel();
+ let mut h = crate::scenario::Harness::new();
+ h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();
+ h.app.run("sketch.line", json!({"points":[[10,10],[40,10]],"infer":false})).unwrap();
+ h.call("ui.view", json!({"view":"top"}));
+ let undo = h.app.session.undo.len();
+ h.step(&json!({"start":"sketch.dimension"})).unwrap();
+ h.step(&json!({"click":{"sketch":[25,10]}})).unwrap();
+ assert!(editing());
+ h.step(&json!({"text":"w = 20"})).unwrap();
+ h.step(&json!({"key":"Enter"})).unwrap();
+ assert!(!editing(), "{:?}", h.app.status);
+ let w = h.app.session.doc.param("w").expect("the user parameter was added");
+ assert!(!w.model && w.expr.as_str() == "20" && w.unit == "mm", "{w:?}");
+ let sk = h.app.session.doc.sketch(h.app.session.active_sketch.unwrap()).unwrap();
+ let dim = sk.constraints.iter().find_map(|c| c.param.as_deref()).expect("the dimension was added");
+ assert_eq!(h.app.session.doc.param(dim).map(|p| p.expr.as_str()), Some("w"));
+ assert_eq!(h.app.session.undo.len(), undo + 1, "one undo step");
+ assert!(h.app.status.as_ref().is_some_and(|s| !s.2 && s.0.contains("`w`")), "{:?}", h.app.status);
+ // The same name again is refused; the editor keeps the text.
+ h.app.run("sketch.line", json!({"points":[[10,30],[40,30]],"infer":false})).unwrap();
+ let undo = h.app.session.undo.len();
+ h.step(&json!({"start":"sketch.dimension"})).unwrap();
+ h.step(&json!({"click":{"sketch":[25,30]}})).unwrap();
+ h.step(&json!({"text":"w = 25"})).unwrap();
+ h.step(&json!({"key":"Enter"})).unwrap();
+ assert!(editing(), "{:?}", h.app.status);
+ // The refusal reads as the command's own words, in the status line and in the box.
+ let taken = "Sketch Dimension: there is already a parameter `w`: type `w` to use it, or change it in Parameters";
+ assert_eq!(h.app.status.as_ref().map(|s| (s.0.as_str(), s.2)), Some((taken, true)));
+ assert_eq!(box_error(), Some(taken.to_string()));
+ assert_eq!(EDIT.with(|e| e.borrow().as_ref().map(|e| e.expr.clone())), Some("w = 25".to_string()));
+ assert_eq!(h.app.session.undo.len(), undo, "a refused definition changed nothing");
+ h.step(&json!({"key":"Escape"})).unwrap();
+ h.step(&json!({"key":"Escape"})).unwrap();
+ // A reserved name says what kind of word it is. The line goes below the first one: the
+ // ribbon floats over the top of the canvas, and a click at sketch y = 50 would land on it.
+ h.app.run("sketch.line", json!({"points":[[10,-10],[40,-10]],"infer":false})).unwrap();
+ h.step(&json!({"start":"sketch.dimension"})).unwrap();
+ h.step(&json!({"click":{"sketch":[25,-10]}})).unwrap();
+ h.step(&json!({"text":"mm = 5"})).unwrap();
+ h.step(&json!({"key":"Enter"})).unwrap();
+ assert!(editing(), "{:?}", h.app.status);
+ let reserved = "Sketch Dimension: `mm` is a unit name, so it cannot be a parameter name";
+ assert_eq!(h.app.status.as_ref().map(|s| (s.0.as_str(), s.2)), Some((reserved, true)));
+ assert_eq!(box_error(), Some(reserved.to_string()));
+ h.step(&json!({"key":"Escape"})).unwrap();
+ h.step(&json!({"key":"Escape"})).unwrap();
+ cancel();
+ }
+
+ /// The error shown inside the open value box.
+ fn box_error() -> Option<String> {
+ EDIT.with(|e| e.borrow().as_ref().and_then(|e| e.draft.as_ref()).and_then(|d| d.error.clone()))
+ }
+
/// Placing a dimension the sketch can't take previews it as driven: in the draft it is a
/// driven constraint with no parameter, labelled in parentheses (#320).
#[test]
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 7c73ef1beb..3a058a0499 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -114,6 +114,16 @@ mod status_tests {
"Shell: offset: must be positive"
);
assert_eq!(super::friendly_error("edit.undo", "nothing to undo"), "Undo: nothing to undo");
+ {
+ // The label follows the interface language; the engine's words stay English.
+ let _polish = crate::i18n::scope("pl");
+ assert_eq!(super::friendly_error("edit.undo", "nothing to undo"), "Cofnij: nothing to undo");
+ assert_eq!(
+ super::friendly_error("sketch.dimension", "invalid parameters for `sketch.dimension`: value: `mm` is a unit name"),
+ "Wymiar szkicu: value: `mm` is a unit name"
+ );
+ }
+ assert_eq!(super::friendly_error("edit.undo", "nothing to undo"), "Undo: nothing to undo");
let mut app = super::SolveApp::new(solidcraft_engine::Session::default(), Default::default());
app.run("solid.box", serde_json::json!({"length": 5, "width": 5, "height": 5})).unwrap();
assert_eq!(app.session.log.last().map(String::as_str), Some("Box done"));
@@ -1829,9 +1839,10 @@ pub fn command_label(id: &str) -> &str {
solidcraft_engine::find_command(id).map_or(id, |c| c.label)
}
-/// An engine error with the command's label instead of its id: "Shell: offset must be …".
+/// An engine error with the command's label instead of its id: "Shell: offset must be …". The
+/// label follows the interface language; the engine's sentence stays as the engine wrote it.
pub fn friendly_error(id: &str, e: &str) -> String {
- let label = command_label(id);
+ let label = i18n::tr_label(command_label(id));
let msg = e.replace(&format!("invalid parameters for `{id}`: "), "").replace(&format!("{id}: "), "").replace(&format!("`{id}`"), label);
if msg.starts_with(label) { msg } else { format!("{label}: {msg}") }
}
diff --git a/docs/book/src/guide/parameters.md b/docs/book/src/guide/parameters.md
index e0cc5892b7..802b277639 100644
--- a/docs/book/src/guide/parameters.md
+++ b/docs/book/src/guide/parameters.md
@@ -10,7 +10,9 @@ name (`d1`, `d2`, …). Click another driving dimension to use its name: when th
just a number (such as `10` or `10 mm`) the name replaces it; otherwise it goes in at the
cursor, replacing selected text and keeping what you typed, so typing `10 + ` and clicking
`d1` gives `10 + d1`. Add arithmetic such as `/ 2` to build a dependent dimension. Press **Enter** to apply
-the expression or **Escape** to cancel the edit.
+the expression or **Escape** to cancel the edit. When placing a new dimension, `width = 40` adds
+the user parameter `width` with that value (a bare number is in the design's units) and
+dimensions with it; a name that is already taken is refused.
Add and edit user parameters through the existing **Change Parameters** command.
In the MANAGE tab's PARAMETERS section, click **Parameters** to open the user and model
diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md
index 090de552c5..2b8b488c1d 100644
--- a/docs/book/src/guide/sketching.md
+++ b/docs/book/src/guide/sketching.md
@@ -202,7 +202,8 @@ Press D, click what you want to measure and type the value: as soon as the click
dimension (one line, circle or arc, or the second point or line of a distance or angle), its
value box takes the keyboard with the measured value selected, so typing replaces it. Numbers,
units (`1 in`), expressions (`2*width`) and parameter names all work; letters go into the box,
-not to tool shortcuts. While you type, the dimension text follows the cursor, and Enter places
+not to tool shortcuts. `width = 40` defines the user parameter `width` and dimensions with it,
+in one step. While you type, the dimension text follows the cursor, and Enter places
it there (or in its default place if you haven't moved the cursor) as one undo step. Esc
cancels the dimension.