Skip to content

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

Feature windows choose Join, New Body or Cut from what the material touches (#6901) (#6903)

froglemonade202ac56d12f72
diff --git a/assets/locales/pending/auto-join-new-cut.json b/assets/locales/pending/auto-join-new-cut.json
new file mode 100644
index 0000000000..205a393dcd
--- /dev/null
+++ b/assets/locales/pending/auto-join-new-cut.json
@@ -0,0 +1,37 @@
+{
+ "en": {
+ "dialog.no_shown_body": "No shown body to change: show one, or choose New Body",
+ "prefs.auto_operation": "Choose the operation automatically",
+ "prefs.auto_operation_note": "Feature windows pick Join, New Body or Cut from what the new material touches, until you pick one. Off: they keep the operation they open with."
+ },
+ "ar": {
+ "dialog.no_shown_body": "لا يوجد جسم ظاهر لتغييره: أظهر جسمًا، أو اختر «جسم جديد»",
+ "prefs.auto_operation": "اختيار العملية تلقائيًا",
+ "prefs.auto_operation_note": "تختار نوافذ الميزات «ضم» أو «جسم جديد» أو «قص» بحسب ما تلامسه المادة الجديدة، إلى أن تختار عملية بنفسك. عند الإيقاف: تحتفظ بالعملية التي تُفتح بها."
+ },
+ "he": {
+ "dialog.no_shown_body": "אין גוף מוצג לשינוי: הציגו גוף, או בחרו „גוף חדש”",
+ "prefs.auto_operation": "בחירת הפעולה באופן אוטומטי",
+ "prefs.auto_operation_note": "חלונות הפיצ'רים בוחרים „איחוד”, „גוף חדש” או „הסרה” לפי מה שהחומר החדש נוגע בו, עד שתבחרו פעולה בעצמכם. כבוי: הם שומרים על הפעולה שאיתה נפתחו."
+ },
+ "ja": {
+ "dialog.no_shown_body": "変更できる表示中のボディがありません。ボディを表示するか、新規ボディを選択してください",
+ "prefs.auto_operation": "操作を自動で選択",
+ "prefs.auto_operation_note": "フィーチャーのウィンドウは、新しい形状が何に接するかから結合・新規ボディ・切り取りを選びます(手動で選ぶまで)。オフ:開いたときの操作のままです。"
+ },
+ "tr": {
+ "dialog.no_shown_body": "Değiştirilecek görünür gövde yok: bir gövdeyi gösterin ya da Yeni gövde seçin",
+ "prefs.auto_operation": "İşlemi otomatik seç",
+ "prefs.auto_operation_note": "Özellik pencereleri, yeni malzemenin neye değdiğine göre Birleştir, Yeni gövde ya da Kes işlemini seçer; siz bir işlem seçene kadar. Kapalıyken açıldıkları işlemi korurlar."
+ },
+ "vi": {
+ "dialog.no_shown_body": "Không có thân khối đang hiển thị để thay đổi: hãy hiển thị một thân khối, hoặc chọn “Tạo mới Thân khối”",
+ "prefs.auto_operation": "Tự động chọn thao tác",
+ "prefs.auto_operation_note": "Cửa sổ tính năng chọn “Nối liền”, “Tạo mới Thân khối” hoặc “Cắt” theo những gì vật liệu mới chạm vào, cho đến khi bạn tự chọn. Tắt: cửa sổ giữ nguyên thao tác lúc mở."
+ },
+ "zh": {
+ "dialog.no_shown_body": "没有可更改的显示实体:请显示一个实体,或选择新建实体",
+ "prefs.auto_operation": "自动选择操作",
+ "prefs.auto_operation_note": "特征窗口根据新材料接触的对象选择连接、新建实体或剪切,直到您手动选择。关闭:保持窗口打开时的操作。"
+ }
+}
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index 620ac01f27..51ec6b3597 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -2721,10 +2721,22 @@ fn note_join_apart(before: &ModelState, after: &ModelState, f: &Feature, warning
if operation != Operation::Join {
return;
}
+ for (name, n) in join_pieces_added(before, after) {
+ append_warning(
+ warning,
+ format!("the joined piece doesn't touch `{name}`, so `{name}` is now in {n} separate pieces (New Body makes it a body of its own)"),
+ );
+ }
+}
+
+/// The bodies a Join from `before` to `after` left in more separate pieces than it found, with
+/// their piece counts now: empty when the joined material made one body with what it touched
+/// (or bridged pieces). A lid closing a cavity adds a void, not a piece.
+pub fn join_pieces_added(before: &ModelState, after: &ModelState) -> Vec<(String, usize)> {
let pieces = |b: &Body| b.lumps().map_or(1, |l| l.len());
// Pieces of the bodies the join changed or absorbed before it, and of those it kept after.
let (mut had, mut have) = (0usize, 0usize);
- let mut grown: Vec<(&str, usize)> = Vec::new();
+ let mut grown: Vec<(String, usize)> = Vec::new();
for was in &before.bodies {
match after.body(&was.name) {
Some(now) if now.body.same_shape(&was.body) => {}
@@ -2733,21 +2745,13 @@ fn note_join_apart(before: &ModelState, after: &ModelState, f: &Feature, warning
had += old;
have += new;
if new > old {
- grown.push((now.name.as_str(), new));
+ grown.push((now.name.clone(), new));
}
}
None => had += pieces(&was.body),
}
}
- if have <= had {
- return;
- }
- for (name, n) in grown {
- append_warning(
- warning,
- format!("the joined piece doesn't touch `{name}`, so `{name}` is now in {n} separate pieces (New Body makes it a body of its own)"),
- );
- }
+ if have <= had { Vec::new() } else { grown }
}
/// Add tool bodies to the model according to the operation.
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 9a5920d312..0139ba2245 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -77,10 +77,10 @@ pub use assembly::{
pub use document::*;
pub use eval::{
EdgeRef, FeatureResult, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SavedModel, SolvedSketch, ThreadInfo, curve_pick_error,
- edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, map_wire, metric_thread_sizes,
- object_height, parse_metric_thread, pattern_matrices, revolve_extent, revolve_extent_with_convention, select_profiles, sketch_hole_direction,
- sketch_line_plane, state_in_frame, state_in_frame_at, suggested_thread, tangent_face_chain, through_all_distance, world_state,
- world_state_reusing,
+ edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, join_pieces_added, map_wire,
+ metric_thread_sizes, object_height, parse_metric_thread, pattern_matrices, revolve_extent, revolve_extent_with_convention, select_profiles,
+ sketch_hole_direction, sketch_line_plane, state_in_frame, state_in_frame_at, suggested_thread, tangent_face_chain, through_all_distance,
+ world_state, world_state_reusing,
};
pub use eval::{EvalCache, KeptResults};
pub use expr::Expr;
diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs
index 8e8fcee82e..c82fe78521 100644
--- a/crates/engine/src/cmd/features.rs
+++ b/crates/engine/src/cmd/features.rs
@@ -880,7 +880,8 @@ fn extrude(s: &mut Session, p: &Value) -> Result<Value> {
p.to_mut()["participants"] = json!(parts);
}
if matches!(operation, Operation::Cut | Operation::Intersect) && targets.is_empty() && string_list(cmd, &p, "participants")?.is_empty() {
- targets = shown_scope(s);
+ // With every body hidden, every body, as before.
+ targets = shown_scope(s).unwrap_or_default();
}
let kind = FeatureKind::Extrude {
sketch: SketchId(sketch),
@@ -1026,17 +1027,6 @@ fn face_body_reached(s: &Session, sketch: u64) -> Result<Option<String>> {
Ok(Some(body.name.clone()))
}
-/// A cut or intersect that names no bodies leaves hidden bodies alone, as hiding a body to keep
-/// it out of a cut is the usual way to (#3961): while some of the active component's bodies
-/// are hidden, its shown ones, stored as the feature's targets so showing the others again
-/// later changes nothing. Empty (every body, as before) when none is hidden, or all are.
-fn shown_scope(s: &Session) -> Vec<String> {
- let st = s.model.state();
- let scope = active_scope(s, &st);
- let shown: Vec<String> = scope.iter().filter(|b| s.body_visible(&b.name)).map(|b| b.name.clone()).collect();
- if shown.len() == scope.len() { Vec::new() } else { shown }
-}
-
/// The body whose face `sketch` is attached to (on the face itself, not offset from it), when
/// it is one the active component works on ([`active_scope`]).
fn sketch_face_body(s: &Session, sketch: u64) -> Option<String> {
@@ -1064,6 +1054,19 @@ fn face_join_targets(s: &Session, p: &Value, operation: Operation, sketches: &[u
Ok(targets.into_iter().map(BodyName).collect())
}
+/// The bodies a Join, Cut or Intersect that names none may change, less the hidden ones, when
+/// some of them are hidden: stored as the feature's `targets`, so a hidden body is left alone
+/// (#3961, #6901) and showing it again later doesn't change the model. None when every one is
+/// shown; empty when none is.
+pub fn shown_scope(s: &Session) -> Option<Vec<String>> {
+ let st = s.model.state();
+ let scope = active_scope(s, &st);
+ if scope.iter().all(|b| s.body_visible(&b.name)) {
+ return None;
+ }
+ Some(scope.into_iter().filter(|b| s.body_visible(&b.name)).map(|b| b.name.clone()).collect())
+}
+
/// The bodies a feature of the active component works on when it names none: the component's
/// own. A component with no body of its own (the root of an opened STEP assembly, whose parts
/// are components inside it) works on the bodies of the components inside it whose geometry is
diff --git a/crates/engine/src/cmd/join_pieces.rs b/crates/engine/src/cmd/join_pieces.rs
new file mode 100644
index 0000000000..ab773f6fef
--- /dev/null
+++ b/crates/engine/src/cmd/join_pieces.rs
@@ -0,0 +1,125 @@
+//! What a feature's material does when it is joined: the test the feature windows use to choose
+//! Join, New Body or Cut by themselves (#6901). It runs the Join itself, so it agrees with the
+//! result OK makes, and with the warning a Join apart gets (#4434).
+
+use serde_json::Value;
+
+use crate::Session;
+
+/// The most commands a feature window previews at once.
+const MAX_COMMANDS: usize = 64;
+
+/// What a feature's material makes, joined to the bodies it may join.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Addition {
+ /// It would be a separate piece (or there is no body to join): a New Body.
+ Apart,
+ /// It makes one body with what it touches: a Join.
+ Joins,
+ /// It adds no material: it lies inside a body (a Cut, where the window offers one).
+ Inside,
+}
+
+/// What `cmds` (a feature window's commands, with operation New Body or Join) make when run with
+/// Join (see [`crate::Ahead::addition`]).
+pub fn addition(s: &Session, cmds: &[(String, Value)], inside: bool) -> Option<Addition> {
+ s.ahead().addition(cmds, inside).0
+}
+
+impl crate::Ahead {
+ /// What `cmds` (a feature window's commands, with operation New Body or Join) make when run
+ /// with Join, and, when they join, the Join evaluated (OK takes it rather than computing it
+ /// again, [`crate::Session::prime`]). `inside`: tell material lying inside a body
+ /// ([`Addition::Inside`]) from material that joins. None when they have no such operation
+ /// (Combine, a Cut chosen by hand, a feature without one), the model has no body, or the Join
+ /// fails.
+ ///
+ /// Material that touches no body can't be fused to one: that is found from the material alone
+ /// and a contact test, without the Join (a boolean that takes seconds on a large body).
+ pub fn addition(self, cmds: &[(String, Value)], inside: bool) -> (Option<Addition>, Option<crate::Evaluated>) {
+ let s = self.0;
+ let before = s.model.state();
+ if cmds.is_empty() || cmds.len() > MAX_COMMANDS || before.bodies.is_empty() {
+ return (None, None);
+ }
+ let (Some(alone), Some(joined)) = (with_operation(cmds, "new"), with_operation(cmds, "join")) else { return (None, None) };
+ let Ok(tools) = s.preview(&alone) else { return (None, None) };
+ let tools: Vec<&solidcraft_doc::ModelBody> = tools.after.bodies.iter().filter(|b| tools.before.body(&b.name).is_none()).collect();
+ // Every body the Join could take part in (its scope is narrower): none touched, none joined.
+ let named: Vec<String> = joined
+ .iter()
+ .flat_map(|(_, p)| {
+ let p = p.get("params").filter(|_| p.get("command").is_some()).unwrap_or(p);
+ crate::params::string_list_or_default(p, "targets").into_iter().chain(crate::params::string_list_or_default(p, "participants"))
+ })
+ .collect();
+ let candidates: Vec<&solidcraft_doc::ModelBody> = before
+ .bodies
+ .iter()
+ .filter(|b| named.is_empty() || named.iter().any(|n| n == "*" || *n == b.name))
+ .filter(|b| !b.body.is_mesh())
+ .collect();
+ if !tools.is_empty() && !tools.iter().any(|t| candidates.iter().any(|b| t.body.meets(&b.body).unwrap_or(true))) {
+ return (Some(Addition::Apart), None);
+ }
+ let Ok((after, _)) = s.preview_in_place(&joined, None) else { return (None, None) };
+ let state = after.model.state();
+ // A Join with nothing to join makes a new body.
+ if state.bodies.iter().any(|b| before.body(&b.name).is_none()) || !solidcraft_doc::join_pieces_added(&before, &state).is_empty() {
+ return (Some(Addition::Apart), None);
+ }
+ if inside && adds_nothing(&before, &state, &tools) {
+ return (Some(Addition::Inside), None);
+ }
+ after.world_state().warm_display();
+ (Some(Addition::Joins), Some(crate::Evaluated(after.model)))
+ }
+}
+
+/// Whether the Join from `before` to `after` added (next to) no volume: its material lies inside
+/// the bodies. Display meshes are close enough for that, against the material's own volume;
+/// measuring a large body exactly takes seconds.
+fn adds_nothing(before: &solidcraft_doc::ModelState, after: &solidcraft_doc::ModelState, tools: &[&solidcraft_doc::ModelBody]) -> bool {
+ let (mut had, mut have) = (0.0, 0.0);
+ for was in &before.bodies {
+ match after.body(&was.name) {
+ Some(now) if now.body.same_shape(&was.body) => {}
+ Some(now) => {
+ had += mesh_volume(&was.mesh());
+ have += mesh_volume(&now.mesh());
+ }
+ None => had += mesh_volume(&was.mesh()),
+ }
+ }
+ let material: f64 = tools.iter().map(|t| mesh_volume(&t.mesh())).sum();
+ material > 0.0 && (have - had) < material * 0.01
+}
+
+/// The volume a closed mesh encloses.
+fn mesh_volume(m: &solidcraft_geom::Mesh) -> f64 {
+ m.triangles.iter().filter_map(|t| m.tri(t)).map(|[a, b, c]| a.dot(b.cross(c)) / 6.0).sum::<f64>().abs()
+}
+
+/// `cmds` with their New Body or Join operation set to `op`; None when none has one.
+fn with_operation(cmds: &[(String, Value)], op: &str) -> Option<Vec<(String, Value)>> {
+ let mut out = cmds.to_vec();
+ let mut any = false;
+ for (command, p) in &mut out {
+ let inner = p.get("command").and_then(Value::as_str).unwrap_or(command.as_str());
+ if inner == "solid.combine" {
+ return None;
+ }
+ let fields = if p.get("command").is_some() { p.get_mut("params")? } else { p };
+ if let Some(o) = fields.get_mut("operation")
+ && o.as_str().is_some_and(|o| o == "new" || o == "join")
+ {
+ *o = Value::from(op);
+ any = true;
+ }
+ }
+ any.then_some(out)
+}
+
+#[cfg(test)]
+#[path = "join_pieces_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/cmd/join_pieces_tests.rs b/crates/engine/src/cmd/join_pieces_tests.rs
new file mode 100644
index 0000000000..a54ad6179c
--- /dev/null
+++ b/crates/engine/src/cmd/join_pieces_tests.rs
@@ -0,0 +1,176 @@
+//! The Join/New Body test agrees with what the Join makes: one body, or a body in pieces.
+
+use serde_json::{Value, json};
+
+use super::{Addition, addition};
+use crate::Session;
+
+fn run(s: &mut Session, id: &str, params: Value) {
+ if let Err(e) = s.execute(id, &params) {
+ panic!("{id} {params}: {e}");
+ }
+}
+
+/// Sketch `circles` (centre, radius) and `rects` (corners) on a plane at height `z`.
+fn sketch(s: &mut Session, z: f64, name: &str, circles: &[([f64; 2], f64)], rects: &[([f64; 2], [f64; 2])]) {
+ run(s, "sketch.create", json!({"plane": {"origin": [0, 0, z], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "name": name}));
+ for (c, r) in circles {
+ run(s, "sketch.circle.center", json!({"center": c, "radius": r}));
+ }
+ for (p0, p1) in rects {
+ run(s, "sketch.rectangle.two_point", json!({"p0": p0, "p1": p1}));
+ }
+ run(s, "sketch.finish", json!({}));
+}
+
+fn extrude(sketch: &str, point: [f64; 2], distance: f64) -> Vec<(String, Value)> {
+ vec![("solid.extrude".to_string(), json!({"sketch": sketch, "profiles": [{"point": point}], "distance": distance, "operation": "new"}))]
+}
+
+/// The pieces of every body after running `cmds` as a Join for real.
+fn pieces_after_join(s: &Session, cmds: &[(String, Value)]) -> Vec<usize> {
+ let mut t = s.scratch();
+ for (id, p) in cmds {
+ let mut p = p.clone();
+ p["operation"] = json!("join");
+ run(&mut t, id, p);
+ }
+ t.model.state().bodies.iter().map(|b| b.body.lumps().map_or(1, |l| l.len())).collect()
+}
+
+/// The verdict (does the material join?), checked against the Join's own result: one body in one
+/// piece, or not.
+fn verdict(label: &str, s: &Session, cmds: &[(String, Value)]) -> bool {
+ let one = addition(s, cmds, false).unwrap_or_else(|| panic!("{label}: no verdict")) != Addition::Apart;
+ let before: Vec<usize> = s.model.state().bodies.iter().map(|b| b.body.lumps().map_or(1, |l| l.len())).collect();
+ let after = pieces_after_join(s, cmds);
+ // Joined: no new body, and no body in more pieces than before (a bridge leaves fewer).
+ let joined = after.len() == before.len() && after.iter().zip(&before).all(|(a, b)| a <= b);
+ assert_eq!(one, joined, "{label}: verdict {one}, pieces {before:?} -> {after:?}");
+ one
+}
+
+/// A 40 × 40 × 10 block centred on the origin with a 5 mm radius hole through it.
+fn holed_block() -> Session {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 10, "corner": [-20, -20, 0], "body_name": "Base"}));
+ sketch(&mut s, 0.0, "Hole", &[([0.0, 0.0], 5.0)], &[]);
+ run(&mut s, "solid.extrude", json!({"sketch": "Hole", "profiles": [{"point": [0, 0]}], "distance": 10, "operation": "cut"}));
+ s
+}
+
+fn cube() -> Session {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Base"}));
+ s
+}
+
+#[test]
+fn material_on_a_body_away_from_its_centre_joins() {
+ // A ring round a hole: its centre is over the hole, its material on the face.
+ let mut s = holed_block();
+ sketch(&mut s, 10.0, "Ring", &[([0.0, 0.0], 5.0), ([0.0, 0.0], 10.0)], &[]);
+ assert!(verdict("ring round a hole", &s, &extrude("Ring", [7.5, 0.0], 5.0)));
+ // A pin filling the bore: it meets the body only on the bore's round wall.
+ sketch(&mut s, 0.0, "Pin", &[([0.0, 0.0], 5.0)], &[]);
+ assert!(verdict("pin filling the bore", &s, &extrude("Pin", [0.0, 0.0], 10.0)));
+ // A block against a side wall, all of it or half of it, and one standing past an edge.
+ let mut s = cube();
+ sketch(&mut s, 0.0, "Side", &[], &[([10.0, 0.0], [20.0, 10.0]), ([10.0, 15.0], [20.0, 25.0])]);
+ assert!(verdict("block against a side wall", &s, &extrude("Side", [15.0, 5.0], 10.0)));
+ sketch(&mut s, 0.0, "Half", &[], &[([10.0, 5.0], [20.0, 15.0])]);
+ assert!(verdict("block half against a side wall", &s, &extrude("Half", [15.0, 10.0], 5.0)));
+ sketch(&mut s, 10.0, "Ledge", &[], &[([8.0, 0.0], [30.0, 10.0])]);
+ assert!(verdict("block past an edge", &s, &extrude("Ledge", [20.0, 5.0], 5.0)));
+}
+
+#[test]
+fn material_apart_stays_a_new_body() {
+ let mut s = holed_block();
+ // A pin in the bore with room round it: inside the block's box, touching nothing.
+ sketch(&mut s, 0.0, "Thin", &[([0.0, 0.0], 4.0)], &[]);
+ assert!(!verdict("pin clear in the bore", &s, &extrude("Thin", [0.0, 0.0], 10.0)));
+ let mut s = cube();
+ sketch(&mut s, 0.0, "Far", &[], &[([30.0, 0.0], [40.0, 10.0])]);
+ assert!(!verdict("block away from the cube", &s, &extrude("Far", [35.0, 5.0], 10.0)));
+ sketch(&mut s, 0.0, "Gap", &[], &[([10.1, 0.0], [20.0, 10.0])]);
+ assert!(!verdict("block 0.1 mm off a side wall", &s, &extrude("Gap", [15.0, 5.0], 10.0)));
+}
+
+#[test]
+fn hairline_gaps_follow_the_join() {
+ // Material closer than the contact test's tolerance: whatever the Join makes of it, the
+ // verdict says the same (`verdict` checks).
+ let mut s = cube();
+ for (i, gap) in [0.001, 0.01].into_iter().enumerate() {
+ let name = format!("Gap{i}");
+ sketch(&mut s, 0.0, &name, &[], &[([10.0 + gap, 0.0], [20.0, 10.0])]);
+ verdict(&format!("block {gap} mm off a side wall"), &s, &extrude(&name, [15.0, 5.0], 10.0));
+ }
+ let mut s = holed_block();
+ sketch(&mut s, 0.0, "Close", &[([0.0, 0.0], 4.99)], &[]);
+ verdict("pin 0.01 mm clear in the bore", &s, &extrude("Close", [0.0, 0.0], 10.0));
+}
+
+#[test]
+fn a_bridge_between_pieces_joins_them() {
+ // Two pieces of one body (a Join apart, kept with its warning) and a block across them.
+ let mut s = cube();
+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "operation": "join"}));
+ assert_eq!(s.model.state().bodies.len(), 1);
+ sketch(&mut s, 10.0, "Bridge", &[], &[([5.0, 0.0], [25.0, 10.0])]);
+ assert!(verdict("bridge", &s, &extrude("Bridge", [15.0, 5.0], 5.0)));
+}
+
+#[test]
+fn material_inside_a_body_adds_nothing() {
+ let s = cube();
+ let box_at = |corner: [f64; 3], size: f64| {
+ vec![("solid.box".to_string(), json!({"length": size, "width": size, "height": size, "corner": corner, "operation": "new"}))]
+ };
+ assert_eq!(addition(&s, &box_at([2.0, 2.0, 2.0], 4.0), true), Some(Addition::Inside), "a box inside the cube");
+ assert_eq!(addition(&s, &box_at([2.0, 2.0, 6.0], 4.0), true), Some(Addition::Inside), "a box sunk flush with the top");
+ assert_eq!(addition(&s, &box_at([2.0, 2.0, 8.0], 4.0), true), Some(Addition::Joins), "a box standing out of the top");
+ assert_eq!(addition(&s, &box_at([2.0, 2.0, 10.0], 4.0), true), Some(Addition::Joins), "a box on the top");
+ assert_eq!(addition(&s, &box_at([20.0, 2.0, 2.0], 4.0), true), Some(Addition::Apart), "a box apart");
+ // A revolve whose volume sits inside the cube: a ring round its middle, inside its walls.
+ let mut s = cube();
+ run(&mut s, "sketch.create", json!({"plane": {"origin": [0, 5, 0], "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]}, "name": "Section"}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [6, 4], "p1": [7, 6]}));
+ run(&mut s, "sketch.finish", json!({}));
+ let ring = |x: f64| {
+ vec![(
+ "solid.revolve".to_string(),
+ json!({"sketch": "Section", "profiles": [0], "axis": {"origin": [x, 5, 0], "dir": [0, 0, 1]}, "angle": "360 deg", "operation": "new"}),
+ )]
+ };
+ assert_eq!(addition(&s, &ring(5.0), true), Some(Addition::Inside), "a ring inside the cube");
+}
+
+#[test]
+fn no_verdict_without_an_operation_or_a_body() {
+ let s = Session::default();
+ assert_eq!(addition(&s, &[("solid.box".into(), json!({"length": 1, "width": 1, "height": 1, "operation": "new"}))], false), None);
+ let s = cube();
+ assert_eq!(addition(&s, &[("solid.fillet".into(), json!({"edges": [[10, 0, 5]], "radius": 1}))], false), None);
+ assert_eq!(addition(&s, &[("solid.combine".into(), json!({"target": "Base", "tools": [], "operation": "join"}))], false), None);
+ // A cut keeps its operation: nothing to choose.
+ assert_eq!(addition(&s, &[("solid.box".into(), json!({"length": 1, "width": 1, "height": 1, "operation": "cut"}))], false), None);
+ // A primitive placed apart, whichever of New Body and Join it has.
+ let apart = json!({"length": 5, "width": 5, "height": 5, "corner": [20, 0, 0], "operation": "join"});
+ assert_eq!(addition(&s, &[("solid.box".into(), apart)], false), Some(Addition::Apart));
+}
+
+#[test]
+fn hidden_bodies_are_out_of_scope() {
+ let mut s = cube();
+ assert_eq!(crate::shown_scope(&s), None, "all shown: nothing to narrow");
+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [30, 0, 0], "operation": "new", "body_name": "Other"}));
+ run(&mut s, "browser.visibility", json!({"items": ["Base"], "visible": false}));
+ assert_eq!(crate::shown_scope(&s), Some(vec!["Other".to_string()]));
+ // A block on the hidden cube, with the shown bodies as its targets: apart from all of them.
+ let on_hidden = json!({"length": 4, "width": 4, "height": 4, "corner": [2, 2, 10], "operation": "new", "targets": ["Other"]});
+ assert_eq!(addition(&s, &[("solid.box".into(), on_hidden)], false), Some(Addition::Apart));
+ run(&mut s, "browser.visibility", json!({"items": ["Other"], "visible": false}));
+ assert_eq!(crate::shown_scope(&s), Some(Vec::new()), "nothing shown");
+}
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index d0cb77ad8d..b008852534 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -35,10 +35,12 @@ mod edit;
mod face;
mod features;
mod features_more;
+mod join_pieces;
pub(crate) use face::{FaceRefForm, face_ref_form};
pub(crate) use features::profiles as feature_profiles;
pub(crate) use features::{EdgeRefForm, axis_dir_form, edge_ref_form, sketch_key};
-pub use features::{auto_operation, extrude_reach};
+pub use features::{auto_operation, extrude_reach, shown_scope};
+pub use join_pieces::{Addition, addition};
pub use sketch::dimension_roles;
pub use sketch_import::drawing_import_command;
pub use sketch_modify::{extend_arc_preview, extend_preview, trim_piece};
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 10cb19c73b..dbee11f2ac 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -43,7 +43,8 @@ use solidcraft_doc::{Document, Model, ModelState};
use solidcraft_geom::Vec3;
pub use cmd::{
- CommandInfo, CommandSpec, auto_operation, command_specs, dimension_roles, extrude_reach, find_command, resolve_design_links, standard_view,
+ Addition, CommandInfo, CommandSpec, addition, auto_operation, command_specs, dimension_roles, extrude_reach, find_command, resolve_design_links,
+ shown_scope, standard_view,
};
pub use solidcraft_doc as doc;
pub use solidcraft_doc::Visibility;
@@ -1482,6 +1483,8 @@ impl Session {
|| id.starts_with("select.");
steps.push(ComputedCommand { id: id.clone(), params: params.clone(), before, after: computed.doc.clone(), changed, reply });
}
+ // What the source was primed with stays out of the session that is adopted (#6901).
+ computed.unprime();
Ok(ComputedCommands { source: self, computed, steps })
}
diff --git a/crates/ui-egui/src/apply_off_thread_tests.rs b/crates/ui-egui/src/apply_off_thread_tests.rs
index 69fdc37e42..489bf4261c 100644
--- a/crates/ui-egui/src/apply_off_thread_tests.rs
+++ b/crates/ui-egui/src/apply_off_thread_tests.rs
@@ -24,6 +24,12 @@ fn square_on_a_block() -> Harness {
h.app.finish_sketch();
h.app.start("solid.extrude");
h.frames(2);
+ // The window's own operation check would hand OK its Join already evaluated (#6901): these
+ // tests are about OK computing it.
+ if let Some(d) = h.app.dialog.as_mut() {
+ d.op_auto.manual = true;
+ }
+ h.app.op_check = Default::default();
h
}
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 782b0df31b..812816f2ab 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -485,6 +485,8 @@ pub struct Dialog {
/// An extrude Press Pull opened with nothing selected: its first pick may be a curved face or
/// an edge, which reopens Press Pull on it (an offset or a fillet).
pub press_pull: bool,
+ /// The operation the window chooses by itself (#6901).
+ pub op_auto: crate::op_auto::OpAuto,
}
#[derive(Clone, Debug)]
@@ -512,9 +514,15 @@ impl DialogComputation {
if app.file_load.busy() || app.file_picker_busy() {
return Err("a file operation is in progress".into());
}
+ let cmds = apply_commands(app, d)?;
+ let mut session = app.session.scratch();
+ // The window's operation check already evaluated this Join (#6901).
+ if let Some(joined) = app.op_check.joined_for(&cmds, app.session.revision) {
+ session.prime(&joined);
+ }
Ok(Self {
- session: app.session.scratch(),
- cmds: apply_commands(app, d)?,
+ session,
+ cmds,
marker: d.editing.map(|(_, marker)| marker),
editing: d
.editing
@@ -733,6 +741,7 @@ impl Dialog {
other_objects: Vec::new(),
shell_chain: Default::default(),
press_pull: false,
+ op_auto: Default::default(),
}
}
@@ -2730,6 +2739,13 @@ fn auto_operation(app: &SolveApp, d: &mut Dialog) {
{
side = crate::smart_extrude::side(reach, 0);
}
+ // Hidden bodies are out of its scope (#6901).
+ let mut params = params;
+ if let Some(shown) = solidcraft_engine::shown_scope(&app.session)
+ && params.get("participants").is_none()
+ {
+ params["participants"] = json!(shown);
+ }
let Some(fresh) = solidcraft_engine::auto_operation(&app.session, &params).and_then(|op| OPS.iter().position(|o| *o == op)) else {
return;
};
@@ -2809,10 +2825,13 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
let corner = app.viewport.corner.take();
app.viewport.corner_ok = false;
sync_feature_edit_sketch(app);
+ app.op_check.poll();
if app.tree.redefine.is_none() {
app.viewport.dialog_rect = None;
}
let Some(mut d) = app.dialog.take() else {
+ // The window a check was for closed: it stops (#6901).
+ app.op_check.abandon();
return;
};
// Edit Text lasts as long as its text: other design changes leave it open.
@@ -2830,6 +2849,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
}
sync_reach(app, &mut d);
auto_operation(app, &mut d);
+ crate::op_auto::update(app, &mut d, ctx);
d.sync_thread(&app.session);
d.sync_material(&app.session);
update_measure(app, &mut d);
@@ -3104,6 +3124,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
}
}
cancel |= !keep;
+ // A window still choosing its operation applies once its check is in (#6901).
+ let ok = crate::op_auto::hold_ok(&mut d, ok, &mut apply_again, cancel);
if ok && !cancel && app.applying.is_none() {
d.repeat_after_apply = apply_again;
// Edit Text applies its own way: its live changes and OK are one undo step.
@@ -3116,7 +3138,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
app.applying = Some(job);
None
}
- None => Some(run_dialog(app, &d)),
+ None => Some(run_primed(app, &d)),
},
};
match run {
@@ -3620,6 +3642,18 @@ fn section_turns_off(s: &Session, inputs: &[selection::SelInput]) -> bool {
s.section.is_some() && selection::items(inputs, 0).is_empty()
}
+/// Run the dialog's commands on the window thread, taking the Join its operation check already
+/// evaluated for them (#6901).
+fn run_primed(app: &mut SolveApp, d: &Dialog) -> Result<(), String> {
+ let joined = apply_commands(app, d).ok().and_then(|cmds| app.op_check.joined_for(&cmds, app.session.revision));
+ if let Some(joined) = &joined {
+ app.session.prime(joined);
+ }
+ let r = run_dialog(app, d);
+ app.session.unprime();
+ r
+}
+
pub(crate) fn run_dialog(app: &mut SolveApp, d: &Dialog) -> Result<(), String> {
if let Kind::ViewDxf { dashed, tolerance } = &d.kind {
return crate::dialogs_view_dxf::run(app, *dashed, *tolerance);
@@ -3716,6 +3750,7 @@ pub fn apply_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>
crate::length_input::extra(&mut normalized.extra, |e| crate::length_input::expression(&app.session.doc, e, ValueKind::Length));
let mut cmds = dialog_commands(app, &normalized)?;
exact_regions(d, &mut cmds);
+ crate::op_auto::scope_targets(app, d, &mut cmds)?;
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) {
diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs
index b4a0f4a4d6..d77d28ef53 100644
--- a/crates/ui-egui/src/dialogs_dense.rs
+++ b/crates/ui-egui/src/dialogs_dense.rs
@@ -275,14 +275,11 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui:
if two_sided(*direction) {
enter |= expr_row(ui, "Distance 2", distance2);
}
- form_row(ui, "Operation", |ui| {
- let before = *operation;
- combo(ui, "ex_op", &OP_LABELS, operation);
- // A choice made by hand sticks.
- if *operation != before {
- *auto_op = false;
- }
- });
+ // A choice made by hand sticks, the shown one included (#6901): Extrude's own choice
+ // stops before the next frame makes it.
+ if crate::op_auto::op_row(ui, "ex_op", operation) {
+ *auto_op = false;
+ }
ui_kit::section(ui, "extrude_options", "Options", true, |ui| {
let was_thin = *thin;
let was_direction = *direction;
@@ -673,7 +670,7 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo
});
}
}
- choice_row(ui, "Operation", "rv_op", operation, &OP_LABELS);
+ crate::op_auto::op_row(ui, "rv_op", operation);
}
Kind::Shell { thickness } => {
// The direction below says which side the wall grows to; the label stays short enough
@@ -798,12 +795,12 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo
}
}
Kind::Loft { operation, rail_fit } => {
- choice_row(ui, "Operation", "lf_op", operation, &OP_LABELS);
+ crate::op_auto::op_row(ui, "lf_op", operation);
crate::dialogs_sweep::rail_fit_row(ui, "lf", rail_fit);
}
Kind::Sweep { operation, opts } => {
enter |= crate::dialogs_sweep::rows_with(ui, opts, "sw", |ui| {
- choice_row(ui, "Operation", "sw_op", operation, &OP_LABELS);
+ crate::op_auto::op_row(ui, "sw_op", operation);
});
}
k @ Kind::Move { .. } => {
@@ -837,7 +834,7 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo
});
});
}
- choice_row(ui, "Operation", "pr_op", operation, &OP_LABELS);
+ crate::op_auto::op_row(ui, "pr_op", operation);
}
Kind::Combine { operation, keep_tools } => {
form_row(ui, "Operation", |ui| {
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 5b984979f6..848e7e3d4c 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -189,6 +189,7 @@ pub mod navigation_bar;
mod navigation_bar_view;
pub use navigation::WebWheelGestures;
pub mod network_prompt;
+pub mod op_auto;
pub mod open_elsewhere;
pub(crate) mod open_meshing;
pub mod params_dialog;
@@ -521,6 +522,8 @@ pub struct SolveApp {
/// A linked component's design edited in place, with its assembly around it.
pub edit_in_place: edit_in_place::EditInPlace,
pub(crate) pending_feature_edit: Option<feature_edit::PendingFeatureEdit>,
+ /// The open feature window's check of what its material does (#6901).
+ pub op_check: op_auto::OpCheck,
/// A command recomputing the history (the marker moved, undo) computing off the window
/// thread, and those asked for meanwhile ([`deferred`]).
pub deferred: Option<deferred::Deferred>,
@@ -727,6 +730,7 @@ impl SolveApp {
editing_state: None,
edit_in_place: Default::default(),
pending_feature_edit: None,
+ op_check: op_auto::OpCheck::default(),
deferred: None,
deferred_queue: Vec::new(),
start_after_roll: None,
diff --git a/crates/ui-egui/src/op_auto.rs b/crates/ui-egui/src/op_auto.rs
new file mode 100644
index 0000000000..4104720166
--- /dev/null
+++ b/crates/ui-egui/src/op_auto.rs
@@ -0,0 +1,333 @@
+//! The operation a feature window chooses by itself, from what its material does (#6901):
+//!
+//! - New Body when the material, joined, would be a separate piece of the body (or there is no
+//! shown body to join), Join when it makes one body with what it touches, and, for Revolve and
+//! the Box, Cylinder, Sphere and Torus, Cut when it lies inside a body. Extrude keeps its own
+//! Cut ([`crate::smart_extrude`]). Pipe, Thicken and Boundary Fill don't choose.
+//! - What the material does is found by running the Join on a copy of the design, off the window
+//! thread ([`OpCheck`]), so the choice is what OK makes.
+//! - The choice changes only when a finished check says so: no guess in between.
+//! - An operation picked by hand stays for good, whatever a check still running says; OK runs
+//! what the window shows, and while the window still chooses, waits for its check.
+//! - A feature being edited keeps its operation.
+//! - With Preferences › Design › "Choose the operation automatically" off (`auto_operation`), no
+//! window chooses: each keeps the operation it opens with, Extrude its own Join or Cut.
+//! - Only shown bodies take part: when some bodies are hidden, the window names the shown ones as
+//! the feature's `targets` ([`scope_targets`]).
+
+use serde_json::Value;
+use solidcraft_engine::Addition;
+
+use crate::SolveApp;
+use crate::dialogs::{Dialog, Kind, OPS};
+
+/// Operation indices (see [`OPS`]).
+pub const NEW: usize = 0;
+pub const JOIN: usize = 1;
+pub const CUT: usize = 2;
+
+/// A feature window's own choice of operation.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct OpAuto {
+ /// The operation was picked by hand: the window no longer chooses.
+ pub manual: bool,
+ /// The operation this window last chose (one that differs now was picked by hand).
+ set: Option<usize>,
+ /// Extrude: the additive operation the last finished check chose, held while the next runs.
+ held: Option<usize>,
+ /// A check for the current inputs is running.
+ pub pending: bool,
+ /// OK (with Apply's "again") waits for that check.
+ pub ok_waiting: Option<bool>,
+}
+
+/// How a window chooses.
+#[derive(Clone, Copy)]
+struct Rule {
+ /// Extrude: its own rule decides Cut; this one only New Body against Join.
+ extrude: bool,
+ /// Material inside a body is a Cut.
+ cut: bool,
+}
+
+fn rule(kind: &Kind) -> Option<Rule> {
+ match kind {
+ Kind::Extrude { .. } => Some(Rule { extrude: true, cut: false }),
+ Kind::Revolve { .. } => Some(Rule { extrude: false, cut: true }),
+ Kind::Loft { .. } | Kind::Sweep { .. } => Some(Rule { extrude: false, cut: false }),
+ Kind::Primitive { cmd, .. } => Some(Rule { extrude: false, cut: *cmd != "solid.coil" }),
+ _ => None,
+ }
+}
+
+fn operation(kind: &mut Kind) -> Option<&mut usize> {
+ match kind {
+ Kind::Extrude { operation, .. }
+ | Kind::Revolve { operation, .. }
+ | Kind::Loft { operation, .. }
+ | Kind::Sweep { operation, .. }
+ | Kind::Primitive { operation, .. } => Some(operation),
+ _ => None,
+ }
+}
+
+/// What a check found, with the Join it evaluated when the material joins.
+type Found = (Option<Addition>, Option<solidcraft_engine::Evaluated>);
+
+/// The finished checks and the one running, for the open window.
+#[derive(Default)]
+pub struct OpCheck {
+ /// The running check: its key, commands, the design revision it started on, its result.
+ running: Option<(u64, Vec<(String, Value)>, u64, std::sync::mpsc::Receiver<Found>)>,
+ /// What stops the running check's evaluation ([`OpCheck::abandon`]).
+ progress: Option<std::sync::Arc<solidcraft_engine::doc::progress::Progress>>,
+ done: Option<(u64, Option<Addition>)>,
+ /// The Join the last check evaluated, with its commands and the design revision: OK of the
+ /// same commands takes it rather than computing it again.
+ joined: Option<(Vec<(String, Value)>, u64, solidcraft_engine::Evaluated)>,
+}
+
+impl OpCheck {
+ /// A check is running.
+ pub fn busy(&self) -> bool {
+ self.running.is_some()
+ }
+
+ /// The window it was for closed, or no longer chooses: stop its check (at the evaluation's
+ /// next feature) and forget what the checks found, so nothing waits for a window that is gone.
+ pub(crate) fn abandon(&mut self) {
+ if let Some(progress) = self.progress.take() {
+ progress.cancel();
+ }
+ self.running = None;
+ self.done = None;
+ self.joined = None;
+ }
+
+ /// Take in a finished check.
+ pub(crate) fn poll(&mut self) {
+ let Some((key, _, _, rx)) = &self.running else { return };
+ let (result, evaluated) = match rx.try_recv() {
+ Ok(found) => found,
+ Err(std::sync::mpsc::TryRecvError::Empty) => return,
+ Err(std::sync::mpsc::TryRecvError::Disconnected) => (None, None),
+ };
+ self.done = Some((*key, result));
+ self.progress = None;
+ if let Some((_, cmds, revision, _)) = self.running.take() {
+ self.joined = evaluated.map(|e| (cmds, revision, e));
+ }
+ }
+
+ /// The Join a check evaluated for exactly `cmds` at `revision`, for OK.
+ pub(crate) fn joined_for(&self, cmds: &[(String, Value)], revision: u64) -> Option<solidcraft_engine::Evaluated> {
+ self.joined.as_ref().filter(|(c, r, _)| c == cmds && *r == revision).map(|(_, _, e)| e.clone())
+ }
+
+ /// The finished check of `cmds` (`key`), or None while it runs; one is started when none
+ /// runs. A check for older inputs runs to its end first: the latest inputs go next.
+ fn result(
+ &mut self,
+ key: u64,
+ ahead: impl FnOnce() -> solidcraft_engine::Ahead,
+ cmds: Vec<(String, Value)>,
+ revision: u64,
+ inside: bool,
+ ) -> Option<Option<Addition>> {
+ if let Some((k, result)) = self.done
+ && k == key
+ {
+ return Some(result);
+ }
+ if self.running.is_none() {
+ self.start(key, ahead(), cmds, revision, inside);
+ }
+ self.done.filter(|(k, _)| *k == key).map(|(_, r)| r)
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ fn start(&mut self, key: u64, ahead: solidcraft_engine::Ahead, cmds: Vec<(String, Value)>, revision: u64, inside: bool) {
+ let (tx, rx) = std::sync::mpsc::channel();
+ let job = cmds.clone();
+ let progress = std::sync::Arc::new(solidcraft_engine::doc::progress::Progress::default());
+ let watching = progress.clone();
+ let spawned = std::thread::Builder::new().name("operation check".into()).spawn(move || {
+ let found = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ solidcraft_engine::doc::progress::watch(watching, || ahead.addition(&job, inside))
+ }))
+ .unwrap_or((None, None));
+ let _ = tx.send(found);
+ });
+ match spawned {
+ Ok(_) => {
+ self.running = Some((key, cmds, revision, rx));
+ self.progress = Some(progress);
+ }
+ Err(_) => self.done = Some((key, None)),
+ }
+ }
+
+ /// No threads on the web: check right away.
+ #[cfg(target_arch = "wasm32")]
+ fn start(&mut self, key: u64, ahead: solidcraft_engine::Ahead, cmds: Vec<(String, Value)>, revision: u64, inside: bool) {
+ let (result, evaluated) = ahead.addition(&cmds, inside);
+ self.done = Some((key, result));
+ self.joined = evaluated.map(|e| (cmds, revision, e));
+ }
+}
+
+/// The window's commands as the check runs them (New Body, Join or a Cut this window chose all
+/// run as a Join), with what tells them from other inputs.
+fn check_commands(cmds: &[(String, Value)], revision: u64) -> (Vec<(String, Value)>, u64) {
+ let mut out = cmds.to_vec();
+ for (_, p) in &mut out {
+ if let Some(op) = p.get_mut("operation")
+ && op.as_str().is_some_and(|o| matches!(o, "new" | "join" | "cut"))
+ {
+ *op = Value::from("join");
+ }
+ }
+ use std::hash::{Hash, Hasher};
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ serde_json::to_string(&out).unwrap_or_default().hash(&mut h);
+ revision.hash(&mut h);
+ (out, h.finish())
+}
+
+/// Bring the window's operation in step with its material (once per frame, after Extrude's own
+/// choice and before the window is drawn).
+pub fn update(app: &mut SolveApp, d: &mut Dialog, ctx: &egui::Context) {
+ d.op_auto.pending = false;
+ // A check still running is taken in whatever the window does now, so it never looks busy.
+ app.op_check.poll();
+ let picked = ctx.data_mut(|m| m.remove_temp::<bool>(picked_id())).unwrap_or(false);
+ // A window that doesn't choose (or no longer does) has no check running for it.
+ let Some(rule) = rule(&d.kind) else {
+ app.op_check.abandon();
+ return;
+ };
+ // Turned off in Preferences › Design: the window keeps its operation, as before.
+ if d.editing.is_some() || !app.preferences.auto_operation {
+ app.op_check.abandon();
+ return;
+ }
+ let Some(op) = operation(&mut d.kind).map(|op| *op) else { return };
+ let changed = if rule.extrude { !matches!(d.kind, Kind::Extrude { auto_op: true, .. }) } else { d.op_auto.set.is_some_and(|set| set != op) };
+ if picked || changed {
+ d.op_auto.manual = true;
+ // Extrude's own choice stops too.
+ if let Kind::Extrude { auto_op, .. } = &mut d.kind {
+ *auto_op = false;
+ }
+ }
+ if d.op_auto.manual {
+ return;
+ }
+ // Extrude cuts into a body by its own rule; this one doesn't undo that.
+ if rule.extrude && op == CUT {
+ d.op_auto.set = Some(op);
+ return;
+ }
+ // No shown body to join: nothing to check.
+ if solidcraft_engine::shown_scope(&app.session).is_some_and(|shown| shown.is_empty()) {
+ if let Some(slot) = operation(&mut d.kind) {
+ *slot = NEW;
+ }
+ d.op_auto.set = Some(NEW);
+ d.op_auto.held = Some(NEW);
+ return;
+ }
+ let Ok(cmds) = crate::dialogs::apply_commands(app, d) else {
+ d.op_auto.set = Some(op);
+ return;
+ };
+ let (cmds, key) = check_commands(&cmds, app.session.revision);
+ let session = &app.session;
+ let found = app.op_check.result(key, || session.ahead(), cmds, session.revision, rule.cut);
+ let chosen = match found {
+ Some(Some(Addition::Apart)) => Some(NEW),
+ Some(Some(Addition::Joins)) => Some(JOIN),
+ Some(Some(Addition::Inside)) if rule.cut => Some(CUT),
+ // Extrude goes into material only by its own rule.
+ Some(Some(Addition::Inside)) => Some(JOIN),
+ // No check to go by (no body, a Join that fails): the operation stays.
+ Some(None) => None,
+ None => {
+ d.op_auto.pending = true;
+ // Extrude's own choice comes back every frame: hold the last finished one.
+ if rule.extrude { d.op_auto.held } else { None }
+ }
+ };
+ let now = chosen.unwrap_or(op);
+ if rule.extrude && found.is_some() {
+ d.op_auto.held = chosen;
+ }
+ if let Some(slot) = operation(&mut d.kind) {
+ *slot = now;
+ }
+ d.op_auto.set = Some(now);
+}
+
+/// Where a pick in an Operation row is noted for the next [`update`].
+pub(crate) fn picked_id() -> egui::Id {
+ egui::Id::new("op_auto_picked")
+}
+
+/// The Operation row of a window that chooses by itself: any pick there, the shown option
+/// included, is the user's, and the window stops choosing. Returns whether there was one.
+pub fn op_row(ui: &mut egui::Ui, id: &str, operation: &mut usize) -> bool {
+ let picked = crate::dialogs::form_row(ui, "Operation", |ui| crate::ui_kit::dropdown_picked(ui, id, operation, &crate::dialogs::OP_LABELS));
+ if picked {
+ ui.ctx().data_mut(|d| d.insert_temp(picked_id(), true));
+ }
+ picked
+}
+
+/// OK in a window still waiting for its check: it applies once the check is in. Returns whether
+/// OK applies now (`again`: Apply, which keeps the window open).
+pub fn hold_ok(d: &mut Dialog, ok: bool, again: &mut bool, cancel: bool) -> bool {
+ if cancel {
+ d.op_auto.ok_waiting = None;
+ return false;
+ }
+ if ok && d.op_auto.pending {
+ d.op_auto.ok_waiting = Some(*again);
+ return false;
+ }
+ if let Some(waiting) = d.op_auto.ok_waiting
+ && !d.op_auto.pending
+ {
+ d.op_auto.ok_waiting = None;
+ *again = waiting;
+ return true;
+ }
+ ok
+}
+
+/// The shown bodies as the `targets` of a new feature's Join, Cut or Intersect that names none,
+/// when some bodies are hidden: a hidden body is left alone. With none shown, such a feature has
+/// nothing to change.
+pub fn scope_targets(app: &SolveApp, d: &Dialog, cmds: &mut [(String, Value)]) -> Result<(), String> {
+ if rule(&d.kind).is_none() || d.editing.is_some() {
+ return Ok(());
+ }
+ let Some(shown) = solidcraft_engine::shown_scope(&app.session) else { return Ok(()) };
+ for (_, p) in cmds {
+ let changes = p.get("operation").and_then(Value::as_str).is_some_and(|o| OPS.contains(&o) && o != "new");
+ let named = ["targets", "participants"].iter().any(|k| p.get(*k).and_then(Value::as_array).is_some_and(|a| !a.is_empty()));
+ if !changes || named {
+ continue;
+ }
+ if shown.is_empty() {
+ return Err(crate::i18n::tr("dialog.no_shown_body").to_string());
+ }
+ if let Some(map) = p.as_object_mut() {
+ map.insert("targets".into(), Value::from(shown.clone()));
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+#[path = "op_auto_tests.rs"]
+mod tests;
diff --git a/crates/ui-egui/src/op_auto_tests.rs b/crates/ui-egui/src/op_auto_tests.rs
new file mode 100644
index 0000000000..6275214bf4
--- /dev/null
+++ b/crates/ui-egui/src/op_auto_tests.rs
@@ -0,0 +1,225 @@
+//! Feature windows choose Join, New Body or Cut from what their material does (#6901).
+
+use std::time::{Duration, Instant};
+
+use serde_json::json;
+use solidcraft_engine::geom::Vec3;
+
+use super::{CUT, JOIN, NEW};
+use crate::dialogs::Kind;
+use crate::scenario::Harness;
+
+/// A 10 mm cube at the origin, named `Base`.
+fn cube() -> Harness {
+ let mut h = Harness::new();
+ h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Base"})).unwrap();
+ h
+}
+
+fn rect_sketch(h: &mut Harness, p0: [f64; 2], p1: [f64; 2]) {
+ h.app.run("sketch.create", json!({"plane": "XY"})).unwrap();
+ h.app.run("sketch.rectangle.two_point", json!({"p0": p0, "p1": p1})).unwrap();
+ h.app.run("sketch.finish", json!({})).unwrap();
+ h.app.run("select.clear", json!({})).unwrap();
+}
+
+/// Frames until the window's check is in.
+fn checked(h: &mut Harness) {
+ let began = Instant::now();
+ while (h.app.op_check.busy() || h.app.dialog.as_ref().is_some_and(|d| d.op_auto.pending)) && began.elapsed() < Duration::from_secs(60) {
+ h.frames(1);
+ std::thread::sleep(Duration::from_millis(1));
+ }
+ h.frames(2);
+}
+
+fn op(h: &mut Harness) -> usize {
+ match h.app.dialog.as_mut().map(|d| &mut d.kind) {
+ Some(
+ Kind::Extrude { operation, .. } | Kind::Revolve { operation, .. } | Kind::Primitive { operation, .. } | Kind::Loft { operation, .. },
+ ) => *operation,
+ other => panic!("a feature window: {other:?}"),
+ }
+}
+
+/// Pick an operation in the window's list (the shown one too): what [`super::op_row`] notes.
+fn pick(h: &mut Harness, to: usize) {
+ if let Some(d) = h.app.dialog.as_mut() {
+ match &mut d.kind {
+ Kind::Extrude { operation, .. } | Kind::Revolve { operation, .. } | Kind::Primitive { operation, .. } | Kind::Loft { operation, .. } => {
+ *operation = to
+ }
+ other => panic!("a feature window: {other:?}"),
+ }
+ }
+ h.ctx.data_mut(|m| m.insert_temp(super::picked_id(), true));
+}
+
+fn bodies(h: &Harness) -> Vec<String> {
+ h.app.session.model.state().bodies.iter().map(|b| b.name.clone()).collect()
+}
+
+fn ok(h: &mut Harness) {
+ h.step(&json!({"key": "Enter"})).unwrap();
+ checked(h);
+ let began = Instant::now();
+ while h.app.dialog.is_some() && began.elapsed() < Duration::from_secs(60) {
+ h.frames(1);
+ }
+ assert!(h.app.dialog.is_none(), "OK closes the window");
+}
+
+#[test]
+fn an_extrude_apart_is_a_new_body_and_one_touching_joins() {
+ for (p0, p1, want) in [([30.0, 0.0], [40.0, 10.0], NEW), ([10.0, 0.0], [20.0, 10.0], JOIN), ([10.0, 5.0], [20.0, 15.0], JOIN)] {
+ let mut h = cube();
+ rect_sketch(&mut h, p0, p1);
+ h.step(&json!({"start": "solid.extrude"})).unwrap();
+ checked(&mut h);
+ assert_eq!(op(&mut h), want, "{p0:?}–{p1:?}");
+ // A Join the check evaluated is OK's: it isn't computed again.
+ let cmds = h.app.dialog.as_ref().and_then(|d| crate::dialogs::apply_commands(&h.app, d).ok()).unwrap_or_default();
+ assert_eq!(h.app.op_check.joined_for(&cmds, h.app.session.revision).is_some(), want == JOIN, "{p0:?}–{p1:?}");
+ ok(&mut h);
+ assert_eq!(bodies(&h).len(), if want == NEW { 2 } else { 1 }, "{p0:?}–{p1:?}");
+ }
+}
+
+#[test]
+fn with_the_preference_off_the_window_keeps_its_operation() {
+ assert!(serde_json::from_value::<crate::prefs::Prefs>(json!({})).unwrap().auto_operation, "on for saved settings without it");
+ let mut h = cube();
+ h.app.preferences.auto_operation = false;
+ rect_sketch(&mut h, [30.0, 0.0], [40.0, 10.0]);
+ h.step(&json!({"start": "solid.extrude"})).unwrap();
+ h.frames(3);
+ assert!(!h.app.op_check.busy(), "no check runs");
+ assert!(h.app.dialog.as_ref().is_some_and(|d| !d.op_auto.pending));
+ assert_eq!(op(&mut h), JOIN, "Extrude keeps its own Join, as before");
+ ok(&mut h);
+ assert_eq!(bodies(&h).len(), 1, "the Join apart makes one body in two pieces");
+}
+
+#[test]
+fn closing_the_window_stops_its_check() {
+ // A larger body, so the check is still running when the window closes.
+ let mut h = Harness::new();
+ h.app.run("solid.box", json!({"length": 40, "width": 40, "height": 10, "corner": [-20, -20, 0], "body_name": "Base"})).unwrap();
+ for (x, y) in [(-10, -10), (10, -10), (-10, 10), (10, 10)] {
+ h.app.run("solid.cylinder", json!({"radius": 3, "height": 10, "base": [x, y, 0], "operation": "cut"})).unwrap();
+ }
+ rect_sketch(&mut h, [20.0, -5.0], [30.0, 5.0]);
+ h.app.start("solid.extrude");
+ h.frames(1);
+ let progress = h.app.op_check.progress.clone();
+ h.app.dialog = None;
+ h.frames(1);
+ assert!(!h.app.op_check.busy(), "nothing waits for a window that is gone");
+ assert!(h.app.op_check.done.is_none() && h.app.op_check.joined.is_none(), "what it found is forgotten");
+ if let Some(progress) = progress {
+ assert!(progress.is_cancelled(), "the running check was told to stop");
+ }
+}
+
+#[test]
+fn a_ring_round_a_hole_joins() {
+ let mut h = Harness::new();
+ h.app.run("solid.box", json!({"length": 40, "width": 40, "height": 10, "corner": [-20, -20, 0], "body_name": "Base"})).unwrap();
+ h.app.run("solid.cylinder", json!({"radius": 5, "height": 10, "operation": "cut"})).unwrap();
+ h.app.run("sketch.create", json!({"plane": {"origin": [0, 0, 10], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})).unwrap();
+ h.app.run("sketch.circle.center", json!({"center": [0, 0], "radius": 5})).unwrap();
+ h.app.run("sketch.circle.center", json!({"center": [0, 0], "radius": 10})).unwrap();
+ h.app.run("sketch.finish", json!({})).unwrap();
+ h.app.run("select.clear", json!({})).unwrap();
+ h.step(&json!({"start": "solid.extrude"})).unwrap();
+ checked(&mut h);
+ if let Some(d) = h.app.dialog.as_mut() {
+ // The ring alone, not the disc inside it.
+ d.inputs[0].items.retain(|s| {
+ matches!(s, solidcraft_engine::Sel::Profile { index, .. } if *index == 1) || !matches!(s, solidcraft_engine::Sel::Profile { .. })
+ });
+ }
+ checked(&mut h);
+ assert_eq!(op(&mut h), JOIN);
+}
+
+#[test]
+fn primitives_and_revolves_join_cut_or_stand_apart() {
+ let at = |h: &mut Harness, point: [f64; 3]| {
+ if let Some(Kind::Primitive { at, .. }) = h.app.dialog.as_mut().map(|d| &mut d.kind) {
+ *at = Some((Vec3::new(point[0], point[1], point[2]), Some(Vec3::Z)));
+ }
+ };
+ for (point, want) in [([50.0, 0.0, 0.0], NEW), ([5.0, 5.0, 10.0], JOIN), ([5.0, 5.0, 5.0], CUT)] {
+ let mut h = cube();
+ h.step(&json!({"start": "solid.sphere"})).unwrap();
+ if let Some(Kind::Primitive { fields, .. }) = h.app.dialog.as_mut().map(|d| &mut d.kind) {
+ fields.iter_mut().for_each(|(_, v)| *v = "4 mm".into());
+ }
+ at(&mut h, point);
+ checked(&mut h);
+ assert_eq!(op(&mut h), want, "sphere at {point:?}");
+ }
+}
+
+#[test]
+fn a_hand_picked_operation_stays_even_while_the_check_runs() {
+ // Picked before the first check is in: that check doesn't undo it.
+ let mut h = cube();
+ rect_sketch(&mut h, [30.0, 0.0], [40.0, 10.0]);
+ h.step(&json!({"start": "solid.extrude"})).unwrap();
+ pick(&mut h, JOIN);
+ checked(&mut h);
+ assert_eq!(op(&mut h), JOIN, "Join picked by hand stays, apart or not");
+ // The same in a window without Extrude's own choice.
+ let mut h = cube();
+ h.step(&json!({"start": "solid.sphere"})).unwrap();
+ h.frames(1);
+ pick(&mut h, NEW);
+ checked(&mut h);
+ assert_eq!(op(&mut h), NEW, "New Body picked by hand on a body stays");
+}
+
+#[test]
+fn ok_runs_what_the_check_chose() {
+ // Enter at once: OK waits for the check, then makes a new body for the block apart.
+ let mut h = cube();
+ rect_sketch(&mut h, [30.0, 0.0], [40.0, 10.0]);
+ h.step(&json!({"start": "solid.extrude"})).unwrap();
+ ok(&mut h);
+ assert_eq!(bodies(&h).len(), 2, "{:?}", bodies(&h));
+}
+
+#[test]
+fn hidden_bodies_take_no_part() {
+ let mut h = cube();
+ h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [40, 0, 0], "body_name": "Other"})).unwrap();
+ h.app.run("browser.visibility", json!({"items": ["Base"], "visible": false})).unwrap();
+ // A block on the hidden cube: apart from what is shown.
+ rect_sketch(&mut h, [10.0, 0.0], [20.0, 10.0]);
+ h.step(&json!({"start": "solid.extrude"})).unwrap();
+ checked(&mut h);
+ assert_eq!(op(&mut h), NEW, "the hidden cube is not joined");
+ // Join picked by hand joins only the shown bodies: the hidden cube stays as it is.
+ pick(&mut h, JOIN);
+ ok(&mut h);
+ let st = h.app.session.model.state();
+ assert!(st.body("Base").is_some_and(|b| b.body.face_count() == 6), "the hidden cube is untouched");
+ // Nothing shown: New Body at once.
+ let mut h = cube();
+ h.app.run("browser.visibility", json!({"items": ["Base"], "visible": false})).unwrap();
+ rect_sketch(&mut h, [10.0, 0.0], [20.0, 10.0]);
+ h.step(&json!({"start": "solid.extrude"})).unwrap();
+ h.frames(2);
+ assert_eq!(op(&mut h), NEW);
+}
+
+#[test]
+fn an_edited_feature_keeps_its_operation() {
+ let mut h = cube();
+ rect_sketch(&mut h, [30.0, 0.0], [40.0, 10.0]);
+ h.app.run("solid.extrude", json!({"distance": 5, "operation": "join", "name": "Apart"})).unwrap();
+ h.step(&json!({"call": "ui.editFeature", "params": {"feature": "Apart"}})).unwrap();
+ checked(&mut h);
+ assert_eq!(op(&mut h), JOIN, "the saved Join stays");
+}
diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs
index a212a5cbd8..36b8ffc36d 100644
--- a/crates/ui-egui/src/prefs.rs
+++ b/crates/ui-egui/src/prefs.rs
@@ -1004,6 +1004,9 @@ preference_settings! {
/// Extrude: with a profile picked, a face, vertex or parallel plane picked off its plane
/// switches the extent to To Object (off: picks only add profiles, as before).
extrude_auto_to_object: bool = false, PAGE_DESIGN => check("Extrude to a picked target", "In Extrude, with a profile picked, picking a face, vertex or parallel plane off its plane switches the extent to To Object");
+ /// Feature windows choose Join, New Body or Cut from what their material touches (`op_auto`,
+ /// #6901). Off: they keep the operation they open with (Extrude its own Join or Cut), as before.
+ auto_operation: bool = true, PAGE_DESIGN => check_id("prefs.auto_operation");
/// Placing a Single hole snaps to the middle of the face and the centres of its round edges
/// (`hole_place`). Off by default: a hole goes where it is clicked.
hole_snaps: bool = false, PAGE_DESIGN => check("Snap to face and edge centres");
diff --git a/crates/ui-egui/src/prefs/design.rs b/crates/ui-egui/src/prefs/design.rs
index ce6553b6fb..964d60a954 100644
--- a/crates/ui-egui/src/prefs/design.rs
+++ b/crates/ui-egui/src/prefs/design.rs
@@ -77,6 +77,9 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
},
);
setting::extrude_auto_to_object(app, ui);
+ let auto = setting::auto_operation(app, ui);
+ crate::scenario::publish_handle("prefs:auto_operation", auto.rect.center());
+ ui_kit::text(ui, app.tr("prefs.auto_operation_note"), ui_kit::Text::Hint("auto_operation"));
setting::hide_origin(app, ui);
ui_kit::text(ui, app.tr("ui.hide_origin_note"), ui_kit::Text::Hint("hide_origin"));
});
diff --git a/crates/ui-egui/src/primitive_units_tests.rs b/crates/ui-egui/src/primitive_units_tests.rs
index 438c58bc74..ee7a15e0d2 100644
--- a/crates/ui-egui/src/primitive_units_tests.rs
+++ b/crates/ui-egui/src/primitive_units_tests.rs
@@ -585,6 +585,9 @@ fn a_point_picked_in_the_box_dialog_becomes_its_corner_or_centre() {
use solidcraft_engine::Sel;
use solidcraft_engine::geom::Vec3;
let mut h = design("mm");
+ // The box made here overlaps Base, which the window would join or cut (#6901): this test is
+ // about where it goes, so the window keeps its New Body.
+ h.app.preferences.auto_operation = false;
h.app.run("solid.box", json!({"length": 40, "width": 30, "height": 20, "body_name": "Base"})).unwrap();
h.frames(2);
// A face picked before the command: the box stands on it, as before (no typed placement).
diff --git a/crates/ui-egui/src/scenario.rs b/crates/ui-egui/src/scenario.rs
index 8cf72ff1b9..16f9897a96 100644
--- a/crates/ui-egui/src/scenario.rs
+++ b/crates/ui-egui/src/scenario.rs
@@ -286,9 +286,10 @@ impl Harness {
}
self.frame();
}
- // A file opening, recovering or saving in the background: wait for it (as a person would).
+ // A file opening, recovering or saving in the background, or a window checking what its
+ // material does: wait for it (as a person would).
let began = std::time::Instant::now();
- while (!self.app.file_load.idle() || self.app.saving.is_some() || crate::open_meshing::active(&self.app))
+ while (!self.app.file_load.idle() || self.app.saving.is_some() || crate::open_meshing::active(&self.app) || self.app.op_check.busy())
&& began.elapsed() < std::time::Duration::from_secs(120)
{
self.frame();
diff --git a/crates/ui-egui/src/ui_kit/fields.rs b/crates/ui-egui/src/ui_kit/fields.rs
index 44028acfef..502c549436 100644
--- a/crates/ui-egui/src/ui_kit/fields.rs
+++ b/crates/ui-egui/src/ui_kit/fields.rs
@@ -299,6 +299,22 @@ pub(crate) fn dropdown(ui: &mut Ui, id: &str, selected: &mut usize, options: &[&
})
}
+/// [`dropdown`] that also says whether an option was clicked, the one already shown included (a
+/// pick of the shown option changes nothing, yet it is a choice).
+pub(crate) fn dropdown_picked(ui: &mut Ui, id: &str, selected: &mut usize, options: &[&str]) -> bool {
+ let text = options.get(*selected).copied().map(crate::i18n::tr_label).unwrap_or("");
+ let row = label(ui).to_string();
+ let mut picked = false;
+ dropdown_menu(ui, id, text, |ui| {
+ for (index, option) in options.iter().enumerate() {
+ let response = ui.selectable_value(selected, index, crate::i18n::tr_label(option));
+ picked |= response.clicked();
+ scenario::publish_handle(&format!("dialog:{row}:{option}"), response.rect.center());
+ }
+ });
+ picked
+}
+
/// Dropdown with caller-supplied kit choices/actions, including disabled entries and stable
/// application handles. Tokens: dropdown tokens. Use `dropdown` for a simple indexed list.
pub(crate) fn dropdown_menu(ui: &mut Ui, id: impl egui::AsIdSalt, current: &str, add: impl FnOnce(&mut Ui)) -> Response {
diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rs
index c3fde5aa64..b4c87efc14 100644
--- a/crates/ui-egui/src/ui_kit/gallery.rs
+++ b/crates/ui-egui/src/ui_kit/gallery.rs
@@ -1161,6 +1161,11 @@ const ELEMENTS: &[Element] = &[
dropdown(ui, "gallery", &mut s.selected, &["One", "Two"]);
});
}),
+ element!("dropdown_picked", "dialog:row:Gallery", Some("dialog:Gallery"), |ui, s| {
+ row(ui, "Gallery", |ui| {
+ dropdown_picked(ui, "gallery_picked", &mut s.selected, &["One", "Two"]);
+ });
+ }),
element!("selection_field", "dialog:row:Gallery", Some("dialog:Gallery"), |ui, _| {
row(ui, "Gallery", |ui| {
selection_field(ui, "Point 1", Selection { active: true, filled: true });
diff --git a/crates/ui-egui/tests/icon_audit.rs b/crates/ui-egui/tests/icon_audit.rs
index 7262c0332a..453513c167 100644
--- a/crates/ui-egui/tests/icon_audit.rs
+++ b/crates/ui-egui/tests/icon_audit.rs
@@ -5,6 +5,14 @@ use std::path::PathBuf;
use serde_json::{Value, json};
use solidcraft_ui_egui::{icon_svg, scenario::Harness, workspace};
+/// A harness whose feature windows don't choose their operation (`auto_operation`): this test
+/// opens every window only to look at its icons, and each choice would run a Join on the design.
+fn harness() -> Harness {
+ let mut h = Harness::new();
+ h.app.preferences.auto_operation = false;
+ h
+}
+
fn click(h: &mut Harness, handle: &str) {
h.step(&json!({"click":{"handle":handle}})).unwrap_or_else(|e| panic!("{handle}: {e}"));
}
@@ -157,7 +165,7 @@ fn requested_menu_icons_have_artwork_and_match_manifest() {
if evidence.exists() {
std::fs::remove_file(&evidence).unwrap();
}
- let mut h = Harness::new();
+ let mut h = harness();
h.app.home.open = false;
h.app.services.install_app = Some(solidcraft_ui_egui::install::InstallApp {
offer: Box::new(|| Some(solidcraft_ui_egui::install::Offer::Prompt)),
@@ -263,7 +271,7 @@ fn requested_menu_icons_have_artwork_and_match_manifest() {
h.app.run("select.clear", json!({})).unwrap();
// Keep history traversal in a small fixture, independent of viewport/browser selection.
- let mut history = Harness::new();
+ let mut history = harness();
history.app.home.open = false;
for name in ["History A", "History B"] {
history.app.run("solid.box", json!({"length":10,"width":10,"height":10,"name":name})).unwrap();
@@ -369,7 +377,7 @@ fn requested_menu_icons_have_artwork_and_match_manifest() {
// Sheet and assembly contexts expose contextual tabs and browser row kinds that
// a single solid part cannot offer. Use repository-owned public sample recipes.
for sample in solidcraft_engine::sample::samples().into_iter().filter(|s| matches!(s.name, "Sheet Metal Bracket" | "Hinge Assembly")) {
- let mut sample_h = Harness::new();
+ let mut sample_h = harness();
sample_h.app.home.open = false;
sample_h.app.session.run_script(&(sample.script)()).unwrap();
sample_h.frames(3);
@@ -387,7 +395,7 @@ fn requested_menu_icons_have_artwork_and_match_manifest() {
panels(&mut sample_h, &mut requested);
collect(&mut sample_h, sample.name, &mut requested);
}
- let mut geometry = Harness::new();
+ let mut geometry = harness();
geometry.app.home.open = false;
geometry.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Audit block"})).unwrap();
geometry.app.run("solid.split_body", json!({"body":"Audit block","plane":{"origin":[5,0,0],"normal":[1,0,0]}})).unwrap();
@@ -430,7 +438,7 @@ fn requested_menu_icons_have_artwork_and_match_manifest() {
collect(&mut geometry, "File recent designs", &mut requested);
escape(&mut geometry);
// Populate actual document slots, then click the same overflow launcher as a person.
- let mut documents = Harness::new();
+ let mut documents = harness();
for _ in 0..12 {
solidcraft_ui_egui::documents::open_tab(&mut documents.app, solidcraft_engine::Session::default()).unwrap();
}
@@ -442,7 +450,7 @@ fn requested_menu_icons_have_artwork_and_match_manifest() {
collect(&mut documents, "document overflow list (active icon is a selection marker)", &mut requested);
// Diagnostic badges and Copy Error/Warning Message only appear on troubled features.
for failing in [false, true] {
- let mut diagnostics = Harness::new();
+ let mut diagnostics = harness();
diagnostics.app.home.open = false;
if failing {
diagnostics.app.session.run_script(&solidcraft_engine::sample::script()).unwrap();
@@ -467,7 +475,7 @@ fn requested_menu_icons_have_artwork_and_match_manifest() {
("sketch Select Other", include_str!("scenarios/select_other_coincident_lines.json")),
("canvas calibration", include_str!("scenarios/s19_canvas_calibrate.json")),
] {
- let mut scenario = Harness::new();
+ let mut scenario = harness();
scenario.run(&serde_json::from_str(source).unwrap()).unwrap_or_else(|e| panic!("{name}: {e}"));
collect(&mut scenario, name, &mut requested);
}
@@ -540,7 +548,7 @@ fn offset_mode_artwork_review() {
#[test]
fn overflow_icons_with_many_pins_at_200_points() {
- let mut h = Harness::new();
+ let mut h = harness();
icon_svg::audit::start();
let steps = serde_json::from_str(include_str!("scenarios/s48_toolbar_many_pins.json")).unwrap();
if let Err(error) = h.run(&steps) {
diff --git a/docs/book/src/guide/features.md b/docs/book/src/guide/features.md
index d70c6fc44f..0ae750e970 100644
--- a/docs/book/src/guide/features.md
+++ b/docs/book/src/guide/features.md
@@ -15,14 +15,23 @@ it.
| Construct | offset plane (at a distance or through a point), plane at angle, plane along path |
| Inspect | measure, section analysis, interference, compare bodies, curvature comb and map, zebra, draft, minimum radius, isocurves, centre of mass |
-Extrude automatically selects **Join** for additions when the active component already has a
-solid, including sideways elbow connections and screw bosses that meet only part of a face.
-Extruding into existing material selects **Cut**. In an empty component it selects **New Body**;
-choose **New Body** explicitly to keep an addition separate. Changing the default does not alter
-operations already saved in a design. A Join (of an extrude, revolve, sweep, loft, primitive…)
-whose material touches none of its target bodies still joins it, to the first one as a separate
-piece, and the feature's warning says so: "`Body1` is now in 2 separate pieces". Combine joins
-the bodies it is given without that warning.
+Extrude, Revolve, Sweep, Loft, Coil and the Box, Cylinder, Sphere and Torus choose their
+operation from what their material does, until you pick one: **Join** when it makes one body with
+a body it touches (a block against a wall, a ring round a hole, a boss meeting only part of a
+face), **New Body** when it would be a separate piece, and **Cut** when it goes into a body
+(Extrude) or lies inside one (Revolve and the Box, Cylinder, Sphere and Torus). The window finds
+out by running the Join on a copy of the design in the background, so its choice is what OK
+makes; it changes only when that check is in, and OK waits for it. An operation you pick stays,
+and a feature you edit keeps its own. Pipe, Thicken and Boundary Fill start as a New Body. Only
+shown bodies take part: with some bodies hidden, the feature names the shown ones as its targets,
+so a hidden body is never joined or cut, and showing it again later changes nothing.
+**Choose the operation automatically** (Preferences › Design, on by default) turns this choice
+off: each window then keeps the operation it opens with, Extrude its own Join or Cut, as before.
+
+A Join you pick whose material touches none of its target bodies still joins it, to the first
+one as a separate piece, and the feature's warning says so: "`Body1` is now in 2 separate
+pieces". Combine joins the bodies it is given without that warning. Changing the default does not
+alter operations already saved in a design.
**Extrude to a picked target** (Preferences › Design, off by default) lets a pick choose the
extent. With it on and a profile selected in the solid Extrude dialog, picking a face away from
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 031b1856a7..9e8ca29401 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -322,6 +322,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox.
One setting per line, sorted by name. A change that adds a setting adds its own line in order, so two such changes only meet when their settings are neighbours.
- `angle_decimals`
+- `auto_operation` (default true: feature windows choose Join, New Body or Cut from what their material touches until one is picked; false: each keeps the operation it opens with, Extrude its own Join or Cut)
- `browser_bodies_folders` (`several` (default): a component with one body and no groups lists it straight under the component in the browser, without a Bodies folder; `always`; `never`: components list their bodies and groups straight under them, and the folder's menu items are on the component's menu; the design's own Bodies folder, and one hidden with its eye, always show; #4217)
- `check_updates` (default true; [updates](book/src/guide/updates.md))
- `color_vision` (`off` (default), `protan`, `deutan`, `tritan`: colour vision modes, #778)