Skip to content

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

Sketch: a construction/normal switch in the construction line tools (#10258) (#10551)

kaltenbrunnermarkusb557f22f9730
diff --git a/assets/locales/pending/sketch-construction-line-length-box.json b/assets/locales/pending/sketch-construction-line-length-box.json
new file mode 100644
index 0000000000..810b6d25b6
--- /dev/null
+++ b/assets/locales/pending/sketch-construction-line-length-box.json
@@ -0,0 +1,26 @@
+{
+ "en": {
+ "ui.construction.side_hint": "Construction line: click the side the line runs towards; right-click to restart"
+ },
+ "de": {
+ "ui.construction.side_hint": "Konstruktionslinie: die Seite anklicken, zu der die Linie läuft; Rechtsklick beginnt neu"
+ },
+ "ja": {
+ "ui.construction.side_hint": "補助直線: 線を伸ばす側をクリック。右クリックで最初から"
+ },
+ "ko": {
+ "ui.construction.side_hint": "보조 직선: 선이 뻗어 나갈 쪽 클릭; 마우스 오른쪽 버튼으로 다시 시작"
+ },
+ "zh": {
+ "ui.construction.side_hint": "构造直线:单击直线延伸的一侧;右键单击重新开始"
+ },
+ "ar": {
+ "ui.construction.side_hint": "خط إنشائي: انقر الجهة التي يمتد نحوها الخط؛ انقر بزر الفأرة الأيمن للبدء من جديد"
+ },
+ "he": {
+ "ui.construction.side_hint": "ישר עזר: לחיצה על הצד שאליו הקו נמשך; לחיצה ימנית להתחלה מחדש"
+ },
+ "vi": {
+ "ui.construction.side_hint": "Đường dựng hình: nhấp phía mà đường kéo dài tới; nhấp chuột phải để bắt đầu lại"
+ }
+}
diff --git a/assets/locales/pending/sketch-construction-line-normal-switch.json b/assets/locales/pending/sketch-construction-line-normal-switch.json
new file mode 100644
index 0000000000..8885eddd9d
--- /dev/null
+++ b/assets/locales/pending/sketch-construction-line-normal-switch.json
@@ -0,0 +1,26 @@
+{
+ "en": {
+ "ui.construction.normal_needs_length": "An infinite line is always construction: type a length to draw a normal line"
+ },
+ "de": {
+ "ui.construction.normal_needs_length": "Eine unendliche Linie ist immer Konstruktion: Länge eingeben, um eine normale Linie zu zeichnen"
+ },
+ "ja": {
+ "ui.construction.normal_needs_length": "無限直線は常に補助線です。通常の線を描くには長さを入力"
+ },
+ "ko": {
+ "ui.construction.normal_needs_length": "무한 직선은 항상 보조선입니다. 일반 선을 그리려면 길이를 입력하세요"
+ },
+ "zh": {
+ "ui.construction.normal_needs_length": "无限直线始终是构造线:输入长度以绘制普通直线"
+ },
+ "ar": {
+ "ui.construction.normal_needs_length": "الخط اللانهائي إنشائي دائمًا: اكتب طولًا لرسم خط عادي"
+ },
+ "he": {
+ "ui.construction.normal_needs_length": "קו אינסופי הוא תמיד קו עזר: הקלדת אורך משרטטת קו רגיל"
+ },
+ "vi": {
+ "ui.construction.normal_needs_length": "Đường vô hạn luôn là đường dựng hình: nhập chiều dài để vẽ đường thường"
+ }
+}
diff --git a/crates/engine/src/cmd/sketch_construction.rs b/crates/engine/src/cmd/sketch_construction.rs
index 2d91ceec0f..f57e48e129 100644
--- a/crates/engine/src/cmd/sketch_construction.rs
+++ b/crates/engine/src/cmd/sketch_construction.rs
@@ -24,7 +24,7 @@ macro_rules! variant {
.enabled(in_sketch)
.contract(&CONTRACT)
.output(output_schema_for::<ConstructionLineResult>)
- .params(concat!("Construction line, ", $mode, ". at: point; through?: second point; curve?, curve2?: sketch references; angle?: degrees from sketch X; near?: solution selector, and the side a line with a length runs towards; solution?: zero-based solution index; length?: a segment of this length from `at`, held by a length dimension, instead of an infinite line (horizontal, vertical, angle, parallel, perpendicular). Tangents take circles/arcs, or an open spline/conic endpoint for tangent_at.", created_doc!()))
+ .params(concat!("Construction line, ", $mode, ". at: point; through?: second point; curve?, curve2?: sketch references; angle?: degrees from sketch X; near?: solution selector, and the side a line with a length runs towards; solution?: zero-based solution index; length?: a segment of this length from `at`, held by a length dimension, instead of an infinite line (horizontal, vertical, angle, parallel, perpendicular); construction?: false makes that segment a normal line. Tangents take circles/arcs, or an open spline/conic endpoint for tangent_at.", created_doc!()))
};
}
@@ -306,6 +306,14 @@ fn run(s: &mut Session, p: &Value, default_mode: &str) -> Result<Value> {
Some((e, value))
}
};
+ let construction = match p.get("construction") {
+ None | Some(Value::Null) => true,
+ Some(Value::Bool(value)) => *value,
+ Some(_) => return Err(bad(CMD, "`construction` must be a boolean")),
+ };
+ if !construction && length.is_none() {
+ return Err(bad(CMD, "only a line with a `length` can be a normal line: an infinite line is construction geometry"));
+ }
let solutions = construction_line_solutions(sk, &params, mode)?;
let choice = construction_line_choice(&solutions, &params)?;
let chosen = solutions.get(choice).ok_or_else(|| bad(CMD, "no solution"))?;
@@ -331,7 +339,7 @@ fn run(s: &mut Session, p: &Value, default_mode: &str) -> Result<Value> {
let l = sk.add_line(start, end, start_ref, through.as_ref().and_then(|q| q.idx()), None)?;
if let Some(c) = sk.curves.get_mut(l) {
c.infinite = length.is_none();
- c.construction = true;
+ c.construction = construction;
}
let mut cons = Vec::new();
let kind = match (mode, reference) {
diff --git a/crates/engine/src/cmd/sketch_infinite_tests.rs b/crates/engine/src/cmd/sketch_infinite_tests.rs
index a63bb413a2..2ca806a34b 100644
--- a/crates/engine/src/cmd/sketch_infinite_tests.rs
+++ b/crates/engine/src/cmd/sketch_infinite_tests.rs
@@ -114,6 +114,30 @@ fn construction_lines_with_a_length_are_segments_held_by_a_dimension() {
}
}
+#[test]
+fn a_construction_line_with_a_length_can_be_a_normal_line() {
+ let mut s = new_sketch();
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 20]}));
+ let p = json!({"at": [20, -10], "length": 40, "near": [20, 30]});
+ let guide = run(&mut s, "sketch.construction_line.vertical", p.clone());
+ assert!(curve(&sketch(&s), guide["curves"][0].as_str().unwrap()).construction);
+ assert_eq!(profiles(&s), 1, "by default it is construction geometry: no profile");
+ let mut p = p;
+ p["construction"] = json!(false);
+ let out = run(&mut s, "sketch.construction_line.vertical", p);
+ let sk = sketch(&s);
+ let c = curve(&sk, out["curves"][0].as_str().unwrap());
+ assert!(!c.construction && !c.infinite);
+ assert_eq!(profiles(&s), 2, "a normal line cuts the rectangle in two");
+ let back = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();
+ assert!(!curve(back.sketch(s.active_sketch.unwrap()).unwrap(), out["curves"][0].as_str().unwrap()).construction);
+ for p in [json!({"at": [0, 0], "construction": false}), json!({"at": [0, 0], "length": 5, "construction": "no"})] {
+ let before = s.doc.to_json();
+ assert!(s.execute("sketch.construction_line.horizontal", &p).is_err(), "{p}");
+ assert_eq!(s.doc.to_json(), before, "{p}");
+ }
+}
+
#[test]
fn construction_angle_keeps_its_parameter_expression() {
let mut s = new_sketch();
diff --git a/crates/engine/src/schema/sketch_create.rs b/crates/engine/src/schema/sketch_create.rs
index f482d9adb2..558045450e 100644
--- a/crates/engine/src/schema/sketch_create.rs
+++ b/crates/engine/src/schema/sketch_create.rs
@@ -32,6 +32,9 @@ pub struct ConstructionLineParams {
/// A segment of this length from `at` instead of an infinite line, held by a length
/// dimension. For the horizontal, vertical, angle, parallel and perpendicular methods.
pub length: Option<LengthExpr>,
+ /// `false` makes a line with a `length` a normal sketch line, ready for a profile, instead
+ /// of construction geometry (default `true`). An infinite line is always construction.
+ pub construction: Option<bool>,
/// The sketch (default: the one being edited).
pub sketch: Option<SketchRef>,
}
diff --git a/crates/engine/src/schema/sketch_create_tests.rs b/crates/engine/src/schema/sketch_create_tests.rs
index 4c4643fcdc..3f841c6260 100644
--- a/crates/engine/src/schema/sketch_create_tests.rs
+++ b/crates/engine/src/schema/sketch_create_tests.rs
@@ -42,7 +42,7 @@ fn construction_line_contracts_and_replies_match() {
use super::{ConstructionLineParams, ConstructionLineResult};
assert_keys(
input_schema_for::<ConstructionLineParams>(),
- &["alternate", "angle", "at", "curve", "curve2", "length", "mode", "near", "sketch", "solution", "through"],
+ &["alternate", "angle", "at", "construction", "curve", "curve2", "length", "mode", "near", "sketch", "solution", "through"],
);
let schema = output_schema_for::<ConstructionLineResult>();
let schema = schema.as_value();
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index d640fd097e..5be45b590c 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -2792,6 +2792,8 @@ impl SolveApp {
if !keymap::capturing(self) {
expression_complete::begin_frame(ctx);
}
+ // A digit for a construction line's Length box is not a shortcut (#10258).
+ sketch_construction::claim_typed_length(self, ctx);
if !self.embedded {
toolbar::shortcuts(self, ctx);
}
diff --git a/crates/ui-egui/src/sketch_construction.rs b/crates/ui-egui/src/sketch_construction.rs
index 3390175c79..2365133839 100644
--- a/crates/ui-egui/src/sketch_construction.rs
+++ b/crates/ui-egui/src/sketch_construction.rs
@@ -2,7 +2,7 @@
use egui::Stroke;
use serde_json::{Value, json};
-use solidcraft_engine::cmd::{construction_line_choice, construction_line_mode, construction_line_solutions};
+use solidcraft_engine::cmd::{construction_line_choice, construction_line_mode, construction_line_solutions, construction_segment};
use solidcraft_engine::geom::Vec2;
use crate::SolveApp;
@@ -17,6 +17,78 @@ fn references(mode: &str) -> usize {
}
}
+/// The one-click methods whose Length box shows from the start (#10258). Without a length they
+/// still draw an infinite line in one click; with one, a second click picks the side it runs to.
+pub(crate) fn length_box_at_start(mode: &str) -> bool {
+ matches!(mode, "horizontal" | "vertical" | "parallel" | "perpendicular")
+}
+
+/// The typed length, or None while the box is empty: an empty box keeps the infinite line.
+pub(crate) fn typed_length(t: &Tool) -> Option<&str> {
+ crate::sketch_dims::locked_expression(t, "Length").map(str::trim).filter(|text| !text.is_empty())
+}
+
+/// A digit typed while a one-click tool's Length box waits gives that box the keyboard, so the
+/// digit is its first character. Anything else (a tool's shortcut letter) still reaches the
+/// shortcuts: the box only takes the keyboard once a number is being typed.
+pub fn claim_typed_length(app: &SolveApp, ctx: &egui::Context) {
+ let Some(t) = app.tool.as_ref() else { return };
+ if !construction_line_mode(t.cmd).is_some_and(length_box_at_start) || !t.pts.is_empty() || t.hover.is_none() {
+ return;
+ }
+ if t.dims.first().is_none_or(|b| b.label != "Length") || ctx.memory(|m| m.focused().is_some()) {
+ return;
+ }
+ let digit = ctx.input(|i| {
+ !i.modifiers.command
+ && !i.modifiers.alt
+ && i.events.iter().any(|e| matches!(e, egui::Event::Text(text) if text.chars().next().is_some_and(|c| c.is_ascii_digit())))
+ });
+ if digit {
+ ctx.memory_mut(|m| m.request_focus(crate::sketch_dims::box_id(0)));
+ }
+}
+
+/// The Construction/Normal switch under a construction line tool's Length box (#10258). Normal
+/// makes the segment an ordinary sketch line, ready to close a profile, without converting it
+/// afterwards. It only works with a length: an infinite line stays construction, so the switch
+/// is greyed out and says why until a length is typed. It belongs to the tool alone and leaves
+/// the Sketch Palette's drawing line type (X) as it is.
+pub fn line_type_switch(ui: &mut egui::Ui, t: &mut Tool) {
+ if construction_line_mode(t.cmd).is_none() {
+ return;
+ }
+ let Some(i) = t.dims.iter().position(|b| b.label == "Length") else { return };
+ let Some(length_box) = ui.ctx().memory(|m| m.area_rect(egui::Id::new(("sc_dim_area", i)))) else { return };
+ let tokens = crate::theme::Tokens::get();
+ let has_length = typed_length(t).is_some();
+ let reason = crate::i18n::tr("ui.construction.normal_needs_length");
+ let refused = [Some(reason), Some(reason)];
+ // The Sketch Palette's own line type names, which `segmented` translates.
+ let options = ["Construction", "Normal"];
+ let mut selected = usize::from(has_length && t.normal);
+ let frame = crate::ui_kit::Container::popup_frame(ui.style()).inner_margin(egui::Margin::same(1)).fill(tokens.panel);
+ crate::ui_kit::Container::new(ui.ctx(), crate::ui_kit::Surface::Canvas)
+ .area(egui::Id::new("sc_construction_switch"))
+ .fixed_pos(length_box.left_bottom() + egui::vec2(0.0, tokens.space_2))
+ .order(egui::Order::Background)
+ .show(ui.ctx(), |ui| {
+ frame.show(ui, |ui| {
+ let segments = crate::ui_kit::Segments {
+ disabled_reasons: if has_length { &[] } else { &refused },
+ targets: &["construction_switch:construction", "construction_switch:normal"],
+ small: true,
+ intrinsic: true,
+ compact: true,
+ ..Default::default()
+ };
+ if crate::ui_kit::segmented(ui, &mut selected, &options, segments) {
+ t.normal = selected == 1;
+ }
+ });
+ });
+}
+
pub fn hint(id: &str) -> String {
let key = match construction_line_mode(id).unwrap_or("free") {
"free" => "ui.construction.free_hint",
@@ -49,8 +121,8 @@ fn params(app: &SolveApp, t: &Tool, pointer: &(Vec2, Option<String>), preview: b
let first = t.pts.first();
let at = match mode {
"free" | "angle" => first?,
- "tangent_external" => first.unwrap_or(pointer),
- _ => pointer,
+ // A line with a length starts where the first click was; the pointer picks its side.
+ _ => first.unwrap_or(pointer),
};
let mut p = json!({"mode": mode, "at": arg(at, preview), "near": [pointer.0.x, pointer.0.y]});
if let Some(id) = t.picks.first() {
@@ -69,6 +141,13 @@ fn params(app: &SolveApp, t: &Tool, pointer: &(Vec2, Option<String>), preview: b
p["angle"] = json!(expression);
}
}
+ if let Some(expression) = typed_length(t) {
+ p["length"] = if preview { json!(crate::sketch_dims::locked_value(app, t, "Length")?) } else { json!(expression) };
+ // An infinite line is always construction, so the switch only counts with a length.
+ if t.normal {
+ p["construction"] = json!(false);
+ }
+ }
Some(p)
}
@@ -116,12 +195,23 @@ pub fn place_point(app: &mut SolveApp, t: &mut Tool, at: (Vec2, Option<String>))
return;
}
let at = crate::sketch_dims::placed(app, t, &at);
- if matches!(mode, "free" | "angle" | "tangent_external") && t.pts.is_empty() {
+ let picks_side = length_box_at_start(mode) && typed_length(t).is_some();
+ if (matches!(mode, "free" | "angle" | "tangent_external") || picks_side) && t.pts.is_empty() {
t.pts.push(at);
+ if picks_side {
+ app.set_status(crate::i18n::tr("ui.construction.side_hint").to_owned(), false);
+ }
+ return;
+ }
+ // A click back on the start names no side: wait for one.
+ if picks_side && t.pts.first().is_some_and(|start| start.0.dist(at.0) < 1e-9) {
return;
}
let Some(p) = params(app, t, &at, false) else { return };
if app.run(t.cmd, p).is_ok() {
+ if !t.pts.is_empty() && length_box_at_start(mode) {
+ app.set_status(hint(t.cmd), false);
+ }
t.pts.clear();
// Retain references for repeated parallel lines/tangents. Right-click resets the picks.
crate::sketch_dims::reset(t);
@@ -140,10 +230,20 @@ pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) {
let tokens = crate::theme::Tokens::get();
let center = ss.plane.to_local(app.cam.target);
let extent = app.cam.half_height().max(1.0) * 20.0;
+ let length = p.get("length").and_then(Value::as_f64);
for (i, line) in lines.iter().enumerate() {
- let origin = line.start + line.direction * (center - line.start).dot(line.direction);
- let points = [ss.plane.to_world(origin - line.direction * extent), ss.plane.to_world(origin + line.direction * extent)];
let selected = chosen == Some(i);
+ // A typed length previews the segment the click will create, on the pointer's side.
+ let points = match length {
+ Some(length) if selected => {
+ let (a, b) = construction_segment(*line, length, Some(pointer.0));
+ [ss.plane.to_world(a), ss.plane.to_world(b)]
+ }
+ _ => {
+ let origin = line.start + line.direction * (center - line.start).dot(line.direction);
+ [ss.plane.to_world(origin - line.direction * extent), ss.plane.to_world(origin + line.direction * extent)]
+ }
+ };
let stroke =
Stroke::new(if selected { 2.0 } else { 1.0 }, if selected { tokens.preview_new } else { tokens.sketch_accent.gamma_multiply(0.35) });
crate::tools::paint_sketch_path(&points, 3, painter, proj, stroke);
diff --git a/crates/ui-egui/src/sketch_construction_tests.rs b/crates/ui-egui/src/sketch_construction_tests.rs
index 3ef812fda5..404a500e2e 100644
--- a/crates/ui-egui/src/sketch_construction_tests.rs
+++ b/crates/ui-egui/src/sketch_construction_tests.rs
@@ -104,3 +104,168 @@ fn construction_family_menu_and_preference() {
}
}
}
+
+fn digit(h: &mut Harness, d: char) {
+ let key = egui::Key::from_name(&d.to_string()).unwrap();
+ h.frame_with(vec![
+ egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE },
+ egui::Event::Text(d.to_string()),
+ ]);
+}
+
+fn length_box_focused(h: &Harness) -> bool {
+ h.ctx.memory(|m| m.focused()) == Some(crate::sketch_dims::box_id(0))
+}
+
+/// The one-click tools show their Length box at once, but it takes the keyboard only for a digit:
+/// a letter still reaches the shortcuts (#10258).
+#[test]
+fn a_waiting_length_box_leaves_letters_to_the_shortcuts_and_takes_a_digit() {
+ for id in ["sketch.construction_line.horizontal", "sketch.construction_line.parallel"] {
+ let mut h = sketch();
+ steps(&mut h, id, &[]);
+ h.step(&json!({"move":{"sketch":[5,10]}})).unwrap();
+ h.settle();
+ let tool = h.app.tool.as_ref().unwrap();
+ assert_eq!(tool.dims.iter().map(|b| (b.label, b.value.as_str(), b.locked)).collect::<Vec<_>>(), [("Length", "\u{221e}", false)], "{id}");
+ assert!(!length_box_focused(&h), "{id}: no keyboard before a digit");
+ h.step(&json!({"key":"L"})).unwrap();
+ h.settle();
+ assert_eq!(h.app.tool.as_ref().map(|t| t.cmd), Some("sketch.line"), "{id}: L still starts a line");
+
+ let mut h = sketch();
+ steps(&mut h, id, &[]);
+ h.step(&json!({"move":{"sketch":[5,10]}})).unwrap();
+ h.settle();
+ digit(&mut h, '2');
+ digit(&mut h, '5');
+ h.frames(2);
+ assert!(length_box_focused(&h), "{id}: a digit gives the box the keyboard");
+ let b = &h.app.tool.as_ref().unwrap().dims[0];
+ assert_eq!((b.value.as_str(), b.locked), ("25", true), "{id}");
+ assert_eq!(h.app.tool.as_ref().map(|t| t.cmd), Some(id), "{id}: digits are not shortcuts");
+ }
+}
+
+/// With a length the tool takes two clicks: the start, then the side the segment runs to. The
+/// segment keeps its start's snap and gets the length as a dimension.
+#[test]
+fn a_typed_length_makes_two_clicks_draw_a_dimensioned_segment() {
+ let cases: &[(&str, &[[f64; 2]], [f64; 2], [f64; 2])] = &[
+ ("sketch.construction_line.horizontal", &[], [20., 0.], [6., 5.]),
+ ("sketch.construction_line.vertical", &[], [20., 0.], [23., -9.]),
+ ("sketch.construction_line.parallel", &[[10., 0.]], [0., 20.], [-10., 24.]),
+ ("sketch.construction_line.perpendicular", &[[10., 0.]], [0., 20.], [-4., 30.]),
+ ];
+ for (id, picks, start, side) in cases {
+ let mut h = sketch();
+ let sid = h.app.session.active_sketch.unwrap();
+ let before = h.app.session.doc.sketch(sid).unwrap().curves.len();
+ steps(&mut h, id, picks);
+ h.step(&json!({"move":{"sketch":start}})).unwrap();
+ h.settle();
+ digit(&mut h, '8');
+ // Apart from the reference pick, so the two clicks are not one double click.
+ h.frames(30);
+ h.step(&json!({"click":{"sketch":start}})).unwrap();
+ h.settle();
+ assert_eq!(h.app.session.doc.sketch(sid).unwrap().curves.len(), before, "{id}: the first click only sets the start");
+ assert_eq!(h.app.tool.as_ref().unwrap().dims[0].value, "8", "{id}: the length stays typed");
+ // A hand moves there first: the box steps out of the way, behind the start.
+ h.step(&json!({"move":{"sketch":side}})).unwrap();
+ h.settle();
+ h.step(&json!({"click":{"sketch":side}})).unwrap();
+ h.settle();
+ let sk = h.app.session.doc.sketch(sid).unwrap();
+ assert_eq!(sk.curves.len(), before + 1, "{id}: {:?}", h.app.status);
+ let curve = sk.curves.last().unwrap();
+ assert!(!curve.infinite && curve.construction, "{id}: {curve:?}");
+ let CurveKind::Line { a, b } = curve.kind else { panic!("{id}: a line") };
+ let (a, b) = (sk.point(a).unwrap(), sk.point(b).unwrap());
+ assert!(a.dist(solidcraft_engine::geom::Vec2::new(start[0], start[1])) < 1e-6, "{id}: starts at the snapped point {a:?}");
+ assert!((a.dist(b) - 8.0).abs() < 1e-6, "{id}: {a:?} {b:?}");
+ let s = solidcraft_engine::geom::Vec2::new(side[0], side[1]);
+ assert!((b - a).dot(s - a) > 0.0, "{id}: runs towards the side clicked");
+ assert!(sk.constraints.iter().any(|c| matches!(c.kind, solidcraft_engine::sketch::ConstraintKind::Length { .. })), "{id}");
+ let tool = h.app.tool.as_ref().unwrap();
+ assert!(tool.pts.is_empty() && tool.dims.iter().all(|b| !b.locked), "{id}: ready for the next line");
+ }
+}
+
+/// The angle tool has a Length box beside Angle; Tab reaches it and Enter places the segment.
+#[test]
+fn the_angle_tool_takes_a_length_beside_its_angle() {
+ let mut h = sketch();
+ steps(&mut h, "sketch.construction_line.angle", &[[5., 10.]]);
+ h.step(&json!({"move":{"sketch":[15,20]}})).unwrap();
+ h.settle();
+ assert_eq!(h.app.tool.as_ref().unwrap().dims.iter().map(|b| b.label).collect::<Vec<_>>(), ["Angle", "Length"]);
+ h.step(&json!({"key":"A","cmd":true})).unwrap();
+ h.step(&json!({"text":"30 deg"})).unwrap();
+ h.step(&json!({"key":"Tab"})).unwrap();
+ h.step(&json!({"text":"12"})).unwrap();
+ h.step(&json!({"key":"Enter"})).unwrap();
+ h.settle();
+ let sid = h.app.session.active_sketch.unwrap();
+ let sk = h.app.session.doc.sketch(sid).unwrap();
+ let curve = sk.curves.last().unwrap();
+ assert!(!curve.infinite && curve.construction, "{curve:?}");
+ let CurveKind::Line { a, b } = curve.kind else { panic!("line") };
+ let d = sk.point(b).unwrap() - sk.point(a).unwrap();
+ assert!((d.len() - 12.0).abs() < 1e-6 && (d.angle().to_degrees() - 30.0).abs() < 1e-6, "{d:?}");
+}
+
+fn click_switch(h: &mut Harness, which: &str) {
+ let at = crate::scenario::handle_at(&format!("construction_switch:{which}")).expect("the Construction/Normal switch");
+ h.call("ui.click", json!({"x": at.x, "y": at.y}));
+ h.settle();
+}
+
+/// The Construction/Normal switch is greyed out while the line is infinite; with a length, Normal
+/// makes the segment a normal sketch line. The Sketch Palette's line type is left alone (#10258).
+#[test]
+fn the_normal_switch_needs_a_length_and_draws_a_normal_line() {
+ let mut h = sketch();
+ crate::sketch_palette::set_mode(&mut h.app, 1);
+ let sid = h.app.session.active_sketch.unwrap();
+ let before = h.app.session.doc.sketch(sid).unwrap().curves.len();
+ steps(&mut h, "sketch.construction_line.horizontal", &[]);
+ h.step(&json!({"move":{"sketch":[20,0]}})).unwrap();
+ h.settle();
+ click_switch(&mut h, "normal");
+ assert!(!h.app.tool.as_ref().unwrap().normal, "an infinite line stays construction");
+
+ h.step(&json!({"move":{"sketch":[20,0]}})).unwrap();
+ h.settle();
+ digit(&mut h, '8');
+ h.frames(2);
+ click_switch(&mut h, "normal");
+ assert!(h.app.tool.as_ref().unwrap().normal, "with a length the switch works");
+ assert!(h.app.tool.as_ref().unwrap().pts.is_empty(), "a click on the switch places no point");
+ assert_eq!(h.app.tool.as_ref().unwrap().dims[0].value, "8");
+
+ h.step(&json!({"move":{"sketch":[20,0]}})).unwrap();
+ h.settle();
+ h.frames(30);
+ h.step(&json!({"click":{"sketch":[20,0]}})).unwrap();
+ h.settle();
+ h.step(&json!({"move":{"sketch":[6,5]}})).unwrap();
+ h.settle();
+ h.step(&json!({"click":{"sketch":[6,5]}})).unwrap();
+ h.settle();
+ let sk = h.app.session.doc.sketch(sid).unwrap();
+ assert_eq!(sk.curves.len(), before + 1, "{:?}", h.app.status);
+ let curve = sk.curves.last().unwrap();
+ assert!(!curve.construction && !curve.infinite && !curve.centerline, "{curve:?}");
+ let CurveKind::Line { a, b } = curve.kind else { panic!("a line") };
+ assert!((sk.point(a).unwrap().dist(sk.point(b).unwrap()) - 8.0).abs() < 1e-6);
+ assert_eq!(crate::sketch_palette::mode(&h.app), 1, "the palette's line type is untouched");
+
+ // Without a length the next line is infinite construction again, whatever the switch says.
+ h.frames(30);
+ h.step(&json!({"click":{"sketch":[5,10]}})).unwrap();
+ h.settle();
+ let sk = h.app.session.doc.sketch(sid).unwrap();
+ let curve = sk.curves.last().unwrap();
+ assert!(curve.construction && curve.infinite, "{curve:?}");
+}
diff --git a/crates/ui-egui/src/sketch_dims.rs b/crates/ui-egui/src/sketch_dims.rs
index 84d90d1683..a846e5014f 100644
--- a/crates/ui-egui/src/sketch_dims.rs
+++ b/crates/ui-egui/src/sketch_dims.rs
@@ -17,6 +17,9 @@ use crate::theme::Tokens;
use crate::tools::Tool;
use crate::viewport::Proj;
+/// What an untyped construction line Length box shows: the line stays infinite.
+const INFINITE: &str = "\u{221e}";
+
/// One value box.
#[derive(Clone, Debug)]
pub struct DimBox {
@@ -39,7 +42,15 @@ pub fn boxes_for(cmd: &str, n: usize) -> Vec<DimBox> {
use ValueKind::*;
let b = DimBox::new;
match (cmd, n) {
- ("sketch.construction_line.angle", 1) => vec![b("Angle", Angle)],
+ // Length boxes start empty: an empty box keeps the infinite line (#10258).
+ ("sketch.construction_line.angle", 1) => vec![b("Angle", Angle), b("Length", Length)],
+ (
+ "sketch.construction_line.horizontal"
+ | "sketch.construction_line.vertical"
+ | "sketch.construction_line.parallel"
+ | "sketch.construction_line.perpendicular",
+ 0 | 1,
+ ) => vec![b("Length", Length)],
("sketch.line" | "sketch.line.midpoint", n) if n >= 1 => vec![b("Length", Length), b("Angle", Angle)],
("sketch.rectangle.two_point" | "sketch.rectangle.center", 1) => vec![b("Width", Length), b("Height", Length)],
("sketch.rectangle.rounded", 1) => vec![b("Width", Length), b("Height", Length), b("Radius", Length)],
@@ -76,7 +87,7 @@ fn eval(doc: &Document, text: &str, kind: ValueKind) -> solidcraft_engine::doc::
/// parameter (sent with the shape); sides and rho are counts and shape factors.
fn is_dimension(t: &Tool, label: &str) -> bool {
if solidcraft_engine::cmd::construction_line_mode(t.cmd).is_some() {
- return t.cmd == "sketch.construction_line.angle" && label == "Angle";
+ return (t.cmd == "sketch.construction_line.angle" && label == "Angle") || label == "Length";
}
!matches!(label, "Sides" | "Rho") && !(t.cmd == "sketch.rectangle.rounded" && label == "Radius")
}
@@ -161,8 +172,9 @@ pub fn effective(app: &SolveApp, t: &Tool, h: Vec2) -> Vec2 {
/// sketch geometry stays there, and one on a curve slides along it to where the axis crosses.
pub fn placed(app: &SolveApp, t: &Tool, p: &(Vec2, Option<String>)) -> (Vec2, Option<String>) {
let line = t.cmd == "sketch.line";
- // A typed length or angle wins over every snap.
- if t.dims.iter().any(|b| b.locked) {
+ // A typed length or angle wins over every snap. A construction line's length leaves its
+ // start where it snapped: the length runs from there.
+ if t.dims.iter().any(|b| b.locked && !construction_length(t, b)) {
return (effective(app, t, p.0), None);
}
// A line snapped through a circle's centre stays on that radial line. The axis snap would
@@ -183,6 +195,16 @@ pub fn placed(app: &SolveApp, t: &Tool, p: &(Vec2, Option<String>)) -> (Vec2, Op
p.clone()
}
+/// The Length box of a construction line tool, which is empty for an infinite line.
+fn construction_length(t: &Tool, b: &DimBox) -> bool {
+ b.label == "Length" && solidcraft_engine::cmd::construction_line_mode(t.cmd).is_some()
+}
+
+/// The id of the `i`th value box of the tool being drawn.
+pub(crate) fn box_id(i: usize) -> egui::Id {
+ egui::Id::new(("sc_dim", i))
+}
+
/// Where the preview and the value boxes put the tool's next point for the hover `p`: for a
/// line, exactly what a click places.
pub fn shown(app: &SolveApp, t: &Tool, p: &(Vec2, Option<String>)) -> Vec2 {
@@ -253,11 +275,25 @@ fn line_boxes(a: Vec2, e: Vec2, px: f64, off: f64) -> Vec<(f64, Vec2)> {
/// `px` is the size of a screen pixel in sketch units: boxes sit a little off the segment they
/// measure so they don't cover it.
fn live(app: &SolveApp, t: &Tool, e: Vec2, px: f64) -> Vec<(f64, Vec2)> {
+ let off = 20.0 * px;
+ // A one-click construction line's Length box waits beside the pointer before any click.
+ if t.pts.is_empty() && t.dims.first().is_some_and(|b| construction_length(t, b)) {
+ return vec![(0.0, e + Vec2::new(2.5 * off, -1.5 * off))];
+ }
let Some(a) = t.pts.last().map(|p| p.0) else { return Vec::new() };
let first = t.pts.first().map(|p| p.0).unwrap_or(a);
- let off = 20.0 * px;
match (t.cmd, t.pts.len()) {
- ("sketch.construction_line.angle", 1) => vec![((e - a).angle(), (a + e) * 0.5 + dir_or_x(e - a).perp() * off)],
+ // As for a line: the angle near the start, the length at the middle (#10258).
+ ("sketch.construction_line.angle", 1) => line_boxes(a, e, px, off).into_iter().rev().collect(),
+ // Behind the start, away from the pointer: the next click, on the pointer's side, picks
+ // the side the line runs to.
+ (
+ "sketch.construction_line.horizontal"
+ | "sketch.construction_line.vertical"
+ | "sketch.construction_line.parallel"
+ | "sketch.construction_line.perpendicular",
+ 1,
+ ) => vec![(0.0, a - dir_or_x(e - a) * (2.5 * off))],
("sketch.line", _) | ("sketch.slot.center_to_center" | "sketch.slot.overall", 1) => line_boxes(a, e, px, off),
// The midpoint line runs from the end's mirror image through the midpoint to the end,
// so its length is the whole line: twice the distance from the midpoint to the cursor.
@@ -372,9 +408,19 @@ pub fn sync(t: &mut Tool) {
} else if t.pts.len() <= t.dims_stage || t.cmd == "sketch.line" {
t.dim_history.clear();
}
- t.dims = boxes_for(t.cmd, t.pts.len());
+ let before = std::mem::replace(&mut t.dims, boxes_for(t.cmd, t.pts.len()));
+ let construction = solidcraft_engine::cmd::construction_line_mode(t.cmd).is_some();
+ if construction && t.pts.len() == t.dims_stage.saturating_add(1) {
+ // A length typed before the start click is still the line's length after it.
+ for b in &mut t.dims {
+ if let Some(kept) = before.iter().find(|old| old.label == b.label && old.locked) {
+ *b = kept.clone();
+ }
+ }
+ }
t.dims_stage = t.pts.len();
- t.dims_focus = !t.dims.is_empty();
+ // Before the first click, the box waits for a digit: letters stay tool shortcuts.
+ t.dims_focus = !t.dims.is_empty() && !(construction && t.pts.is_empty());
}
}
@@ -420,6 +466,9 @@ pub fn dimensions(t: &Tool) -> Value {
/// Invalid values stay in the current field, so users can correct them before another stage.
pub fn validate(app: &SolveApp, t: &Tool) -> Result<(), String> {
for dimension in t.dim_history.iter().chain(&t.dims).filter(|dimension| dimension.locked) {
+ if construction_length(t, dimension) && dimension.value.trim().is_empty() {
+ continue;
+ }
if dimension.value.len() > 4096 {
return Err(format!("{} expression is too long", dimension.label));
}
@@ -508,6 +557,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui, proj: &Proj) {
let Some(mut t) = app.tool.take() else { return };
sync(&mut t);
let place = if t.dims.is_empty() { None } else { boxes(app, ui, proj, &mut t) };
+ crate::sketch_construction::line_type_switch(ui, &mut t);
app.tool = Some(t);
if let Some(p) = place {
crate::tools::place(app, (p, None));
@@ -553,9 +603,11 @@ fn boxes(app: &SolveApp, ui: &mut egui::Ui, proj: &Proj, t: &mut Tool) -> Option
let mut any_focused = false;
let view = app.viewport.layout.as_ref().map(|l| l.drawable).filter(|r| r.is_finite() && r.is_positive());
let field_frame = Container::popup_frame(ui.style()).inner_margin(egui::Margin::symmetric(tk.space_3 as i8, 1));
+ let construction = solidcraft_engine::cmd::construction_line_mode(t.cmd).is_some();
for (b, (v, _)) in t.dims.iter_mut().zip(&lv) {
if !b.locked {
- b.value = fmt(app, b.label, b.kind, *v);
+ // A construction line's untyped length is infinite, whatever the pointer does.
+ b.value = if construction && b.label == "Length" { INFINITE.to_owned() } else { fmt(app, b.label, b.kind, *v) };
}
}
// Polygon values used to sit inside the radius, so both boxes covered a small polygon
@@ -630,7 +682,8 @@ fn boxes(app: &SolveApp, ui: &mut egui::Ui, proj: &Proj, t: &mut Tool) -> Option
ui.ctx().memory_mut(|memory| memory.request_focus(id));
}
let enter = ui.input(|i| i.key_pressed(egui::Key::Enter));
- let nothing = ui.ctx().memory(|m| m.focused().is_none());
+ // A box waiting before the first click only places on Enter once it has the keyboard.
+ let nothing = ui.ctx().memory(|m| m.focused().is_none()) && !(construction && t.pts.is_empty());
(enter && (any_focused || nothing)).then_some(e)
}
diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs
index b7c4b79264..b8378aba51 100644
--- a/crates/ui-egui/src/sketch_tools.rs
+++ b/crates/ui-egui/src/sketch_tools.rs
@@ -777,6 +777,7 @@ pub fn tool_for(id: &str) -> Option<Tool> {
arc_turn: 0.0,
lined: Vec::new(),
chain: Default::default(),
+ normal: false,
})
}
diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs
index 56b99357f5..fa8254e0f7 100644
--- a/crates/ui-egui/src/tools.rs
+++ b/crates/ui-egui/src/tools.rs
@@ -100,6 +100,9 @@ pub struct Tool {
/// The Line tool's chain, which a rest on its last point switches to tangent arcs and back
/// (#9489).
pub chain: crate::sketch_line_arc::LineChain,
+ /// The construction line tools' Construction/Normal switch (#10258): a segment with a length
+ /// becomes a normal sketch line. Each start of a tool begins at Construction.
+ pub normal: bool,
}
impl Tool {
@@ -153,6 +156,7 @@ impl Tool {
arc_turn: 0.0,
lined: Vec::new(),
chain: Default::default(),
+ normal: false,
})
}
}
diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md
index db87eeedd0..8fed36e2d0 100644
--- a/docs/book/src/guide/sketching.md
+++ b/docs/book/src/guide/sketching.md
@@ -132,9 +132,19 @@ Parallel and perpendicular lines ask for a straight sketch line, then a point;
the reference stays picked so you can place several lines. Right-click clears the current
points and references; Escape ends the tool.
+The horizontal, vertical, parallel and perpendicular tools show a **Length** box beside the
+pointer, which stays empty (infinite) until you type a digit: letters still start other tools.
+With a length, the first click sets the start and a second click the side the segment runs to;
+the angle tool has the Length box beside its Angle box. The segment gets a length dimension
+that follows the typed expression. An empty box keeps the infinite line. The
+**Construction | Normal** switch under the Length box makes such a segment a normal sketch line,
+ready to close a profile; it starts at Construction, is greyed out while the line is infinite
+(an infinite line is always construction), and leaves the Sketch Palette's line type alone.
+
A command call can cut a horizontal, vertical, angle, parallel or perpendicular construction
line to a length instead: `length` makes a segment from the point `at`, running towards `near`,
-and adds a length dimension that follows its expression (#10258).
+and adds a length dimension that follows its expression (#10258). With `construction: false` that
+segment is a normal sketch line, ready to close a profile.
Tangents through an external point take a circle or circular arc, the external point, and a
click choosing the desired preview. A common tangent takes two circles/arcs and a click choosing