Skip to content

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

Browser: list the features that built each body under it, as an option (#11945) (#12709)

PaddleStroke30be21a2244a
diff --git a/assets/locales/pending/browser-body-features.json b/assets/locales/pending/browser-body-features.json
new file mode 100644
index 0000000000..a607a7dd86
--- /dev/null
+++ b/assets/locales/pending/browser-body-features.json
@@ -0,0 +1,42 @@
+{
+ "en": {
+ "cmd.model_body_features": "List Body Features",
+ "prefs.browser_body_features": "Features under bodies",
+ "prefs.browser_body_features_note": "Each body in the browser folds open on the timeline features that built it, in timeline order."
+ },
+ "ar": {
+ "cmd.model_body_features": "سرد ميزات الجسم",
+ "prefs.browser_body_features": "الميزات تحت الأجسام",
+ "prefs.browser_body_features_note": "يمكن فتح كل جسم في المستعرض لعرض ميزات المخطط الزمني التي بنته، بترتيب المخطط الزمني."
+ },
+ "de": {
+ "cmd.model_body_features": "Körper-Features auflisten",
+ "prefs.browser_body_features": "Features unter Körpern",
+ "prefs.browser_body_features_note": "Jeder Körper im Browser lässt sich aufklappen und zeigt die Features der Zeitleiste, die ihn erzeugt haben, in deren Reihenfolge."
+ },
+ "fr": {
+ "cmd.model_body_features": "Lister les fonctions du corps",
+ "prefs.browser_body_features": "Fonctions sous les corps",
+ "prefs.browser_body_features_note": "Chaque corps du navigateur se déplie sur les fonctions de l'historique qui l'ont construit, dans l'ordre de l'historique."
+ },
+ "he": {
+ "cmd.model_body_features": "הצגת פיצ'רים של גוף",
+ "prefs.browser_body_features": "פיצ'רים מתחת לגופים",
+ "prefs.browser_body_features_note": "כל גוף בדפדפן נפתח ומציג את הפיצ'רים מציר הזמן שבנו אותו, לפי סדר ציר הזמן."
+ },
+ "ja": {
+ "cmd.model_body_features": "ボディのフィーチャーを一覧表示",
+ "prefs.browser_body_features": "ボディの下にフィーチャー",
+ "prefs.browser_body_features_note": "ブラウザーの各ボディを展開すると、そのボディを作ったタイムラインのフィーチャーがタイムライン順に表示されます。"
+ },
+ "vi": {
+ "cmd.model_body_features": "Liệt kê tính năng của thân",
+ "prefs.browser_body_features": "Tính năng dưới thân",
+ "prefs.browser_body_features_note": "Mỗi thân trong trình duyệt có thể mở ra để hiện các tính năng trên dòng thời gian đã tạo nên nó, theo thứ tự dòng thời gian."
+ },
+ "zh": {
+ "cmd.model_body_features": "列出实体特征",
+ "prefs.browser_body_features": "实体下显示特征",
+ "prefs.browser_body_features_note": "浏览器中的每个实体都可展开,按时间线顺序显示构建它的时间线特征。"
+ }
+}
diff --git a/crates/engine/src/cmd/body_features.rs b/crates/engine/src/cmd/body_features.rs
new file mode 100644
index 0000000000..4a77d9afb9
--- /dev/null
+++ b/crates/engine/src/cmd/body_features.rs
@@ -0,0 +1,100 @@
+//! Which timeline features built each body (#11945): the data behind `model.body_features` and
+//! the Browser's optional features-under-bodies tree.
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+
+use serde_json::Value;
+
+use crate::params::{bad, str_};
+use crate::schema::inspect::{BodyFeature, BodyFeatures, ModelBodyFeatures};
+use crate::{Result, Session};
+
+impl Session {
+ /// The features that built each body of the evaluated model, by the body's model name, in
+ /// timeline order: the feature that created it, every later feature that changed its
+ /// geometry, and the features of the bodies a feature consumed while it made or changed this
+ /// one (a Combine's tools, a body joined in). A piece a cut split off keeps the features of
+ /// the body it was cut from. Features behind the history marker, which built nothing yet,
+ /// are not listed.
+ ///
+ /// Decided on exact body identity (a body a feature passed through unchanged is the same
+ /// record), never on a mesh.
+ pub fn body_features(&self) -> BTreeMap<String, Vec<u64>> {
+ let order: HashMap<u64, usize> = self.doc.features.iter().enumerate().map(|(i, f)| (f.id, i)).collect();
+ // Each body before the feature being looked at: its geometry, its creator and its features.
+ let mut before: HashMap<String, (solidcraft_doc::kernel::Body, u64, Vec<u64>)> = HashMap::new();
+ for r in &self.model.results {
+ let id = r.id;
+ let after = &r.state.bodies;
+ let names: HashSet<&str> = after.iter().map(|b| b.name.as_str()).collect();
+ // What the feature consumed: bodies there before and gone after.
+ let consumed: Vec<u64> =
+ before.iter().filter(|(name, _)| !names.contains(name.as_str())).flat_map(|(_, (_, _, list))| list.iter().copied()).collect();
+ let mut next: HashMap<String, (solidcraft_doc::kernel::Body, u64, Vec<u64>)> = HashMap::with_capacity(after.len());
+ for b in after {
+ let list = match before.get(&b.name) {
+ // Passed through unchanged.
+ Some((old, creator, list)) if old.same(&b.body) && *creator == b.feature => list.clone(),
+ // Changed: it keeps what built it so far.
+ Some((_, creator, list)) if *creator == b.feature => touched(list.clone(), &consumed, id, &order),
+ // Made by this feature.
+ _ if b.feature == id => touched(Vec::new(), &consumed, id, &order),
+ // A piece of a body made earlier (a split): what built the bodies of its creator.
+ _ => {
+ let inherited =
+ before.values().filter(|(_, creator, _)| *creator == b.feature).flat_map(|(_, _, list)| list.iter().copied()).collect();
+ touched(inherited, &consumed, id, &order)
+ }
+ };
+ next.insert(b.name.clone(), (b.body.clone(), b.feature, list));
+ }
+ before = next;
+ }
+ // The model as it stands (a sketch shown live keeps its last results).
+ self.model
+ .state()
+ .bodies
+ .iter()
+ .map(|b| (b.name.clone(), before.get(&b.name).map(|(_, _, list)| list.clone()).unwrap_or_else(|| vec![b.feature])))
+ .collect()
+ }
+}
+
+/// `list` with the features of what was consumed and the feature `id` added, once each, in
+/// timeline order.
+fn touched(mut list: Vec<u64>, consumed: &[u64], id: u64, order: &HashMap<u64, usize>) -> Vec<u64> {
+ list.extend(consumed.iter().copied());
+ list.push(id);
+ list.sort_by_key(|f| order.get(f).copied().unwrap_or(usize::MAX));
+ list.dedup();
+ list
+}
+
+/// `model.body_features`: the features that built each body, or one body (a placed copy's name
+/// means the body it shows).
+pub(super) fn model_body_features(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "model.body_features";
+ let all = s.body_features();
+ let wanted = match str_(p, "body") {
+ Some(name) => {
+ let st = s.world_state()?;
+ let b = st.body(name).ok_or_else(|| bad(cmd, format!("no body `{name}`")))?;
+ Some((b.name.clone(), b.definition_name().to_string()))
+ }
+ None => None,
+ };
+ let feature = |id: &u64| BodyFeature { id: *id, name: s.doc.feature(*id).map(|f| f.name.clone()).unwrap_or_default() };
+ let bodies = match wanted {
+ Some((shown, definition)) => {
+ vec![BodyFeatures { body: shown, features: all.get(&definition).map(|l| l.iter().map(feature).collect()).unwrap_or_default() }]
+ }
+ None => s
+ .model
+ .state()
+ .bodies
+ .iter()
+ .map(|b| BodyFeatures { body: b.name.clone(), features: all.get(&b.name).map(|l| l.iter().map(feature).collect()).unwrap_or_default() })
+ .collect(),
+ };
+ serde_json::to_value(ModelBodyFeatures { bodies, param_warnings: Vec::new() }).map_err(|e| bad(cmd, e.to_string()))
+}
diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs
index 89f4d728f2..06516e8b5e 100644
--- a/crates/engine/src/cmd/inspect.rs
+++ b/crates/engine/src/cmd/inspect.rs
@@ -12,13 +12,15 @@ use solidcraft_sketch::CurveKind;
use super::CommandSpec;
use crate::params::{bad, bool_, str_, string_list};
use crate::schema::inspect::{
- BodyListParams, FaceCylinder, ModelEdge, ModelEdges, ModelFace, ModelFaces, ModelThread, ModelThreads, ModelThreadsParams,
+ BodyFeaturesParams, BodyListParams, FaceCylinder, ModelBodyFeatures, ModelEdge, ModelEdges, ModelFace, ModelFaces, ModelThread, ModelThreads,
+ ModelThreadsParams,
};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
const BODY_LIST_CONTRACT: TypedContract<BodyListParams> = TypedContract::new();
const THREADS_CONTRACT: TypedContract<ModelThreadsParams> = TypedContract::new();
+const BODY_FEATURES_CONTRACT: TypedContract<BodyFeaturesParams> = TypedContract::new();
#[path = "appearance_chain.rs"]
mod appearance_chain;
@@ -26,6 +28,9 @@ mod appearance_chain;
#[path = "appearance_gestures.rs"]
pub(super) mod appearance_gestures;
+#[path = "body_features.rs"]
+mod body_features;
+
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("inspect.colored_components", "Component Colors", colored_components)
.at("SOLID", "INSPECT").icon("colored_components").noundo()
@@ -65,6 +70,15 @@ pub static COMMANDS: &[CommandSpec] = &[
.noundo()
.contract(&THREADS_CONTRACT)
.output(output_schema_for::<ModelThreads>),
+ CommandSpec::new("model.body_features", "List Body Features", crate::checked!("model.body_features", body_features::model_body_features))
+ .icon("inspect")
+ .noundo()
+ .contract(&BODY_FEATURES_CONTRACT)
+ .output(output_schema_for::<ModelBodyFeatures>)
+ .params(
+ "body?: name (a placed copy's name means the body it shows; default every body) → bodies: [{body, features: [{id, name}]}], \
+ in timeline order the feature that created each body, every later one that changed it, and those of bodies consumed into it. Read-only",
+ ),
CommandSpec::new("material.assign", "Physical Material", physical_material)
.at("SOLID", "MODIFY")
.icon("material")
diff --git a/crates/engine/src/schema/inspect.rs b/crates/engine/src/schema/inspect.rs
index cc674dcf03..3472f792e2 100644
--- a/crates/engine/src/schema/inspect.rs
+++ b/crates/engine/src/schema/inspect.rs
@@ -50,6 +50,44 @@ pub struct BodyListParams {
#[schemars(deny_unknown_fields)]
pub struct ModelThreadsParams {}
+/// List the timeline features that built each body (#11945).
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct BodyFeaturesParams {
+ /// One body, by name (a placed copy's name means the body it shows); every body when left out.
+ #[serde(default)]
+ pub body: Option<String>,
+}
+
+/// What `model.body_features` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ModelBodyFeatures {
+ /// The bodies, in the model's order (the one asked for alone).
+ pub bodies: Vec<BodyFeatures>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// A body and the features that built it.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BodyFeatures {
+ /// The body's name.
+ pub body: String,
+ /// In timeline order: the feature that created it, every later one that changed its
+ /// geometry, and those of the bodies consumed into it (a Combine's tools, a body joined in).
+ pub features: Vec<BodyFeature>,
+}
+
+/// A timeline feature.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BodyFeature {
+ /// The feature's id.
+ pub id: u64,
+ /// Its name in the timeline.
+ pub name: String,
+}
+
/// What `model.edges` returns.
#[derive(Debug, Serialize, JsonSchema)]
pub struct ModelEdges {
diff --git a/crates/engine/src/schema/inspect_tests.rs b/crates/engine/src/schema/inspect_tests.rs
index 0281835f2b..ea47e36cb3 100644
--- a/crates/engine/src/schema/inspect_tests.rs
+++ b/crates/engine/src/schema/inspect_tests.rs
@@ -1,6 +1,6 @@
use serde_json::{Value, json};
-use super::{BodyListParams, DescribeParams, ModelEdges, ModelFaces, ModelThreads, ModelThreadsParams};
+use super::{BodyFeaturesParams, BodyListParams, DescribeParams, ModelBodyFeatures, ModelEdges, ModelFaces, ModelThreads, ModelThreadsParams};
use crate::Session;
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
@@ -10,6 +10,7 @@ fn schemas_and_the_key_check_agree() {
assert_keys(input_schema_for::<DescribeParams>(), &["command"]);
assert_keys(input_schema_for::<BodyListParams>(), &["body"]);
assert_keys(input_schema_for::<ModelThreadsParams>(), &[]);
+ assert_keys(input_schema_for::<BodyFeaturesParams>(), &["body"]);
}
#[test]
@@ -22,6 +23,7 @@ fn strict_keeps_todays_errors() {
("model.edges", json!({"body": "Nope"})),
("model.faces", json!({})),
("model.faces", json!({"body": "Nope"})),
+ ("model.body_features", json!({"body": "Nope"})),
]);
}
@@ -87,3 +89,47 @@ fn describe_returns_both_schemas() {
let e = s.execute("engine.describe", &json!({"command": "solid.extrud"})).err().map(|e| e.to_string());
assert!(e.as_deref().is_some_and(|e| e.contains("did you mean `solid.extrude`")), "{e:?}");
}
+
+/// #11945: each body lists the features that built it, in timeline order: its own box, the fillet
+/// that changed it, and the cutting box a Combine consumed into it with that Combine. Another body
+/// keeps only its own. Rolled back before the Combine, neither it nor the tool's box are listed.
+#[test]
+fn body_features_list_what_built_each_body() {
+ let schema = output_schema_for::<ModelBodyFeatures>();
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let run = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ let id = |r: Value| r["feature"].as_u64().unwrap_or_else(|| panic!("{r}"));
+ let a = id(run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 10, "body_name": "A"})));
+ let b =
+ id(run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [50, 0, 0], "operation": "new", "body_name": "B"})));
+ let fillet = id(run(&mut s, "solid.fillet", json!({"body": "A", "edges": [[10, 0, 10]], "radius": 1})));
+ let tool =
+ id(run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 20, "corner": [5, 5, -5], "operation": "new", "body_name": "T"})));
+ let combine = id(run(&mut s, "solid.combine", json!({"target": "A", "tools": ["T"], "operation": "cut"})));
+
+ let listed = |r: &Value, body: &str| -> Vec<u64> {
+ let entry = r["bodies"].as_array().into_iter().flatten().find(|e| e["body"] == body).unwrap_or_else(|| panic!("no {body} in {r}"));
+ entry["features"].as_array().into_iter().flatten().filter_map(|f| f["id"].as_u64()).collect()
+ };
+ let r = run(&mut s, "model.body_features", json!({}));
+ assert!(conforms(schema.as_value(), schema.as_value(), &r), "{r}");
+ assert!(r.get("param_warnings").is_none(), "{r}");
+ assert_eq!(listed(&r, "A"), vec![a, fillet, tool, combine], "{r}");
+ assert_eq!(listed(&r, "B"), vec![b], "{r}");
+ assert_eq!(r["bodies"].as_array().map(Vec::len), Some(2), "the consumed tool is gone: {r}");
+ assert_eq!(r["bodies"][0]["features"][1]["name"], s.doc.feature(fillet).map(|f| f.name.clone()).unwrap_or_default().as_str());
+
+ // One body, and the Session data the browser reads agree.
+ let one = run(&mut s, "model.body_features", json!({"body": "B"}));
+ assert_eq!((one["bodies"].as_array().map(Vec::len), listed(&one, "B")), (Some(1), vec![b]), "{one}");
+ assert_eq!(s.body_features().get("A"), Some(&vec![a, fillet, tool, combine]));
+
+ run(&mut s, "timeline.rollback", json!({"position": 3}));
+ assert_eq!(s.body_features().get("A"), Some(&vec![a, fillet]));
+ assert_eq!(s.body_features().get("B"), Some(&vec![b]));
+
+ // A misspelt key warns; an unknown body is refused.
+ let warned = run(&mut s, "model.body_features", json!({"bdy": "A"}));
+ assert!(warned.get("param_warnings").is_some(), "{warned}");
+ assert!(s.execute("model.body_features", &json!({"body": "Nope"})).is_err());
+}
diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs
index 2bffbfb351..54eae2340b 100644
--- a/crates/ui-egui/src/browser.rs
+++ b/crates/ui-egui/src/browser.rs
@@ -3150,10 +3150,25 @@ fn entry_row(
let patterns_open = pattern_key.is_some_and(|key| is_open(app, key, start_open));
let rect = row_rect(ui);
let revealed = folder == "bodies" && body_reveal(app).is_some_and(|b| e.row_key.strip_prefix("b:") == Some(b));
- if !ui.is_rect_visible(rect) && !patterns_open && !revealed {
+ // Features under bodies (#11945): the body row folds open on the features that built it.
+ let built_key = (folder == "bodies"
+ && app.preferences.browser_body_features
+ && !crate::render_workspace::active(app)
+ && matches!(e.sel, Some(Sel::Body { .. })))
+ .then(|| format!("{}/features", e.row_key));
+ let built_open = built_key.as_deref().is_some_and(|key| is_open(app, key, false));
+ if !ui.is_rect_visible(rect) && !patterns_open && !revealed && !built_open {
ui.allocate_space(rect.size());
return;
}
+ let built: Vec<u64> = match &built_key {
+ Some(_) => {
+ prepare_model(app);
+ app.tree.model.as_mut().map(|model| model.body_features(&app.session, &e.key)).unwrap_or_default()
+ }
+ None => Vec::new(),
+ };
+ let built_key = built_key.filter(|_| !built.is_empty());
let (selected, mark) = lit_row(acts.lit.entry(app, e));
let visible = e.is_visible(app);
let locked = match &e.sel {
@@ -3173,7 +3188,7 @@ fn entry_row(
ui.scope_id().with(("item", &e.row_key)),
&Row {
depth,
- fold: pattern_key.map(|_| patterns_open),
+ fold: pattern_key.map(|_| patterns_open).or(built_key.as_ref().map(|_| built_open)),
eye: Some(visible),
icon: e.icon,
kind_tip: e.tip,
@@ -3205,6 +3220,10 @@ fn entry_row(
&& let Some(key) = pattern_key
{
toggle(app, key, start_open);
+ } else if r.fold
+ && let Some(key) = &built_key
+ {
+ toggle(app, key, false);
}
if folder == "bodies"
&& body_reveal(app).is_some_and(|b| e.row_key.strip_prefix("b:") == Some(b))
@@ -3276,6 +3295,9 @@ fn entry_row(
if patterns_open && let Some(Sel::Feature { id }) = &e.sel {
crate::sketch_pattern_tree::rows(app, ui, *id, depth + 1, "browser", path.map(|path| (comp, path)), !visible || parent_hidden);
}
+ if built_open && built_key.is_some() {
+ features::body_rows(app, ui, acts, comp, path.unwrap_or_default(), &e.row_key, &built, depth + 1);
+ }
let Some(resp) = &r.resp else { return };
// Drag: the selected items of this folder when this one is selected, else just this one.
if resp.drag_started()
diff --git a/crates/ui-egui/src/browser/features.rs b/crates/ui-egui/src/browser/features.rs
index 0260e4361f..45a3d50279 100644
--- a/crates/ui-egui/src/browser/features.rs
+++ b/crates/ui-egui/src/browser/features.rs
@@ -137,7 +137,7 @@ pub(super) fn rows(app: &mut SolveApp, ui: &mut egui::Ui, component: u64, path:
.filter_map(|(i, f)| (f.component == component && (compact || !matches!(f.kind, FeatureKind::Sketch { .. }))).then_some(i))
.collect(),
};
- let here = Here { component, path, scope: &scope };
+ let here = Here { component, path, scope: &scope, body_row: None };
// The feature that made what is under the cursor or picked in the viewport, as the history
// lights it, and in the history layout what a selected history row lights.
let from_view = [crate::timeline::hovered_feature(app), crate::timeline::picked_feature(app)];
@@ -206,6 +206,32 @@ pub(super) fn rows(app: &mut SolveApp, ui: &mut egui::Ui, component: u64, path:
drag_rows(app, ui, &plan, drag_id, dragged, &drops, resp.rect.center().y);
}
+/// The features that built a body, one level in under its row (#11945): the feature rows the
+/// Features folder draws, without dragging, each lit as there when the view lights it.
+#[allow(clippy::too_many_arguments)]
+pub(super) fn body_rows(
+ app: &mut SolveApp,
+ ui: &mut egui::Ui,
+ acts: &mut Actions,
+ component: u64,
+ path: &[u64],
+ body_row: &str,
+ features: &[u64],
+ depth: usize,
+) {
+ let scope = if path.is_empty() { format!("c{component}") } else { occurrence_key(path) };
+ let here = Here { component, path, scope: &scope, body_row: Some(body_row) };
+ let from_view = [crate::timeline::hovered_feature(app), crate::timeline::picked_feature(app)];
+ // A feature that built several bodies is listed under each: its rows need ids of their own.
+ ui.push_id(("body_features", body_row), |ui| {
+ for id in features {
+ let Some(index) = app.session.doc.features.iter().position(|f| f.id == *id) else { continue };
+ let mark = if from_view.contains(&Some(*id)) { Mark::Here } else { Mark::None };
+ let _ = feature_row(app, ui, acts, &here, index, depth, None, mark, None);
+ }
+ });
+}
+
/// A place in the browser's History where dragged rows can land: its height, the timeline
/// position they move to and the folder they join (`None`: the timeline root).
#[derive(Clone, Copy)]
@@ -220,6 +246,9 @@ struct Here<'a> {
component: u64,
path: &'a [u64],
scope: &'a str,
+ /// The body row a feature row is listed under (#11945): its row-order key is then its own,
+ /// `<body row>/s:<id>`, so a feature listed under two bodies is a range end at each row.
+ body_row: Option<&'a str>,
}
/// The component's history rows, `indices` its features' timeline positions: with Sketches:
@@ -277,7 +306,8 @@ fn feature_row(
// stays the face or edge.
let by_geometry = !app.session.selection.contains(&Sel::Feature { id }) && crate::timeline::picked_feature(app) == Some(id);
let selected = app.session.selection.contains(&Sel::Feature { id }) || by_geometry;
- app.tree.remember(&format!("f:{id}"));
+ let order_key = here.body_row.map_or_else(|| format!("f:{id}"), |row| format!("{row}/s:{id}"));
+ app.tree.remember(&order_key);
let action = sketch.map(|_| ("sketch", "Edit Profile Sketch"));
// A sketch row has the eye its Sketches folder row has. A feature's eye shows and hides the
// bodies it made (#5099); a component listed on its own stands for all of its placements.
@@ -343,7 +373,7 @@ fn feature_row(
// active before comes back when the editor ends (#12720).
app.edit_feature_in(id, Some((component, path)));
} else if r.clicked {
- click_select(app, ui, format!("f:{id}"), Some(Sel::Feature { id }));
+ click_select(app, ui, order_key, Some(Sel::Feature { id }));
}
if let Some(at) = r.secondary {
acts.menu = Some((at, if is_sketch { Target::Sketch { id } } else { Target::Feature { id } }));
@@ -1342,4 +1372,81 @@ mod tests {
assert_eq!(h.app.session.doc.marker, Some(2), "the marker drag still rolls back");
assert_eq!(order(&h), [ids[2], ids[0], ids[1]], "rolling back moves no feature");
}
+
+ /// #11945: with Features under bodies on, a body row folds open on the features that built it,
+ /// in timeline order and only those; a click on one selects it. Off, the default, body rows
+ /// have no fold arrow and list nothing.
+ #[test]
+ fn body_rows_fold_open_on_the_features_that_built_them() {
+ let mut h = Harness::new();
+ h.app.run("solid.box", json!({"length":20,"width":20,"height":10,"name":"Base","body_name":"Plate"})).unwrap();
+ h.app
+ .run("solid.box", json!({"length":5,"width":5,"height":5,"corner":[50,0,0],"operation":"new","name":"Block","body_name":"Other"}))
+ .unwrap();
+ let round =
+ h.app.run("solid.fillet", json!({"body":"Plate","edges":[[10,0,10]],"radius":1,"name":"Round"})).unwrap()["feature"].as_u64().unwrap();
+ h.frames(3);
+ assert_eq!(fold_of("Plate"), None, "off by default: no fold arrow on a body");
+ assert_eq!(count("Round"), 0);
+
+ assert_eq!(h.call("ui.prefs", json!({"browser_body_features": true}))["ok"], true);
+ h.frames(2);
+ assert_eq!(fold_of("Plate"), Some(false), "the body starts folded");
+ assert_eq!(count("Round"), 0);
+ h.step(&json!({"click": {"handle": "fold:Plate"}})).unwrap();
+ h.frames(2);
+ let rows = drawn_rows();
+ let top = |label: &str| rows.iter().find(|(l, ..)| l == label).map(|row| row.1.top()).unwrap();
+ assert_eq!((count("Base"), count("Round"), count("Block")), (1, 1, 0), "only what built Plate");
+ assert!(top("Plate") < top("Base") && top("Base") < top("Round") && top("Round") < top("Other"), "under Plate, in timeline order");
+
+ let at = rows.iter().find(|(l, ..)| l == "Round").map(|row| row.1.center()).unwrap();
+ h.step(&json!({"click": [at.x, at.y]})).unwrap();
+ assert_eq!(h.app.session.selection, [Sel::Feature { id: round }]);
+
+ h.call("ui.prefs", json!({"browser_body_features": false}));
+ h.frames(2);
+ assert_eq!((fold_of("Plate"), count("Round")), (None, 0), "off again: as before");
+ }
+
+ /// #11945: a feature that changed two bodies is listed under each; Shift-clicking its second
+ /// row takes the range from the anchor to that row, not to its first row under the other body.
+ #[test]
+ fn a_feature_under_two_bodies_is_a_range_end_at_each_row() {
+ let mut h = Harness::new();
+ h.app.run("solid.box", json!({"length":20,"width":20,"height":10,"name":"Base","body_name":"Plate"})).unwrap();
+ let block = h
+ .app
+ .run("solid.box", json!({"length":5,"width":5,"height":10,"corner":[50,0,0],"operation":"new","name":"Block","body_name":"Other"}))
+ .unwrap()["feature"]
+ .as_u64()
+ .unwrap();
+ // A groove along the top of both bodies, splitting neither.
+ let groove = h
+ .app
+ .run(
+ "solid.box",
+ json!({"length":70,"width":2,"height":10,"corner":[-5,1,5],"operation":"cut","targets":["Plate","Other"],"name":"Groove"}),
+ )
+ .unwrap()["feature"]
+ .as_u64()
+ .unwrap();
+ assert_eq!(h.call("ui.prefs", json!({"browser_body_features": true}))["ok"], true);
+ h.frames(2);
+ for body in ["Plate", "Other"] {
+ h.step(&json!({"click": {"handle": format!("fold:{body}")}})).unwrap();
+ h.frames(2);
+ }
+ assert_eq!(count("Groove"), 2, "listed under both bodies");
+ let rows = drawn_rows();
+ let at = |label: &str, last: bool| {
+ let mut hits = rows.iter().filter(|(l, ..)| l == label);
+ let hit = if last { hits.next_back() } else { hits.next() };
+ hit.map(|row| row.1.center()).unwrap()
+ };
+ let (block_at, groove_at) = (at("Block", false), at("Groove", true));
+ h.step(&json!({"click": [block_at.x, block_at.y]})).unwrap();
+ h.step(&json!({"click": [groove_at.x, groove_at.y], "shift": true})).unwrap();
+ assert_eq!(h.app.session.selection, [Sel::Feature { id: block }, Sel::Feature { id: groove }], "only the rows under Other");
+ }
}
diff --git a/crates/ui-egui/src/browser_model.rs b/crates/ui-egui/src/browser_model.rs
index 4f80ce0581..5fc042b6cc 100644
--- a/crates/ui-egui/src/browser_model.rs
+++ b/crates/ui-egui/src/browser_model.rs
@@ -22,6 +22,8 @@ pub(super) struct Model {
placements: HashMap<Vec<u64>, Option<Arc<OccurrencePlacement>>>,
/// Each placed body's placement path, by the body's world name (built on first use).
body_paths: Option<HashMap<String, Vec<u64>>>,
+ /// The features that built each body, by its model name (worked out on first use, #11945).
+ body_features: Option<BTreeMap<String, Vec<u64>>>,
}
impl Model {
@@ -67,9 +69,16 @@ impl Model {
children,
placements: HashMap::new(),
body_paths: None,
+ body_features: None,
}
}
+ /// The features that built the body with this model name, in timeline order
+ /// ([`Session::body_features`]), worked out once per model.
+ pub fn body_features(&mut self, session: &Session, body: &str) -> Vec<u64> {
+ self.body_features.get_or_insert_with(|| session.body_features()).get(body).cloned().unwrap_or_default()
+ }
+
pub fn matches(&self, session: &Session) -> bool {
Arc::ptr_eq(&self.doc, &session.doc) && Arc::ptr_eq(&self.state, &session.model.state()) && self.pending_moves == session.pending_moves
}
diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs
index 72ccaa3200..176dfd62a8 100644
--- a/crates/ui-egui/src/prefs.rs
+++ b/crates/ui-egui/src/prefs.rs
@@ -1423,6 +1423,9 @@ preference_settings! {
/// Every component placement in the browser starts open, as before #9274, instead of closed
/// until the user opens it. Off by default.
browser_components_open: bool = false, PAGE_LAYOUT;
+ /// Each body row in the Browser folds open on the timeline features that built it, in
+ /// timeline order (#11945). Off by default: body rows have no fold arrow, as before.
+ browser_body_features: bool = false, PAGE_LAYOUT;
/// Folders in the Browser start closed, and placements too whatever "Components start open"
/// says, and they open only on request (#8768): with their arrow, Expand All or Find in
/// Browser, which opens just the rows down to its body and closes again the ones the last find
diff --git a/crates/ui-egui/src/prefs/interface.rs b/crates/ui-egui/src/prefs/interface.rs
index b9246d50d1..f979c6d32c 100644
--- a/crates/ui-egui/src/prefs/interface.rs
+++ b/crates/ui-egui/src/prefs/interface.rs
@@ -458,6 +458,13 @@ pub(super) fn layout(app: &mut SolveApp, ui: &mut egui::Ui) {
&mut app.preferences.browser_eye_left,
"browser_eye_left",
);
+ layout_check(
+ ui,
+ app.tr("prefs.browser_body_features"),
+ app.tr("prefs.browser_body_features_note"),
+ &mut app.preferences.browser_body_features,
+ "browser_body_features",
+ );
});
});
ui_kit::settings_section(ui, "dialogs", app.tr("prefs.dialogs"), |ui| {
diff --git a/tests/kernel-cases/EXEMPT b/tests/kernel-cases/EXEMPT
index 2ed26b6372..b63f899298 100644
--- a/tests/kernel-cases/EXEMPT
+++ b/tests/kernel-cases/EXEMPT
@@ -107,6 +107,7 @@ material.inspect materials and their properties
material.list materials and their properties
material.properties.directional materials and their properties
material.properties.validate materials and their properties
+model.body_features a listing of the model's timeline per body; crates/engine/src/schema/inspect_tests.rs
model.edges a listing of the model's topology
model.faces a listing of the model's topology
model.threads a listing of the model's topology