Skip to content

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

Respect design units across length fields (#3271) (#3315)

fkirill9d45fa6b34d1
diff --git a/ROADMAP.md b/ROADMAP.md
index 168dca2fd8..15ba808c25 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -206,6 +206,11 @@ completed drawings publish atomically. The browser still exports synchronously.
## Dimensioning and error reporting
+- Operation length fields share design-unit defaults and input evaluation, including secondary
+ distances, thin walls, blend controls, sheet/plastic rules, joints and motion keys. Canvas
+ handles and sketch previews use the same lengths as committed geometry. Existing stored
+ millimetre values retain their size when edited in a design using another unit (#3271).
+
- MCP `execute` accepts `verbose: false`, sharing the compact reply helper used by
`batch`: body changes and created sketch IDs stay, while repeated lists are omitted.
Both tools retain full replies by default.
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 270cc56ba7..4887ac0a02 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -86,7 +86,7 @@ pub fn anchor(app: &SolveApp, d: &Dialog) -> Option<(Vec3, Option<Vec3>)> {
let n = normal?;
let plane = solidcraft_engine::geom::Plane::from_normal(at, n)?;
let from = reference_height(app, d, "From Object", &plane, at).unwrap_or(0.0);
- let offset = if start.trim().is_empty() { 0.0 } else { app.session.doc.eval(start, ValueKind::Length).ok()? };
+ let offset = if start.trim().is_empty() { 0.0 } else { crate::length_input::eval(&app.session.doc, start, ValueKind::Length).ok()? };
(at + n * (from + offset), Some(n))
}
// A hole on a curved face drills against the face's normal where it was picked.
@@ -378,10 +378,8 @@ pub(crate) fn along(proj: &Proj, pos: Pos2, base: Vec3, dir: Vec3) -> Option<f64
Some((b * e - d) / den)
}
-pub(crate) fn format_len(v: f64) -> String {
- let s = format!("{v:.3}");
- let s = s.trim_end_matches('0').trim_end_matches('.');
- format!("{} mm", if s == "-0" { "0" } else { s })
+pub(crate) fn format_len(doc: &solidcraft_engine::doc::Document, v: f64) -> String {
+ crate::length_input::model(doc, v)
}
/// Where a sketch point picked as "<sketch id>:<point id>" (or a bare id of the active sketch) is.
@@ -469,16 +467,16 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj,
}
// Two sides: the second distance gets its own arrow, the other way from the first side.
if let (Kind::Extrude { direction: crate::dialogs::TWO_SIDES | crate::dialogs::TWO_SIDES_REVERSED, distance2, .. }, Some(n)) = (&mut d.kind, dir)
- && let Some(l2) = app.session.doc.eval(distance2, ValueKind::Length).ok().filter(|v| v.is_finite())
+ && let Some(l2) = crate::length_input::eval(&app.session.doc, distance2, ValueKind::Length).ok().filter(|v| v.is_finite())
{
- drag_arrow(ui, painter, proj, base, bs, -(n * sign), l2, true, egui::Id::new("sc_manipulator2"), half_height, distance2);
+ drag_arrow(&app.session.doc, ui, painter, proj, base, bs, -(n * sign), l2, true, egui::Id::new("sc_manipulator2"), half_height, distance2);
}
// A chamfer of two distances: Distance 2 gets its own arrow along the other face.
let faces = chamfer_face_dirs(app, d, base);
if let (Kind::Fillet { distance2, .. }, Some((_, t2))) = (&mut d.kind, faces)
- && let Some(l2) = app.session.doc.eval(distance2, ValueKind::Length).ok().filter(|v| v.is_finite())
+ && let Some(l2) = crate::length_input::eval(&app.session.doc, distance2, ValueKind::Length).ok().filter(|v| v.is_finite())
{
- drag_arrow(ui, painter, proj, base, bs, t2, l2, false, egui::Id::new("sc_manipulator2"), half_height, distance2);
+ drag_arrow(&app.session.doc, ui, painter, proj, base, bs, t2, l2, false, egui::Id::new("sc_manipulator2"), half_height, distance2);
}
// A rectangular pattern's second direction gets its own arrow for Spacing 2 (#2462), as the
// first direction's arrow sets Spacing.
@@ -488,9 +486,9 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj,
_ => None,
};
if let Some(spacing2) = spacing2
- && let Some(l2) = app.session.doc.eval(spacing2, ValueKind::Length).ok().filter(|v| v.is_finite())
+ && let Some(l2) = crate::length_input::eval(&app.session.doc, spacing2, ValueKind::Length).ok().filter(|v| v.is_finite())
{
- drag_arrow(ui, painter, proj, base, bs, n2, l2, false, egui::Id::new("sc_manipulator2"), half_height, spacing2);
+ drag_arrow(&app.session.doc, ui, painter, proj, base, bs, n2, l2, false, egui::Id::new("sc_manipulator2"), half_height, spacing2);
}
}
// An offset plane shows where it will be: at the distance, or through the picked point.
@@ -500,7 +498,7 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj,
_ => None,
});
if let (Kind::OffsetPlane { offset }, Some(n)) = (&d.kind, dir)
- && let Some(off) = through.map(|p| (p - base).dot(n)).or_else(|| app.session.doc.eval(offset, ValueKind::Length).ok())
+ && let Some(off) = through.map(|p| (p - base).dot(n)).or_else(|| crate::length_input::eval(&app.session.doc, offset, ValueKind::Length).ok())
&& let Some(q) = offset_plane_quad(proj, base + n * off, n, half_height * 0.25)
{
painter.extend(projected_polygon(&q, t.construction_plane, Stroke::new(1.2, t.origin_plane_edge)));
@@ -512,14 +510,15 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj,
let cam_right = app.cam.basis().0;
if let (Kind::Extrude { direction: 0 | 1, distance, taper, taper_present, to_offset, .. }, Some(n)) = (&mut d.kind, dir) {
let n = n * sign;
- let span = to_span.map(|span| span.abs() + app.session.doc.eval(to_offset, ValueKind::Length).unwrap_or(0.0)).or(all_span);
- if let Ok(l) = span.map(Ok).unwrap_or_else(|| app.session.doc.eval(distance, ValueKind::Length))
+ let span =
+ to_span.map(|span| span.abs() + crate::length_input::eval(&app.session.doc, to_offset, ValueKind::Length).unwrap_or(0.0)).or(all_span);
+ if let Ok(l) = span.map(Ok).unwrap_or_else(|| crate::length_input::eval(&app.session.doc, distance, ValueKind::Length))
&& l.is_finite()
&& l.abs() > 1e-9
&& let Some(e) = (cam_right - n * cam_right.dot(n)).normalized()
{
let px = 2.0 * half_height / f64::from(proj.rect.height().max(1.0));
- let ang = app.session.doc.eval(taper, ValueKind::Angle).ok().filter(|v| v.is_finite()).unwrap_or(0.0);
+ let ang = crate::length_input::eval(&app.session.doc, taper, ValueKind::Angle).ok().filter(|v| v.is_finite()).unwrap_or(0.0);
let before = taper.clone();
let st = app.session.world_state();
let regions: Vec<&solidcraft_engine::geom::Region2> = d
@@ -541,9 +540,13 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj,
}
}
if let (Kind::Hole { depth, opts, .. }, Some(n)) = (&mut d.kind, dir) {
- let l = if opts.all { 0.0 } else { app.session.doc.eval(depth, ValueKind::Length).ok().filter(|v| v.is_finite()).unwrap_or(0.0) };
+ let l = if opts.all {
+ 0.0
+ } else {
+ crate::length_input::eval(&app.session.doc, depth, ValueKind::Length).ok().filter(|v| v.is_finite()).unwrap_or(0.0)
+ };
let before = depth.clone();
- drag_arrow(ui, painter, proj, base, bs, -n, l, false, egui::Id::new("sc_manipulator_depth"), half_height, depth);
+ drag_arrow(&app.session.doc, ui, painter, proj, base, bs, -n, l, false, egui::Id::new("sc_manipulator_depth"), half_height, depth);
// Dragging the depth turns "through all" into a distance.
if *depth != before {
opts.all = false;
@@ -568,9 +571,20 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj,
&& let Some(l2) = app.session.doc.eval(distance2, ValueKind::Length).ok().filter(|v| v.is_finite())
{
let before = distance2.clone();
- if let Some(ts) =
- drag_arrow(ui, painter, proj, base, bs, -n, l2.abs(), false, egui::Id::new("sc_manipulator_offset2"), half_height, distance2)
- {
+ if let Some(ts) = drag_arrow(
+ &app.session.doc,
+ ui,
+ painter,
+ proj,
+ base,
+ bs,
+ -n,
+ l2.abs(),
+ false,
+ egui::Id::new("sc_manipulator_offset2"),
+ half_height,
+ distance2,
+ ) {
// Its own area and field, so it does not share Distance's focus or text.
value_box_in(
ui,
@@ -585,7 +599,11 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj,
}
let Some((label, kind, value)) = d.primary() else { return };
let len = all_span.or_else(|| {
- if to_span.is_some() && value.trim().is_empty() { Some(0.0) } else { app.session.doc.eval(value, kind).ok().filter(|v| v.is_finite()) }
+ if to_span.is_some() && value.trim().is_empty() {
+ Some(0.0)
+ } else {
+ crate::length_input::eval(&app.session.doc, value, kind).ok().filter(|v| v.is_finite())
+ }
});
let before = value.clone();
let mut box_at = bs + vec2(16.0, -30.0);
@@ -594,15 +612,28 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj,
let baseline = to_span.map(f64::abs).unwrap_or(0.0);
// Through All already supplies a reach per side; dragging switches to an entered distance.
let half = if all_span.is_some() { l } else { l * symmetric_scale };
- let mut shown_value = format_len(half + baseline);
+ let mut shown_value = format_len(&app.session.doc, half + baseline);
let original_shown = shown_value.clone();
let dragged = if to_span.is_some() || symmetric_scale != 1.0 { &mut shown_value } else { &mut *value };
- if let Some(ts) = drag_arrow(ui, painter, proj, base, bs, n, half + baseline, signed, egui::Id::new("sc_manipulator"), half_height, dragged) {
+ if let Some(ts) = drag_arrow(
+ &app.session.doc,
+ ui,
+ painter,
+ proj,
+ base,
+ bs,
+ n,
+ half + baseline,
+ signed,
+ egui::Id::new("sc_manipulator"),
+ half_height,
+ dragged,
+ ) {
if (to_span.is_some() || symmetric_scale != 1.0)
&& shown_value != original_shown
- && let Ok(v) = app.session.doc.eval(&shown_value, ValueKind::Length)
+ && let Ok(v) = crate::length_input::eval(&app.session.doc, &shown_value, ValueKind::Length)
{
- *value = format_len((v - baseline) / symmetric_scale);
+ *value = format_len(&app.session.doc, (v - baseline) / symmetric_scale);
}
if symmetric && let Some(bt) = proj.to_screen(base - n * half) {
arrow(painter, bs, bt, t.manipulator);
@@ -720,6 +751,7 @@ fn to_segment(p: Pos2, a: Pos2, b: Pos2) -> f32 {
/// pointer does. Returns the tip's screen position.
#[allow(clippy::too_many_arguments)]
fn drag_arrow(
+ doc: &solidcraft_engine::doc::Document,
ui: &mut egui::Ui,
painter: &egui::Painter,
proj: &Proj,
@@ -768,7 +800,7 @@ fn drag_arrow(
if !signed {
v = v.max(if free { 1e-3 } else { step });
}
- *value = format_len(v);
+ *value = format_len(doc, v);
ts = tip(v)?;
}
// Paint the value just read from this frame's pointer, including the value box anchor.
@@ -818,7 +850,7 @@ fn radius_spline_handles(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Pain
})
.collect();
let Some(&(_, _, a0, b0)) = edges.first() else { return false };
- let eval = |e: &str| app.session.doc.eval(e, ValueKind::Length).ok().filter(|v| v.is_finite());
+ let eval = |e: &str| crate::length_input::eval(&app.session.doc, e, ValueKind::Length).ok().filter(|v| v.is_finite());
let style = d.extra.get("type").and_then(Value::as_str).unwrap_or("constant").to_string();
// Each edge's spline with the end its positions start from; the spline the handles edit,
// whether it starts at the first edge's far end, and whether it is still the taper's.
@@ -957,12 +989,12 @@ fn radius_spline_handles(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Pain
Some(Edit::Set(k, v)) if !taper => {
if k == 0 {
if let Kind::Fillet { radius, .. } = &mut d.kind {
- *radius = format_len(v);
+ *radius = format_len(&app.session.doc, v);
}
} else if let Some(Value::Array(rs)) = d.extra.get_mut("radii")
&& let Some(slot) = rs.get_mut(k - 1)
{
- *slot = json!(format_len(v));
+ *slot = json!(format_len(&app.session.doc, v));
}
None
}
@@ -982,9 +1014,9 @@ fn radius_spline_handles(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Pain
d.extra.remove("fit");
d.extra.insert("knots".into(), json!(law.knots));
d.extra.insert("swap_ends".into(), json!(swap));
- d.extra.insert("radii".into(), json!(law.radii.iter().skip(1).map(|r| format_len(*r)).collect::<Vec<_>>()));
+ d.extra.insert("radii".into(), json!(law.radii.iter().skip(1).map(|r| format_len(&app.session.doc, *r)).collect::<Vec<_>>()));
if let Kind::Fillet { radius, .. } = &mut d.kind {
- *radius = format_len(law.radii.first().copied().unwrap_or(0.0));
+ *radius = format_len(&app.session.doc, law.radii.first().copied().unwrap_or(0.0));
}
}
true
@@ -1224,7 +1256,7 @@ fn draw_revolve(
.extra
.get("angle2")
.and_then(|value| value.as_str())
- .and_then(|value| app.session.doc.eval(value, ValueKind::Angle).ok())
+ .and_then(|value| crate::length_input::eval(&app.session.doc, value, ValueKind::Angle).ok())
.unwrap_or(0.0);
let range = if extent.sweep < 0.0 { (-std::f64::consts::TAU, 0.0) } else { (0.0, std::f64::consts::TAU) };
if let Kind::Revolve { angle, .. } = &mut d.kind {
@@ -1353,8 +1385,13 @@ fn revolve_display_extent(app: &SolveApp, d: &Dialog, axis: (Vec3, Vec3)) -> Opt
let angles = if to_mode {
(0.0, None)
} else {
- let angle = app.session.doc.eval(angle, ValueKind::Angle).ok()?;
- let other = d.extra.get("angle2").map(|value| app.session.doc.eval(value.as_str().unwrap_or_default(), ValueKind::Angle)).transpose().ok()?;
+ let angle = crate::length_input::eval(&app.session.doc, angle, ValueKind::Angle).ok()?;
+ let other = d
+ .extra
+ .get("angle2")
+ .map(|value| crate::length_input::eval(&app.session.doc, value.as_str().unwrap_or_default(), ValueKind::Angle))
+ .transpose()
+ .ok()?;
(angle, other)
};
solidcraft_engine::doc::revolve_extent_with_convention(
@@ -1519,9 +1556,9 @@ mod tests {
assert_eq!(snap_step(40.0), 1.0);
assert_eq!(snap_step(100.0), 2.0);
assert_eq!(snap_step(4.0), 0.1);
- assert_eq!(format_len(12.0), "12 mm");
- assert_eq!(format_len(-2.5), "-2.5 mm");
- assert_eq!(format_len(-0.0001), "0 mm");
+ assert_eq!(format_len(&solidcraft_engine::doc::Document::default(), 12.0), "12 mm");
+ assert_eq!(format_len(&solidcraft_engine::doc::Document::default(), -2.5), "-2.5 mm");
+ assert_eq!(format_len(&solidcraft_engine::doc::Document::default(), -0.0001), "-0.0001 mm");
}
}
diff --git a/crates/ui-egui/src/configuration_rules_ui.rs b/crates/ui-egui/src/configuration_rules_ui.rs
index 804f322f28..e92316817a 100644
--- a/crates/ui-egui/src/configuration_rules_ui.rs
+++ b/crates/ui-egui/src/configuration_rules_ui.rs
@@ -28,7 +28,7 @@ impl Default for Editor {
enabled: true,
length_unit: None,
condition: RuleCondition::Always,
- effect: RuleEffect::DriveParameter { parameter: String::new(), expression: "10 mm".into() },
+ effect: RuleEffect::DriveParameter { parameter: String::new(), expression: "10".into() },
},
row: String::new(),
preview: None,
@@ -164,9 +164,9 @@ pub(super) fn show(ui: &mut Ui, app: &mut SolveApp, error: &mut Option<String>,
let parameter = parameters.first().cloned().unwrap_or_default();
editor.rule.effect = match effect_kind.as_str() {
"Drive suppression" => RuleEffect::DriveSuppression { feature: suppression_features.first().map(|f| f.0).unwrap_or(0), value: true },
- "Range" => RuleEffect::ParameterRange { parameter, minimum: "0 mm".into(), maximum: "100 mm".into() },
- "Allowed values" => RuleEffect::AllowParameterValues { parameter, expressions: vec!["10 mm".into(), "20 mm".into()] },
- _ => RuleEffect::DriveParameter { parameter, expression: "10 mm".into() },
+ "Range" => RuleEffect::ParameterRange { parameter, minimum: "0".into(), maximum: "100".into() },
+ "Allowed values" => RuleEffect::AllowParameterValues { parameter, expressions: vec!["10".into(), "20".into()] },
+ _ => RuleEffect::DriveParameter { parameter, expression: "10".into() },
};
}
match &mut editor.rule.effect {
@@ -343,7 +343,7 @@ fn condition_editor(ui: &mut Ui, condition: &mut RuleCondition, parameters: &[St
"Parameter" => RuleCondition::Parameter {
parameter: parameters.first().cloned().unwrap_or_default(),
operator: RuleOperator::Ge,
- expression: "10 mm".into(),
+ expression: "10".into(),
},
"Suppression" => RuleCondition::Suppression { feature: features.first().map(|f| f.0).unwrap_or(0), value: true },
"All" => RuleCondition::All { conditions: vec![RuleCondition::Always] },
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 9dd1e11b50..faa4abdcd7 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -676,21 +676,21 @@ impl Dialog {
"sketch.create" => Dialog::new(Kind::Sketch, vec![SelInput::new("Plane", PLANES | PLANAR_FACES, false)]),
"solid.extrude" => Dialog::new(
Kind::Extrude {
- distance: "10 mm".into(),
+ distance: length_default(s, "10"),
direction: 0,
operation: usize::from(has_bodies),
auto_op: true,
smart: crate::smart_extrude::Smart { auto_to_object: app.preferences.extrude_auto_to_object, ..Default::default() },
- distance2: "10 mm".into(),
+ distance2: length_default(s, "10"),
taper: "0 deg".into(),
taper_present: false,
to_offset: String::new(),
start: String::new(),
all: false,
thin: false,
- wall: "2 mm".into(),
+ wall: length_default(s, "2"),
wall_side: 0,
- wall2: "1 mm".into(),
+ wall2: length_default(s, "1"),
},
vec![SelInput::new("Profiles", EXTRUDE_ACCEPT, true)],
),
@@ -698,11 +698,11 @@ impl Dialog {
Kind::Revolve { angle: "360 deg".into(), operation: 0, axis: None },
vec![SelInput::new("Profile", PROFILES | PLANAR_FACES, true), SelInput::new("Axis", AXES, false)],
),
- "solid.fillet" => Dialog::new(fillet_kind("2 mm", false), vec![SelInput::new("Edges", EDGES | FACES, true)]),
- "solid.chamfer" => Dialog::new(fillet_kind("1 mm", true), vec![SelInput::new("Edges", EDGES | FACES, true)]),
+ "solid.fillet" => Dialog::new(fillet_kind(&length_default(s, "2"), false), vec![SelInput::new("Edges", EDGES | FACES, true)]),
+ "solid.chamfer" => Dialog::new(fillet_kind(&length_default(s, "1"), true), vec![SelInput::new("Edges", EDGES | FACES, true)]),
"solid.shell" => {
let (kind, inputs) = Kind::simple_start(id)?;
- let mut d = Dialog::new(kind, inputs);
+ let mut d = Dialog::new(crate::length_input::defaults(&s.doc, kind), inputs);
// Faces joined smoothly to the picked ones too.
d.extra.insert("tangent_chain".into(), json!(true));
d
@@ -711,7 +711,7 @@ impl Dialog {
Dialog::new(Kind::Mirror, vec![SelInput::new("Objects", BODIES, true), SelInput::new("Mirror Plane", PLANES | PLANAR_FACES, false)])
}
"solid.rib" | "solid.web" => Dialog::new(
- Kind::Rib { web: id == "solid.web", thickness: "2 mm".into(), depth: String::new(), flip: false, normal: false },
+ Kind::Rib { web: id == "solid.web", thickness: length_default(s, "2"), depth: String::new(), flip: false, normal: false },
vec![SelInput::new("Curves", CURVES, true)],
),
"solid.replace_face" => Dialog::new(
@@ -732,10 +732,13 @@ impl Dialog {
),
"solid.remove" => Dialog::new(Kind::Remove, vec![SelInput::new("Bodies", BODIES, true)]),
"solid.pattern.path" => Dialog::new(
- Kind::PathPattern { count: "4".into(), spacing: "20 mm".into() },
+ Kind::PathPattern { count: "4".into(), spacing: length_default(s, "20") },
vec![SelInput::new("Objects", BODIES, true), SelInput::new("Path", CURVES, true)],
),
- "mesh.convert" => Dialog::new(Kind::MeshConvert { tolerance: "0.05 mm".into() }, vec![SelInput::new("Mesh body", BODIES, false)]),
+ "mesh.convert" => Dialog::new(
+ Kind::MeshConvert { tolerance: crate::length_input::model(&s.doc, 0.05) },
+ vec![SelInput::new("Mesh body", BODIES, false)],
+ ),
"construct.plane.midplane" => Dialog::new(
Kind::Midplane,
vec![SelInput::new("First plane", PLANES | PLANAR_FACES, false), SelInput::new("Second plane", PLANES | PLANAR_FACES, false)],
@@ -760,7 +763,7 @@ impl Dialog {
),
"material.assign" => Dialog::new(Kind::Material { index: 1, editor: Default::default() }, vec![SelInput::new("Bodies", BODIES, true)]),
"inspect.section" => Dialog::new(
- Kind::Section { offset: "0 mm".into(), flip: false, hatch: true },
+ Kind::Section { offset: length_default(s, "0"), flip: false, hatch: true },
vec![SelInput::new("Plane", PLANES | PLANAR_FACES, false)],
),
"inspect.measure" => Dialog::new(
@@ -779,7 +782,7 @@ impl Dialog {
)],
),
"solid.pattern.rectangular" => Dialog::new(
- Kind::PatternRect { count: "3".into(), spacing: "20 mm".into(), count2: "1".into(), spacing2: "20 mm".into() },
+ Kind::PatternRect { count: "3".into(), spacing: length_default(s, "20"), count2: "1".into(), spacing2: length_default(s, "20") },
vec![
SelInput::new("Objects", BODIES, true),
SelInput::new("Direction", AXES | EDGES, false),
@@ -804,8 +807,8 @@ impl Dialog {
rail2,
]
}),
- "solid.move" => Dialog::new(crate::dialogs_move::kind(0), crate::dialogs_move::inputs(0)),
- "solid.hole" => Dialog::new(hole_defaults(), single_hole_inputs()),
+ "solid.move" => Dialog::new(crate::dialogs_move::kind(0, &s.doc), crate::dialogs_move::inputs(0)),
+ "solid.hole" => Dialog::new(hole_defaults(s), single_hole_inputs()),
"solid.box" => Dialog::new(
Kind::Primitive {
cmd: "solid.box",
@@ -857,6 +860,7 @@ impl Dialog {
),
_ => {
let (kind, inputs) = Kind::simple_start(id)
+ .map(|(kind, inputs)| (crate::length_input::defaults(&s.doc, kind), inputs))
.or_else(|| crate::dialogs_assembly::start(app, id))
.or_else(|| crate::dialogs_sheet::start(app, id))
.or_else(|| crate::dialogs_surface::start(app, id))
@@ -1971,13 +1975,13 @@ fn object_type_row(d: &mut Dialog, ui: &mut egui::Ui) {
/// Rows above the selection inputs: the pattern type and object type, the Hole placement (one
/// face point, or sketch points).
-fn placement_row(d: &mut Dialog, ui: &mut egui::Ui) {
+fn placement_row(d: &mut Dialog, ui: &mut egui::Ui, session: &Session) {
if matches!(d.kind, Kind::Mirror) {
object_type_row(d, ui);
return;
}
if matches!(d.kind, Kind::Move { .. }) {
- crate::dialogs_move::type_row(d, ui);
+ crate::dialogs_move::type_row(d, ui, &session.doc);
return;
}
let current = match d.kind {
@@ -1994,7 +1998,12 @@ fn placement_row(d: &mut Dialog, ui: &mut egui::Ui) {
let objects = d.inputs.first().map(|i| i.items.clone()).unwrap_or_default();
let (kind, mut inputs) = match ty {
0 => (
- Kind::PatternRect { count: "3".into(), spacing: "20 mm".into(), count2: "1".into(), spacing2: "20 mm".into() },
+ Kind::PatternRect {
+ count: "3".into(),
+ spacing: length_default(session, "20"),
+ count2: "1".into(),
+ spacing2: length_default(session, "20"),
+ },
vec![
SelInput::new("Objects", BODIES, true),
SelInput::new("Direction", AXES | EDGES, false),
@@ -2006,7 +2015,7 @@ fn placement_row(d: &mut Dialog, ui: &mut egui::Ui) {
vec![SelInput::new("Objects", BODIES, true), SelInput::new("Axis", AXES, false)],
),
_ => (
- Kind::PathPattern { count: "4".into(), spacing: "20 mm".into() },
+ Kind::PathPattern { count: "4".into(), spacing: length_default(session, "20") },
vec![SelInput::new("Objects", BODIES, true), SelInput::new("Path", CURVES, true)],
),
};
@@ -2418,7 +2427,7 @@ fn auto_operation(app: &SolveApp, d: &mut Dialog) {
}
}
let Kind::Extrude { direction, distance, .. } = &d.kind else { return };
- let Ok(dist) = app.session.doc.eval(distance, solidcraft_engine::doc::expr::Kind::Length) else { return };
+ let Ok(dist) = crate::length_input::eval(&app.session.doc, distance, ValueKind::Length) else { return };
let mut side = crate::smart_extrude::side(dist, *direction);
if !matches!(d.kind, Kind::Extrude { auto_op: true, .. }) {
return;
@@ -3017,11 +3026,7 @@ fn fillet_kind(size: &str, chamfer: bool) -> Kind {
/// field shows it as the other dialogs show theirs ("20 mm", "20 in"). OK makes the size the bare
/// number would.
pub(crate) fn length_default(s: &Session, number: &str) -> String {
- match s.doc.with_design_unit(number, ValueKind::Length) {
- e if e != number => e,
- // A millimetre design (or one whose units are not a length): bare numbers are mm.
- _ => format!("{} mm", number.trim()),
- }
+ crate::length_input::default(&s.doc, number)
}
/// A feature's length as its edit field shows it. A bare number is kept in millimetres: where the
@@ -3044,14 +3049,14 @@ pub(crate) fn shown_expr(e: &str, kind: ValueKind) -> String {
if solidcraft_engine::doc::expr::is_bare_number(e) { format!("{} {unit}", e.trim()) } else { e.to_string() }
}
-fn hole_defaults() -> Kind {
+fn hole_defaults(s: &Session) -> Kind {
Kind::Hole {
- diameter: "5 mm".into(),
- depth: "10 mm".into(),
+ diameter: length_default(s, "5"),
+ depth: length_default(s, "10"),
kind: 0,
- cb_diameter: "9 mm".into(),
- cb_depth: "3 mm".into(),
- cs_diameter: "10 mm".into(),
+ cb_diameter: length_default(s, "9"),
+ cb_depth: length_default(s, "3"),
+ cs_diameter: length_default(s, "10"),
cs_angle: "90 deg".into(),
opts: HoleOpts::default(),
}
@@ -3274,7 +3279,12 @@ pub(crate) fn report_title(d: &Dialog) -> String {
/// The commands OK runs (an edit rebuilds its feature in place); the live preview runs the same.
pub fn apply_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>, String> {
- let cmds = dialog_commands(app, d)?;
+ let mut normalized = d.clone();
+ for value in crate::length_input::fields(&app.session.doc, &mut normalized.kind) {
+ *value = crate::length_input::expression(&app.session.doc, value, ValueKind::Length);
+ }
+ crate::length_input::extra(&mut normalized.extra, |e| crate::length_input::expression(&app.session.doc, e, ValueKind::Length));
+ let cmds = dialog_commands(app, &normalized)?;
if let Some((id, _)) = d.editing {
let (cmd, mut params) = cmds.into_iter().next().ok_or("nothing to apply")?;
if let Some(feature) = app.session.doc.feature(id) {
@@ -4102,7 +4112,8 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>, S
/// on `p` across the face), otherwise centred on `p`. Sizes that are expressions stay
/// expressions, so the box keeps standing on the face when they change.
fn box_corner(s: &Session, fields: &[(&'static str, String)], p: Vec3, normal: Option<Vec3>) -> Value {
- let size = |k: &str| fields.iter().find(|f| f.0 == k).map(|f| s.doc.with_design_unit(&f.1, ValueKind::Length)).unwrap_or_default();
+ let size =
+ |k: &str| fields.iter().find(|f| f.0 == k).map(|f| crate::length_input::expression(&s.doc, &f.1, ValueKind::Length)).unwrap_or_default();
let along = |axis: Vec3| normal.map(|n| n.dot(axis)).filter(|d| d.abs() > 1.0 - 1e-9);
let coord = |c: f64, size: String, axis: Vec3| {
// How much of the size lies behind `p`: none (or all) along the face normal, half across it.
@@ -4581,16 +4592,16 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option<usize>) -> Option<Dia
operation: op_index(operation),
auto_op: false,
smart: crate::smart_extrude::Smart { manual_dir: true, auto_to_object: app.preferences.extrude_auto_to_object, ..Default::default() },
- distance2: extent.distance2.as_deref().map(str::to_string).unwrap_or_else(|| "10 mm".into()),
+ distance2: extent.distance2.as_deref().map(str::to_string).unwrap_or_else(|| length_default(s, "10")),
taper: extent.taper.as_deref().map(str::to_string).unwrap_or_else(|| "0 deg".into()),
taper_present: extent.taper.is_some(),
to_offset: extent.to_offset.as_deref().map(str::to_string).unwrap_or_default(),
start: extent.start_offset.as_deref().map(str::to_string).unwrap_or_default(),
all: extent.through_all,
thin: thin.is_some(),
- wall: thin.as_ref().map_or_else(|| "2 mm".into(), |t| t.thickness.to_string()),
+ wall: thin.as_ref().map_or_else(|| length_default(s, "2"), |t| t.thickness.to_string()),
wall_side: thin.as_ref().map_or(0, |t| WALL_SIDES.iter().position(|w| ThinSide::parse(w) == Some(t.side)).unwrap_or(0)),
- wall2: thin.as_ref().and_then(|t| t.thickness2.as_deref().map(str::to_string)).unwrap_or_else(|| "1 mm".into()),
+ wall2: thin.as_ref().and_then(|t| t.thickness2.as_deref().map(str::to_string)).unwrap_or_else(|| length_default(s, "1")),
};
d.extra.insert("convention".into(), json!(extent.convention));
// Extent references belong to the extrude's authoring frame, including free
@@ -4782,7 +4793,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option<usize>) -> Option<Dia
}
FeatureKind::Hole { position, at, direction, diameter, depth, hole, points, thread, thread_depth, to, references } => {
let mut d = start("solid.hole")?;
- let mut k = hole_defaults();
+ let mut k = hole_defaults(s);
if let Kind::Hole { diameter: dia, depth: dep, kind, cb_diameter, cb_depth, cs_diameter, cs_angle, opts } = &mut k {
*dia = diameter.to_string();
opts.all = depth.is_none();
@@ -5048,7 +5059,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option<usize>) -> Option<Dia
count: count1.to_string(),
spacing: spacing1.to_string(),
count2: count2.as_deref().map(str::to_string).unwrap_or_else(|| "1".into()),
- spacing2: spacing2.as_deref().map(str::to_string).unwrap_or_else(|| "20 mm".into()),
+ spacing2: spacing2.as_deref().map(str::to_string).unwrap_or_else(|| length_default(s, "20")),
};
// Directions along the origin axes show as those axes; others are kept as is.
for (i, (key, dir)) in [("dir1", Some(*dir1)), ("dir2", *dir2)].into_iter().enumerate() {
@@ -5349,6 +5360,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option<usize>) -> Option<Dia
FeatureKind::Move { bodies, translate, rotate_axis, angle, copy } => {
let mut d = start("solid.move")?;
crate::dialogs_move::for_feature(
+ &s.doc,
&mut d,
&solidcraft_engine::doc::plain(bodies),
translate,
@@ -5368,6 +5380,12 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option<usize>) -> Option<Dia
d
}
};
+ if crate::length_input::unit(&s.doc) != "mm" {
+ for value in crate::length_input::fields(&s.doc, &mut d.kind) {
+ *value = crate::length_input::stored(&s.doc, value);
+ }
+ crate::length_input::extra(&mut d.extra, |e| crate::length_input::stored(&s.doc, e));
+ }
d.editing = Some((id, marker));
d.active = 0;
d.error = None;
diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs
index 20678bbada..1f18e6da61 100644
--- a/crates/ui-egui/src/dialogs_assembly.rs
+++ b/crates/ui-egui/src/dialogs_assembly.rs
@@ -139,14 +139,14 @@ pub struct JointForm {
}
impl JointForm {
- fn new(as_built: bool) -> JointForm {
+ fn new(as_built: bool, doc: &solidcraft_engine::doc::Document) -> JointForm {
JointForm {
as_built,
editing: None,
kind: 0,
flip: false,
angle: "0 deg".into(),
- offset: ["0 mm".into(), "0 mm".into(), "0 mm".into()],
+ offset: std::array::from_fn(|_| crate::length_input::default(doc, "0")),
limits: Vec::new(),
animate: false,
phase: 0.0,
@@ -154,17 +154,21 @@ impl JointForm {
}
}
- fn joint_kind(&self) -> JointKind {
+ pub(crate) fn joint_kind(&self) -> JointKind {
TYPES.get(self.kind).and_then(|t| JointKind::parse(t)).unwrap_or(JointKind::Rigid)
}
/// Limits rows sized to the joint's values.
- fn fit_limits(&mut self) {
+ fn fit_limits(&mut self, doc: &solidcraft_engine::doc::Document) {
let k = self.joint_kind();
let n = k.dofs().len();
while self.limits.len() < n {
let i = self.limits.len();
- self.limits.push(if k.is_angle(i) { (false, "-90 deg".into(), "90 deg".into()) } else { (false, "0 mm".into(), "20 mm".into()) });
+ self.limits.push(if k.is_angle(i) {
+ (false, "-90 deg".into(), "90 deg".into())
+ } else {
+ (false, crate::length_input::default(doc, "0"), crate::length_input::default(doc, "20"))
+ });
}
self.limits.truncate(n);
}
@@ -203,12 +207,13 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {
let (asm, inputs) = match id {
"component.create" => (Asm::NewComponent { name: String::new(), activate: true }, vec![SelInput::new("Bodies (optional)", BODIES, true)]),
"joint.create" => (
- Asm::Joint(Box::new(JointForm::new(false))),
+ Asm::Joint(Box::new(JointForm::new(false, &app.session.doc))),
vec![SelInput::new("Component 1", SNAPS, false), SelInput::new("Component 2", SNAPS, false)],
),
- "joint.as_built" => {
- (Asm::Joint(Box::new(JointForm::new(true))), vec![SelInput::new("Components", BODIES, true), SelInput::new("Position", SNAPS, false)])
- }
+ "joint.as_built" => (
+ Asm::Joint(Box::new(JointForm::new(true, &app.session.doc))),
+ vec![SelInput::new("Components", BODIES, true), SelInput::new("Position", SNAPS, false)],
+ ),
"joint.origin" => (Asm::JointOrigin { name: String::new(), hover: None }, vec![SelInput::new("Snap", SNAPS, false)]),
"joint.rigid_group" => (Asm::RigidGroup, vec![SelInput::new("Components", BODIES, true)]),
"joint.drive" => {
@@ -293,7 +298,7 @@ fn current_values(s: &Session, index: usize) -> Vec<String> {
(0..j.kind.dofs().len())
.map(|i| {
let v = j.values.get(i).copied().unwrap_or(0.0);
- if j.kind.is_angle(i) { num(v.to_degrees(), "deg") } else { num(v, "mm") }
+ if j.kind.is_angle(i) { num(v.to_degrees(), "deg") } else { crate::length_input::model(&s.doc, v) }
})
.collect()
}
@@ -306,18 +311,18 @@ pub(crate) fn num(v: f64, unit: &str) -> String {
/// The Edit Joint dialog for a joint (by id).
pub fn edit_joint(app: &SolveApp, id: u64) -> Option<Dialog> {
let j = app.session.doc.assembly.joints.iter().find(|j| j.id == id)?;
- let mut f = JointForm::new(false);
+ let mut f = JointForm::new(false, &app.session.doc);
f.editing = Some(id);
f.kind = TYPES.iter().position(|t| JointKind::parse(t) == Some(j.kind)).unwrap_or(0);
f.flip = j.flip;
// An offset or angle typed as an expression shows (and is sent back) as that expression, so
// the joint keeps following its parameters.
f.angle = j.exprs.angle.clone().unwrap_or_else(|| num(j.angle.to_degrees(), "deg"));
- f.offset[2] = j.exprs.offset.clone().unwrap_or_else(|| num(j.offset, "mm"));
- f.fit_limits();
+ f.offset[2] = j.exprs.offset.clone().unwrap_or_else(|| crate::length_input::model(&app.session.doc, j.offset));
+ f.fit_limits(&app.session.doc);
for (i, l) in f.limits.iter_mut().enumerate() {
if let Some(Some((lo, hi))) = j.limits.get(i) {
- let fmt = |v: f64| if j.kind.is_angle(i) { num(v.to_degrees(), "deg") } else { num(v, "mm") };
+ let fmt = |v: f64| if j.kind.is_angle(i) { num(v.to_degrees(), "deg") } else { crate::length_input::model(&app.session.doc, v) };
*l = (true, fmt(*lo), fmt(*hi));
}
}
@@ -548,7 +553,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se
ui.label("");
});
choice_row(ui, "Type", "jt_type", &mut f.kind, &TYPE_LABELS);
- f.fit_limits();
+ f.fit_limits(&app.session.doc);
if !f.as_built {
enter |= expr_row(ui, "Angle", &mut f.angle);
crate::ui_kit::section(ui, "joint_position", "Position", false, |ui| {
@@ -647,7 +652,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se
None if angle => (-std::f64::consts::PI, std::f64::consts::PI),
None => (-100.0, 100.0),
};
- let cur = s.doc.eval(v, unit_kind).ok().filter(|x| x.is_finite()).unwrap_or(0.0);
+ let cur = crate::length_input::eval(&s.doc, v, unit_kind).ok().filter(|x| x.is_finite()).unwrap_or(0.0);
let (mut shown, scale) = if angle { (cur.to_degrees(), 1f64.to_degrees()) } else { (cur, 1.0) };
ui.vertical(|ui| {
let r = crate::ui_kit::slider(
@@ -658,13 +663,16 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se
);
crate::scenario::publish_handle(&format!("drive_slider:{i}"), r.rect.center());
if r.changed() {
- *v = if angle { format!("{shown:.1} deg") } else { format!("{shown:.2} mm") };
+ *v = if angle { format!("{shown:.1} deg") } else { crate::length_input::model(&s.doc, shown) };
}
});
// The slider's range: the joint's limits, or the default span when it has none.
let limited = j.limits.get(i).copied().flatten().is_some();
let fmt = |x: f64| {
- let (x, unit) = if angle { (x.to_degrees(), "°") } else { (x, " mm") };
+ if !angle {
+ return crate::prefs::show_mm(app, x, 1);
+ }
+ let (x, unit) = (x.to_degrees(), "°");
if x.fract().abs() < 1e-6 { format!("{x:.0}{unit}") } else { format!("{x:.1}{unit}") }
};
ui.vertical(|ui| {
@@ -902,7 +910,7 @@ pub fn commands(app: &SolveApp, k: &Asm, inputs: &[SelInput]) -> Result<Vec<(Str
sel_items(inputs, i).first().and_then(|x| snap_of(s, x)).ok_or_else(|| format!("select {what} first"))
};
let eval = |e: &str, kind: ValueKind| -> Result<f64, String> {
- if e.trim().is_empty() { Ok(0.0) } else { s.doc.eval(e, kind).map_err(|e| e.to_string()) }
+ if e.trim().is_empty() { Ok(0.0) } else { crate::length_input::eval(&s.doc, e, kind).map_err(|e| e.to_string()) }
};
let cmd = |id: &str, p: Value| vec![(id.to_string(), p)];
Ok(match k {
@@ -1011,7 +1019,9 @@ pub fn animate(app: &SolveApp, k: &Asm, cmds: &mut Vec<(String, Value)>) {
let limited = f.limits.get(i).filter(|l| l.0);
let angle = kind.is_angle(i);
let vk = if angle { ValueKind::Angle } else { ValueKind::Length };
- match limited.and_then(|(_, lo, hi)| Some((app.session.doc.eval(lo, vk).ok()?, app.session.doc.eval(hi, vk).ok()?))) {
+ match limited.and_then(|(_, lo, hi)| {
+ Some((crate::length_input::eval(&app.session.doc, lo, vk).ok()?, crate::length_input::eval(&app.session.doc, hi, vk).ok()?))
+ }) {
// Back and forth between the limits.
Some((lo, hi)) => {
let v = lo + (hi - lo) * (0.5 - 0.5 * (f.phase * tau).cos());
diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rs
index 1c2730624f..f8c39683c5 100644
--- a/crates/ui-egui/src/dialogs_assembly_tests.rs
+++ b/crates/ui-egui/src/dialogs_assembly_tests.rs
@@ -31,7 +31,7 @@ fn joint_from_two_snaps() {
d.pick(&app.session, fb);
if let Kind::Assembly(Asm::Joint(f)) = &mut d.kind {
f.kind = 1;
- f.fit_limits();
+ f.fit_limits(&solidcraft_engine::doc::Document::default());
f.limits[0] = (true, "-45 deg".into(), "45 deg".into());
}
let c = apply_commands(&app, &d).unwrap();
@@ -76,7 +76,7 @@ fn revolute_joint_uses_the_picked_straight_edges() {
}
if let Kind::Assembly(Asm::Joint(f)) = &mut d.kind {
f.kind = 1;
- f.fit_limits();
+ f.fit_limits(&app.session.doc);
}
for (id, p) in apply_commands(&app, &d).unwrap() {
app.run(&id, p).unwrap();
@@ -871,3 +871,40 @@ fn motion_trace_keeps_the_picked_point_path() {
let updated = &app.session.doc.sketch(sketch).unwrap().wires[0].fit;
assert!(updated.len() == wire.fit.len() && updated.iter().zip(&wire.fit).all(|(a, b)| (*a - *b - Vec3::new(0.0, 0.0, 2.0)).len() < 1e-6));
}
+
+#[test]
+fn inch_joint_offsets_limits_and_drive_values_keep_their_units() {
+ let mut app = two_boxes();
+ app.run("document.units", json!({"units":"in"})).unwrap();
+ app.start("joint.create");
+ let mut d = app.dialog.clone().unwrap();
+ d.pick(&app.session, face_sel(&app.session, Vec3::new(10.0, 10.0, 10.0)).unwrap());
+ d.pick(&app.session, face_sel(&app.session, Vec3::new(40.0, 10.0, 0.0)).unwrap());
+ let Kind::Assembly(Asm::Joint(f)) = &mut d.kind else { panic!("no joint") };
+ f.kind = TYPES.iter().position(|t| *t == "slider").unwrap();
+ f.fit_limits(&app.session.doc);
+ assert_eq!((f.limits[0].1.as_str(), f.limits[0].2.as_str()), ("0 in", "20 in"));
+ f.offset[0] = "0.25".into();
+ f.offset[2] = "2 mm".into();
+ f.limits[0] = (true, "0".into(), "0.5".into());
+ let (_, p) = apply_commands(&app, &d).unwrap().remove(0);
+ assert_eq!(p["offset"], json!("2 mm"));
+ assert_eq!(p["limits"], json!([["0 in", "0.5 in"]]));
+ let origin = &p["a"]["frame"]["origin"];
+ let at = Vec3::new(origin[0].as_f64().unwrap(), origin[1].as_f64().unwrap(), origin[2].as_f64().unwrap());
+ assert!((at.dist(Vec3::new(10.0, 10.0, 10.0)) - 6.35).abs() < 1e-9);
+ app.run("joint.create", p).unwrap();
+ let joint = app.session.doc.assembly.joints[0].id;
+ app.start("joint.drive");
+ let mut d = app.dialog.clone().unwrap();
+ let Kind::Assembly(Asm::Drive { values, .. }) = &mut d.kind else { panic!("no drive") };
+ values[0] = "0.25".into();
+ let (_, p) = apply_commands(&app, &d).unwrap().remove(0);
+ assert_eq!(p["values"], json!(["0.25 in"]));
+ app.run("joint.drive", p).unwrap();
+ let actual = app.session.doc.assembly.joints.iter().find(|j| j.id == joint).unwrap().values[0];
+ assert!((actual - 6.35).abs() < 1e-9, "{actual}");
+ let edit = edit_joint(&app, joint).unwrap();
+ let Kind::Assembly(Asm::Joint(f)) = edit.kind else { panic!("no edit") };
+ assert_eq!((f.limits[0].1.as_str(), f.limits[0].2.as_str()), ("0 in", "0.5 in"));
+}
diff --git a/crates/ui-egui/src/dialogs_cam.rs b/crates/ui-egui/src/dialogs_cam.rs
index 4f156917d2..a99c18604d 100644
--- a/crates/ui-egui/src/dialogs_cam.rs
+++ b/crates/ui-egui/src/dialogs_cam.rs
@@ -56,7 +56,16 @@ pub fn start(app: &SolveApp) -> (Asm, Vec<SelInput>) {
let a = cams.first().map(|j| j.0).unwrap_or(0);
// A slider first, else another revolute than the cam's.
let b = followers.iter().find(|j| j.0 != a).map(|j| j.0).unwrap_or(0);
- let f = CamForm { a, b, follower: 0, radius: "5 mm".into(), flip: false, picked: None, animate: false, phase: 0.0 };
+ let f = CamForm {
+ a,
+ b,
+ follower: 0,
+ radius: crate::dialogs::length_default(&app.session, "5"),
+ flip: false,
+ picked: None,
+ animate: false,
+ phase: 0.0,
+ };
let inputs = vec![
SelInput::new("Profile", PROFILES | EDGES, true),
SelInput::new("Roller (optional)", ROUND, false),
diff --git a/crates/ui-egui/src/dialogs_coupling.rs b/crates/ui-egui/src/dialogs_coupling.rs
index 90ac4f1a6d..abb8b5324a 100644
--- a/crates/ui-egui/src/dialogs_coupling.rs
+++ b/crates/ui-egui/src/dialogs_coupling.rs
@@ -69,21 +69,21 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Asm, Vec<SelInput>)> {
"joint.gear",
first(&turns),
turns.get(1).map(|j| j.0).unwrap_or(0),
- ["10 mm".to_string(), "20 mm".to_string()],
+ [crate::dialogs::length_default(&app.session, "10"), crate::dialogs::length_default(&app.session, "20")],
vec![SelInput::new("Gear 1 (optional)", ROUND, false), SelInput::new("Gear 2 (optional)", ROUND, false)],
),
"joint.rack_pinion" => (
"joint.rack_pinion",
first(&turns),
first(&b_list),
- ["10 mm".to_string(), String::new()],
+ [crate::dialogs::length_default(&app.session, "10"), String::new()],
vec![SelInput::new("Pinion (optional)", ROUND, false)],
),
"joint.screw" => {
// A joint that turns and slides is a screw on its own.
let both = turns.iter().find(|t| b_list.iter().any(|l| l.0 == t.0)).map(|t| t.0);
let a = both.unwrap_or(first(&turns));
- ("joint.screw", a, both.unwrap_or(first(&b_list)), ["1.5 mm".to_string(), String::new()], vec![])
+ ("joint.screw", a, both.unwrap_or(first(&b_list)), [crate::dialogs::length_default(&app.session, "1.5"), String::new()], vec![])
}
_ => return None,
};
@@ -113,7 +113,9 @@ fn picked_radius(s: &Session, inputs: &[SelInput], i: usize) -> Option<f64> {
/// Size `i` in mm: the picked face's radius, or the typed one.
fn size(s: &Session, f: &CouplingForm, inputs: &[SelInput], i: usize) -> Option<f64> {
- picked_radius(s, inputs, i).or_else(|| s.doc.eval(f.sizes.get(i)?, ValueKind::Length).ok()).filter(|v| v.is_finite() && *v > 0.0)
+ picked_radius(s, inputs, i)
+ .or_else(|| crate::length_input::eval(&s.doc, f.sizes.get(i)?, ValueKind::Length).ok())
+ .filter(|v| v.is_finite() && *v > 0.0)
}
/// A joint row: the joints `list` offers, `sel` the chosen id.
diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs
index 1bef6ee6a3..31e4aae62d 100644
--- a/crates/ui-egui/src/dialogs_dense.rs
+++ b/crates/ui-egui/src/dialogs_dense.rs
@@ -182,7 +182,7 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui:
if let Some(key) = manage_hint {
ui_kit::text(ui, tr(key), ui_kit::Text::Hint("manage"));
}
- placement_row(d, ui);
+ placement_row(d, ui, &app.session);
if matches!(&d.kind, Kind::Hole { opts, .. } if !opts.multiple) {
// Each reference edge with its distance (#37).
enter |= crate::hole_refs::input_rows(d, ui, &app.session);
@@ -318,7 +318,7 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui:
if st != old {
set_object(&mut d.inputs, &mut d.active, FROM_OBJECT, st == 2);
if st == 1 && start.is_empty() {
- *start = "5 mm".into();
+ *start = length_default(&app.session, "5");
}
if st == 0 {
start.clear();
@@ -384,7 +384,7 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui:
}
if rtype == 2 {
form_row(ui, "End Radius", |ui| {
- enter |= extra_field(ui, &mut d.extra, "radius2", "1 mm");
+ enter |= extra_field(ui, &mut d.extra, "radius2", &length_default(&app.session, "1"));
});
// Which end of the first edge takes the start radius.
form_row(ui, "Swap Ends", |ui| {
@@ -764,7 +764,7 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo
d.extra.insert("modeled".into(), json!(modeled));
}
if full != was_full {
- *length = if full { String::new() } else { "10 mm".into() };
+ *length = if full { String::new() } else { length_default(&app.session, "10") };
}
enter |= submitted;
if reset {
diff --git a/crates/ui-egui/src/dialogs_motion.rs b/crates/ui-egui/src/dialogs_motion.rs
index 54ad8ecbf1..db69a2cec3 100644
--- a/crates/ui-egui/src/dialogs_motion.rs
+++ b/crates/ui-egui/src/dialogs_motion.rs
@@ -227,7 +227,10 @@ pub fn study_tracks(s: &Session, key: &str, id_first: bool) -> Result<(u64, Stri
let joint = s.doc.assembly.joints.iter().position(|j| j.id == k.joint)?;
let angle = s.doc.assembly.joints.get(joint)?.kind.is_angle(k.index);
let value = |v: f64| {
- let (x, unit) = if angle { (v.to_degrees(), "deg") } else { (v, "mm") };
+ if !angle {
+ return crate::length_input::model(&s.doc, v);
+ }
+ let (x, unit) = (v.to_degrees(), "deg");
// Short where that keeps the value; else all its digits, so OK keeps the key.
let short = crate::dialogs_assembly::num(x, unit);
let kept = short.split(' ').next().and_then(|n| n.parse::<f64>().ok()).is_some_and(|y| (y - x).abs() <= 1e-9 * x.abs().max(1.0));
@@ -267,7 +270,9 @@ pub fn study_params(s: &Session, name: &str, study: Option<&str>, steps: &str, t
.filter(|t| !t.points.is_empty())
.map(|t| {
let j = s.doc.assembly.joints.get(t.joint).ok_or("no such joint")?;
- Ok(json!({"joint": j.id, "index": t.index, "points": t.points.iter().map(|(st, v)| json!([st, v])).collect::<Vec<_>>()}))
+ let kind = if j.kind.is_angle(t.index) { solidcraft_engine::doc::expr::Kind::Angle } else { solidcraft_engine::doc::expr::Kind::Length };
+ let points: Vec<_> = t.points.iter().map(|(st, v)| json!([st, crate::length_input::expression(&s.doc, v, kind)])).collect();
+ Ok(json!({"joint": j.id, "index": t.index, "points": points}))
})
.collect::<Result<_, &str>>()?;
if keys.is_empty() {
@@ -670,8 +675,14 @@ fn motion_study_rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Mo, inputs:
.clicked()
&& !tr.points.iter().any(|(s, _)| *s == now)
{
- let unit =
- app.session.doc.assembly.joints.get(tr.joint).map(|j| if j.kind.is_angle(tr.index) { "deg" } else { "mm" }).unwrap_or("mm");
+ let unit = app
+ .session
+ .doc
+ .assembly
+ .joints
+ .get(tr.joint)
+ .map(|j| if j.kind.is_angle(tr.index) { "deg" } else { crate::length_input::unit(&app.session.doc) })
+ .unwrap_or(crate::length_input::unit(&app.session.doc));
tr.points.push((now, format!("0 {unit}")));
tr.points.sort_by_key(|p| p.0);
}
@@ -692,7 +703,7 @@ fn motion_study_rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Mo, inputs:
.clicked()
&& let Some((ji, _, kind)) = moving.first()
{
- let unit = if kind.is_angle(0) { "deg" } else { "mm" };
+ let unit = if kind.is_angle(0) { "deg" } else { crate::length_input::unit(&app.session.doc) };
tracks.push(Track { joint: *ji, index: 0, points: vec![(now, format!("0 {unit}"))] });
}
export = crate::ui_kit::button(ui, crate::i18n::tr_label("Export Animation…"), crate::ui_kit::Button::Normal)
@@ -968,7 +979,7 @@ mod tests {
click_config_handle(&mut h, "config:preview_row");
assert_eq!(h.app.session.doc.configs.rules[0].id, "last");
reveal_config_handle(&mut h, "config:preview:param:length");
- assert!(h.widget("length = 10 mm").is_some());
+ assert!(h.widget("length = 10").is_some());
assert_eq!(h.app.session.doc.param("length").unwrap().expr, "40 mm");
}
@@ -1002,7 +1013,8 @@ mod tests {
configuration_steps(&mut h, &json!([{"widget":"Preview Row"}])).unwrap();
assert_eq!(h.app.session.doc, before);
configuration_steps(&mut h, &json!([{"widget":"Apply"}])).unwrap();
- assert_eq!(h.app.session.doc.param("length").unwrap().expr, "10 mm");
+ assert_eq!(h.app.session.doc.param("length").unwrap().expr, "10");
+ assert_eq!(h.app.session.doc.eval("length", solidcraft_engine::doc::expr::Kind::Length).unwrap(), 10.0);
assert!(h.app.session.doc.configuration_matches());
configuration_steps(
&mut h,
diff --git a/crates/ui-egui/src/dialogs_move.rs b/crates/ui-egui/src/dialogs_move.rs
index d5bfde810e..83b718abdc 100644
--- a/crates/ui-egui/src/dialogs_move.rs
+++ b/crates/ui-egui/src/dialogs_move.rs
@@ -23,8 +23,8 @@ pub const POINT_TO_POSITION: usize = 4;
const POINTS: u16 = VERTICES | FACES | EDGES | ORIGIN;
/// A fresh Move dialog of a type (all values zero).
-pub fn kind(mode: usize) -> Kind {
- let z = || "0 mm".to_string();
+pub fn kind(mode: usize, doc: &solidcraft_engine::doc::Document) -> Kind {
+ let z = || crate::length_input::default(doc, "0");
let a = || "0 deg".to_string();
Kind::Move { mode, x: z(), y: z(), z: z(), rx: a(), ry: a(), rz: a(), angle: a() }
}
@@ -46,13 +46,13 @@ pub fn inputs(mode: usize) -> Vec<SelInput> {
}
/// The Move Type row (above the inputs); switching keeps the bodies and resets the values.
-pub fn type_row(d: &mut Dialog, ui: &mut egui::Ui) {
+pub fn type_row(d: &mut Dialog, ui: &mut egui::Ui, doc: &solidcraft_engine::doc::Document) {
let Kind::Move { mode, .. } = d.kind else { return };
let mut m = mode;
choice_row(ui, "Move Type", "move_type", &mut m, &TYPES);
if m != mode {
let bodies = d.inputs.first().map(|i| i.items.clone()).unwrap_or_default();
- d.kind = kind(m);
+ d.kind = kind(m, doc);
d.inputs = inputs(m);
if let Some(i) = d.inputs.first_mut() {
i.items = bodies;
@@ -137,11 +137,15 @@ fn pivot(app: &SolveApp, d: &Dialog) -> Option<Vec3> {
}
fn len(app: &SolveApp, s: &str) -> Result<f64, String> {
- app.session.doc.eval(s, ValueKind::Length).map_err(|e| e.to_string()).and_then(|v| if v.is_finite() { Ok(v) } else { Err("not a number".into()) })
+ crate::length_input::eval(&app.session.doc, s, ValueKind::Length)
+ .map_err(|e| e.to_string())
+ .and_then(|v| if v.is_finite() { Ok(v) } else { Err("not a number".into()) })
}
fn ang(app: &SolveApp, s: &str) -> Result<f64, String> {
- app.session.doc.eval(s, ValueKind::Angle).map_err(|e| e.to_string()).and_then(|v| if v.is_finite() { Ok(v) } else { Err("not a number".into()) })
+ crate::length_input::eval(&app.session.doc, s, ValueKind::Angle)
+ .map_err(|e| e.to_string())
+ .and_then(|v| if v.is_finite() { Ok(v) } else { Err("not a number".into()) })
}
fn mm(v: f64) -> String {
@@ -298,9 +302,9 @@ pub fn drag(app: &SolveApp, d: &mut Dialog, g: Drag) {
let Kind::Move { x, y, z, rx, ry, rz, .. } = &mut d.kind else { return };
match g.change {
Change::Translate(t) => {
- *x = mm(v0[0] + t.x);
- *y = mm(v0[1] + t.y);
- *z = mm(v0[2] + t.z);
+ *x = crate::length_input::model(&app.session.doc, v0[0] + t.x);
+ *y = crate::length_input::model(&app.session.doc, v0[1] + t.y);
+ *z = crate::length_input::model(&app.session.doc, v0[2] + t.z);
}
Change::Rotate { axis, angle } => {
let slot = match axis {
@@ -319,6 +323,7 @@ pub fn drag(app: &SolveApp, d: &mut Dialog, g: Drag) {
/// The dialog for editing a move: Free Move with its translation and, about a world axis
/// through the origin, its angle (another axis is kept as it is).
pub fn for_feature(
+ doc: &solidcraft_engine::doc::Document,
d: &mut Dialog,
bodies: &[String],
translate: &[solidcraft_engine::doc::Expr; 3],
@@ -327,7 +332,7 @@ pub fn for_feature(
copy: bool,
) {
let [x, y, z] = translate.clone().map(String::from);
- let mut k = kind(FREE);
+ let mut k = kind(FREE, doc);
if let Kind::Move { x: kx, y: ky, z: kz, rx, ry, rz, .. } = &mut k {
(*kx, *ky, *kz) = (x, y, z);
if let Some(a) = angle {
diff --git a/crates/ui-egui/src/dialogs_move_tests.rs b/crates/ui-egui/src/dialogs_move_tests.rs
index 8e4461bc4b..ba5895360f 100644
--- a/crates/ui-egui/src/dialogs_move_tests.rs
+++ b/crates/ui-egui/src/dialogs_move_tests.rs
@@ -13,7 +13,7 @@ fn move_dialog(mode: usize) -> Dialog {
let mut app = SolveApp::new(s, Services::default());
app.start("solid.move");
let mut d = app.dialog.clone().unwrap();
- d.kind = kind(mode);
+ d.kind = kind(mode, &app.session.doc);
d.inputs = inputs(mode);
if let Some(inp) = d.inputs.first_mut() {
inp.items = vec![Sel::Body { name: "Body1".into() }];
@@ -84,7 +84,7 @@ fn point_to_point_takes_the_origin_point() {
h.app.start("solid.move");
{
let d = h.app.dialog.as_mut().unwrap();
- d.kind = kind(POINT_TO_POINT);
+ d.kind = kind(POINT_TO_POINT, &h.app.session.doc);
d.inputs = inputs(POINT_TO_POINT);
d.inputs[0].items = vec![Sel::Body { name: "Body1".into() }];
d.active = 1;
@@ -230,7 +230,7 @@ fn move_reference_box_selection_can_still_use_an_inactive_body() {
h.app.start("solid.move");
{
let d = h.app.dialog.as_mut().unwrap();
- d.kind = kind(ROTATE);
+ d.kind = kind(ROTATE, &h.app.session.doc);
d.inputs = inputs(ROTATE);
d.inputs[0].items = vec![Sel::Body { name: "Inside".into() }];
d.active = 1;
@@ -240,3 +240,39 @@ fn move_reference_box_selection_can_still_use_an_inactive_body() {
let axis = &h.app.dialog.as_ref().unwrap().inputs[1].items;
assert!(matches!(axis.as_slice(), [Sel::Edge { body, .. }] if body == "Outside"), "{axis:?}");
}
+
+/// The triad and the command must agree even when Free Move precomputes a pivoted rotation.
+#[test]
+fn inch_move_lengths_agree_in_the_triad_and_every_numeric_move_route() {
+ for mode in [FREE, TRANSLATE, POINT_TO_POSITION] {
+ let mut s = Session::default();
+ s.execute("solid.box", &json!({"length":20,"width":20,"height":20})).unwrap();
+ s.execute("document.units", &json!({"units":"in"})).unwrap();
+ let mut app = SolveApp::new(s, Services::default());
+ let mut d = move_dialog(mode);
+ d.kind = kind(mode, &app.session.doc);
+ if let Kind::Move { x, y, z, rz, .. } = &mut d.kind {
+ *x = "0.25".into();
+ *y = "2 mm".into();
+ *z = "0".into();
+ if mode == FREE {
+ *rz = "90 deg".into();
+ }
+ }
+ if mode == POINT_TO_POSITION {
+ d.inputs[1].items = vec![Sel::Vertex { body: "Body1".into(), point: Vec3::new(10.0, 10.0, 10.0) }];
+ } else {
+ let center = triad(&app, &d).unwrap().center;
+ assert!(center.dist(Vec3::new(16.35, 12.0, 10.0)) < 1e-9, "{center:?}");
+ }
+ for (id, p) in crate::dialogs::apply_commands(&app, &d).unwrap() {
+ app.run(&id, p).unwrap();
+ }
+ let measured = app.session.execute("inspect.measure", &json!({})).unwrap();
+ let center: Vec<f64> = measured["bodies"][0]["center_of_mass"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();
+ let expected = if mode == POINT_TO_POSITION { [6.35, 2.0, 0.0] } else { [16.35, 12.0, 10.0] };
+ for (got, expected) in center.into_iter().zip(expected) {
+ assert!((got - expected).abs() < 1e-6, "mode {mode}: {got}, expected {expected}");
+ }
+ }
+}
diff --git a/crates/ui-egui/src/dialogs_plastic.rs b/crates/ui-egui/src/dialogs_plastic.rs
index 2d98738ac4..e044b5a838 100644
--- a/crates/ui-egui/src/dialogs_plastic.rs
+++ b/crates/ui-egui/src/dialogs_plastic.rs
@@ -95,21 +95,21 @@ impl Pl {
}
}
-fn snap_fit() -> Pl {
+fn snap_fit(app: &SolveApp) -> Pl {
Pl::SnapFit {
hook: 0,
- length: "10 mm".into(),
- thickness: "1.5 mm".into(),
- width: "5 mm".into(),
- catch_depth: "1 mm".into(),
- catch_length: "2 mm".into(),
+ length: crate::dialogs::length_default(&app.session, "10"),
+ thickness: crate::dialogs::length_default(&app.session, "1.5"),
+ width: crate::dialogs::length_default(&app.session, "5"),
+ catch_depth: crate::dialogs::length_default(&app.session, "1"),
+ catch_length: crate::dialogs::length_default(&app.session, "2"),
}
}
/// The dialog for a plastic command.
pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {
let (pl, inputs) = match id {
- "plastic.snap_fit" => (snap_fit(), vec![SelInput::new("Position", PLANAR_FACES, false)]),
+ "plastic.snap_fit" => (snap_fit(app), vec![SelInput::new("Position", PLANAR_FACES, false)]),
"plastic.manage_rules" => {
let rules = app.session.doc.plastic_rules();
let pick = app.session.doc.plastic.active.as_ref().and_then(|a| rules.iter().position(|r| &r.name == a)).unwrap_or(0);
@@ -118,7 +118,7 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {
"plastic.assign_rule" => (Pl::Assign { rule: 1 }, vec![SelInput::new("Bodies", BODIES, true)]),
_ => Pl::simple_start(id)?,
};
- Some((Kind::Plastic(pl), inputs))
+ Some((crate::length_input::defaults(&app.session.doc, Kind::Plastic(pl)), inputs))
}
/// A value row whose empty value means "from the rule" (or another default).
@@ -154,12 +154,12 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Pl, inputs: &[SelInpu
enter |= expr_row(ui, "Diameter", diameter);
enter |= expr_row(ui, "Height", height);
crate::ui_kit::section(ui, "boss_options", "Options", true, |ui| {
- enter |= opt_field(ui, "Hole Diameter", hole_diameter, "mm", "no hole");
- enter |= opt_field(ui, "Hole Depth", hole_depth, "mm", "to the face");
+ enter |= opt_field(ui, "Hole Diameter", hole_diameter, crate::length_input::unit(&app.session.doc), "no hole");
+ enter |= opt_field(ui, "Hole Depth", hole_depth, crate::length_input::unit(&app.session.doc), "to the face");
});
crate::ui_kit::section(ui, "boss_advanced", "Advanced", false, |ui| {
enter |= opt_field(ui, "Draft Angle", draft, "deg", "from the rule");
- enter |= opt_field(ui, "Root Fillet", fillet, "mm", "none");
+ enter |= opt_field(ui, "Root Fillet", fillet, crate::length_input::unit(&app.session.doc), "none");
enter |= expr_row(ui, "Ribs", ribs);
if app.session.doc.eval(ribs, ValueKind::Unitless).is_ok_and(|n| n >= 1.0) {
enter |= expr_row(ui, " Rib Thickness", rib_thickness);
@@ -182,7 +182,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Pl, inputs: &[SelInpu
enter |= expr_row(ui, "Width", width);
enter |= expr_row(ui, "Height", height);
if *groove {
- enter |= opt_field(ui, "Clearance", gap, "mm", "from the rule");
+ enter |= opt_field(ui, "Clearance", gap, crate::length_input::unit(&app.session.doc), "from the rule");
}
}
Pl::SnapFit { hook, length, thickness, width, catch_depth, catch_length } => {
@@ -210,7 +210,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Pl, inputs: &[SelInpu
enter |= expr_row(ui, "Height", height);
crate::ui_kit::section(ui, "rest_advanced", "Advanced", false, |ui| {
enter |= opt_field(ui, "Draft Angle", draft, "deg", "from the rule");
- enter |= opt_field(ui, "Wall Thickness", thickness, "mm", "solid");
+ enter |= opt_field(ui, "Wall Thickness", thickness, crate::length_input::unit(&app.session.doc), "solid");
});
}
Pl::Rules { pick, name, values, active, loaded } => {
@@ -221,7 +221,15 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Pl, inputs: &[SelInpu
load: {
let base = rules.get(*pick).or(rules.first()).cloned();
if let Some(b) = base {
- *values = std::iter::once(b.material.clone()).chain(b.fields().iter().map(|(_, e, _)| (*e).clone())).collect();
+ *values = std::iter::once(b.material.clone())
+ .chain(b.fields().iter().map(|(_, e, kind)| {
+ if *kind == ValueKind::Length {
+ crate::length_input::stored(&app.session.doc, e)
+ } else {
+ crate::dialogs::shown_expr(e, *kind)
+ }
+ }))
+ .collect();
*active = app.session.doc.plastic.active.as_deref() == Some(b.name.as_str()) && *pick < rules.len();
}
},
diff --git a/crates/ui-egui/src/dialogs_plastic_tests.rs b/crates/ui-egui/src/dialogs_plastic_tests.rs
index 5a28428604..5cde4207bf 100644
--- a/crates/ui-egui/src/dialogs_plastic_tests.rs
+++ b/crates/ui-egui/src/dialogs_plastic_tests.rs
@@ -151,3 +151,22 @@ fn shown_expr_adds_units_to_bare_numbers() {
assert_eq!(shown_expr("w * 2", ValueKind::Length), "w * 2");
assert_eq!(shown_expr("", ValueKind::Length), "");
}
+
+#[test]
+fn inch_plastic_rule_edit_preserves_material_angles_and_stored_lengths() {
+ let mut h = crate::scenario::Harness::new();
+ h.app.run("plastic.manage_rules", json!({"name":"Test","thickness":"2","draft":"3","active":true})).unwrap();
+ h.app.run("document.units", json!({"units":"in"})).unwrap();
+ h.app.start("plastic.manage_rules");
+ h.frames(3);
+ let mut d = h.app.dialog.clone().unwrap();
+ let unchanged = apply_commands(&h.app, &d).unwrap().remove(0).1;
+ assert_eq!(unchanged["thickness"], json!("2 mm"));
+ assert_eq!(unchanged["draft"], json!("3 deg"));
+ let Kind::Plastic(Pl::Rules { values, .. }) = &mut d.kind else { panic!("no rules") };
+ values[1] = "0.25".into();
+ let changed = apply_commands(&h.app, &d).unwrap().remove(0).1;
+ assert_eq!(changed["thickness"], json!("0.25 in"));
+ assert_eq!(changed["draft"], unchanged["draft"]);
+ assert_eq!(changed["material"], unchanged["material"]);
+}
diff --git a/crates/ui-egui/src/dialogs_sheet.rs b/crates/ui-egui/src/dialogs_sheet.rs
index dfe47d6cf7..b346ad1a40 100644
--- a/crates/ui-egui/src/dialogs_sheet.rs
+++ b/crates/ui-egui/src/dialogs_sheet.rs
@@ -141,15 +141,15 @@ impl Sm {
}
}
-fn new_flange(ty: usize) -> Sm {
+fn new_flange(app: &SolveApp, ty: usize) -> Sm {
Sm::Flange {
ty,
- height: "10 mm".into(),
+ height: crate::dialogs::length_default(&app.session, "10"),
angle: "90 deg".into(),
radius: String::new(),
position: 0,
flip: false,
- distance: "20 mm".into(),
+ distance: crate::dialogs::length_default(&app.session, "20"),
reverse: false,
rule: 0,
own: Vec::new(),
@@ -161,7 +161,7 @@ fn new_flange(ty: usize) -> Sm {
/// The dialog for a sheet metal command.
pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {
let (sm, inputs) = match id {
- "sheet.flange" => (new_flange(0), vec![SelInput::new("Profile / Edges", PROFILES | EDGES | CURVES, true)]),
+ "sheet.flange" => (new_flange(app, 0), vec![SelInput::new("Profile / Edges", PROFILES | EDGES | CURVES, true)]),
"sheet.unfold" => (Sm::Unfold { refold: false }, vec![SelInput::new("Body (last if none)", BODIES, false)]),
"sheet.refold" => (Sm::Unfold { refold: true }, vec![SelInput::new("Body (last if none)", BODIES, false)]),
"sheet.convert" => {
@@ -176,7 +176,7 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {
"sheet.flat_pattern" => (Sm::FlatPattern { data: None, key: None, status: None }, vec![SelInput::new("Body (last if none)", BODIES, false)]),
_ => Sm::simple_start(id)?,
};
- Some((Kind::Sheet(sm), inputs))
+ Some((crate::length_input::defaults(&app.session.doc, Kind::Sheet(sm)), inputs))
}
/// The design's rules (the default steel rule when it has none).
@@ -301,14 +301,14 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Sm, inputs: &mut [Sel
// A new rule starts from the first rule.
let base = rules.get(*pick).cloned().unwrap_or_else(|| rules.first().cloned().unwrap_or_else(SheetRule::steel));
*values = vec![
- base.thickness.clone(),
+ crate::length_input::stored(&app.session.doc, &base.thickness),
base.k_factor.clone(),
- base.bend_radius.clone(),
- base.relief_width.clone(),
- base.relief_depth.clone(),
- base.corner_relief.clone(),
- base.hem_gap.clone(),
- base.gap.clone(),
+ crate::length_input::stored(&app.session.doc, &base.bend_radius),
+ crate::length_input::stored(&app.session.doc, &base.relief_width),
+ crate::length_input::stored(&app.session.doc, &base.relief_depth),
+ crate::length_input::stored(&app.session.doc, &base.corner_relief),
+ crate::length_input::stored(&app.session.doc, &base.hem_gap),
+ crate::length_input::stored(&app.session.doc, &base.gap),
];
*relief = RELIEF_SHAPES.iter().position(|s| s.eq_ignore_ascii_case(base.corner_relief_shape.trim())).unwrap_or(0);
*angles = ANGLE_DISPLAYS.iter().position(|d| d.eq_ignore_ascii_case(base.angle_display.trim())).unwrap_or(0);
@@ -605,7 +605,7 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec<SelI
let (k, items): (Sm, Vec<Sel>) = match kind {
FeatureKind::SheetBase { sketch, profiles, rule, flip } => {
let ps = st.sketch(sketch.0).map(|ss| profile_indices(ss, profiles)).unwrap_or_default();
- let mut f = new_flange(0);
+ let mut f = new_flange(app, 0);
if let Sm::Flange { flip: fl, rule: r, .. } = &mut f {
*fl = *flip;
*r = rule_index(rule);
@@ -613,7 +613,7 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec<SelI
(f, ps.into_iter().map(|index| Sel::Profile { sketch: sketch.0, index }).collect())
}
FeatureKind::SheetContour { curves, distance, rule, flip, reverse, .. } => {
- let mut f = new_flange(2);
+ let mut f = new_flange(app, 2);
if let Sm::Flange { flip: fl, rule: r, distance: d, reverse: rv, .. } = &mut f {
*fl = *flip;
*r = rule_index(rule);
@@ -647,7 +647,7 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec<SelI
radius: radius.as_deref().map(str::to_string).unwrap_or_default(),
position: POSITIONS.iter().position(|p| p == position).unwrap_or(0),
flip: *flip,
- distance: "20 mm".into(),
+ distance: crate::dialogs::length_default(&app.session, "20"),
reverse: false,
rule: 0,
own,
diff --git a/crates/ui-egui/src/dialogs_sheet_tests.rs b/crates/ui-egui/src/dialogs_sheet_tests.rs
index 3371d278b9..aa6063fb89 100644
--- a/crates/ui-egui/src/dialogs_sheet_tests.rs
+++ b/crates/ui-egui/src/dialogs_sheet_tests.rs
@@ -1002,3 +1002,21 @@ fn hem_handle_runs_along_the_hem_to_its_tip() {
assert!((at.y + 5.0 - tip_y).abs() < 0.05, "flip={flipped}: start plus Length reaches the tip: {at:?} vs y={tip_y}");
}
}
+
+#[test]
+fn inch_sheet_rule_edit_preserves_stored_lengths_and_dimensionless_k_factor() {
+ let mut h = crate::scenario::Harness::new();
+ h.app.run("sheet.manage_rules", json!({"name":"Test","thickness":"1.5","k_factor":"0.4","active":true})).unwrap();
+ h.app.run("document.units", json!({"units":"in"})).unwrap();
+ h.app.start("sheet.manage_rules");
+ h.frames(3);
+ let mut d = h.app.dialog.clone().unwrap();
+ let unchanged = apply_commands(&h.app, &d).unwrap().remove(0).1;
+ assert_eq!(unchanged["thickness"], json!("1.5 mm"));
+ assert_eq!(unchanged["k_factor"], json!("0.4"));
+ let Kind::Sheet(Sm::Rules { values, .. }) = &mut d.kind else { panic!("no rules") };
+ values[0] = "0.125".into();
+ let changed = apply_commands(&h.app, &d).unwrap().remove(0).1;
+ assert_eq!(changed["thickness"], json!("0.125 in"));
+ assert_eq!(changed["k_factor"], unchanged["k_factor"]);
+}
diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs
index 650775a95b..cbe47536d5 100644
--- a/crates/ui-egui/src/dialogs_surface.rs
+++ b/crates/ui-egui/src/dialogs_surface.rs
@@ -195,9 +195,9 @@ fn inputs(k: &Surf) -> Vec<SelInput> {
}
/// The dialog for a surface command.
-pub fn start(_app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {
+pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {
let k = match id {
- "surface.extrude" => Surf::Extrude { distance: "10 mm".into(), direction: 0 },
+ "surface.extrude" => Surf::Extrude { distance: crate::dialogs::length_default(&app.session, "10"), direction: 0 },
"surface.revolve" => Surf::Revolve { angle: "360 deg".into(), symmetric: false, axis: None },
"surface.sweep" => Surf::Sweep(crate::dialogs_sweep::SweepOpts::default()),
"surface.loft" => Surf::Loft { rail_fit: 0 },
@@ -206,14 +206,16 @@ pub fn start(_app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {
"surface.patch" => Surf::Patch { continuity: 0 },
"surface.unstitch" => Surf::Unstitch,
"surface.reverse_normal" => Surf::ReverseNormal,
- "surface.ruled" => Surf::Ruled { distance: "10 mm".into(), mode: 0, angle: "5 deg".into(), flip: false, round: false },
+ "surface.ruled" => {
+ Surf::Ruled { distance: crate::dialogs::length_default(&app.session, "10"), mode: 0, angle: "5 deg".into(), flip: false, round: false }
+ }
"surface.trim" => Surf::Trim { extend: false, stitch: false, direction: None },
"surface.untrim" => Surf::Untrim { holes: 0, outer: false, in_place: false },
"solid.split_face" => Surf::SplitFace,
_ => Surf::simple_start(id)?.0,
};
let i = inputs(&k);
- Some((Kind::Surface(k), i))
+ Some((crate::length_input::defaults(&app.session.doc, Kind::Surface(k)), i))
}
/// The rows after the inputs; true when Enter was pressed in a field.
diff --git a/crates/ui-egui/src/dialogs_trace.rs b/crates/ui-egui/src/dialogs_trace.rs
index f39e845709..c187880705 100644
--- a/crates/ui-egui/src/dialogs_trace.rs
+++ b/crates/ui-egui/src/dialogs_trace.rs
@@ -45,7 +45,11 @@ pub fn form(s: &Session, joint: usize) -> TraceForm {
fn range(s: &Session, joint: usize, index: usize) -> (String, String) {
let Some(j) = s.doc.assembly.joints.get(joint) else { return Default::default() };
let v = j.values.get(index).copied().unwrap_or(0.0);
- if j.kind.is_angle(index) { (num(v.to_degrees(), "deg"), num(v.to_degrees() + 360.0, "deg")) } else { (num(v, "mm"), num(v + 20.0, "mm")) }
+ if j.kind.is_angle(index) {
+ (num(v.to_degrees(), "deg"), num(v.to_degrees() + 360.0, "deg"))
+ } else {
+ (crate::length_input::model(&s.doc, v), crate::length_input::model(&s.doc, v + 20.0))
+ }
}
/// The occurrence path placing the picked body: the instance clicked, also when its component
@@ -95,8 +99,9 @@ pub fn params(s: &Session, f: &TraceForm, inputs: &[SelInput]) -> Result<Value,
let j = s.doc.assembly.joints.get(f.joint).ok_or("no joint that moves yet")?;
p["joint"] = json!(j.id);
p["index"] = json!(f.index);
- p["from"] = json!(f.from.trim());
- p["to"] = json!(f.to.trim());
+ let kind = if j.kind.is_angle(f.index) { solidcraft_engine::doc::expr::Kind::Angle } else { solidcraft_engine::doc::expr::Kind::Length };
+ p["from"] = json!(crate::length_input::expression(&s.doc, &f.from, kind));
+ p["to"] = json!(crate::length_input::expression(&s.doc, &f.to, kind));
}
if !f.samples.trim().is_empty() {
p["samples"] = json!(f.samples.trim().parse::<f64>().map_err(|_| "samples must be a number")?);
diff --git a/crates/ui-egui/src/dialogs_view_dxf.rs b/crates/ui-egui/src/dialogs_view_dxf.rs
index cea79a83ce..d604455bc7 100644
--- a/crates/ui-egui/src/dialogs_view_dxf.rs
+++ b/crates/ui-egui/src/dialogs_view_dxf.rs
@@ -21,7 +21,7 @@ pub fn rows(app: &SolveApp, ui: &mut egui::Ui, dashed: &mut bool, tolerance: &mu
}
}
form_row(ui, "dxf.tolerance", |ui| {
- let r = crate::ui_kit::number_field(ui, tolerance, 0.0001..=1.0, 0.001, " mm");
+ let r = crate::ui_kit::bounded_length_field(ui, tolerance, &app.session.doc.units, 8, 0.0001..=1.0, 0.001);
crate::scenario::publish_handle("dialog:dxf:tolerance", r.rect.center());
});
crate::ui_kit::text(
@@ -116,6 +116,20 @@ mod tests {
assert!(!h.app.preferences.view_dxf_dashed);
}
+ #[test]
+ fn inch_dxf_tolerance_is_edited_in_inches_and_kept_in_millimetres() {
+ let mut h = crate::scenario::Harness::new();
+ h.app.run("document.units", json!({"units":"in"})).unwrap();
+ h.app.start("file.export_view_dxf");
+ h.frames(3);
+ h.step(&json!({"click":{"handle":"dialog:dxf:tolerance"},"double":true})).unwrap();
+ h.step(&json!({"key":"A","cmd":true})).unwrap();
+ h.step(&json!({"text":"0.001"})).unwrap();
+ h.step(&json!({"key":"Tab"})).unwrap();
+ let Some(Kind::ViewDxf { tolerance, .. }) = h.app.dialog.as_ref().map(|d| &d.kind) else { panic!("no DXF dialog") };
+ assert!((*tolerance - 0.0254).abs() < 1e-10, "{tolerance}");
+ }
+
fn wait_for_export(h: &mut crate::scenario::Harness) {
let began = std::time::Instant::now();
loop {
diff --git a/crates/ui-egui/src/dim_view.rs b/crates/ui-egui/src/dim_view.rs
index a8e116614b..f6586b732d 100644
--- a/crates/ui-egui/src/dim_view.rs
+++ b/crates/ui-egui/src/dim_view.rs
@@ -805,7 +805,7 @@ fn edit_box(app: &mut SolveApp, ctx: &egui::Context) {
.and_then(|p| solidcraft_engine::doc::expr::unit_info(&p.unit))
.map(|(k, _)| k)
.unwrap_or(solidcraft_engine::doc::expr::Kind::Unitless);
- let expression = app.session.doc.with_design_unit(&e.expr, kind);
+ let expression = crate::length_input::expression(&app.session.doc, &e.expr, kind);
app.run("parameters.change", json!({"name": e.param, "expression": expression})).map_err(|err| shown_error("parameters.change", &err))
};
match result {
diff --git a/crates/ui-egui/src/drag_extrude.rs b/crates/ui-egui/src/drag_extrude.rs
index 2616665407..7abb1dabcb 100644
--- a/crates/ui-egui/src/drag_extrude.rs
+++ b/crates/ui-egui/src/drag_extrude.rs
@@ -152,7 +152,7 @@ pub fn to(app: &mut SolveApp, proj: &Proj, p: Pos2) {
let Some(Kind::Extrude { distance, direction, .. }) = app.dialog.as_mut().map(|d| &mut d.kind) else { return };
// A reversed extrude measures its distance against the normal.
let sign = if matches!(*direction, 1 | crate::dialogs::TWO_SIDES_REVERSED) { -1.0 } else { 1.0 };
- *distance = crate::canvas::format_len(travelled * sign);
+ *distance = crate::canvas::format_len(&app.session.doc, travelled * sign);
}
/// The button is up: the window stays open for the user to adjust and confirm.
@@ -170,7 +170,7 @@ pub fn tick(app: &mut SolveApp) {
/// The step of the last pull, for the value box next to the distance.
pub fn step_note(app: &SolveApp) -> Option<String> {
let step = app.viewport.drag_extrude.last_step?;
- Some(format!("Step {}", crate::canvas::format_len(step)))
+ Some(format!("Step {}", crate::canvas::format_len(&app.session.doc, step)))
}
/// The ladder of steps beside the pointer while pulling: the one in use between its neighbours.
@@ -182,7 +182,7 @@ pub fn show(app: &SolveApp, painter: &egui::Painter) {
let galley = |i: usize, current: bool| {
let size = if current { t.font_body * 1.25 } else { t.font_body };
let color = if current { t.accent } else { t.text_dim };
- let text = STEPS.get(i).map(|s| crate::canvas::format_len(*s)).unwrap_or_default();
+ let text = STEPS.get(i).map(|s| crate::canvas::format_len(&app.session.doc, *s)).unwrap_or_default();
painter.layout_no_wrap(text, egui::FontId::proportional(size), color)
};
let cells: Vec<_> = (now.saturating_sub(2)..=(now + 2).min(STEPS.len() - 1)).map(|i| (galley(i, i == now), i == now)).collect();
diff --git a/crates/ui-egui/src/hole_refs.rs b/crates/ui-egui/src/hole_refs.rs
index 876a3f419e..e86d37ec7a 100644
--- a/crates/ui-egui/src/hole_refs.rs
+++ b/crates/ui-egui/src/hole_refs.rs
@@ -160,7 +160,7 @@ pub(crate) fn sync(s: &Session, d: &mut Dialog) {
if let Some(slot) = refs.distance.get_mut(*k)
&& (moved || new_edge || slot.trim().is_empty())
{
- *slot = crate::canvas::format_len(v.max(0.0));
+ *slot = crate::canvas::format_len(&s.doc, v.max(0.0));
}
if new_edge && edges.get(*k).is_some_and(Option::is_some) {
refs.focus = Some(*k);
diff --git a/crates/ui-egui/src/length_input.rs b/crates/ui-egui/src/length_input.rs
new file mode 100644
index 0000000000..68f286d8e3
--- /dev/null
+++ b/crates/ui-egui/src/length_input.rs
@@ -0,0 +1,225 @@
+//! Lengths at the UI boundary. Bare values use the current design unit; explicit units and
+//! parameter expressions keep their meaning. The engine and saved geometry remain in mm.
+
+use solidcraft_engine::doc::{
+ Document,
+ expr::{Kind, unit_info},
+};
+
+pub(crate) fn unit(doc: &Document) -> &str {
+ solidcraft_engine::doc::expr::length_unit_or_mm(&doc.units)
+}
+
+/// A new field follows the same numeric-default policy as the primitive and sketch dialogs.
+pub(crate) fn default(doc: &Document, number: &str) -> String {
+ format!("{} {}", number.trim(), unit(doc))
+}
+
+/// Apply the design unit to numeric defaults from declarative dialog descriptors.
+/// Called only for new dialogs; stored expressions keep their original units.
+pub(crate) fn defaults(doc: &Document, mut kind: crate::dialogs::Kind) -> crate::dialogs::Kind {
+ for value in fields(doc, &mut kind) {
+ if let Some(number) = value.strip_suffix(" mm")
+ && solidcraft_engine::doc::expr::is_literal(number)
+ {
+ *value = default(doc, number);
+ }
+ }
+ kind
+}
+
+/// Freeze the unit of UI input before handing it to an API that reads bare lengths in mm.
+/// Keep named and dimensional expressions intact so they remain driving expressions.
+pub(crate) fn expression(doc: &Document, text: &str, kind: Kind) -> String {
+ let text = text.trim();
+ let normalized = doc.with_design_unit(text, kind);
+ if kind == Kind::Length && unit(doc) != "mm" && normalized == text && doc.eval(text, Kind::Unitless).is_ok() {
+ // A decimal comma is numeric only outside parentheses. Preserve function-argument
+ // commas while moving the expression inside the unit multiplication's parentheses.
+ let mut depth = 0usize;
+ let grouped: String = text
+ .chars()
+ .map(|c| match c {
+ '(' => {
+ depth = depth.saturating_add(1);
+ c
+ }
+ ')' => {
+ depth = depth.saturating_sub(1);
+ c
+ }
+ ',' if depth == 0 => '.',
+ _ => c,
+ })
+ .collect();
+ format!("({grouped}) * 1 {}", unit(doc))
+ } else {
+ normalized
+ }
+}
+
+pub(crate) fn eval(doc: &Document, text: &str, kind: Kind) -> solidcraft_engine::doc::Result<f64> {
+ doc.eval(&expression(doc, text, kind), kind)
+}
+
+/// Legacy bare literals are millimetres, including decimal-comma literals. An unchanged
+/// edit must identify that unit before the UI applies its current design-unit default.
+pub(crate) fn stored(doc: &Document, text: &str) -> String {
+ if solidcraft_engine::doc::expr::is_literal(text) && doc.eval(text, Kind::Unitless).is_ok() {
+ format!("{} mm", text.trim())
+ } else {
+ text.to_string()
+ }
+}
+
+/// A computed model-space value written back to an editable field. Use all significant digits:
+/// display precision must never round a value that will be sent back to the model.
+pub(crate) fn model(doc: &Document, mm: f64) -> String {
+ let unit = unit(doc);
+ let scale = unit_info(unit).map(|(_, scale)| scale).unwrap_or(1.0);
+ format!("{} {unit}", mm / scale)
+}
+
+/// The editable length expressions in a dialog. Counts, angles, ratios, selectors and standard
+/// part designations never go through length conversion. Keep this list shared by submission
+/// and feature refill, so a bare stored millimetre cannot become inches just by pressing OK.
+pub(crate) fn fields<'a>(doc: &Document, kind: &'a mut crate::dialogs::Kind) -> Vec<&'a mut String> {
+ use crate::dialogs::Kind as D;
+ use crate::dialogs_assembly::Asm;
+ use crate::dialogs_plastic::Pl;
+ use crate::dialogs_sheet::Sm;
+ use crate::dialogs_surface::Surf;
+ match kind {
+ D::Extrude { distance, distance2, to_offset, start, wall, wall2, .. } => vec![distance, distance2, to_offset, start, wall, wall2],
+ D::Fillet { radius, distance2, .. } => vec![radius, distance2],
+ D::Shell { thickness } => vec![thickness],
+ D::PatternRect { spacing, spacing2, .. } => vec![spacing, spacing2],
+ D::OffsetPlane { offset } | D::Section { offset, .. } => vec![offset],
+ D::OffsetFaces { distance } => vec![distance],
+ D::MeshConvert { tolerance } => vec![tolerance],
+ D::Thread { length, .. } | D::Emboss { depth: length, .. } => vec![length],
+ D::Rib { thickness, depth, .. } => vec![thickness, depth],
+ D::PathPattern { spacing, .. } => vec![spacing],
+ D::Pipe { diameter, wall } => vec![diameter, wall],
+ D::Stock { margin } => vec![margin],
+ D::Move { x, y, z, .. } => vec![x, y, z],
+ D::Hole { diameter, depth, cb_diameter, cb_depth, cs_diameter, .. } => vec![diameter, depth, cb_diameter, cb_depth, cs_diameter],
+ D::Primitive { fields, .. } => fields.iter_mut().filter(|(key, _)| *key != "revolutions").map(|(_, value)| value).collect(),
+ D::Surface(k) => match k {
+ Surf::Extrude { distance, .. } | Surf::Offset { distance, .. } | Surf::Ruled { distance, .. } | Surf::Extend { distance } => {
+ vec![distance]
+ }
+ Surf::Thicken { thickness, .. } => vec![thickness],
+ Surf::Stitch { tolerance } => vec![tolerance],
+ _ => vec![],
+ },
+ D::Sheet(k) => match k {
+ Sm::Flange { height, radius, distance, relief_size, own, .. } => {
+ let mut values = vec![height, radius, distance, relief_size];
+ values.extend(own.iter_mut().map(|(_, _, height)| height));
+ values
+ }
+ Sm::Hem { length, gap, .. } => vec![length, gap],
+ Sm::Fold { radius, .. } => vec![radius],
+ // K factor is the only dimensionless sheet rule value.
+ Sm::Rules { values, .. } => values.iter_mut().enumerate().filter(|(i, _)| *i != 1).map(|(_, value)| value).collect(),
+ _ => vec![],
+ },
+ D::Plastic(k) => match k {
+ Pl::Boss { diameter, height, hole_diameter, hole_depth, fillet, rib_thickness, rib_length, rib_offset, .. } => {
+ vec![diameter, height, hole_diameter, hole_depth, fillet, rib_thickness, rib_length, rib_offset]
+ }
+ Pl::Lip { width, height, gap, .. } => vec![width, height, gap],
+ Pl::SnapFit { length, thickness, width, catch_depth, catch_length, .. } => vec![length, thickness, width, catch_depth, catch_length],
+ Pl::Rest { width, length, height, thickness, .. } => vec![width, length, height, thickness],
+ Pl::Rules { values, .. } => {
+ let kinds = solidcraft_engine::doc::plastic::PlasticRule::library()
+ .first()
+ .map(|rule| rule.fields().iter().map(|(_, _, kind)| *kind).collect::<Vec<_>>())
+ .unwrap_or_default();
+ values.iter_mut().skip(1).zip(kinds).filter_map(|(value, kind)| (kind == Kind::Length).then_some(value)).collect()
+ }
+ _ => vec![],
+ },
+ D::Assembly(k) => match k {
+ Asm::Joint(f) => {
+ let kind = f.joint_kind();
+ let mut values: Vec<_> = f.offset.iter_mut().collect();
+ for (i, (_, lo, hi)) in f.limits.iter_mut().enumerate() {
+ if !kind.is_angle(i) {
+ values.extend([lo, hi]);
+ }
+ }
+ values
+ }
+ Asm::Drive { joint, values, .. } => values
+ .iter_mut()
+ .enumerate()
+ .filter(|(i, _)| doc.assembly.joints.get(*joint).is_some_and(|j| !j.kind.is_angle(*i)))
+ .map(|(_, v)| v)
+ .collect(),
+ Asm::MotionLink { b, ib, offset, .. }
+ if doc
+ .assembly
+ .joints
+ .iter()
+ .filter(|j| j.kind != solidcraft_engine::doc::joints::JointKind::Rigid)
+ .nth(*b)
+ .is_some_and(|j| !j.kind.is_angle(*ib)) =>
+ {
+ vec![offset]
+ }
+ Asm::Coupling(f) => f.sizes.iter_mut().collect(),
+ Asm::Cam(f) => vec![&mut f.radius],
+ Asm::Interference { clearance, .. } => vec![clearance],
+ Asm::Trace(f) if doc.assembly.joints.get(f.joint).is_some_and(|j| !j.kind.is_angle(f.index)) => vec![&mut f.from, &mut f.to],
+ _ => vec![],
+ },
+ D::Motion(crate::dialogs_motion::Mo::MotionStudy { tracks, .. }) => tracks
+ .iter_mut()
+ .filter(|t| doc.assembly.joints.get(t.joint).is_some_and(|j| !j.kind.is_angle(t.index)))
+ .flat_map(|t| t.points.iter_mut().map(|(_, v)| v))
+ .collect(),
+ D::SketchModify(k) => {
+ use crate::sketch_modify_ui::Mod;
+ match k {
+ Mod::Offset { distance, distance2, .. } => vec![distance, distance2],
+ Mod::Move { x, y, .. } => vec![x, y],
+ Mod::PatternRect { spacing, spacing2, .. } => vec![spacing, spacing2],
+ Mod::Corner { size, distance2, .. } => vec![size, distance2],
+ _ => vec![],
+ }
+ }
+ _ => vec![],
+ }
+}
+
+/// Extra length expressions of variable fillets and surface extents. Geometric picks and
+/// direction vectors are already in model coordinates and must not be converted.
+pub(crate) fn extra(extra: &mut serde_json::Map<String, serde_json::Value>, mut convert: impl FnMut(&str) -> String) {
+ use serde_json::{Value, json};
+ for key in ["radius2", "start_offset", "to_offset", "distance2", "thickness", "thickness2"] {
+ if let Some(value) = extra.get_mut(key) {
+ let text = value.as_str().map(str::to_string).or_else(|| value.as_number().map(ToString::to_string));
+ if let Some(text) = text {
+ *value = json!(convert(&text));
+ }
+ }
+ }
+ if let Some(Value::Array(radii)) = extra.get_mut("radii") {
+ for value in radii {
+ if let Some(text) = value.as_str() {
+ *value = json!(convert(text));
+ }
+ }
+ }
+ if let Some(Value::Array(mid)) = extra.get_mut("mid") {
+ for point in mid {
+ if let Some(value) = point.as_array_mut().and_then(|p| p.get_mut(1))
+ && let Some(text) = value.as_str()
+ {
+ *value = json!(convert(text));
+ }
+ }
+ }
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 1d450a834e..042b4b9d74 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -89,6 +89,7 @@ pub mod install;
pub mod issue_report;
pub mod joint_drag;
pub mod keymap;
+mod length_input;
mod linked_source;
#[cfg(test)]
mod loft_rails_dialog_tests;
diff --git a/crates/ui-egui/src/params_dialog.rs b/crates/ui-egui/src/params_dialog.rs
index 73fcbd6b41..62195c5de4 100644
--- a/crates/ui-egui/src/params_dialog.rs
+++ b/crates/ui-egui/src/params_dialog.rs
@@ -152,7 +152,10 @@ fn show_value(r: &Row) -> String {
/// Open the dialog (Change Parameters on the toolbar).
pub fn open(app: &mut SolveApp) {
- app.params = Some(ParamsDialog::new());
+ let mut dialog = ParamsDialog::new();
+ let unit = crate::length_input::unit(&app.session.doc);
+ dialog.new_unit = UNITS.iter().position(|u| *u == unit).unwrap_or(0);
+ app.params = Some(dialog);
}
/// Cancel before drawing the editors: egui has already blurred the focused TextEdit on Esc,
diff --git a/crates/ui-egui/src/pattern_arrow_tests.rs b/crates/ui-egui/src/pattern_arrow_tests.rs
index 135823a0db..26efe08cf8 100644
--- a/crates/ui-egui/src/pattern_arrow_tests.rs
+++ b/crates/ui-egui/src/pattern_arrow_tests.rs
@@ -116,3 +116,32 @@ fn a_pattern_of_features_puts_its_arrow_on_the_patterned_feature() {
assert!(vx * ux + vy * uy > 0.0, "tip {tip:?} base {b:?}");
assert!((vx * uy - vy * ux).abs() / (ux * ux + uy * uy).sqrt() < 3.0, "tip {tip:?} off the X line through {b:?}");
}
+
+#[test]
+fn inch_pattern_arrows_follow_bare_primary_and_secondary_distances() {
+ let mut h = Harness::new();
+ h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap();
+ h.app.run("document.units", json!({"units":"in"})).unwrap();
+ h.run(&json!([
+ {"call":"ui.view","params":{"view":"iso"}},
+ {"start":"solid.pattern.rectangular"},
+ {"click":{"world":[5,5,10]}},
+ {"call":"ui.dialogInput","params":{"index":1}}, {"click":{"axis":"X"}},
+ {"call":"ui.dialogInput","params":{"index":2}}, {"click":{"axis":"Y"}}
+ ]))
+ .unwrap();
+ if let Kind::PatternRect { spacing, spacing2, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
+ *spacing = "0.5".into();
+ *spacing2 = "0.25".into();
+ }
+ h.settle();
+ let bare = (handle_at("arrow").unwrap(), handle_at("arrow2").unwrap());
+ if let Kind::PatternRect { spacing, spacing2, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
+ *spacing = "12.7 mm".into();
+ *spacing2 = "6.35 mm".into();
+ }
+ h.settle();
+ let explicit = (handle_at("arrow").unwrap(), handle_at("arrow2").unwrap());
+ assert!(bare.0.distance(explicit.0) < 0.01, "primary: {bare:?} vs {explicit:?}");
+ assert!(bare.1.distance(explicit.1) < 0.01, "secondary: {bare:?} vs {explicit:?}");
+}
diff --git a/crates/ui-egui/src/primitive_units_tests.rs b/crates/ui-egui/src/primitive_units_tests.rs
index 02fcbaf150..692c2bde9c 100644
--- a/crates/ui-egui/src/primitive_units_tests.rs
+++ b/crates/ui-egui/src/primitive_units_tests.rs
@@ -141,7 +141,7 @@ fn in_an_inch_design_primitive_dialogs_show_inches_and_read_bare_numbers_as_inch
type_into(&mut h, "height", "10 mm");
h.frames(2);
let (_, params) = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap().remove(0);
- assert_eq!((&params["length"], &params["width"], &params["height"]), (&json!("20 in"), &json!("2"), &json!("10 mm")));
+ assert_eq!((&params["length"], &params["width"], &params["height"]), (&json!("20 in"), &json!("2 in"), &json!("10 mm")));
ok(&mut h);
assert_size(&mut h.app.session, [508.0, 50.8, 10.0]);
}
@@ -272,3 +272,124 @@ fn editing_a_coil_reopens_its_dialog_filled_in_and_ok_redefines_it() {
other => panic!("not a coil: {other:?}"),
}
}
+
+/// #3271: cover secondary and optional lengths as well as each tool's primary canvas value.
+#[test]
+fn operation_length_defaults_follow_every_design_unit() {
+ const CASES: &[(&str, &[&str])] = &[
+ ("solid.extrude", &["10", "10", "", "", "2", "1"]),
+ ("solid.fillet", &["2", "2"]),
+ ("solid.chamfer", &["1", "1"]),
+ ("solid.shell", &["2"]),
+ ("solid.hole", &["5", "10", "9", "3", "10"]),
+ ("solid.rib", &["2", ""]),
+ ("solid.web", &["2", ""]),
+ ("solid.emboss", &["1"]),
+ ("solid.offset_face", &["2"]),
+ ("solid.pattern.rectangular", &["20", "20"]),
+ ("solid.pattern.path", &["20"]),
+ ("solid.pipe", &["5", ""]),
+ ("solid.bounding_solid", &["2"]),
+ ("solid.move", &["0", "0", "0"]),
+ ("construct.plane.offset", &["0"]),
+ ("inspect.section", &["0"]),
+ ("surface.extrude", &["10"]),
+ ("surface.offset", &["2"]),
+ ("surface.ruled", &["10"]),
+ ("surface.thicken", &["2"]),
+ ("surface.extend", &["10"]),
+ ("surface.stitch", &[""]),
+ ("sheet.flange", &["10", "", "20", ""]),
+ ("sheet.hem", &["5", ""]),
+ ("sheet.fold", &[""]),
+ ("plastic.boss", &["6", "10", "3", "", "", "1", "3", "1"]),
+ ("plastic.lip", &["1.5", "2", ""]),
+ ("plastic.snap_fit", &["10", "1.5", "5", "1", "2"]),
+ ("plastic.rest", &["10", "15", "2", ""]),
+ ("joint.create", &["0", "0", "0"]),
+ ("joint.gear", &["10", "20"]),
+ ("joint.rack_pinion", &["10", ""]),
+ ("joint.screw", &["1.5", ""]),
+ ("joint.cam", &["5"]),
+ ("sketch.offset", &["2", "2"]),
+ ("sketch.move", &["0", "0"]),
+ ("sketch.pattern.rectangular", &["20", "20"]),
+ ("sketch.fillet", &["2", "2"]),
+ ("sketch.chamfer.two_distance", &["2", "2"]),
+ ];
+ for units in ["mm", "cm", "m", "in", "ft"] {
+ let h = design(units);
+ for &(command, numbers) in CASES {
+ let mut d = crate::dialogs::Dialog::for_command(&h.app, command).unwrap_or_else(|| panic!("no dialog for {command}"));
+ let values: Vec<_> = crate::length_input::fields(&h.app.session.doc, &mut d.kind).into_iter().map(|v| v.clone()).collect();
+ let expected: Vec<_> = numbers.iter().map(|n| if n.is_empty() { String::new() } else { format!("{n} {units}") }).collect();
+ assert_eq!(values, expected, "{command} in {units}");
+ }
+ }
+}
+
+#[test]
+fn length_input_expressions_and_computed_values_round_trip_without_display_rounding() {
+ use solidcraft_engine::doc::expr::Kind as K;
+ for (units, scale) in [("mm", 1.0), ("cm", 10.0), ("m", 1000.0), ("in", 25.4), ("ft", 304.8)] {
+ let mut h = design(units);
+ h.app.run("parameters.add", json!({"name":"span","expression":"12 mm"})).unwrap();
+ for (text, expected) in [
+ ("0.25", 0.25 * scale),
+ ("1 / 4", 0.25 * scale),
+ ("0,25", 0.25 * scale),
+ ("0,25 + max(1,2)", 2.25 * scale),
+ ("2 mm", 2.0),
+ ("span / 2", 6.0),
+ ("span + 2 mm", 14.0),
+ ] {
+ let value = crate::length_input::eval(&h.app.session.doc, text, K::Length).unwrap();
+ assert!((value - expected).abs() < 1e-9, "{units}: {text} -> {value}");
+ }
+ for mm in [0.0, -12.3456789123, 0.0000123456789, 25.4, 123456.789123] {
+ let text = crate::length_input::model(&h.app.session.doc, mm);
+ assert!(text.ends_with(units), "{text}");
+ let value = crate::length_input::eval(&h.app.session.doc, &text, K::Length).unwrap();
+ assert!((value - mm).abs() < 1e-10 * mm.abs().max(1.0), "{text} -> {value}, wanted {mm}");
+ }
+ for text in ["", "NaN", "1e400", "2 deg", "missing_parameter"] {
+ assert!(crate::length_input::eval(&h.app.session.doc, text, K::Length).is_err(), "{text}");
+ }
+ assert_eq!(crate::length_input::expression(&h.app.session.doc, "45", K::Angle), "45");
+ assert_eq!(crate::length_input::expression(&h.app.session.doc, "3", K::Unitless), "3");
+ assert_eq!(crate::length_input::expression(&h.app.session.doc, "span / 2", K::Length), "span / 2");
+ }
+}
+
+#[test]
+fn inch_extrude_secondary_lengths_and_unchanged_edit_keep_their_physical_sizes() {
+ let mut h = design("mm");
+ h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();
+ h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[40,30]})).unwrap();
+ h.app.run("solid.extrude", json!({"distance":10,"distance2":5})).unwrap();
+ let feature = h.app.session.doc.features.last().unwrap().id;
+ let before = volume(&mut h.app.session);
+ h.app.run("document.units", json!({"units":"in"})).unwrap();
+ h.app.edit_feature(feature);
+ h.frames(3);
+ let Kind::Extrude { distance, distance2, .. } = &h.app.dialog.as_ref().unwrap().kind else { panic!("no extrude") };
+ assert_eq!((distance.as_str(), distance2.as_str()), ("10 mm", "5 mm"));
+ ok(&mut h);
+ assert!((volume(&mut h.app.session) - before).abs() < 1e-6);
+ h.app.edit_feature(feature);
+ if let Kind::Extrude { distance, distance2, start, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
+ *distance = "0.25".into();
+ *distance2 = "2 mm".into();
+ *start = "0.125".into();
+ }
+ let commands = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap();
+ let p = &commands[0].1["params"];
+ assert_eq!((&p["distance"], &p["distance2"], &p["start_offset"]), (&json!("0.25 in"), &json!("2 mm"), &json!("0.125 in")));
+ h.frames(3);
+ ok(&mut h);
+ let measurements = h.app.session.execute("inspect.measure", &json!({})).unwrap();
+ let bbox = &measurements["bodies"][0]["bbox"];
+ assert!((bbox["max"][2].as_f64().unwrap() - 9.525).abs() < 1e-6);
+ let reopened = Session::new(solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap());
+ assert_eq!(reopened.doc.length_inputs(), h.app.session.doc.length_inputs());
+}
diff --git a/crates/ui-egui/src/sketch_dims.rs b/crates/ui-egui/src/sketch_dims.rs
index 571d7a0b3c..0da74f2eb4 100644
--- a/crates/ui-egui/src/sketch_dims.rs
+++ b/crates/ui-egui/src/sketch_dims.rs
@@ -57,7 +57,7 @@ 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)?;
- app.session.doc.eval(&b.value, b.kind).ok().filter(|v| v.is_finite())
+ crate::length_input::eval(&app.session.doc, &b.value, b.kind).ok().filter(|v| v.is_finite())
}
fn dir_or_x(v: Vec2) -> Vec2 {
@@ -346,7 +346,8 @@ 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 = app.session.doc.eval(&dimension.value, dimension.kind).map_err(|error| format!("{}: {error}", dimension.label))?;
+ let value =
+ crate::length_input::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));
}
diff --git a/crates/ui-egui/src/sketch_dims_tests.rs b/crates/ui-egui/src/sketch_dims_tests.rs
index 3c075a00a9..ec1068b860 100644
--- a/crates/ui-egui/src/sketch_dims_tests.rs
+++ b/crates/ui-egui/src/sketch_dims_tests.rs
@@ -187,6 +187,9 @@ fn inch_live_lengths_use_design_units_and_typed_four_digits_commit_in_inches() {
type_value(&mut h, "1.2345");
tab(&mut h, false);
type_value(&mut h, "0.500");
+ let tool = h.app.tool.as_ref().unwrap();
+ assert!((crate::sketch_dims::locked_value(&h.app, tool, "Width").unwrap() - 31.3563).abs() < 1e-6);
+ assert!((crate::sketch_dims::locked_value(&h.app, tool, "Height").unwrap() - 12.7).abs() < 1e-6);
h.step(&json!({"key":"Enter"})).unwrap();
let st = h.app.session.world_state();
let sk = &st.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch;
diff --git a/crates/ui-egui/src/sketch_modify_ui.rs b/crates/ui-egui/src/sketch_modify_ui.rs
index afb3950673..6de62dff7a 100644
--- a/crates/ui-egui/src/sketch_modify_ui.rs
+++ b/crates/ui-egui/src/sketch_modify_ui.rs
@@ -196,14 +196,25 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {
};
let k = match id {
"sketch.scale" => Mod::Scale { factor: "2".into() },
- "sketch.offset" => Mod::Offset { distance: "2 mm".into(), distance2: "2 mm".into(), mode: 0, chain: true, flip: false },
+ "sketch.offset" => Mod::Offset {
+ distance: crate::dialogs::length_default(&app.session, "2"),
+ distance2: crate::dialogs::length_default(&app.session, "2"),
+ mode: 0,
+ chain: true,
+ flip: false,
+ },
"sketch.mirror" => Mod::Mirror,
- "sketch.move" => Mod::Move { x: "0 mm".into(), y: "0 mm".into(), angle: "0 deg".into(), copy: false },
+ "sketch.move" => Mod::Move {
+ x: crate::dialogs::length_default(&app.session, "0"),
+ y: crate::dialogs::length_default(&app.session, "0"),
+ angle: "0 deg".into(),
+ copy: false,
+ },
"sketch.pattern.rectangular" => Mod::PatternRect {
count: "3".into(),
- spacing: "20 mm".into(),
+ spacing: crate::dialogs::length_default(&app.session, "20"),
count2: "1".into(),
- spacing2: "20 mm".into(),
+ spacing2: crate::dialogs::length_default(&app.session, "20"),
alignment: PatternAlignment::Right,
alignment2: PatternAlignment::Right,
reversed: false,
@@ -576,7 +587,7 @@ fn value(app: &SolveApp, text: &str, kind: ValueKind, label: &str) -> Result<f64
return Ok(0.0);
}
let doc = &app.session.doc;
- let v = doc.eval(&doc.with_design_unit(text, kind), kind).map_err(|e| format!("{label}: {e}"))?;
+ let v = crate::length_input::eval(doc, text, kind).map_err(|e| format!("{label}: {e}"))?;
if !v.is_finite() {
return Err(format!("{label} must be a number"));
}
@@ -588,7 +599,7 @@ fn value(app: &SolveApp, text: &str, kind: ValueKind, label: &str) -> Result<f64
/// as a typed sketch value does everywhere else.
fn signed_length(app: &SolveApp, label: &str, text: &str, flip: bool) -> Result<f64, String> {
let doc = &app.session.doc;
- let v = doc.eval(&doc.with_design_unit(text.trim(), ValueKind::Length), ValueKind::Length).map_err(|e| format!("{label}: {e}"))?;
+ let v = crate::length_input::eval(doc, text.trim(), ValueKind::Length).map_err(|e| format!("{label}: {e}"))?;
if !v.is_finite() || v.abs() <= 1e-9 {
return Err(format!("{label} must be a non-zero number"));
}
@@ -616,7 +627,7 @@ fn whole(app: &SolveApp, label: &str, text: &str) -> Result<u64, String> {
/// zero, which a Move window wants and a pattern spacing does not.
fn length(app: &SolveApp, label: &str, text: &str) -> Result<f64, String> {
let doc = &app.session.doc;
- let v = doc.eval(&doc.with_design_unit(text.trim(), ValueKind::Length), ValueKind::Length).map_err(|e| format!("{label}: {e}"))?;
+ let v = crate::length_input::eval(doc, text.trim(), ValueKind::Length).map_err(|e| format!("{label}: {e}"))?;
if !v.is_finite() {
return Err(format!("{label} must be a number"));
}
@@ -645,7 +656,7 @@ fn corner_ids(app: &SolveApp, inputs: &[SelInput], i: usize) -> Vec<String> {
/// a radius or a chamfer leg, so this one is its own.
fn corner_size(app: &SolveApp, label: &str, text: &str, kind: ValueKind) -> Result<f64, String> {
let doc = &app.session.doc;
- let v = doc.eval(&doc.with_design_unit(text.trim(), kind), kind).map_err(|e| format!("{label}: {e}"))?;
+ let v = crate::length_input::eval(doc, text.trim(), kind).map_err(|e| format!("{label}: {e}"))?;
if !v.is_finite() || v <= 1e-9 {
return Err(format!("{label} must be a positive number"));
}
@@ -823,7 +834,7 @@ pub fn commands(app: &SolveApp, k: &Mod, inputs: &[SelInput], extra: &Map<String
let lines = line_ids(inputs, 0);
// The engine keeps its millimetre API; bare UI values use the design unit.
// Keep expressions intact so the radius remains a driving dimension.
- let radius = app.session.doc.with_design_unit(size.trim(), ValueKind::Length);
+ let radius = crate::length_input::expression(&app.session.doc, size, ValueKind::Length);
match (corners.is_empty(), lines.as_slice()) {
(true, []) => return Err("select the corners to round first".into()),
(false, []) => ("sketch.fillet", json!({"points": corners, "radius": radius})),
diff --git a/crates/ui-egui/src/sketch_text.rs b/crates/ui-egui/src/sketch_text.rs
index 205f067f3d..4e9e0fa09a 100644
--- a/crates/ui-egui/src/sketch_text.rs
+++ b/crates/ui-egui/src/sketch_text.rs
@@ -632,7 +632,7 @@ fn edit_params(app: &SolveApp, k: &Tx) -> Result<Value, String> {
*slot = if value == initial {
*original
} else {
- let typed = doc.with_design_unit(value.trim(), *kind);
+ let typed = crate::length_input::expression(doc, value, *kind);
let v = doc.eval(&typed, *kind).map_err(|e| format!("{label}: {e}"))?;
if !v.is_finite() {
return Err(format!("{label}: not a finite number"));
diff --git a/crates/ui-egui/src/sketch_text_move.rs b/crates/ui-egui/src/sketch_text_move.rs
index c034e0c1b7..4301d6cfed 100644
--- a/crates/ui-egui/src/sketch_text_move.rs
+++ b/crates/ui-egui/src/sketch_text_move.rs
@@ -44,7 +44,7 @@ pub(crate) fn commands(app: &SolveApp, k: &TextMove) -> Result<Vec<(String, Valu
let mut values = [0.0; 3];
for (i, (input, value)) in k.values.iter().zip(&mut values).enumerate() {
let kind = if i == 2 { ValueKind::Angle } else { ValueKind::Length };
- *value = doc.eval(&doc.with_design_unit(input.trim(), kind), kind).map_err(|e| e.to_string())?;
+ *value = crate::length_input::eval(doc, input.trim(), kind).map_err(|e| e.to_string())?;
if !value.is_finite() {
return Err("Move values must be finite".into());
}
diff --git a/crates/ui-egui/src/ui_kit/fields.rs b/crates/ui-egui/src/ui_kit/fields.rs
index 701febc612..3b660a8fa6 100644
--- a/crates/ui-egui/src/ui_kit/fields.rs
+++ b/crates/ui-egui/src/ui_kit/fields.rs
@@ -514,6 +514,20 @@ pub(crate) fn length_field(ui: &mut Ui, value: &mut f64, units: &str, decimals:
response
}
+/// A model-space length with tool-specific bounds and drag step, shown in design units.
+pub(crate) fn bounded_length_field(
+ ui: &mut Ui,
+ value: &mut f64,
+ units: &str,
+ decimals: u8,
+ range: std::ops::RangeInclusive<f64>,
+ speed: f64,
+) -> Response {
+ let response = ui.add(length_drag(value, units, decimals).range(range).speed(speed));
+ scenario::publish_target(&format!("dialog:length:{}", label(ui)), response.rect);
+ response
+}
+
/// Angle in degrees, dragged or typed. Tokens: control_height, scope control/font tokens.
pub(crate) fn angle_field(ui: &mut Ui, value: &mut f64) -> Response {
let response = ui.add(egui::DragValue::new(value).speed(1.0).suffix(" deg").custom_parser(crate::prefs::parse_number));
diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rs
index b5adbecd44..d86a660f12 100644
--- a/crates/ui-egui/src/ui_kit/gallery.rs
+++ b/crates/ui-egui/src/ui_kit/gallery.rs
@@ -706,6 +706,9 @@ const ELEMENTS: &[Element] = &[
element!("length_field", |ui, _| {
length_field(ui, &mut 12.7, "in", 2);
}),
+ element!("bounded_length_field", |ui, _| {
+ bounded_length_field(ui, &mut 12.7, "in", 2, 0.0..=25.4, 0.254);
+ }),
element!("angle_field", |ui, _| {
angle_field(ui, &mut 45.0);
}),
diff --git a/crates/ui-egui/tests/parameter_enter.rs b/crates/ui-egui/tests/parameter_enter.rs
index a04985b17c..c842d3e9ff 100644
--- a/crates/ui-egui/tests/parameter_enter.rs
+++ b/crates/ui-egui/tests/parameter_enter.rs
@@ -4,7 +4,11 @@ use serde_json::json;
use solidcraft_ui_egui::scenario::Harness;
fn open() -> Harness {
+ open_in_units("mm")
+}
+fn open_in_units(units: &str) -> Harness {
let mut h = Harness::new();
+ h.app.run("document.units", json!({"units": units})).unwrap();
// The Browser's Parameters row starts this command; the ribbon shows only the active tab, so no
// Parameters button is on screen to click.
h.call("ui.start", json!({"command":"parameters.change"}));
@@ -144,14 +148,19 @@ fn parameter_rename_arrow_keys_move_cursor_and_keep_editing() {
}
#[test]
fn parameter_add_resets_expression_for_next_row() {
- let mut h = open();
- let initial = h.app.params.as_ref().unwrap().new_expr.clone();
- fill(&mut h, "expression", "25 mm");
- fill(&mut h, "name", "width");
- enter(&mut h, false);
- let result = h.app.session.execute("parameters.list", &json!({})).unwrap();
- assert!(result["parameters"].as_array().unwrap().iter().any(|p| p["name"] == "width" && p["expression"] == "25 mm"));
- let d = h.app.params.as_ref().unwrap();
- assert!(d.new_name.is_empty());
- assert_eq!(d.new_expr, initial);
+ for (units, selected) in [("mm", 0), ("cm", 1), ("m", 2), ("in", 3), ("ft", 4)] {
+ let mut h = open_in_units(units);
+ let d = h.app.params.as_ref().unwrap();
+ assert!(d.new_expr.is_empty(), "{units}: the initial draft is blank");
+ assert_eq!(d.new_unit, selected, "{units}: the document unit is selected");
+ fill(&mut h, "expression", "25 mm");
+ fill(&mut h, "name", "width");
+ enter(&mut h, false);
+ let result = h.app.session.execute("parameters.list", &json!({})).unwrap();
+ assert!(result["parameters"].as_array().unwrap().iter().any(|p| p["name"] == "width" && p["expression"] == "25 mm"));
+ let d = h.app.params.as_ref().unwrap();
+ assert!(d.new_name.is_empty());
+ assert!(d.new_expr.is_empty(), "{units}: adding a parameter clears the next draft");
+ assert_eq!(d.new_unit, selected, "{units}: adding preserves the selected unit");
+ }
}
diff --git a/docs/book/src/guide/parameters.md b/docs/book/src/guide/parameters.md
index 54a821d8ac..aed8aa12fe 100644
--- a/docs/book/src/guide/parameters.md
+++ b/docs/book/src/guide/parameters.md
@@ -50,13 +50,18 @@ parameter updates every expression, dimension and feature input that uses it, an
in use can't be deleted (the error lists its users).
The design's units (Document Settings in the browser: mm, cm, m, in or ft) set how a bare number
-typed into a feature is read. In an inch design `2` means 2 in. The Box, Cylinder, Sphere, Torus
-and Coil dialogs start with their sizes in the design's units, unit shown (`20 mm`, `20 in`).
-Changing the units never moves existing geometry. A size worked out from a bare number keeps
-the unit the number was given in: a sphere with a bare diameter of 20 has the radius
-`(20 mm) / 2` in a millimetre design. Beside a unit-less expression such as `2 * 5` or a
-unit-less parameter, which is read in the design's units, the number stays bare and is read
-with it.
+or unitless arithmetic expression typed into a length field is read. In an inch design `0.25`
+and `1 / 4` mean 0.25 in. Operation dialogs start with lengths in the design's units, including
+secondary distances, wall thicknesses, gaps, offsets and radii. Canvas handles and live sketch
+values use the same units as the operation. Angles, counts and scale factors keep their own
+units. Preferences selects the default units for new designs; existing designs use their own
+Document Settings.
+
+Explicit units override that choice: `2 mm` is still two millimetres in an inch design.
+Parameter expressions such as `width / 2` remain driving expressions. Editing a saved feature
+preserves its physical size; an existing millimetre expression can still show `mm` so accepting
+an unchanged field cannot reinterpret it. Computed sizes and tolerances keep their full
+precision when written back into editable fields, independently of display precision.
Parameters export to and import from CSV or JSON (`parameters.export`, `parameters.import`).
**Configurations** (`config.*`) keep a table of rows, each with its own parameter values and