* 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:
1 parent
5dc95ef7f6
commit
c8c5c882de
8 files changed
+203
-13
No files matched your search
@@ -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")
|
||||
|
||||
@@ -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", ¶ms).expect_err(¶ms.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);
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,14 @@
|
||||
//! boxes (line length and angle, rectangle width and height, circle diameter…) sit next to the
|
||||
//! segment they measure and follow the cursor. Typing goes straight into the first box and
|
||||
//! locks that value; Tab moves to the next box; Enter places the shape with the typed values,
|
||||
//! which become dimension constraints. Values are expressions ("25", "1 in", "d1 * 2").
|
||||
//! which become dimension constraints. Values are expressions ("25", "1 in", "d1 * 2"), or
|
||||
//! `name = expression`, which also defines the user parameter `name` (#7567).
|
||||
|
||||
use crate::ui_kit::{Container, Surface};
|
||||
use egui::{Pos2, vec2};
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_engine::doc::expr::Kind as ValueKind;
|
||||
use solidcraft_engine::doc::Document;
|
||||
use solidcraft_engine::doc::expr::{Kind as ValueKind, definition};
|
||||
use solidcraft_engine::geom::Vec2;
|
||||
|
||||
use crate::SolveApp;
|
||||
@@ -57,7 +59,19 @@ pub fn boxes_for(cmd: &str, n: usize) -> Vec<DimBox> {
|
||||
/// A locked box's value (mm or radians).
|
||||
fn locked(app: &SolveApp, t: &Tool, label: &str) -> Option<f64> {
|
||||
let b = t.dims.iter().chain(&t.dim_history).find(|b| b.label == label && b.locked)?;
|
||||
crate::length_input::eval(&app.session.doc, &b.value, b.kind).ok().filter(|v| v.is_finite())
|
||||
eval(&app.session.doc, &b.value, b.kind).ok().filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
/// A box value's size. `name = expression` is the right-hand side's: the size the parameter
|
||||
/// `name` will hold once the shape is placed.
|
||||
fn eval(doc: &Document, text: &str, kind: ValueKind) -> solidcraft_engine::doc::Result<f64> {
|
||||
crate::length_input::eval(doc, definition(text).map_or(text, |(_, rhs)| rhs), kind)
|
||||
}
|
||||
|
||||
/// Whether a box becomes one of the shape's dimensions. A rounded rectangle's radius is its own
|
||||
/// parameter (sent with the shape); sides and rho are counts and shape factors.
|
||||
fn is_dimension(t: &Tool, label: &str) -> bool {
|
||||
!matches!(label, "Sides" | "Rho") && !(t.cmd == "sketch.rectangle.rounded" && label == "Radius")
|
||||
}
|
||||
|
||||
fn dir_or_x(v: Vec2) -> Vec2 {
|
||||
@@ -346,10 +360,7 @@ pub fn dimensions(t: &Tool) -> Value {
|
||||
.dim_history
|
||||
.iter()
|
||||
.chain(&t.dims)
|
||||
// A rounded rectangle's radius is its own parameter (sent with the shape), not a dimension.
|
||||
.filter(|dimension| {
|
||||
dimension.locked && !matches!(dimension.label, "Sides" | "Rho") && !(t.cmd == "sketch.rectangle.rounded" && dimension.label == "Radius")
|
||||
})
|
||||
.filter(|dimension| dimension.locked && is_dimension(t, dimension.label))
|
||||
.map(|dimension| (dimension.label.to_ascii_lowercase(), json!(dimension.value)))
|
||||
.collect::<serde_json::Map<_, _>>();
|
||||
Value::Object(values)
|
||||
@@ -361,8 +372,15 @@ pub fn validate(app: &SolveApp, t: &Tool) -> Result<(), String> {
|
||||
if dimension.value.len() > 4096 {
|
||||
return Err(format!("{} expression is too long", dimension.label));
|
||||
}
|
||||
let value =
|
||||
crate::length_input::eval(&app.session.doc, &dimension.value, dimension.kind).map_err(|error| format!("{}: {error}", dimension.label))?;
|
||||
if let Some((name, rhs)) = definition(&dimension.value) {
|
||||
if !is_dimension(t, dimension.label) {
|
||||
return Err(format!("{}: only a box that becomes a dimension can define `{name}`; type the value alone", dimension.label));
|
||||
}
|
||||
if rhs.is_empty() {
|
||||
return Err(format!("{}: `{name} =` needs a value after the `=`", dimension.label));
|
||||
}
|
||||
}
|
||||
let value = eval(&app.session.doc, &dimension.value, dimension.kind).map_err(|error| format!("{}: {error}", dimension.label))?;
|
||||
if !value.is_finite() || value.abs() > 1e9 {
|
||||
return Err(format!("{} must be finite and within the model's size limits", dimension.label));
|
||||
}
|
||||
|
||||
@@ -454,3 +454,66 @@ fn value_boxes_stay_in_view_and_off_the_cursor() {
|
||||
let tiny = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(80.0, 30.0));
|
||||
assert!(tiny.contains_rect(egui::Rect::from_min_size(in_view(egui::pos2(-200.0, -200.0), Some(tiny), Some(egui::pos2(40.0, 15.0))), BOX)));
|
||||
}
|
||||
|
||||
/// `name = expression` in a value box, as in the Dimension tool's: the shape takes the
|
||||
/// expression's size while it is typed and when placed, and the new parameter `name` drives its
|
||||
/// dimension (#7567).
|
||||
#[test]
|
||||
fn a_box_typed_name_equals_value_defines_the_parameter_driving_the_dimension() {
|
||||
let mut h = drawing("sketch.circle.center");
|
||||
type_value(&mut h, "width=20");
|
||||
let tool = h.app.tool.as_ref().unwrap();
|
||||
assert_eq!(crate::sketch_dims::locked_value(&h.app, tool, "Diameter"), Some(20.0), "the preview follows the typed size");
|
||||
h.step(&json!({"key": "Enter"})).unwrap();
|
||||
let state = h.app.session.world_state();
|
||||
let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch;
|
||||
assert_eq!(sk.curves.len(), 1, "{:?}", h.app.status);
|
||||
assert!(sk.radius(0).is_some_and(|r| (r - 10.0).abs() < 1e-6), "{:?}", sk.radius(0));
|
||||
let width = h.app.session.doc.param("width").expect("the parameter is defined");
|
||||
assert_eq!((width.expr.as_str(), width.unit.as_str(), width.model), ("20", "mm", false));
|
||||
let dimension = sk.constraints.iter().find_map(|c| c.param.as_deref()).expect("a driving dimension");
|
||||
assert_eq!(h.app.session.doc.param(dimension).unwrap().expr, "width");
|
||||
assert_eq!(h.app.status.as_ref().map(|(text, _, error)| (text.as_str(), *error)), Some(("Parameter `width` defined", false)));
|
||||
|
||||
// In an inch design the right-hand side is in inches, while typing too.
|
||||
let mut h = Harness::new();
|
||||
h.app.run("document.units", json!({"units":"in"})).unwrap();
|
||||
h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();
|
||||
h.step(&json!({"start":"sketch.rectangle.two_point"})).unwrap();
|
||||
h.step(&json!({"click":{"world":[0,0,0]}})).unwrap();
|
||||
h.step(&json!({"move":{"world":[25.4,12.7,0]}})).unwrap();
|
||||
type_value(&mut h, "#w = 2");
|
||||
tab(&mut h, false);
|
||||
type_value(&mut h, "h = 1");
|
||||
let tool = h.app.tool.as_ref().unwrap();
|
||||
assert!((crate::sketch_dims::locked_value(&h.app, tool, "Width").unwrap() - 50.8).abs() < 1e-6);
|
||||
h.step(&json!({"key":"Enter"})).unwrap();
|
||||
assert_eq!(h.app.session.doc.param("w").map(|p| p.unit.as_str()), Some("in"), "{:?}", h.app.status);
|
||||
assert!(h.app.session.doc.param("h").is_some());
|
||||
assert_eq!(h.app.status.as_ref().map(|(text, _, _)| text.as_str()), Some("Parameters `h`, `w` defined"));
|
||||
}
|
||||
|
||||
/// A box that is not a dimension (a polygon's sides, a rounded rectangle's corner radius) has
|
||||
/// nothing for a parameter to drive: `name = ...` there is refused, not quietly dropped.
|
||||
#[test]
|
||||
fn a_definition_in_a_box_that_is_not_a_dimension_is_refused() {
|
||||
for (command, tabs, text, says) in [
|
||||
("sketch.polygon.inscribed", 1, "n = 6", "Sides: only a box that becomes a dimension can define `n`"),
|
||||
("sketch.rectangle.rounded", 2, "r = 2", "Radius: only a box that becomes a dimension can define `r`"),
|
||||
("sketch.circle.center", 0, "w =", "Diameter: `w =` needs a value after the `=`"),
|
||||
] {
|
||||
let mut h = drawing(command);
|
||||
for _ in 0..tabs {
|
||||
tab(&mut h, false);
|
||||
}
|
||||
type_value(&mut h, text);
|
||||
h.step(&json!({"key": "Enter"})).unwrap();
|
||||
let state = h.app.session.world_state();
|
||||
let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch;
|
||||
assert!(sk.curves.is_empty(), "{command} {text}: placed {:?}", h.app.status);
|
||||
assert!(h.app.session.doc.params.iter().all(|p| p.model), "{command} {text}: no user parameter");
|
||||
let status = h.app.status.as_ref().expect("the refusal is reported");
|
||||
assert!(status.2 && status.0.starts_with(says), "{command} {text}: {status:?}");
|
||||
assert_eq!(h.app.tool.as_ref().unwrap().pts.len(), 1, "{command} {text}: the first point stays down");
|
||||
}
|
||||
}
|
||||
@@ -508,6 +508,13 @@ pub(crate) fn draw(app: &mut SolveApp, t: &Tool, params: Value) -> Result<Value,
|
||||
let history = std::mem::take(&mut app.session.undo);
|
||||
crate::sketch_palette::apply_mode(app, t.cmd, &result);
|
||||
app.session.undo = history;
|
||||
// A box typed `name = expression` defined the parameter `name` (#7567).
|
||||
let defined: Vec<_> = result["defined"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|name| format!("`{name}`")).collect();
|
||||
match defined.as_slice() {
|
||||
[] => {}
|
||||
[name] => app.set_status(format!("Parameter {name} defined"), false),
|
||||
names => app.set_status(format!("Parameters {} defined", names.join(", ")), false),
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,9 @@ cursor, replacing selected text and keeping what you typed, so typing `10 + ` an
|
||||
`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. When placing a new dimension, `width = 40` (or `#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.
|
||||
dimensions with it; a name that is already taken is refused. The value boxes shown while drawing
|
||||
a shape (a line's length, a rectangle's width and height, a circle's diameter) take the same
|
||||
form: the shape is drawn at that size, and its dimension uses the new parameter.
|
||||
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
|
||||
|
||||
@@ -44,6 +44,14 @@ drop-down. The button and the family's shortcut start the variant you picked las
|
||||
shortcut such as L can start a Midpoint Line; pick the variant you want from the drop-down to
|
||||
change it ([Keyboard shortcuts](shortcuts.md)).
|
||||
|
||||
Once a shape's first point is down, value boxes (a line's length and angle, a rectangle's width
|
||||
and height, a circle's diameter…) follow the cursor. Typing goes into the first box, Tab moves to
|
||||
the next and Enter places the shape; each typed value becomes a dimension. A value is an
|
||||
expression (`25`, `1 in`, `d1 * 2`), or `width = 20` (also `#width = 20`), which also adds the
|
||||
user parameter `width` and dimensions with it, as when [placing a dimension](parameters.md). A
|
||||
box that does not become a dimension (a polygon's sides, a rounded rectangle's corner radius)
|
||||
takes a value only.
|
||||
|
||||
The Sketch Palette's **Construction Geometries** option hides construction curves while you
|
||||
work. A hidden construction curve cannot be picked by a click or by a box. Nothing invisible
|
||||
is selectable. The option belongs to one sketch and is saved with the design. Centerlines are
|
||||
|
||||
Reference in new issue
Block a user