Skip to content

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

Sketch dimensions: double-click a shown dimension in the model view to edit it (#7079) (#7080)

bherbruck3de2f96b7f84
diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs
index e8e5034a15..68208634f9 100644
--- a/crates/ui-egui/src/browser.rs
+++ b/crates/ui-egui/src/browser.rs
@@ -2467,14 +2467,17 @@ pub(crate) fn occurrence_triad(app: &mut SolveApp, ui: &mut egui::Ui, painter: &
}
/// Dimensions of finished sketches whose dimensions are shown (Show Dimensions), drawn over the
-/// viewport like the sketch being edited draws its own (`crate::dim_view`), but not editable.
+/// viewport like the sketch being edited draws its own (`crate::dim_view`). A double-click on a
+/// value edits it in place without editing the sketch (`crate::dim_view::model_double_click`).
pub fn dims_overlay(app: &SolveApp, ctx: &egui::Context) {
use solidcraft_engine::geom::Vec2;
use solidcraft_engine::sketch::{DimFrame, chain_centres, default_text, dim_frame, dim_layout_reaching, dim_reach};
+ crate::dim_view::set_model_drawn(Vec::new());
let Some(rect) = app.viewport.rect else { return };
if app.session.visibility.shown_dimensions.is_empty() {
return;
}
+ let mut drawn = Vec::new();
let tk = Tokens::get();
let proj = crate::viewport::projection(app, rect);
let painter = ctx.layer_painter(egui::LayerId::background()).with_clip_rect(rect);
@@ -2527,8 +2530,12 @@ pub fn dims_overlay(app: &SolveApp, ctx: &egui::Context) {
let r = Rect::from_center_size(tc, size);
painter.rect_filled(r, tk.radius_sm / 2, tk.viewport_top.gamma_multiply(0.85));
painter.galley(r.min + vec2(3.0, 1.0), galley, col);
+ if rect.contains(tc) {
+ drawn.push(crate::dim_view::ModelDim { sketch: *id, id: c.id.clone(), param: c.param.clone(), text: r });
+ }
}
}
+ crate::dim_view::set_model_drawn(drawn);
}
/// Keep browser panels beside the browser and below the ribbon, including the floating shell.
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 424f22480e..62d7c376b6 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -738,6 +738,10 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) ->
"dialog": app.dialog.as_ref().map(|d| d.inputs.iter().map(|i| json!({"label": i.label, "items": i.items})).collect::<Vec<_>>()),
"hover": app.viewport.hover.as_ref().map(|h| format!("{h:?}")),
"dimensions": crate::dim_view::drawn().into_iter().map(|(id, p)| json!({"id": id, "x": p.x, "y": p.y})).collect::<Vec<_>>(),
+ "shown_dimensions": crate::dim_view::model_drawn()
+ .into_iter()
+ .map(|(sketch, id, p)| json!({"sketch": sketch, "id": id, "x": p.x, "y": p.y}))
+ .collect::<Vec<_>>(),
"dimension_selected": crate::dim_view::selected(app),
"dimension_editing": crate::dim_view::editing(),
})),
diff --git a/crates/ui-egui/src/dim_view.rs b/crates/ui-egui/src/dim_view.rs
index d5ee8dca1e..3c5aeae49a 100644
--- a/crates/ui-egui/src/dim_view.rs
+++ b/crates/ui-egui/src/dim_view.rs
@@ -6,7 +6,9 @@
//!
//! A click selects a dimension (Delete removes it), a drag moves its text (and so the offset of
//! its dimension line), a double-click (or one click with the Dimension tool) edits its value
-//! in place with parameter completion.
+//! in place with parameter completion. A finished sketch's shown dimensions (Show Dimensions,
+//! drawn by `crate::browser::dims_overlay`) take the same double-click from the model view: the
+//! value is edited without editing the sketch.
//! Everything acts through commands: `sketch.dimension_text`, `sketch.delete`,
//! `parameters.change`.
@@ -55,6 +57,9 @@ struct Edit {
/// The last dimension a click referenced, and when: the second click of a double-click on
/// it must not insert its name again.
picked: Option<(String, f64)>,
+ /// A shown dimension of a finished sketch, edited from the model view without editing the
+ /// sketch (its id). None: a dimension of the sketch being edited.
+ sketch: Option<u64>,
}
#[derive(Clone, Copy, Debug)]
@@ -148,7 +153,7 @@ pub fn begin_dimension(app: &mut SolveApp, entities: Vec<String>, at: Vec2) -> R
}
EDIT.with(|edit| {
*edit.borrow_mut() =
- Some(Edit { param, expr, at: None, fresh: FRESH, wait: 10, draft: Some(draft), live: None, selection: None, picked: None })
+ Some(Edit { param, expr, at: None, fresh: FRESH, wait: 10, draft: Some(draft), live: None, selection: None, picked: None, sketch: None })
});
PLACEMENT.with(|preview| *preview.borrow_mut() = None);
Ok(())
@@ -168,7 +173,8 @@ pub fn begin_live(app: &mut SolveApp, entities: Vec<String>, pointer: Option<Pos
}
let live = Some(Live { origin: pointer, moved: false, typed: false });
EDIT.with(|edit| {
- *edit.borrow_mut() = Some(Edit { param, expr, at: None, fresh: FRESH, wait: 10, draft: Some(draft), live, selection: None, picked: None })
+ *edit.borrow_mut() =
+ Some(Edit { param, expr, at: None, fresh: FRESH, wait: 10, draft: Some(draft), live, selection: None, picked: None, sketch: None })
});
PLACEMENT.with(|preview| *preview.borrow_mut() = None);
Ok(true)
@@ -329,6 +335,64 @@ thread_local! {
static DRAG: RefCell<Option<(String, usize, Vec2)>> = const { RefCell::new(None) };
static EDIT: RefCell<Option<Edit>> = const { RefCell::new(None) };
static PLACEMENT: RefCell<Option<Placement>> = const { RefCell::new(None) };
+ /// Value texts of finished sketches' shown dimensions (Show Dimensions), as the model view
+ /// drew them last frame: sketch, constraint id, parameter (None: driven), text box.
+ static MODEL: RefCell<Vec<ModelDim>> = const { RefCell::new(Vec::new()) };
+}
+
+/// A shown dimension of a finished sketch, as drawn in the model view (screen space).
+#[derive(Clone, Debug)]
+pub(crate) struct ModelDim {
+ pub sketch: u64,
+ pub id: String,
+ pub param: Option<String>,
+ pub text: Rect,
+}
+
+/// Remember the finished sketches' dimensions the model view drew this frame.
+pub(crate) fn set_model_drawn(dims: Vec<ModelDim>) {
+ MODEL.with(|m| *m.borrow_mut() = dims);
+}
+
+/// The finished sketch's shown dimension whose value text is under a screen position.
+fn model_hit(pos: Pos2) -> Option<ModelDim> {
+ MODEL.with(|m| m.borrow().iter().rev().find(|x| x.text.expand(2.0).contains(pos)).cloned())
+}
+
+/// Shown dimensions of finished sketches drawn last frame: (sketch, id, text centre), for tests
+/// and the control channel.
+pub fn model_drawn() -> Vec<(u64, String, Pos2)> {
+ MODEL.with(|m| m.borrow().iter().map(|x| (x.sketch, x.id.clone(), x.text.center())).collect())
+}
+
+/// A double-click on a finished sketch's shown dimension (outside sketch editing) opens its value
+/// in the same inline editor, without editing the sketch or moving the view (true: it was on one).
+/// Enter changes the dimension's own expression through `parameters.change`, one undo step.
+pub fn model_double_click(app: &mut SolveApp, pos: Pos2) -> bool {
+ if app.session.active_sketch.is_some() {
+ return false;
+ }
+ let Some(d) = model_hit(pos) else { return false };
+ let Some(param) = d.param else {
+ app.set_status("A driven dimension measures the sketch; it has no value to edit", false);
+ return true;
+ };
+ let expr = app.session.doc.param(&param).map(|p| p.expr.clone()).unwrap_or_default();
+ EDIT.with(|e| {
+ *e.borrow_mut() = Some(Edit {
+ param,
+ expr,
+ at: Some(d.text.center()),
+ fresh: FRESH,
+ wait: 0,
+ draft: None,
+ live: None,
+ selection: None,
+ picked: None,
+ sketch: Some(d.sketch),
+ })
+ });
+ true
}
/// Frames the inline editor holds on to the keyboard after opening.
@@ -405,8 +469,18 @@ fn open_editor(app: &mut SolveApp, id: Option<String>) -> bool {
};
let expr = app.session.doc.param(&param).map(|p| p.expr.clone()).unwrap_or_default();
EDIT.with(|e| {
- *e.borrow_mut() =
- Some(Edit { param, expr, at: Some(d.text.center()), fresh: FRESH, wait: 0, draft: None, live: None, selection: None, picked: None })
+ *e.borrow_mut() = Some(Edit {
+ param,
+ expr,
+ at: Some(d.text.center()),
+ fresh: FRESH,
+ wait: 0,
+ draft: None,
+ live: None,
+ selection: None,
+ picked: None,
+ sketch: None,
+ })
});
true
}
@@ -508,9 +582,31 @@ pub fn show(app: &mut SolveApp, ui: &egui::Ui, painter: &egui::Painter, proj: &P
let st = app.session.world_state();
let Some(ss) = app.session.active_sketch.and_then(|s| st.sketch(s)) else {
DRAWN.with(|d| d.borrow_mut().clear());
- EDIT.with(|e| *e.borrow_mut() = None);
+ // Only a finished sketch's dimension edited from the model view stays open, at its text.
+ let model = EDIT.with(|e| {
+ let mut e = e.borrow_mut();
+ let keep = e.as_ref().and_then(|x| x.sketch).is_some_and(|s| app.session.active_sketch.is_none() && st.sketch(s).is_some());
+ if !keep {
+ *e = None;
+ } else if let Some(x) = e.as_mut()
+ && let Some(d) = MODEL.with(|m| m.borrow().iter().find(|d| d.param.as_deref() == Some(x.param.as_str())).cloned())
+ {
+ x.at = Some(d.text.center());
+ }
+ keep
+ });
+ if model {
+ edit_box(app, ui.ctx());
+ }
return;
};
+ // Editing a sketch closes a value opened from the model view.
+ EDIT.with(|e| {
+ let mut e = e.borrow_mut();
+ if e.as_ref().is_some_and(|x| x.sketch.is_some()) {
+ *e = None;
+ }
+ });
let sk = &ss.sketch;
if sk.view.hide_dimensions {
DRAWN.with(|d| d.borrow_mut().clear());
@@ -635,8 +731,18 @@ fn pos2_mid_top(r: Rect) -> Pos2 {
pub fn edit_param(app: &SolveApp, param: &str) {
let expr = app.session.doc.param(param).map(|p| p.expr.clone()).unwrap_or_default();
EDIT.with(|e| {
- *e.borrow_mut() =
- Some(Edit { param: param.to_string(), expr, at: None, fresh: FRESH, wait: 10, draft: None, live: None, selection: None, picked: None })
+ *e.borrow_mut() = Some(Edit {
+ param: param.to_string(),
+ expr,
+ at: None,
+ fresh: FRESH,
+ wait: 10,
+ draft: None,
+ live: None,
+ selection: None,
+ picked: None,
+ sketch: None,
+ })
});
}
@@ -694,8 +800,13 @@ pub fn pick_reference(ctx: &egui::Context, pos: Pos2, double: bool) -> bool {
EDIT.with(|editor| {
let mut editor = editor.borrow_mut();
let Some(edit) = editor.as_mut() else { return false };
- let Some(id) = hit(pos) else { return false };
- let param = DRAWN.with(|d| d.borrow().iter().find(|d| d.id == id).and_then(|d| d.param.clone()));
+ let param = if edit.sketch.is_some() {
+ let Some(d) = model_hit(pos) else { return false };
+ d.param
+ } else {
+ let Some(id) = hit(pos) else { return false };
+ DRAWN.with(|d| d.borrow().iter().find(|d| d.id == id).and_then(|d| d.param.clone()))
+ };
// Self references and driven dimensions cannot supply a reference.
if let Some(param) = param.filter(|p| p != &edit.param) {
let now = ctx.input(|i| i.time);
diff --git a/crates/ui-egui/src/dimension_create_ui_tests.rs b/crates/ui-egui/src/dimension_create_ui_tests.rs
index 953e7d1fa8..1c5b15091a 100644
--- a/crates/ui-egui/src/dimension_create_ui_tests.rs
+++ b/crates/ui-egui/src/dimension_create_ui_tests.rs
@@ -1132,3 +1132,142 @@ fn midpoint_dimension_orientation_follows_the_pointer_before_placement() {
}
}
}
+
+/// A finished, extruded 20 x 10 rectangle whose dimensions are shown in the model view (Show
+/// Dimensions): the width `d1` is driven by the user parameter `width`, the height `d2` is a
+/// plain value. Returns the harness and the sketch id.
+fn shown_dimensions() -> (Harness, u64) {
+ crate::dim_view::cancel();
+ let mut h = Harness::new();
+ h.app.run("parameters.add", json!({"name":"width","expression":"20 mm"})).unwrap();
+ let sketch = h.app.run("sketch.create", json!({"plane":"XY"})).unwrap()["sketch"].as_u64().unwrap();
+ h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[20,10]})).unwrap();
+ h.app.run("sketch.dimension", json!({"entities":["l1"],"value":"width","text_at":[10,-4]})).unwrap();
+ h.app.run("sketch.dimension", json!({"entities":["l2"],"value":10,"text_at":[24,5]})).unwrap();
+ h.app.run("sketch.finish", json!({})).unwrap();
+ h.app.run("solid.extrude", json!({"sketch":sketch,"distance":5,"body_name":"Plate"})).unwrap();
+ crate::browser::set_sketch_visible(&mut h.app, sketch, true);
+ h.app.session.visibility.shown_dimensions.push(sketch);
+ h.call("ui.view", json!({"view":"top"}));
+ h.app.cam.distance = 80.0;
+ h.app.cam.target = solidcraft_engine::geom::Vec3::new(10.0, 5.0, 0.0);
+ h.settle();
+ (h, sketch)
+}
+
+/// The model view's text of the dimension driven by `param` (screen).
+fn model_text(h: &Harness, param: &str) -> [f32; 2] {
+ let sk = h
+ .app
+ .session
+ .world_state()
+ .sketch(h.app.session.doc.features.iter().find(|f| f.name.starts_with("Sketch")).unwrap().id)
+ .unwrap()
+ .sketch
+ .clone();
+ let id = sk.constraints.iter().find(|c| c.param.as_deref() == Some(param)).unwrap().id.clone();
+ let (_, _, p) = crate::dim_view::model_drawn().into_iter().find(|(_, d, _)| *d == id).expect("the dimension is shown in the model view");
+ [p.x, p.y]
+}
+
+/// The extruded plate's width and depth (x, y), rounded to 0.001 mm.
+fn plate_max(h: &Harness) -> [f64; 2] {
+ let b = h.app.session.world_state().body("Plate").unwrap().mesh().bounds();
+ [((b.max.x - b.min.x) * 1000.0).round() / 1000.0, ((b.max.y - b.min.y) * 1000.0).round() / 1000.0]
+}
+
+#[test]
+fn double_clicking_a_shown_dimension_edits_it_without_editing_the_sketch() {
+ let (mut h, _) = shown_dimensions();
+ let camera = (h.app.cam.target, h.app.cam.distance);
+ let undo = h.app.session.undo.len();
+ assert!((plate_max(&h)[1] - 10.0).abs() < 1e-6);
+ let at = model_text(&h, "d2");
+ h.step(&json!({"click":at,"double":true})).unwrap();
+ assert!(crate::dim_view::editing(), "the double-click opens the value");
+ assert_eq!(h.ctx.memory(|m| m.focused()), Some(egui::Id::new("sc_dim_edit")));
+ assert_eq!(h.app.session.active_sketch, None, "the sketch is not edited");
+ type_value(&mut h, "14");
+ h.step(&json!({"key":"Enter"})).unwrap();
+ h.settle();
+ assert!(!crate::dim_view::editing());
+ assert_eq!(h.app.session.active_sketch, None);
+ assert_eq!((h.app.cam.target, h.app.cam.distance), camera, "the view stays put");
+ assert_eq!(h.app.session.undo.len(), undo + 1, "one undo step");
+ assert!((plate_max(&h)[1] - 14.0).abs() < 1e-6, "the extrude follows: {:?}", plate_max(&h));
+ h.app.run("edit.undo", json!({})).unwrap();
+ h.settle();
+ assert!((plate_max(&h)[1] - 10.0).abs() < 1e-6, "undo restores it");
+}
+
+#[test]
+fn escape_cancels_a_shown_dimensions_value() {
+ let (mut h, _) = shown_dimensions();
+ let doc = h.app.session.doc.to_json();
+ let at = model_text(&h, "d2");
+ h.step(&json!({"click":at,"double":true})).unwrap();
+ assert!(crate::dim_view::editing());
+ type_value(&mut h, "30");
+ h.step(&json!({"key":"Escape"})).unwrap();
+ h.settle();
+ assert!(!crate::dim_view::editing());
+ assert_eq!(h.app.session.doc.to_json(), doc, "nothing changed");
+ assert!((plate_max(&h)[1] - 10.0).abs() < 1e-6);
+}
+
+#[test]
+fn a_parameter_driven_shown_dimension_edits_its_own_expression() {
+ let (mut h, _) = shown_dimensions();
+ let at = model_text(&h, "d1");
+ h.step(&json!({"click":at,"double":true})).unwrap();
+ assert!(crate::dim_view::editing());
+ assert!(h.widget("width").is_some(), "the box shows the expression that drives it");
+ type_value(&mut h, "width + 5");
+ h.step(&json!({"key":"Enter"})).unwrap();
+ h.settle();
+ assert_eq!(h.app.session.doc.param("width").unwrap().expr, "20 mm", "the user parameter is left alone");
+ assert_eq!(h.app.session.doc.param("d1").unwrap().expr, "width + 5");
+ assert!((plate_max(&h)[0] - 25.0).abs() < 1e-6, "{:?}", plate_max(&h));
+ assert_eq!(h.app.session.active_sketch, None);
+}
+
+#[test]
+fn a_driven_shown_dimension_is_read_only() {
+ let (mut h, sketch) = shown_dimensions();
+ h.app.run("sketch.edit", json!({"sketch":sketch})).unwrap();
+ h.app.run("sketch.dimension", json!({"entities":["l3"],"driven":true,"text_at":[10,14]})).unwrap();
+ h.app.run("sketch.finish", json!({})).unwrap();
+ h.settle();
+ let id = h.app.session.world_state().sketch(sketch).unwrap().sketch.constraints.iter().find(|c| c.driven).unwrap().id.clone();
+ let (_, _, p) = crate::dim_view::model_drawn().into_iter().find(|(_, d, _)| *d == id).unwrap();
+ let doc = h.app.session.doc.to_json();
+ h.step(&json!({"click":[p.x, p.y],"double":true})).unwrap();
+ assert!(!crate::dim_view::editing());
+ assert!(h.app.status.as_ref().is_some_and(|s| s.0.contains("driven")), "{:?}", h.app.status);
+ assert_eq!(h.app.session.doc.to_json(), doc);
+}
+
+/// The value applies like any other change: the fillet it breaks reports its error on the
+/// timeline, and Undo brings back the value and the fillet.
+#[test]
+fn a_shown_dimension_that_breaks_a_later_feature_reports_it_and_undoes() {
+ let (mut h, _) = shown_dimensions();
+ h.app.run("solid.fillet", json!({"edges":[[10,10,5]],"radius":4,"name":"Round"})).unwrap();
+ h.settle();
+ let round = h.app.session.doc.features.iter().find(|f| f.name == "Round").unwrap().id;
+ let failed = |h: &Harness| h.app.session.model.result(round).is_some_and(|r| r.error.is_some());
+ assert!(!failed(&h));
+ let before = h.app.session.doc.to_json();
+ let at = model_text(&h, "d2");
+ h.step(&json!({"click":at,"double":true})).unwrap();
+ type_value(&mut h, "3");
+ h.step(&json!({"key":"Enter"})).unwrap();
+ h.settle();
+ assert_eq!(h.app.session.doc.param("d2").unwrap().expr, "3");
+ assert!(failed(&h), "the fillet no longer fits and says so");
+ assert_eq!(h.app.session.active_sketch, None);
+ h.app.run("edit.undo", json!({})).unwrap();
+ h.settle();
+ assert_eq!(h.app.session.doc.to_json(), before);
+ assert!(!failed(&h), "undo brings the fillet back");
+}
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index 99068efd19..a1e3887a30 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -3611,13 +3611,16 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
}
}
}
- // Double-click a dimension: edit its value in place.
+ // Double-click a dimension: edit its value in place (a finished sketch's shown dimension
+ // too, without editing the sketch).
let dim_edit = resp.double_clicked()
&& !held
&& !crate::dim_view::editing()
&& app.tool.is_none()
&& app.dialog.is_none()
- && (crate::sketch_modify_ui::double_click_pattern(app, p) || crate::dim_view::double_click(app, p));
+ && (crate::sketch_modify_ui::double_click_pattern(app, p)
+ || crate::dim_view::double_click(app, p)
+ || crate::dim_view::model_double_click(app, p));
// Double-click a text (an outline or inside a letter; the first click selected it): edit it.
if resp.double_clicked()
&& !held
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index bc732274a7..53e307c3ca 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -282,7 +282,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox.
| `ui.menuPick` | `item`: id or label | runs an item of the open menu, as clicking it does |
| `ui.selectOther` | `x?`, `y?`, `pick?`, `add?`, `hover?`, `close?` | Select Other: with a point, list everything pickable there (as holding the left button does); `pick`: select row `pick` (`add`: as Shift-click; with a dialog open, into its active input); `hover`: light a row up; without: the open list (`open`, `at`, `total`: everything under the cursor, `rows`: label, icon, sel, at most 20 per kind, nearest first) |
| `ui.rename` | `text?`, `commit?` (default true) | finishes the rename box a Rename item opened |
-| `ui.selection` | | the selection, the open dialog's inputs, the hovered item, and the active sketch's drawn dimensions (`dimensions`: id and text centre, `dimension_selected`, `dimension_editing`) |
+| `ui.selection` | | the selection, the open dialog's inputs, the hovered item, and the active sketch's drawn dimensions (`dimensions`: id and text centre, `dimension_selected`, `dimension_editing`), and finished sketches' dimensions shown in the model view (`shown_dimensions`: sketch, id and text centre; a double-click there edits the value) |
| `ui.worldToScreen` | `points`: `[[x, y, z]…]` world points | their screen points |
| `ui.triad` | | screen points of the 3D sketch move triad's handles (`x`, `y`, `z`, `plane`) |
| `ui.sketchToScreen` | `points`: `[[x, y]…]` in active-sketch coordinates | their screen points (null when behind the camera) |