SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
sketch(feat): a click on another dimension inserts its name into the value being edited (#3186)
SS-EN76b17f2663fa
diff --git a/crates/ui-egui/src/dim_view.rs b/crates/ui-egui/src/dim_view.rsindex ca2ebd0932..7910a37e55 100644--- a/crates/ui-egui/src/dim_view.rs+++ b/crates/ui-egui/src/dim_view.rs@@ -50,6 +50,9 @@ struct Edit {/// dimension, and its text follows the pointer until a click pins it or Enter places it.live: Option<Live>,selection: Option<egui::text::CCursorRange>,+ /// 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)>,}#[derive(Clone, Copy, Debug)]@@ -134,7 +137,8 @@ pub fn begin_dimension(app: &mut SolveApp, entities: Vec<String>, at: Vec2) -> Rreturn Ok(());}EDIT.with(|edit| {- *edit.borrow_mut() = Some(Edit { param, expr, at: None, fresh: FRESH, wait: 10, draft: Some(draft), live: None, selection: None })+ *edit.borrow_mut() =+ Some(Edit { param, expr, at: None, fresh: FRESH, wait: 10, draft: Some(draft), live: None, selection: None, picked: None })});PLACEMENT.with(|preview| *preview.borrow_mut() = None);Ok(())@@ -150,7 +154,9 @@ pub fn begin_live(app: &mut SolveApp, entities: Vec<String>, pointer: Option<Posreturn Ok(false);}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 }));+ EDIT.with(|edit| {+ *edit.borrow_mut() = Some(Edit { param, expr, at: None, fresh: FRESH, wait: 10, draft: Some(draft), live, selection: None, picked: None })+ });PLACEMENT.with(|preview| *preview.borrow_mut() = None);Ok(true)}@@ -355,7 +361,8 @@ pub fn double_click(app: &mut SolveApp, pos: Pos2) -> bool {};let expr = app.session.doc.param(¶m).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 })+ *e.borrow_mut() =+ Some(Edit { param, expr, at: Some(d.text.center()), fresh: FRESH, wait: 0, draft: None, live: None, selection: None, picked: None })});true}@@ -583,24 +590,45 @@ 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 })+ *e.borrow_mut() =+ Some(Edit { param: param.to_string(), expr, at: None, fresh: FRESH, wait: 10, draft: None, live: None, selection: None, picked: None })});}-/// Insert a reference at the expression's selection, using character offsets (not bytes).+/// A lone value such as `10`, `-3`, `12.5`, `2,5`, `10 mm` or `45 deg`: a number, optionally+/// followed by a unit, with no operator or name.+fn is_plain_value(text: &str) -> bool {+ let t = text.trim();+ let t = t.strip_prefix(['-', '+']).unwrap_or(t);+ let digits = t.find(|c: char| !(c.is_ascii_digit() || c == '.' || c == ',')).unwrap_or(t.len());+ let (number, unit) = t.split_at(digits);+ number.chars().any(|c| c.is_ascii_digit()) && unit.trim().chars().all(|c| c.is_alphabetic() || matches!(c, '°' | '"' | '\''))+}++/// Insert a reference into the expression, using character offsets (not bytes). The rule:+/// - the field holds a lone value (a number, optionally with a unit: `10`, `10 mm`): the name+/// replaces the whole text, so `10` becomes `d10`;+/// - otherwise (an expression in progress such as `10 + ` or `2 * (`): the name goes in at the+/// cursor, replacing selected text, so `10 + ` becomes `10 + d10`; with no cursor it is+/// appended. Nothing else (spaces, operators) is added.+///+/// The cursor ends just after the name and the field keeps the keyboard.fn insert_reference(ctx: &egui::Context, edit: &mut Edit, name: &str) {let id = egui::Id::new("sc_dim_edit");let mut state = egui::TextEdit::load_state(ctx, id).unwrap_or_default();let len = edit.expr.chars().count();- let (start, end) = edit- .selection- .or_else(|| state.cursor.char_range())- .map(|r| {- let a = r.primary.index.0.min(len);- let b = r.secondary.index.0.min(len);- (a.min(b), a.max(b))- })- .unwrap_or((len, len));+ let (start, end) = if is_plain_value(&edit.expr) {+ (0, len)+ } else {+ edit.selection+ .or_else(|| state.cursor.char_range())+ .map(|r| {+ let a = r.primary.index.0.min(len);+ let b = r.secondary.index.0.min(len);+ (a.min(b), a.max(b))+ })+ .unwrap_or((len, len))+ };let before: String = edit.expr.chars().take(start).collect();let after: String = edit.expr.chars().skip(end).collect();edit.expr = format!("{before}{name}{after}");@@ -614,17 +642,25 @@ fn insert_reference(ctx: &egui::Context, edit: &mut Edit, name: &str) {}}-/// Consume dimension clicks while editing; only a double-click inserts a reference.+/// Consume dimension clicks while editing: a click on another driving dimension inserts its+/// name at the cursor (replacing selected text), keeping what was typed. The second click of a+/// double-click on the same dimension does not insert it again.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()));- if double && let Some(param) = param.filter(|p| p != &edit.param) {- insert_reference(ctx, edit, ¶m);- }// 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);+ let delay = ctx.options(|o| o.input_options.max_double_click_delay);+ let repeat = double && edit.picked.as_ref().is_some_and(|(p, at)| *p == param && now - *at <= delay);+ if !repeat {+ insert_reference(ctx, edit, ¶m);+ edit.picked = Some((param, now));+ }+ }edit.fresh = FRESH - 1;true})@@ -663,7 +699,7 @@ fn edit_box(app: &mut SolveApp, ctx: &egui::Context) {egui::Frame::popup(ui.style()).inner_margin(egui::Margin::symmetric(3, 1)).show(ui, |ui| {ui.set_max_width(popup_width);ui.label(egui::RichText::new(format!("Dimension: {}", e.param)).strong())- .on_hover_text("Double-click another driving dimension to insert its name");+ .on_hover_text("Click another driving dimension to insert its name");let r = ui.add(egui::TextEdit::singleline(&mut e.expr).id(id).desired_width(popup_width));if r.has_focus() {e.selection = egui::TextEdit::load_state(ctx, id).and_then(|s| s.cursor.char_range());@@ -758,6 +794,16 @@ pub fn drawn() -> Vec<(String, Pos2)> {mod tests {use super::*;+ #[test]+ fn plain_values_are_numbers_with_an_optional_unit() {+ for t in ["10", " 10 mm ", "12.5", "2,5", "-3", "+4", "45 deg", "45°", "1in"] {+ assert!(is_plain_value(t), "{t:?}");+ }+ for t in ["", "10 + ", "2 * (", "Width - ", "width", "d1", "10 mm + d2", "(10)", "mm", "-"] {+ assert!(!is_plain_value(t), "{t:?}");+ }+ }+#[test]fn placement_previews_radial_and_angular_dimensions_and_invalidates_on_document_change() {cancel();diff --git a/crates/ui-egui/src/dimension_create_ui_tests.rs b/crates/ui-egui/src/dimension_create_ui_tests.rsindex 6ee556f7ce..8ddf532039 100644--- a/crates/ui-egui/src/dimension_create_ui_tests.rs+++ b/crates/ui-egui/src/dimension_create_ui_tests.rs@@ -66,8 +66,8 @@ fn dimension_editor_names_and_reference_picks_drive_new_and_existing_dimensions(crate::dim_view::cancel();}-#[test]-fn single_clicking_another_dimension_does_not_change_the_expression() {+/// Two dimensioned lines, editing `d2` with `typed` in its value field.+fn editing_d2(typed: &str) -> Harness {let mut h = line([20., 0.]);h.app.run("sketch.dimension", json!({"entities":["l1"],"value":20,"text_at":[10,8]})).unwrap();h.app.run("sketch.line", json!({"points":[[0,-10],[12,-10]],"infer":false})).unwrap();@@ -75,11 +75,79 @@ fn single_clicking_another_dimension_does_not_change_the_expression() {h.settle();crate::dim_view::edit_param(&h.app, "d2");h.frames(5);- type_value(&mut h, "8");+ type_value(&mut h, typed);+ h+}++/// Click `d1`, check the editor stays focused, then apply and return d2's expression.+fn click_d1_and_apply(h: &mut Harness) -> String {h.step(&json!({"click":{"dimension":"d1"}})).unwrap();- assert!(crate::dim_view::editing());+ assert!(crate::dim_view::editing(), "a reference click keeps the editor open");+ h.frames(2);+ assert_eq!(h.ctx.memory(|m| m.focused()), Some(egui::Id::new("sc_dim_edit")), "the value field keeps the keyboard");+ h.step(&json!({"key":"Enter"})).unwrap();+ assert!(!crate::dim_view::editing(), "{}", h.call("ui.inspect", json!({})));+ let expr = h.app.session.doc.param("d2").unwrap().expr.clone();+ crate::dim_view::cancel();+ expr+}++#[test]+fn clicking_another_dimension_appends_its_name_to_the_typed_text() {+ for (typed, expected) in [("2 * ", "2 * d1"), ("10 + ", "10 + d1")] {+ let mut h = editing_d2(typed);+ assert_eq!(click_d1_and_apply(&mut h), expected, "typed {typed:?}");+ }+}++#[test]+fn clicking_another_dimension_replaces_a_lone_value() {+ for typed in ["10", "10 mm", "-3.5"] {+ let mut h = editing_d2(typed);+ assert_eq!(click_d1_and_apply(&mut h), "d1", "typed {typed:?}");+ }+ // The cursor inside the number does not matter: the whole value goes.+ let mut h = editing_d2("125");+ h.step(&json!({"key":"Home"})).unwrap();+ h.step(&json!({"key":"ArrowRight"})).unwrap();+ assert_eq!(click_d1_and_apply(&mut h), "d1");+}++#[test]+fn clicking_another_dimension_lets_typing_continue_after_its_name() {+ let mut h = editing_d2("2 * ");+ h.step(&json!({"click":{"dimension":"d1"}})).unwrap();+ h.frames(2);+ h.step(&json!({"text":" + 1"})).unwrap();+ h.step(&json!({"key":"Enter"})).unwrap();+ assert_eq!(h.app.session.doc.param("d2").unwrap().expr, "2 * d1 + 1");+ crate::dim_view::cancel();+}++#[test]+fn clicking_another_dimension_inserts_its_name_at_the_cursor() {+ let mut h = editing_d2("( ) / 2");+ h.step(&json!({"key":"Home"})).unwrap();+ h.step(&json!({"key":"ArrowRight"})).unwrap();+ h.step(&json!({"key":"ArrowRight"})).unwrap();+ assert_eq!(click_d1_and_apply(&mut h), "( d1) / 2");+}++#[test]+fn clicking_another_dimension_replaces_the_selected_text() {+ let mut h = editing_d2("5 + 7");+ h.step(&json!({"key":"ArrowLeft","shift":true})).unwrap();+ assert_eq!(click_d1_and_apply(&mut h), "5 + d1");+}++#[test]+fn double_clicking_another_dimension_inserts_its_name_once() {+ let mut h = editing_d2("3 * ");+ // Synthetic input feeds one pointer event per frame, so this is a click and, a frame+ // later, a second click that egui reads as a double-click.+ h.step(&json!({"click":{"dimension":"d1"},"double":true})).unwrap();h.step(&json!({"key":"Enter"})).unwrap();- assert_eq!(h.app.session.doc.param("d2").unwrap().expr, "8");+ assert_eq!(h.app.session.doc.param("d2").unwrap().expr, "3 * d1");crate::dim_view::cancel();}diff --git a/docs/book/src/guide/parameters.md b/docs/book/src/guide/parameters.mdindex 369ca6330f..6ed4fcc018 100644--- a/docs/book/src/guide/parameters.md+++ b/docs/book/src/guide/parameters.md@@ -6,10 +6,11 @@ are ones you add yourself, with a unit, an expression and an optional comment. Cuses them.When creating or editing a sketch dimension, its value editor shows its model parameter-name (`d1`, `d2`, …). Double-click another driving dimension to insert its name at the cursor,-replacing selected text; add arithmetic such as `/ 2` to build a dependent dimension.-Single clicks on dimensions leave the expression unchanged. Press **Enter** to apply the-expression or **Escape** to cancel the edit.+name (`d1`, `d2`, …). Click another driving dimension to use its name: when the value is+just a number (such as `10` or `10 mm`) the name replaces it; otherwise it goes in at the+cursor, replacing selected text and keeping what you typed, so typing `10 + ` and clicking+`d1` gives `10 + d1`. Add arithmetic such as `/ 2` to build a dependent dimension. Press **Enter** to apply+the expression or **Escape** to cancel the edit.Add and edit user parameters through the existing **Change Parameters** command.In the SOLID toolbar's CONFIGURE panel, click **Parameters** to open the user and model