SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Resolve picked-face feature actions and reveal the creator in Browser (#2301) (#2431)
amolinari-autotexe984e7d73890
diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rsindex 40f19acaea..42adc5cffb 100644--- a/crates/ui-egui/src/browser.rs+++ b/crates/ui-egui/src/browser.rs@@ -17,6 +17,12 @@ mod occurrence_gizmo_tests;#[path = "browser_model.rs"]mod model;+mod features;++pub(crate) fn reveal_feature(app: &mut SolveApp, id: u64, body: &str) {+ features::reveal(app, id, body);+}+#[cfg(test)]#[path = "browser_model_tests.rs"]mod model_tests;@@ -61,6 +67,8 @@ pub struct TreeState {pub expanded: BTreeSet<String>,/// Scroll to this body's row and open its folders (Find in Browser).pub reveal: Option<String>,+ /// A native feature to reveal in its placed component's Features folder.+ pub(super) reveal_feature: Option<features::Reveal>,/// The Move/Copy panel of an occurrence.pub occurrence_move: Option<OccMove>,/// The Redefine Sketch Plane panel (sketch id).@@ -488,7 +496,7 @@ fn sel_of_key(k: &str) -> Option<Sel> {if let Some(b) = k.strip_prefix("b:") {return Some(Sel::Body { name: b.to_string() });}- if let Some(s) = k.strip_prefix("s:") {+ if let Some(s) = k.strip_prefix("s:").or_else(|| k.strip_prefix("f:")) {return s.parse().ok().map(|id| Sel::Feature { id });}None@@ -952,6 +960,7 @@ fn component_rows(app: &mut SolveApp, ui: &mut egui::Ui, id: u64, depth: usize,for folder in ["bodies", "sketches", "construction"] {folder_rows(app, ui, id, folder, d, acts);}+ features::rows(app, ui, id, &[], d, acts);if id == 0 {crate::dialogs_assembly::browser_joints(app, ui, d);}@@ -1057,6 +1066,7 @@ fn occurrence_rows(app: &mut SolveApp, ui: &mut egui::Ui, path: Vec<u64>, depth:for folder in ["bodies", "sketches", "construction"] {occurrence_folder_rows(app, ui, placement.component, &path, folder, depth + 1, acts);}+ features::rows(app, ui, placement.component, &path, depth + 1, acts);let children = model_children(app, placement.component);if path.len() < 64 {for occurrence in children {diff --git a/crates/ui-egui/src/browser/features.rs b/crates/ui-egui/src/browser/features.rsnew file mode 100644index 0000000000..3cb44fc012--- /dev/null+++ b/crates/ui-egui/src/browser/features.rs@@ -0,0 +1,186 @@+//! Native feature rows in the component browser, separate from timeline layout and order.++use super::*;++#[derive(Clone, Debug)]+pub(crate) struct Reveal {+ pub id: u64,+ pub path: Vec<u64>,+}++/// Reveal the actual creating feature without changing the active component or history marker.+pub(crate) fn reveal(app: &mut SolveApp, id: u64, body: &str) {+ let Some(feature) = app.session.doc.feature(id) else { return };+ let component = feature.component;+ let state = app.session.model.state();+ let world = app.session.world_state();+ let Some(selected) = world.body(body) else { return };+ let source = selected.definition_name();+ let Some((_, path, _)) = app+ .session+ .doc+ .placements()+ .into_iter()+ .find(|(owner, path, _)| *owner == component && app.session.doc.world_body_name(&state, source, component, path) == body)+ else {+ return;+ };+ app.ui.show_browser = true;+ app.preferences.timeline_left_browser_collapsed = false;+ app.tree.reveal = None;+ app.tree.collapsed.remove("c0");+ for depth in 1..=path.len() {+ app.tree.collapsed.remove(&occurrence_key(&path[..depth]));+ }+ let scope = if path.is_empty() { format!("c{component}") } else { occurrence_key(&path) };+ app.tree.expanded.insert(format!("{scope}/features"));+ app.tree.reveal_feature = Some(Reveal { id, path });+ let _ = app.run("select.set", json!({"items":[Sel::Feature { id }]}));+}++pub(super) fn rows(app: &mut SolveApp, ui: &mut egui::Ui, component: u64, path: &[u64], depth: usize, acts: &mut Actions) {+ let has_features = match app.tree.model.as_ref().filter(|m| m.matches(&app.session)) {+ Some(model) => model.features.get(&component).is_some_and(|features| !features.is_empty()),+ None => app.session.doc.features.iter().any(|feature| feature.component == component),+ };+ if !has_features {+ return;+ }+ let scope = if path.is_empty() { format!("c{component}") } else { occurrence_key(path) };+ let key = format!("{scope}/features");+ let open = is_open(app, &key, false);+ let r = draw_row(ui, ui.id().with(&key), &Row { depth, fold: Some(open), icon: "folder", label: "Features", ..Default::default() });+ if r.fold || r.clicked {+ toggle(app, &key, false);+ }+ if !open {+ return;+ }+ let indices = match app.tree.model.as_ref().filter(|m| m.matches(&app.session)) {+ Some(model) => model.features.get(&component).cloned().unwrap_or_default(),+ None => app.session.doc.features.iter().enumerate().filter_map(|(i, f)| (f.component == component).then_some(i)).collect(),+ };+ for index in indices {+ let Some(feature) = app.session.doc.features.get(index) else { continue };+ let (id, label, icon) = (feature.id, feature.name.clone(), crate::timeline::icon_of(&feature.kind));+ let selected = app.session.selection.contains(&Sel::Feature { id });+ app.tree.order.push(format!("f:{id}"));+ let r = draw_row(ui, ui.id().with(("browser_feature", id)), &Row { depth: depth + 1, icon, label: &label, selected, ..Default::default() });+ if let Some(rect) = r.rect {+ crate::scenario::publish_handle(&format!("row:browser-feature:{scope}:{id}"), rect.center());+ if app.tree.reveal_feature.as_ref().is_some_and(|target| target.id == id && target.path == path) {+ ui.scroll_to_rect(rect, Some(egui::Align::Center));+ app.tree.reveal_feature = None;+ }+ }+ if r.double {+ if !path.is_empty() {+ let _ = app.run("component.activate", json!({"component":component,"occurrence":path.last(),"path":path}));+ }+ app.edit_feature(id);+ } else if r.clicked {+ click_select(app, ui, format!("f:{id}"), Some(Sel::Feature { id }));+ }+ if let Some(at) = r.secondary {+ acts.menu = Some((at, Target::Feature { id }));+ }+ }+}++#[cfg(test)]+#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]+mod tests {+ use super::*;+ use crate::scenario::Harness;++ fn find(app: &mut SolveApp, feature: u64, body: &str) {+ let state = app.session.world_state();+ let model_body = state.body(body).unwrap();+ let names = solidcraft_engine::doc::naming::face_names(model_body);+ let index = names.iter().position(|name| name.starts_with(&format!("F{feature}:"))).unwrap();+ app.session.selection = vec![Sel::Face { body: body.into(), index, point: solidcraft_engine::geom::Vec3::ZERO }];+ let item = crate::context_menu::items(app, &Target::Viewport).into_iter().find(|item| item.id == "ui.findBrowser").unwrap();+ assert!(item.enabled);+ crate::context_menu::run_item(app, &item, pos2(0.0, 0.0));+ assert_eq!(app.session.selection, [Sel::Feature { id: feature }]);+ }++ #[test]+ fn browser_feature_reveal_opens_the_picked_placement_and_survives_reopen() {+ let mut h = Harness::new();+ let assembly = h.app.run("component.create", json!({"name":"Assembly"})).unwrap();+ let component = h.app.run("component.create", json!({"name":"Part"})).unwrap();+ let base = h.app.run("solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Plate"})).unwrap()["feature"].as_u64().unwrap();+ let hole = h.app.run("solid.hole", json!({"position":[20,15,20],"diameter":8})).unwrap()["feature"].as_u64().unwrap();+ let fillet = h.app.run("solid.fillet", json!({"edges":[[0,0,10]],"radius":2})).unwrap()["feature"].as_u64().unwrap();+ h.app.run("solid.hole", json!({"position":[32,20,20],"diameter":4})).unwrap();+ let copy = h.app.run("occurrence.copy", json!({"occurrence":assembly["occurrence"],"translate":[70,25,10]})).unwrap();+ h.app.run("occurrence.move", json!({"occurrence":copy["occurrence"],"axis":[0,0,1],"angle":"35 deg","capture":true})).unwrap();+ let path = vec![copy["occurrence"].as_u64().unwrap(), component["occurrence"].as_u64().unwrap()];+ h.app.run("component.activate", json!({"component":0})).unwrap();+ let world_body = h.app.session.occurrence_bodies(&path, false).unwrap()[0].clone();+ let saved = h.app.session.doc.to_json();+ h.app.session = solidcraft_engine::Session::new(solidcraft_engine::doc::Document::from_json(&saved).unwrap());+ h.app.tree.collapsed.insert("c0".into());+ h.app.tree.collapsed.insert(occurrence_key(&path));+ h.app.preferences.timeline_left_browser_collapsed = true;+ let undo = h.app.session.undo.len();+ for id in [base, hole, fillet] {+ find(&mut h.app, id, &world_body);+ assert_eq!(h.app.tree.reveal_feature.as_ref().unwrap().path, path);+ assert!(!h.app.tree.collapsed.contains("c0"));+ assert!(!h.app.tree.collapsed.contains(&occurrence_key(&path)));+ assert!(!h.app.preferences.timeline_left_browser_collapsed);+ h.frames(2);+ assert!(h.app.tree.reveal_feature.is_none(), "the actual feature row was drawn and scrolled to");+ let at = h.call("ui.at", json!({"handle":format!("row:browser-feature:{}:{id}",occurrence_key(&path))}));+ assert!(at["ok"].as_bool().unwrap_or(false), "{at}");+ }+ assert_eq!(h.app.session.doc.to_json(), saved);+ assert_eq!(h.app.session.undo.len(), undo);+ assert_eq!(h.app.session.active_component, 0);+ }++ #[test]+ fn browser_feature_body_only_and_stale_targets_keep_their_meaning() {+ let mut h = Harness::new();+ h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Plate"})).unwrap();+ h.app.session.selection = vec![Sel::Body { name: "Plate".into() }];+ let item = crate::context_menu::items(&h.app, &Target::Viewport).into_iter().find(|item| item.id == "ui.findBrowser").unwrap();+ crate::context_menu::run_item(&mut h.app, &item, pos2(0.0, 0.0));+ assert_eq!(h.app.tree.reveal.as_deref(), Some("Plate"));+ assert!(h.app.tree.reveal_feature.is_none());+ let before = h.app.session.selection.clone();+ reveal(&mut h.app, u64::MAX, "Plate");+ reveal(&mut h.app, 1, "Missing");+ assert_eq!(h.app.session.selection, before);+ }++ #[test]+ fn browser_feature_imported_source_ids_never_reveal_an_unrelated_native_feature() {+ struct Source(std::path::PathBuf);+ impl Drop for Source {+ fn drop(&mut self) {+ let _ = std::fs::remove_file(&self.0);+ }+ }+ let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();+ let source = Source(std::env::temp_dir().join(format!("solidcraft-browser-import-{}-{stamp}.solidcraft", std::process::id())));+ let mut saved = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());+ saved.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Imported"})).unwrap();+ saved.run("file.save", json!({"path":source.0.to_string_lossy()})).unwrap();+ let mut h = Harness::new();+ let base = h.app.run("solid.box", json!({"length":5,"width":5,"height":5,"body_name":"Native"})).unwrap()["feature"].as_u64().unwrap();+ let inserted = h.app.run("component.insert_design", json!({"path":source.0.to_string_lossy()})).unwrap();+ let path = vec![inserted["occurrence"].as_u64().unwrap()];+ let name = h.app.session.occurrence_bodies(&path, false).unwrap()[0].clone();+ let state = h.app.session.world_state();+ let owner = state.body(&name).unwrap().feature;+ assert_ne!(owner, base);+ h.app.session.selection = vec![Sel::Face { body: name, index: 0, point: solidcraft_engine::geom::Vec3::ZERO }];+ for id in ["ui.findBrowser", "ui.findTimeline", "ui.editFeature"] {+ let item = crate::context_menu::items(&h.app, &Target::Viewport).into_iter().find(|item| item.id == id).unwrap();+ assert!(!item.enabled || item.params.as_ref().unwrap()["feature"] == json!(owner), "{id}: {item:?}");+ }+ }+}diff --git a/crates/ui-egui/src/browser_model.rs b/crates/ui-egui/src/browser_model.rsindex b1316dfa3d..8eb41ba30b 100644--- a/crates/ui-egui/src/browser_model.rs+++ b/crates/ui-egui/src/browser_model.rs@@ -17,6 +17,7 @@ pub(super) struct Model {pub bodies: HashMap<u64, Vec<usize>>,pub sketches: HashMap<u64, Vec<usize>>,pub planes: HashMap<u64, Vec<usize>>,+ pub features: HashMap<u64, Vec<usize>>,pub children: HashMap<u64, Vec<u64>>,placements: HashMap<Vec<u64>, Option<Arc<OccurrencePlacement>>>,/// Each placed body's placement path, by the body's world name (built on first use).@@ -32,7 +33,9 @@ impl Model {}let mut sketches: HashMap<u64, Vec<usize>> = HashMap::new();let mut planes: HashMap<u64, Vec<usize>> = HashMap::new();+ let mut features: HashMap<u64, Vec<usize>> = HashMap::new();for (i, feature) in session.doc.features.iter().enumerate() {+ features.entry(feature.component).or_default().push(i);let index = match feature.kind {FeatureKind::Sketch { .. } => &mut sketches,FeatureKind::ConstructionPlane { .. } => &mut planes,@@ -51,6 +54,7 @@ impl Model {bodies,sketches,planes,+ features,children,placements: HashMap::new(),body_paths: None,diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rsindex e02217e2b1..0c1d9e4a5c 100644--- a/crates/ui-egui/src/context_menu.rs+++ b/crates/ui-egui/src/context_menu.rs@@ -37,6 +37,10 @@ pub enum Target {Plane {id: u64,},+ /// A native feature row in a component's Features folder.+ Feature {+ id: u64,+ },/// An origin plane (XY, XZ or YZ).OriginPlane {name: String,@@ -270,6 +274,7 @@ pub fn target_bodies(app: &SolveApp, target: &Target) -> Vec<String> {Target::Occurrence { path } => app.session.occurrence_bodies(path, true).unwrap_or_default(),Target::Group { id, .. } => crate::browser::group_bodies(app, *id),Target::Sketch { .. }+ | Target::Feature { .. }| Target::Plane { .. }| Target::OriginPlane { .. }| Target::Folder { .. }@@ -329,6 +334,10 @@ pub fn items(app: &SolveApp, target: &Target) -> Vec<Item> {Target::Viewport => viewport_items(app),Target::Body { name } => body_items(app, std::slice::from_ref(name), true),Target::Sketch { id } => sketch_items(app, *id),+ Target::Feature { id } => vec![+ act("ui.editFeature", "Edit Feature", "").with(json!({"feature":id})).on(app.session.doc.feature(*id).is_some()),+ act("ui.findTimeline", "Find in Timeline", "").with(json!({"feature":id})).on(app.session.doc.feature(*id).is_some()),+ ],Target::Plane { id } => plane_items(app, *id),Target::OriginPlane { name } => origin_plane_items(app, name),Target::Component { id } => component_items(app, *id),@@ -373,9 +382,30 @@ pub fn items(app: &SolveApp, target: &Target) -> Vec<Item> {v}-/// The feature a body was made by, and that feature's sketch if it has one.-fn body_feature_and_sketch(app: &SolveApp, body: &str) -> (Option<u64>, Option<u64>) {- let f = body_feature(app, body);+/// Resolve the picked face's creator, rather than the feature that first made its body.+/// Persistent face names retain their creator through later trims and placements.+fn picked_face_feature(app: &SolveApp) -> Option<u64> {+ let (body, index) = app.session.selection.iter().find_map(|s| match s {+ Sel::Face { body, index, .. } => Some((body, *index)),+ _ => None,+ })?;+ let state = app.session.world_state();+ let body = state.body(body)?;+ let names = solidcraft_engine::doc::naming::face_names(body);+ let name = names.get(index)?;+ let (creator, _) = name.strip_prefix('F')?.split_once(':')?;+ let id = creator.parse::<u64>().ok()?;+ let owner = app.session.doc.feature(body.feature)?;+ if matches!(owner.kind, solidcraft_engine::doc::FeatureKind::Import { .. } | solidcraft_engine::doc::FeatureKind::MeshImport { .. })+ && id != owner.id+ {+ return None;+ }+ app.session.doc.feature(id).filter(|f| f.component == app.session.doc.model_body_component(body)).map(|f| f.id)+}++/// A feature and its profile sketch, if it has one.+fn feature_and_sketch(app: &SolveApp, f: Option<u64>) -> (Option<u64>, Option<u64>) {let sketch = f.and_then(|f| app.session.doc.feature(f)).and_then(|f| serde_json::to_value(&f.kind).ok())@@ -421,7 +451,7 @@ fn viewport_items(app: &SolveApp) -> Vec<Item> {v.extend(sketch_items(app, sketch));} else if has(|s| matches!(s, Sel::Face { .. })) {let face = sel.iter().find_map(|s| if let Sel::Face { body, .. } = s { Some(body.clone()) } else { None }).unwrap_or_default();- let (feature, sketch) = body_feature_and_sketch(app, &face);+ let (feature, sketch) = feature_and_sketch(app, picked_face_feature(app));let hidden = app.session.visibility.hidden_bodies.contains(&face);v.push(cmd(app, "sketch.create", "Create Sketch"));v.push(cmd(app, "solid.extrude", "Extrude"));@@ -437,8 +467,8 @@ fn viewport_items(app: &SolveApp) -> Vec<Item> {v.push(act("ui.delete", "Delete", "delete").key("Del"));v.push(act(if hidden { "ui.show" } else { "ui.hide" }, "Show/Hide", "eye").key("V").with(json!({ "bodies": [face] })));v.push(Item::sep());- v.push(act("ui.findBrowser", "Find in Browser", "").with(json!({ "body": face })));- v.push(act("ui.findTimeline", "Find in Timeline", "").with(json!({ "body": face })));+ v.push(act("ui.findBrowser", "Find in Browser", "").with(json!({ "body": face, "feature": feature })).on(feature.is_some()));+ v.push(act("ui.findTimeline", "Find in Timeline", "").with(json!({ "feature": feature })).on(feature.is_some()));v.push(Item::sep());v.push(cmd(app, "solid.press_pull", "Press Pull"));v.push(cmd(app, "inspect.measure", "Measure"));@@ -1000,8 +1030,16 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) {app.pick_save_command(&format!("{name}.step"), &["step", "stp", "igs", "stl", "3mf", "obj"], "file.export", json!({"bodies": bodies}));}"ui.findBrowser" => {+ if let Some(feature) = id_of(&p, "feature") {+ if let Some(body) = p.get("body").and_then(Value::as_str) {+ crate::browser::reveal_feature(app, feature, body);+ }+ return;+ }if let Some(b) = p.get("body").and_then(Value::as_str) {app.ui.show_browser = true;+ app.preferences.timeline_left_browser_collapsed = false;+ app.tree.reveal_feature = None;app.tree.reveal = Some(b.to_string());let _ = app.run("select.set", json!({"items": [{"type": "body", "name": b}]}));}diff --git a/crates/ui-egui/src/menu_tests.rs b/crates/ui-egui/src/menu_tests.rsindex ad09152be4..cfe1c47925 100644--- a/crates/ui-egui/src/menu_tests.rs+++ b/crates/ui-egui/src/menu_tests.rs@@ -805,3 +805,56 @@ fn menus_near_the_window_corner_open_inward() {}}}++#[test]+fn contribution_picked_faces_open_their_own_feature_after_later_modifiers() {+ use solidcraft_engine::{Sel, geom::Vec3};+ for expected in [1, 2, 3] {+ let mut app = SolveApp::new(Session::default(), Services::default());+ app.run("solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Plate"})).unwrap();+ app.run("solid.hole", json!({"position":[20,15,20],"diameter":8})).unwrap();+ app.run("solid.fillet", json!({"edges":[[0,0,10]],"radius":2})).unwrap();+ app.run("solid.hole", json!({"position":[32,20,20],"diameter":4})).unwrap();+ let state = app.session.world_state();+ let b = state.body("Plate").unwrap();+ let names = solidcraft_engine::doc::naming::face_names(b);+ let index = names.iter().position(|n| n.starts_with(&format!("F{expected}:"))).unwrap();+ let mesh = b.mesh();+ let point = mesh+ .triangles+ .iter()+ .enumerate()+ .find_map(|(i, t)| (mesh.tri_face.get(i).copied() == Some(index as u32)).then(|| mesh.tri(t)).flatten())+ .map(|t| (t[0] + t[1] + t[2]) / 3.0)+ .unwrap_or(Vec3::ZERO);+ let pick = Sel::Face { body: "Plate".into(), index, point };+ app.session.selection = vec![pick.clone()];+ let items = context_menu::items(&app, &Target::Viewport);+ for label in ["Edit Feature", "Find in Timeline", "Find in Browser"] {+ let item = find(&items, label);+ assert!(item.enabled, "{label}, {expected}: {names:?}");+ assert_eq!(item.params.as_ref().unwrap()["feature"], json!(expected));+ }+ act(&mut app, &Target::Viewport, "Find in Timeline");+ assert_eq!(app.session.selection, vec![Sel::Feature { id: expected }]);+ app.session.selection = vec![pick.clone()];+ act(&mut app, &Target::Viewport, "Find in Browser");+ assert_eq!(app.session.selection, vec![Sel::Feature { id: expected }]);+ assert_eq!(app.tree.reveal_feature.as_ref().unwrap().id, expected);+ app.session.selection = vec![pick];+ act(&mut app, &Target::Viewport, "Edit Feature");+ assert_eq!(app.dialog.as_ref().unwrap().editing.unwrap().0, expected);+ }+}++#[test]+fn contribution_unresolvable_face_does_not_edit_the_body_creator() {+ let mut app = SolveApp::new(Session::default(), Services::default());+ app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Plate"})).unwrap();+ app.session.selection =+ vec![solidcraft_engine::Sel::Face { body: "Plate".into(), index: usize::MAX, point: solidcraft_engine::geom::Vec3::ZERO }];+ let items = context_menu::items(&app, &Target::Viewport);+ assert!(!find(&items, "Edit Feature").enabled);+ assert!(!find(&items, "Find in Timeline").enabled);+ assert!(!find(&items, "Find in Browser").enabled);+}diff --git a/docs/picked-face-navigation.md b/docs/picked-face-navigation.mdnew file mode 100644index 0000000000..70dac8b5b6--- /dev/null+++ b/docs/picked-face-navigation.md@@ -0,0 +1,7 @@+# Picked-face navigation++A face selected in the viewport uses its persistent creating feature for **Edit Feature**, **Find in Timeline** and **Find in Browser**. Later holes, blends and trims do not redirect the action to the feature that originally created the whole body.++The Browser contains a **Features** folder for each native component with history. Find in Browser opens the ancestors and this folder in the selected body's actual occurrence, selects the creating feature and scrolls its row into view. Double-clicking the row opens its editor. This leaves the timeline layout, active component and history marker unchanged until an edit is requested.++Selecting a whole body keeps the existing body navigation. A face with an unavailable creator does not fall back to the body's base feature. Imported source identifiers do not acquire an unrelated editable native history.