Sketch: name = value in a drawing tool's value box defines the parameter (#7567) (#7660)

* claim: #7567

* Sketch: a drawing tool's value box takes `name = value` (#7567)

While drawing, a value box (circle diameter, line length, rectangle width and
height, slot, arc, polygon) now accepts `name = expression` and
`#name = expression`, as the Dimension tool already does: the shape is drawn at
the expression's size and its dimension defines and uses the user parameter
`name`, in one undo step.

- sketch.draw.dimensioned checks a definition's right-hand side, read as the
  new parameter will hold it (a bare number in the design's unit), and passes
  the text on to sketch.dimension; the reply lists `defined`.
- The value boxes size the preview and validate by the right-hand side, refuse
  a definition in a box that is not a dimension (polygon sides, rounded
  rectangle corner radius, conic rho), and the status line names the
  parameters defined.
- Guides: parameters and sketching.

Fixes #7567

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Erlis Vidal
2026-10-27 19:02:09 +00:00
committed by GitHub
parent 5dc95ef7f6
commit c8c5c882de
8 changed files with 203 additions and 13 deletions
+1 -1
View File
@@ -51,7 +51,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.params(concat!("points: [[x,y] | \"l1.end\" | {at, ref}…] (x and y each a number or an expression over the design's parameters, \"W / 2\": such a point is fixed where it comes to and follows the parameters; likewise wherever a point argument also takes a point id), closed?: bool, construction?: bool, ids?: [..], infer?: bool (add horizontal/vertical)", connect_doc!(), created_doc!())),
CommandSpec::new("sketch.draw.dimensioned", "Draw Dimensioned Sketch Geometry", draw_dimensioned).icon("dimension")
.enabled(in_sketch)
.params(concat!("command: sketch creation command, params: object, dimensions: object of role to numeric or expression value; creates geometry and all driving dimensions atomically in one undo step", created_doc!())),
.params(concat!("command: sketch creation command, params: object, dimensions: object of role to numeric or expression value, or `name = expression` (also `#name = expression`), which defines the user parameter `name` as sketch.dimension does (the reply's `defined` lists the names); creates geometry and all driving dimensions atomically in one undo step", created_doc!())),
CommandSpec::new("sketch.rectangle.two_point", "2-Point Rectangle", rect_two_point)
.at("SKETCH", "CREATE")
.icon("rect")
+16 -2
View File
@@ -1,6 +1,6 @@
//! Shape creation and its typed driving dimensions form one command and one undo step.
use serde_json::{Value, json};
use solidcraft_doc::expr::Kind;
use solidcraft_doc::expr::{Kind, definition};
use crate::{
Result, Session,
@@ -38,7 +38,14 @@ pub(super) fn draw(s: &mut Session, p: &Value) -> Result<Value> {
.filter(|e| e.len() <= 4096)
.ok_or_else(|| bad(cmd, "dimension values must be bounded expressions or finite numbers"))?;
let kind = if role == "angle" || role == "sweep" { Kind::Angle } else { Kind::Length };
let evaluated = s.doc.eval(&e, kind)?;
// `name = expression` is checked by its right-hand side, read as the user parameter
// `sketch.dimension` defines will hold it (a bare number in the design's unit) (#7567).
let rhs = match definition(&e) {
Some((name, "")) => return Err(bad(cmd, format!("{role}: `{name} =` needs a value after the `=`"))),
Some((_, rhs)) => rhs,
None => e.as_str(),
};
let evaluated = s.doc.eval(&s.doc.with_design_unit(rhs, kind), kind)?;
if role == "length" {
overall_length = Some(evaluated);
}
@@ -85,6 +92,7 @@ pub(super) fn draw(s: &mut Session, p: &Value) -> Result<Value> {
curves.get(index).filter(|v| v.is_string()).cloned().ok_or_else(|| bad(cmd, "creator did not return the expected curve"))
};
let mut added = serde_json::Map::new();
let mut defined = Vec::new();
for (role, value) in dimensions {
let (entities, ty) = match (create, role.as_str()) {
("sketch.line" | "sketch.line.midpoint", "length") => (vec![curve(0)?], "length"),
@@ -120,12 +128,18 @@ pub(super) fn draw(s: &mut Session, p: &Value) -> Result<Value> {
dimension["sketch"] = sketch.clone();
}
let result = scratch.execute("sketch.dimension", &dimension)?;
if let Some(name) = result.get("defined").filter(|v| v.is_string()) {
defined.push(name.clone());
}
added.insert(role.clone(), result);
}
// Session::execute records the wrapper's before snapshot. Nested history must not leak.
scratch.undo.clear();
s.accept_computed(scratch);
out["dimensions"] = Value::Object(added);
if !defined.is_empty() {
out["defined"] = Value::Array(defined);
}
Ok(out)
}
@@ -227,3 +227,81 @@ fn dimensioned_authoring_uses_selected_occurrence_and_keeps_local_geometry() {
close(sk.points[a].pos.x, 0.0);
close(sk.points[b].pos.x, 5.0 / std::f64::consts::SQRT_2);
}
/// The expression of the parameter driving the first dimension `kind` matches.
fn driving(s: &Session, kind: fn(&ConstraintKind) -> bool) -> String {
let sk = sketch(s);
let c = sk.constraints.iter().find(|c| kind(&c.kind)).unwrap();
s.doc.param(c.param.as_deref().unwrap()).unwrap().expr.clone()
}
/// A typed box value `name = expression` defines the user parameter `name`, which drives the
/// dimension, as the Dimension tool's value does (#7567).
#[test]
fn a_typed_definition_defines_the_parameter_that_drives_the_dimension() {
let is_diameter = |k: &ConstraintKind| matches!(k, ConstraintKind::Diameter { .. });
let mut s = session();
let undo = s.undo.len();
let out = draw(&mut s, "sketch.circle.center", json!({"center":[0,0],"radius":3}), json!({"diameter":"width = 20"}));
assert_eq!(s.undo.len(), undo + 1);
assert_eq!(out["defined"], json!(["width"]), "{out}");
close(measure(&s, is_diameter), 20.0);
let width = s.doc.param("width").unwrap();
assert_eq!((width.expr.as_str(), width.unit.as_str(), width.model), ("20", "mm", false));
assert_eq!(driving(&s, is_diameter), "width");
run(&mut s, "edit.undo", json!({}));
assert!(sketch(&s).curves.is_empty() && s.doc.param("width").is_none());
// A bare number is in the design's unit, in the size checks too.
let mut s = session();
run(&mut s, "document.units", json!({"units":"in"}));
draw(&mut s, "sketch.circle.center", json!({"center":[0,0],"radius":3}), json!({"diameter":"#w = 2"}));
close(measure(&s, is_diameter), 50.8);
assert_eq!(s.doc.param("w").unwrap().unit, "in");
let mut s = session();
run(&mut s, "document.units", json!({"units":"in"}));
let slot = json!({"p0":[0,0],"p1":[60,0],"width":10,"connect":false});
draw(&mut s, "sketch.slot.overall", slot.clone(), json!({"length":"len = 2","width":"0.5"}));
close(measure(&s, |k| matches!(k, ConstraintKind::SlotOverallLength { .. })), 50.8);
// Both boxes of a rectangle may define a name.
let mut s = session();
let out = draw(&mut s, "sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[5,5]}), json!({"width":"w = 30","height":"h=10"}));
assert_eq!(out["defined"], json!(["h", "w"]), "{out}");
let is_length = |k: &ConstraintKind| matches!(k, ConstraintKind::Length { .. });
let sk = sketch(&s);
let mut lengths: Vec<_> =
sk.constraints.iter().filter(|c| is_length(&c.kind)).map(|c| solidcraft_sketch::measure_dimension(&sk, &c.kind).unwrap()).collect();
lengths.sort_by(f64::total_cmp);
assert_eq!(lengths.len(), 2);
close(lengths[0], 10.0);
close(lengths[1], 30.0);
}
#[test]
fn a_refused_typed_definition_changes_nothing() {
let mut s = session();
run(&mut s, "parameters.add", json!({"name":"taken","expression":"5","unit":"mm"}));
let circle = |value: &str| json!({"command":"sketch.circle.center","params":{"center":[0,0],"radius":3},"dimensions":{"diameter":value}});
let rect =
|w: &str, h: &str| json!({"command":"sketch.rectangle.two_point","params":{"p0":[0,0],"p1":[5,5]},"dimensions":{"width":w,"height":h}});
for (params, says) in [
(circle("taken = 20"), "already a parameter"),
(circle("w ="), "needs a value"),
(circle("2 = 3"), ""),
(circle("w == 3"), ""),
(circle("w = -4"), "invalid diameter"),
(circle(&format!("w = {}", "1".repeat(4096))), "bounded"),
// The same name twice: the second box finds it taken.
(rect("w = 30", "w = 10"), "already a parameter"),
// A box's value can't use a name the other box defines: neither exists yet.
(rect("w = 30", "h = w / 2"), ""),
] {
let snapshot = serde_json::to_value(&*s.doc).unwrap();
let undo = s.undo.len();
let error = s.execute("sketch.draw.dimensioned", &params).expect_err(&params.to_string()).to_string();
assert!(error.contains(says), "{params}: {error}");
assert_eq!(serde_json::to_value(&*s.doc).unwrap(), snapshot, "{params}");
assert_eq!(s.undo.len(), undo);
}
}