Sketch: switch a circle or arc dimension between radius and diameter (#7499) (#7729)

* Sketch: switch a circle or arc dimension between radius and diameter (#7499)

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

* Sketch: Toggle Radius / Diameter for a circle's or an arc's dimension (#7499)

New command sketch.toggle_diameter, with input and output schemas, and a
context-menu item on a single selected radius or diameter dimension. The
circle keeps its size: the dimension's parameter is halved or doubled (a
plain value is rewritten, an expression is wrapped). Refused, with nothing
changed, when anything else uses that parameter.

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

---------

Co-authored-by: Phanoob <phanoob@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
phanoob
2026-10-27 18:49:30 +00:00
committed by GitHub
parent d14dbe5e39
commit d139e415e4
7 changed files with 279 additions and 1 deletions
@@ -0,0 +1,11 @@
{
"en": { "cmd.sketch_toggle_diameter": "Toggle Radius / Diameter" },
"ar": { "cmd.sketch_toggle_diameter": "تبديل نصف القطر / القطر" },
"de": { "cmd.sketch_toggle_diameter": "Radius / Durchmesser umschalten" },
"es": { "cmd.sketch_toggle_diameter": "Alternar radio / diámetro" },
"fr": { "cmd.sketch_toggle_diameter": "Basculer rayon / diamètre" },
"he": { "cmd.sketch_toggle_diameter": "מעבר בין רדיוס לקוטר" },
"ja": { "cmd.sketch_toggle_diameter": "半径 / 直径の切り替え" },
"vi": { "cmd.sketch_toggle_diameter": "Chuyển đổi bán kính / đường kính" },
"zh": { "cmd.sketch_toggle_diameter": "切换半径 / 直径" }
}
@@ -8,8 +8,12 @@ use solidcraft_sketch::{ConstraintKind, CurveKind, Sketch};
use super::sketch::{add_c, constraint_result, dof_now, edit, listed, redundancy, residual_of};
use super::{CommandSpec, in_sketch};
use crate::params::{bad, num, req_vec2, str_, string_list, vec2};
use crate::schema::sketch_constraints::{ToggleDiameterParams, ToggleDiameterResult};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
const TOGGLE_DIAMETER_CONTRACT: TypedContract<ToggleDiameterParams> = TypedContract::new();
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("sketch.constraint.curvature", "Curvature", c_smooth)
.at("SKETCH", "CONSTRAINTS")
@@ -44,6 +48,12 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("sketch.toggle_driven", "Toggle Driven Dimension", toggle_driven).icon("dimension")
.enabled(in_sketch)
.params("constraint: dimension id, driven?: bool (default toggles); a driving dimension gets a parameter with its current value"),
CommandSpec::new("sketch.toggle_diameter", "Toggle Radius / Diameter", crate::checked!("sketch.toggle_diameter", toggle_diameter))
.icon("dimension")
.enabled(in_sketch)
.contract(&TOGGLE_DIAMETER_CONTRACT)
.output(output_schema_for::<ToggleDiameterResult>)
.params("constraint: a circle's or an arc's radius or diameter dimension id; diameter?: bool (default: the other one); sketch?: id|name (default: the one being edited). The circle stays the same size: its parameter is halved or doubled (a plain value is rewritten, an expression becomes `(e) / 2` or `2 * (e)`); refused when anything else uses that parameter"),
CommandSpec::new("sketch.glyphs", "Constraint Glyphs", glyphs).icon("eye")
.enabled(in_sketch)
.noundo()
@@ -408,6 +418,60 @@ fn toggle_driven(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"constraint": cid, "driven": driven, "sketch": info}))
}
fn toggle_diameter(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.toggle_diameter";
let cid = str_(p, "constraint").ok_or_else(|| bad(cmd, "`constraint` must be a dimension id"))?.to_string();
let want = crate::params::bool_(p, "diameter");
let sketch = super::sketch::target_sketch(s, p, cmd)?;
let (diameter, info) = edit(s, p, cmd, true, |sk, doc| {
let c = sk.constraints.iter().find(|c| c.id == cid).cloned().ok_or_else(|| bad(cmd, format!("no constraint `{cid}`")))?;
let round = |curve: usize| matches!(sk.curves.get(curve).map(|c| &c.kind), Some(CurveKind::Circle { .. } | CurveKind::Arc { .. }));
let (curve, value, now) = match c.kind {
ConstraintKind::Radius { c, value } if round(c) => (c, value, false),
ConstraintKind::Diameter { c, value } if round(c) => (c, value, true),
_ => return Err(bad(cmd, format!("`{cid}` is not a circle's or an arc's radius or diameter dimension"))),
};
let diameter = want.unwrap_or(!now);
if diameter == now {
return Ok(diameter);
}
let (kind, value) = if diameter {
(ConstraintKind::Diameter { c: curve, value: 2.0 * value }, 2.0 * value)
} else {
(ConstraintKind::Radius { c: curve, value: value / 2.0 }, value / 2.0)
};
// Its parameter now holds the other measure, so the circle keeps its size; another user
// of that parameter would change size with it.
if let Some(name) = &c.param {
let others: Vec<String> = doc
.param_users(name)
.into_iter()
.filter(
|u| !matches!(u, solidcraft_doc::ParamUser::Dimension { feature, constraint, .. } if *feature == sketch && *constraint == cid),
)
.map(|u| u.describe())
.collect();
if !others.is_empty() {
return Err(bad(cmd, format!("`{name}` is also used by {}; switching `{cid}` would change them", others.join(", "))));
}
let e = doc.param(name).map(|p| p.expr.clone()).ok_or_else(|| bad(cmd, format!("no parameter `{name}`")))?;
let e = if solidcraft_doc::expr::references(&e).is_empty() {
doc.design_length(value).1
} else if diameter {
format!("2 * ({e})")
} else {
format!("({e}) / 2")
};
doc.set_param(name, &e, None, None).map_err(|e| bad(cmd, e.to_string()))?;
}
let slot = sk.constraints.iter_mut().find(|c| c.id == cid).ok_or_else(|| bad(cmd, "constraint"))?;
slot.kind = kind;
Ok(diameter)
})?;
let reply = ToggleDiameterResult { constraint: cid, diameter, sketch: info, param_warnings: Vec::new() };
serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string()))
}
/// Where a constraint's glyph goes (sketch coordinates): beside the middle of its first curve,
/// or at its point.
fn anchor(sk: &Sketch, k: &ConstraintKind) -> Option<Vec2> {
@@ -285,6 +285,62 @@ fn smart_constrain_and_driven_toggle() {
assert_eq!(r["driven"], false);
}
/// #7499: a circle's or an arc's dimension switches between its radius and its diameter, the
/// circle keeping its size: the parameter is halved or doubled, an expression wrapped.
#[test]
fn a_radius_dimension_switches_to_a_diameter_and_back() {
use solidcraft_sketch::ConstraintKind;
let mut s = new_sketch();
let dim = |s: &Session, param: &str| sketch(s).constraints.iter().find(|c| c.param.as_deref() == Some(param)).unwrap().clone();
let c1 = ids(&run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10}))["curves"])[0].clone();
let d = run(&mut s, "sketch.dimension", json!({"entities": [c1]}));
let p1 = d["param"].as_str().unwrap().to_string();
let did = dim(&s, &p1).id;
assert!(matches!(dim(&s, &p1).kind, ConstraintKind::Diameter { .. }), "a circle is dimensioned by its diameter");
let r = run(&mut s, "sketch.toggle_diameter", json!({"constraint": did}));
assert_eq!(r["diameter"], false, "{r}");
assert!(matches!(dim(&s, &p1).kind, ConstraintKind::Radius { value, .. } if (value - 10.0).abs() < 1e-9), "{:?}", dim(&s, &p1).kind);
assert_eq!(s.doc.param(&p1).unwrap().expr, "10 mm");
assert!((sketch(&s).radius(0).unwrap() - 10.0).abs() < 1e-9, "the circle keeps its size");
// Asking for what it already is changes nothing; then back to the diameter.
let r = run(&mut s, "sketch.toggle_diameter", json!({"constraint": did, "diameter": false}));
assert_eq!(r["diameter"], false, "{r}");
run(&mut s, "sketch.toggle_diameter", json!({"constraint": did}));
assert!(matches!(dim(&s, &p1).kind, ConstraintKind::Diameter { value, .. } if (value - 20.0).abs() < 1e-9));
assert_eq!(s.doc.param(&p1).unwrap().expr, "20 mm");
// An expression is wrapped, so it still reads the parameters it names.
run(&mut s, "parameters.add", json!({"name": "w", "expression": "30 mm"}));
let c2 = ids(&run(&mut s, "sketch.circle.center", json!({"center": [50, 0], "radius": 10}))["curves"])[0].clone();
let p2 = run(&mut s, "sketch.dimension", json!({"entities": [c2], "value": "w"}))["param"].as_str().unwrap().to_string();
let d2 = dim(&s, &p2).id;
run(&mut s, "sketch.toggle_diameter", json!({"constraint": d2}));
assert_eq!(s.doc.param(&p2).unwrap().expr, "(w) / 2");
assert!((sketch(&s).radius(1).unwrap() - 15.0).abs() < 1e-6, "{:?}", sketch(&s).radius(1));
// Another user of the parameter would change size with it: refused, nothing changes.
run(&mut s, "parameters.add", json!({"name": "k", "expression": format!("{p1} + 1 mm")}));
let e = s.execute("sketch.toggle_diameter", &json!({"constraint": did})).unwrap_err().to_string();
assert!(e.contains("also used by parameter k"), "{e}");
assert!(matches!(dim(&s, &p1).kind, ConstraintKind::Diameter { .. }));
assert_eq!(s.doc.param(&p1).unwrap().expr, "20 mm");
// An arc's driven radius becomes its driven diameter; a line's length is no radius.
let a = ids(&run(&mut s, "sketch.arc.center_point", json!({"center": [0, 80], "start": [20, 80], "sweep": 90}))["curves"])[0].clone();
run(&mut s, "sketch.dimension", json!({"entities": [a], "driven": true}));
let arc = sketch(&s).curves.iter().position(|c| c.id == a).unwrap();
let driven = sketch(&s).constraints.iter().find(|c| matches!(c.kind, ConstraintKind::Radius { c, .. } if c == arc)).unwrap().clone();
assert!(driven.driven && driven.param.is_none());
run(&mut s, "sketch.toggle_diameter", json!({"constraint": driven.id}));
let now = sketch(&s).constraints.iter().find(|c| c.id == driven.id).unwrap().clone();
assert!(now.driven && matches!(now.kind, ConstraintKind::Diameter { value, .. } if (value - 40.0).abs() < 1e-6), "{now:?}");
let l = ids(&run(&mut s, "sketch.line", json!({"points": [[0, -50], [10, -50]]}))["curves"])[0].clone();
let pl = run(&mut s, "sketch.dimension", json!({"entities": [l], "value": 10}))["param"].as_str().unwrap().to_string();
let dl = dim(&s, &pl).id;
let e = s.execute("sketch.toggle_diameter", &json!({"constraint": dl})).unwrap_err().to_string();
assert!(e.contains("is not a circle's or an arc's radius or diameter dimension"), "{e}");
}
/// #4691: a point put on a line's midpoint snap is held there (a MidPoint constraint), and one
/// put on a curve stays on it, as a line's end does: they no longer move freely.
#[test]
+1
View File
@@ -57,6 +57,7 @@ mod tests;
pub mod edit;
pub mod features;
pub mod inspect;
pub mod sketch_constraints;
pub use check::{Contract, Issue, ParamCheck, TypedContract, input_schema_for, output_schema_for, run_checked, run_checked_as};
pub use types::*;
@@ -0,0 +1,49 @@
//! Contracts and result types for the commands in `cmd/sketch_constraints.rs`.
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::types::{SketchRef, present};
/// Switch a circle's or an arc's dimension between its radius and its diameter.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ToggleDiameterParams {
/// The radius or diameter dimension's constraint id.
#[serde(deserialize_with = "dimension_id")]
pub constraint: String,
/// `true` for a diameter, `false` for a radius (default: the other one).
#[serde(default)]
pub diameter: Option<bool>,
/// The sketch (default: the one being edited).
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
#[schemars(with = "SketchRef")]
pub sketch: Option<SketchRef>,
}
/// A constraint id, with the handler's message for anything else.
fn dimension_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
match Value::deserialize(d)? {
Value::String(s) => Ok(s),
_ => Err(serde::de::Error::custom("must be a dimension id")),
}
}
/// What `sketch.toggle_diameter` returns.
#[derive(Debug, Serialize, JsonSchema)]
pub struct ToggleDiameterResult {
/// The dimension's constraint id (unchanged).
pub constraint: String,
/// Whether it now holds the diameter.
pub diameter: bool,
/// The sketch's solve: `{solved, dof}`.
pub sketch: Value,
/// 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 = "sketch_constraints_tests.rs"]
mod tests;
@@ -0,0 +1,48 @@
use serde_json::json;
use super::{ToggleDiameterParams, ToggleDiameterResult};
use crate::Session;
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
#[test]
fn schemas_and_the_key_check_agree() {
assert_keys(input_schema_for::<ToggleDiameterParams>(), &["constraint", "diameter", "sketch"]);
}
#[test]
fn strict_keeps_todays_errors() {
assert_strict_keeps_todays_errors(&[
("sketch.toggle_diameter", json!({"constraint": 5})),
("sketch.toggle_diameter", json!({"constraint": null})),
("sketch.toggle_diameter", json!({"constraint": "c1"})),
("sketch.toggle_diameter", json!({"constraint": "c1", "diameter": true})),
]);
}
#[test]
fn toggle_diameter_reply_matches_its_schema() {
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
let run = |s: &mut Session, id: &str, p: serde_json::Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"));
run(&mut s, "sketch.create", json!({"plane": "XY"}));
let c = run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10}));
let circle = c["curves"][0].as_str().unwrap_or_else(|| panic!("{c}")).to_string();
let d = run(&mut s, "sketch.dimension", json!({"entities": [circle]}));
let g = run(&mut s, "sketch.glyphs", json!({}));
let did = g["glyphs"]
.as_array()
.into_iter()
.flatten()
.find(|x| x["param"] == d["param"])
.and_then(|x| x["id"].as_str())
.unwrap_or_else(|| panic!("{g}"))
.to_string();
let schema = output_schema_for::<ToggleDiameterResult>();
let schema = schema.as_value();
let r = run(&mut s, "sketch.toggle_diameter", json!({"constraint": did}));
assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");
assert_eq!(r["diameter"], false, "{r}");
let r = run(&mut s, "sketch.toggle_diameter", json!({"constraint": did, "unknown": 1}));
assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");
assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{r}");
}
+50 -1
View File
@@ -953,7 +953,7 @@ fn alignment_items(selection: &[Sel]) -> Vec<Item> {
/// Sketch entity items: construction, fix, delete, dimension and the constraints the selection
/// can take.
fn sketch_entity_items(app: &SolveApp) -> Vec<Item> {
use solidcraft_engine::sketch::CurveKind;
use solidcraft_engine::sketch::{ConstraintKind, CurveKind};
let Some(sid) = app.session.active_sketch else { return Vec::new() };
let st = app.session.world_state();
let Some(ss) = st.sketch(sid) else { return Vec::new() };
@@ -1002,6 +1002,16 @@ fn sketch_entity_items(app: &SolveApp) -> Vec<Item> {
if curves.is_empty() && points.is_empty() {
if dims.len() == 1 {
v.push(cmd(app, "sketch.toggle_driven", "Toggle Driven Dimension").with(json!({ "constraint": dims[0] })));
// A circle's or an arc's radius or diameter switches to the other one (#7499).
let round = |c: usize| matches!(ss.sketch.curves.get(c).map(|c| &c.kind), Some(CurveKind::Circle { .. } | CurveKind::Arc { .. }));
if ss
.sketch
.constraints
.iter()
.any(|k| k.id == dims[0] && matches!(k.kind, ConstraintKind::Radius { c, .. } | ConstraintKind::Diameter { c, .. } if round(c)))
{
v.push(cmd(app, "sketch.toggle_diameter", "Toggle Radius / Diameter").with(json!({ "constraint": dims[0] })));
}
}
if app.session.selection.iter().any(|s| matches!(s, Sel::SketchConstraint { .. })) {
v.push(act("ui.delete", "Delete", "delete").key("Del"));
@@ -2291,6 +2301,45 @@ mod tests {
assert!(!items(&h.app, &Target::Viewport).iter().any(|i| i.id == "sketch.toggle_driven"));
}
/// #7499: a selected circle's dimension offers Toggle Radius / Diameter, which switches it
/// both ways; a line's length does not.
#[test]
fn a_circle_dimension_menu_toggles_radius_and_diameter() {
use solidcraft_engine::sketch::ConstraintKind;
let mut h = crate::scenario::Harness::new();
h.app.home.open = false;
h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();
let sid = h.app.session.active_sketch.unwrap();
let c = h.app.run("sketch.circle.center", json!({"center":[0,0],"radius":10})).unwrap()["curves"][0].as_str().unwrap().to_owned();
let l = h.app.run("sketch.line", json!({"points":[[30,0],[50,0]],"connect":false,"infer":false})).unwrap()["curves"][0]
.as_str()
.unwrap()
.to_owned();
let pc = h.app.run("sketch.dimension", json!({"entities":[c]})).unwrap()["param"].as_str().unwrap().to_owned();
let pl = h.app.run("sketch.dimension", json!({"entities":[l],"value":20})).unwrap()["param"].as_str().unwrap().to_owned();
let dim = |h: &crate::scenario::Harness, p: &str| {
h.app.session.world_state().sketch(sid).unwrap().sketch.constraints.iter().find(|c| c.param.as_deref() == Some(p)).unwrap().clone()
};
let did = dim(&h, &pc).id;
h.app.session.selection = vec![Sel::SketchConstraint { id: did.clone() }];
let menu = items(&h.app, &Target::Viewport);
let item = menu.iter().find(|i| i.id == "sketch.toggle_diameter").expect("a circle's dimension must offer Toggle Radius / Diameter");
assert!(item.enabled);
assert_eq!(item.params, Some(json!({"constraint": did})));
run_item(&mut h.app, item, egui::pos2(0.0, 0.0));
assert!(matches!(dim(&h, &pc).kind, ConstraintKind::Radius { .. }), "the diameter is a radius now");
let menu = items(&h.app, &Target::Viewport);
let item = menu.iter().find(|i| i.id == "sketch.toggle_diameter").expect("a radius still offers the toggle");
run_item(&mut h.app, item, egui::pos2(0.0, 0.0));
assert!(matches!(dim(&h, &pc).kind, ConstraintKind::Diameter { .. }), "and a diameter again");
h.app.session.selection = vec![Sel::SketchConstraint { id: dim(&h, &pl).id }];
let menu = items(&h.app, &Target::Viewport);
assert!(menu.iter().any(|i| i.id == "sketch.toggle_driven"));
assert!(!menu.iter().any(|i| i.id == "sketch.toggle_diameter"), "a length is no radius");
}
#[test]
fn units_toolbar_start_offers_choices_and_one_undo_step() {
let mut h = crate::scenario::Harness::new();