diff --git a/crates/doc/src/component_removal.rs b/crates/doc/src/component_removal.rs index 3899e7da3..009eae8dc 100644 --- a/crates/doc/src/component_removal.rs +++ b/crates/doc/src/component_removal.rs @@ -81,6 +81,9 @@ impl Document { .filter(|j| occurrences.contains(&j.a.occurrence) || occurrences.contains(&j.b.occurrence)) .map(|j| j.id) .collect(); + for group in &mut self.timeline_groups { + group.joints.retain(|id| !joints.contains(id)); + } let assembly = &mut self.assembly; assembly.joints.retain(|j| !joints.contains(&j.id)); assembly.links.retain(|l| !joints.contains(&l.a) && !joints.contains(&l.b)); diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index bd3061665..ddb2da037 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -2851,7 +2851,7 @@ pub struct BrowserGroup { pub items: Vec, } -/// A saved feature-history folder. Folders may nest, and a feature can belong to at most one folder. +/// A saved history folder. Folders may nest; each feature or joint belongs to at most one folder. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct TimelineGroup { pub id: u64, @@ -2861,6 +2861,9 @@ pub struct TimelineGroup { pub parent: Option, #[serde(default)] pub features: Vec, + /// Joints stored in this timeline folder. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub joints: Vec, } /// The first feature-history folder whose own and nested features do not form one diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs index c6c524cf8..46cc22376 100644 --- a/crates/doc/src/format.rs +++ b/crates/doc/src/format.rs @@ -712,7 +712,9 @@ pub fn read(s: &str) -> Result { || d.params.len() > crate::document::MAX_PARAMS || d.components.len() > crate::document::MAX_FEATURES || d.timeline_groups.len() > crate::document::MAX_FEATURES - || d.timeline_groups.iter().any(|group| group.features.len() > crate::document::MAX_FEATURES) + || d.timeline_groups + .iter() + .any(|group| group.features.len() > crate::document::MAX_FEATURES || group.joints.len() > crate::document::MAX_FEATURES) { return Err(DocError::Invalid("document too large".into())); } @@ -720,6 +722,8 @@ pub fn read(s: &str) -> Result { let feature_ids: std::collections::BTreeSet<_> = d.features.iter().map(|feature| feature.id).collect(); let mut group_ids = std::collections::BTreeSet::new(); let mut grouped_features = std::collections::BTreeSet::new(); + let joint_ids: std::collections::BTreeSet<_> = d.assembly.joints.iter().map(|joint| joint.id).collect(); + let mut grouped_joints = std::collections::BTreeSet::new(); for group in &d.timeline_groups { if group.name.trim().is_empty() || group.name.len() > 128 || !group_ids.insert(group.id) { return Err(DocError::Invalid("damaged design: invalid timeline folder".into())); @@ -727,6 +731,9 @@ pub fn read(s: &str) -> Result { if group.parent.is_some_and(|parent| parent == group.id) { return Err(DocError::Invalid("damaged design: timeline folder cannot contain itself".into())); } + if group.joints.iter().any(|joint| !joint_ids.contains(joint) || !grouped_joints.insert(*joint)) { + return Err(DocError::Invalid("damaged design: invalid joint in a timeline folder".into())); + } if group.features.iter().any(|feature| !feature_ids.contains(feature) || !grouped_features.insert(*feature)) { return Err(DocError::Invalid("damaged design: invalid feature in a timeline folder".into())); } diff --git a/crates/doc/src/format/pending/timeline-joint-folders.rs b/crates/doc/src/format/pending/timeline-joint-folders.rs new file mode 100644 index 000000000..8862e1861 --- /dev/null +++ b/crates/doc/src/format/pending/timeline-joint-folders.rs @@ -0,0 +1,3 @@ +//! Timeline folders save joint ids alongside their feature ids. Older designs default to no +//! joint membership; empty membership is omitted. The last release refuses the newer format +//! and asks for an update instead of losing folder membership. diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 0122031b0..cc9b05989 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -566,7 +566,7 @@ fn feature_inserted_at_a_marker_inside_a_timeline_folder_joins_it() { let first = doc.add_feature(FeatureKind::Sketch { plane: PlaneRef::Origin { name: "XY".into() }, sketch: Sketch::new() }, Some("First")).unwrap(); let second = doc.add_feature(FeatureKind::Sketch { plane: PlaneRef::Origin { name: "XY".into() }, sketch: Sketch::new() }, Some("Second")).unwrap(); - doc.timeline_groups.push(TimelineGroup { id: 100, name: "Pair".into(), parent: None, features: vec![first, second] }); + doc.timeline_groups.push(TimelineGroup { id: 100, name: "Pair".into(), parent: None, features: vec![first, second], joints: vec![] }); doc.marker = Some(1); let inserted = @@ -700,3 +700,18 @@ fn empty_boolean_targets_without_overlap_keep_plain_message() { assert_eq!(model.result(cut).unwrap().error.as_deref(), Some("there is no body to cut or intersect")); } } + +#[test] +fn timeline_group_legacy_json_omits_empty_joint_membership() { + let old = serde_json::json!({"id":100, "name":"Folder", "parent":null, "features":[]}); + let group: TimelineGroup = serde_json::from_value(old.clone()).unwrap(); + assert!(group.joints.is_empty()); + assert_eq!(serde_json::to_value(&group).unwrap(), old); + let mut doc = Document::new("legacy folders"); + doc.timeline_groups.push(group); + doc.next_id = 101; + let saved = doc.to_json(); + let value: serde_json::Value = serde_json::from_str(&saved).unwrap(); + assert!(value["timeline_groups"][0].get("joints").is_none()); + assert_eq!(Document::from_json(&saved).unwrap().to_json(), saved); +} diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index ce2b3f31f..c31fc295a 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -382,6 +382,9 @@ fn unlock(s: &mut Session, p: &Value) -> Result { } let doc = s.doc_mut(); doc.assembly.joints.retain(|j| !gone.contains(&j.id)); + for group in &mut doc.timeline_groups { + group.joints.retain(|id| !gone.contains(id)); + } doc.assembly.links.retain(|l| !gone.contains(&l.a) && !gone.contains(&l.b)); s.visibility.hidden_joints.retain(|h| !gone.contains(h)); Ok(json!({"component": id, "joints": gone})) diff --git a/crates/engine/src/cmd/component_clone_assembly.rs b/crates/engine/src/cmd/component_clone_assembly.rs index 082e05df5..eba9472b3 100644 --- a/crates/engine/src/cmd/component_clone_assembly.rs +++ b/crates/engine/src/cmd/component_clone_assembly.rs @@ -267,6 +267,17 @@ pub(super) fn clone_assembly( features: &BTreeMap, bodies: &BTreeMap, ) -> Result> { + clone_assembly_with_joint_ids(doc, source, occurrences, features, bodies).map(|(messages, _)| messages) +} + +/// The copied joint identity map is also needed when extracting saved timeline folders. +pub(super) fn clone_assembly_with_joint_ids( + doc: &mut Document, + source: &Document, + occurrences: &BTreeMap, + features: &BTreeMap, + bodies: &BTreeMap, +) -> Result<(Vec, BTreeMap)> { budget(&source.assembly)?; budget(&doc.assembly)?; validate_map(occurrences)?; @@ -419,7 +430,7 @@ pub(super) fn clone_assembly( budget(&a)?; doc.next_id = item_id.checked_add(1).ok_or_else(|| invalid("assembly identifier space is exhausted"))?; doc.assembly = a; - Ok(messages) + Ok((messages, joints)) } #[cfg(test)] diff --git a/crates/engine/src/cmd/component_extract.rs b/crates/engine/src/cmd/component_extract.rs index 4933b4b22..4a7022091 100644 --- a/crates/engine/src/cmd/component_extract.rs +++ b/crates/engine/src/cmd/component_extract.rs @@ -357,8 +357,6 @@ fn part_design(s: &Session, sc: &Scope, stem: &str, cmd: &str) -> Result<(Sessio for g in &mut part.timeline_groups { g.features.retain(|f| sc.inside.contains(f)); } - let parents: BTreeSet = part.timeline_groups.iter().filter_map(|g| g.parent).collect(); - part.timeline_groups.retain(|g| !g.features.is_empty() || parents.contains(&g.id)); part.named_views.clear(); part.configs = Default::default(); part.assembly = Default::default(); @@ -371,7 +369,14 @@ fn part_design(s: &Session, sc: &Scope, stem: &str, cmd: &str) -> Result<(Sessio scope.assembly.origins.retain(|o| mapped(&o.origin.occurrence)); scope.assembly.contact_sets.retain(|c| c.occurrences.iter().all(mapped)); scope.assembly.exploded.retain(|v| v.moves.iter().all(|(o, _)| mapped(o))); - let mut notices = super::super::component_clone_assembly::clone_assembly(&mut part, &scope, &sc.occurrences, &features, &body_map)?; + let (mut notices, joints) = + super::super::component_clone_assembly::clone_assembly_with_joint_ids(&mut part, &scope, &sc.occurrences, &features, &body_map)?; + // Extracted joints receive new ids. References to joints outside the extracted part go away. + for group in &mut part.timeline_groups { + group.joints = group.joints.iter().filter_map(|id| joints.get(id).copied()).collect(); + } + let parents: BTreeSet = part.timeline_groups.iter().filter_map(|g| g.parent).collect(); + part.timeline_groups.retain(|g| !g.features.is_empty() || !g.joints.is_empty() || parents.contains(&g.id)); prune_params(&mut part); if !source.configs.is_empty() { notices.push(format!("the configurations stay in this design; {stem} has none")); @@ -785,6 +790,7 @@ mod tests { fn extract_moves_the_history_to_its_own_design_and_links_it() { let dir = folder("basic"); let (mut s, plate, other) = assembly(); + run(&mut s, "timeline.group", json!({"name":"Internal joints", "joints":["PinHold"]})); run(&mut s, "file.save", json!({"path": dir.join("asm.solidcraft")})); let (vol, cen) = (volumes(&s), centroids(&s)); let other_features: Vec = s.doc.features.iter().filter(|f| f.component == other).map(|f| f.id).collect(); @@ -815,6 +821,7 @@ mod tests { assert_eq!(part.doc.components.iter().map(|c| c.name.as_str()).collect::>(), ["Pin"]); assert_eq!(part.doc.occurrences.len(), 1); assert_eq!(part.doc.assembly.joints.iter().map(|j| j.name.as_str()).collect::>(), ["PinHold"]); + assert_eq!(part.doc.timeline_groups[0].joints, [part.doc.assembly.joints[0].id], "joint folders follow the extracted ids"); assert!(part.doc.param("plate_h").is_some() && part.doc.param("unused").is_none()); assert!(part.model.results.iter().all(|r| r.error.is_none())); let part_vol = volumes(&part); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 2a30b0c63..7be0b3ac9 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -42,19 +42,19 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SOLID", "MODIFY") .icon("delete") .key("Delete") - .params("feature: id|name | features: [id|name] | groups: [timeline folder ids] (a folder goes with all its features and nested folders; one undo step; a sketch takes its dependent features with it) → deleted: [ids]; groups?: [folder ids deleted]; failing?: [{feature, error}] (later features that worked and now fail)"), + .params("feature: id|name | features: [id|name] | groups: [timeline folder ids] (a folder goes with all its features, joints and nested folders; one undo step; a sketch takes its dependent features with it) → deleted: [feature ids]; joints?: [joint ids]; groups?: [folder ids deleted]; failing?: [{feature, error}] (later features that worked and now fail)"), CommandSpec::new("timeline.rename", "Rename", rename).icon("rename").params("feature: id|name, name (references to it follow)"), CommandSpec::new("timeline.group", "New Feature Folder", group) .icon("folder") .doc_only() - .params("name?; features?: [id|name]; parent?: folder id (features leave any other timeline folder)"), + .params("name?; features?: [id|name]; joints?: [id|name]; groups?: [folder ids]; parent?: folder id (features and joints leave any other timeline folder)"), CommandSpec::new("timeline.ungroup", "Remove Feature Folders", ungroup).icon("folder") .doc_only() - .params("group: id | groups: [ids] (features remain in the timeline)"), - CommandSpec::new("timeline.rename_group", "Rename Feature Folder", rename_group).icon("rename").doc_only().params("group: id, name"), + .params("group: id | groups: [ids] (features and joints remain in the timeline)"), + CommandSpec::new("timeline.rename_group", "Rename Feature Folder", rename_group).icon("rename").doc_only().params("group: id, name (renames the folder holding features and joints)"), CommandSpec::new("timeline.move_to_group", "Move Features to Folder", move_to_group).icon("folder") .doc_only() - .params("features?: [id|name], groups?: [ids], group?: id (omit or null to move to the timeline root)"), + .params("features?: [id|name], joints?: [id|name], groups?: [ids], group?: id (omit or null to move to the timeline root)"), CommandSpec::new("timeline.move_many", "Move Timeline Items", move_many).icon("reorder").params( "features?: [id|name], groups?: [folder ids], group?: folder id, position: insertion slot, active?: bool (true = the moved contents end up before the history marker, false = behind it; other features keep their state); atomically changes folder membership and moves all selected contents as one block", ), @@ -72,9 +72,9 @@ pub static COMMANDS: &[CommandSpec] = &[ .noundo() .params("feature: id|name → features deleted with it, and features that would fail without it"), CommandSpec::new("timeline.suppress", "Suppress Feature", suppress).icon("suppress").params( - "feature: id|name | features: [id|name] | groups: [timeline folder ids] (every feature in those folders and their nested \ - folders; one undo step), suppressed?: bool (default toggles: several features are all \ - suppressed unless all of them already are, then all are unsuppressed) → feature: id (or features: [ids]; groups: [ids] when given), suppressed", + "feature: id|name | features: [id|name] | groups: [timeline folder ids] (every feature and joint in those folders and their nested \ + folders; one undo step), suppressed?: bool (default toggles: features and joints are all \ + suppressed unless all of them already are, then all are unsuppressed) → feature: id (or features: [ids]; groups: [ids] and joints: [ids] when groups are given), suppressed", ), CommandSpec::new("timeline.edit", "Edit Feature", edit_feature).icon("edit").params( "feature: id|name, set: {fields to change, merged into the feature's definition as timeline.inspect returns it, \ @@ -83,7 +83,7 @@ pub static COMMANDS: &[CommandSpec] = &[ expressions are text, or a number in mm or degrees} → recomputed: features rebuilt, restored: features whose earlier result for the same inputs was reused", ), CommandSpec::new("timeline.inspect", "Inspect Feature", inspect_feature).icon("inspect").noundo().params( - "feature: id|name → type, definition (the fields timeline.edit's set changes, with their current values), \ + "group: folder id → group, name, parent, features, joints; or feature: id|name → type, definition (the fields timeline.edit's set changes, with their current values), \ inputs: [{label, param, expression, unit}] (named inputs parameters.change can also set), error, warning", ), CommandSpec::new("select.set", "Select", select_set).icon("select") @@ -205,10 +205,12 @@ fn delete(s: &mut Session, p: &Value) -> Result { } // A folder goes with its features and nested folders, its features in timeline order. let (folders, contents) = group_tree(&s.doc, &groups); + let joints = group_joint_ids(&s.doc, &groups); keys.extend(s.doc.features.iter().filter(|f| contents.contains(&f.id)).map(|f| f.id.to_string())); // Features that work now; any of them failing after the delete is reported (a later // feature that names a deleted body, #267). let worked: std::collections::BTreeSet = s.model.results.iter().filter(|r| r.error.is_none() && !r.skipped).map(|r| r.id).collect(); + super::joints::delete_joints(s.doc_mut(), &joints); let mut gone = Vec::new(); for k in keys { let Some(id) = s.doc.find_feature(&k).map(|f| f.id) else { @@ -239,6 +241,9 @@ fn delete(s: &mut Session, p: &Value) -> Result { .filter_map(|r| r.error.as_ref().map(|e| json!({"feature": r.name, "error": e}))) .collect(); let mut out = json!({"deleted": gone}); + if !joints.is_empty() { + out["joints"] = json!(joints); + } if !folders.is_empty() { out["groups"] = json!(folders); } @@ -315,6 +320,26 @@ fn group_features(s: &Session, p: &Value, required: bool, cmd: &str) -> Result Result> { + let values = match p.get("joints") { + None => return Ok(Vec::new()), + Some(Value::Array(values)) if values.len() <= 10_000 => values, + _ => return Err(bad(cmd, "`joints` must list at most 10000 joint ids or names")), + }; + let mut ids = std::collections::BTreeSet::new(); + for value in values { + ids.insert(super::joints::joint_id(s, Some(value), cmd)?); + } + Ok(ids.into_iter().collect()) +} + +fn group_joint_ids(doc: &solidcraft_doc::Document, roots: &[u64]) -> Vec { + let folders = group_tree(doc, roots).0; + let ids: std::collections::BTreeSet = + doc.timeline_groups.iter().filter(|group| folders.contains(&group.id)).flat_map(|group| group.joints.iter().copied()).collect(); + doc.assembly.joints.iter().filter(|joint| ids.contains(&joint.id)).map(|joint| joint.id).collect() +} + fn group_ids(s: &Session, p: &Value, required: bool, cmd: &str) -> Result> { let values = match p.get("groups") { Some(Value::Array(values)) => values, @@ -403,6 +428,7 @@ fn require_contiguous_groups(doc: &solidcraft_doc::Document, cmd: &str) -> Resul fn group(s: &mut Session, p: &Value) -> Result { let cmd = "timeline.group"; let mut features = group_features(s, p, false, cmd)?; + let mut joints = group_joints(s, p, cmd)?; let groups = group_ids(s, p, false, cmd)?; let name = match str_(p, "name").map(str::trim).filter(|name| !name.is_empty()) { Some(name) if name.len() <= 128 => name.to_string(), @@ -421,14 +447,17 @@ fn group(s: &mut Session, p: &Value) -> Result { } let nested = group_feature_ids(&s.doc, &groups); features.retain(|feature| !nested.contains(feature)); + let nested_joints = group_joint_ids(&s.doc, &groups); + joints.retain(|joint| !nested_joints.contains(joint)); let mut next = (*s.doc).clone(); for group in &mut next.timeline_groups { + group.joints.retain(|joint| !joints.contains(joint)); group.features.retain(|feature| !features.contains(feature)); if groups.contains(&group.id) { group.parent = Some(id); } } - next.timeline_groups.push(solidcraft_doc::TimelineGroup { id, name: name.clone(), parent, features }); + next.timeline_groups.push(solidcraft_doc::TimelineGroup { id, name: name.clone(), parent, features, joints }); sort_group_features(&mut next); require_contiguous_groups(&next, cmd)?; *s.doc_mut() = next; @@ -469,18 +498,19 @@ fn ungroup(s: &mut Session, p: &Value) -> Result { parent }; let mut next = (*s.doc).clone(); - let moved_features: Vec<(Option, Vec)> = next + let moved_features: Vec<(Option, Vec, Vec)> = next .timeline_groups .iter() .filter(|group| ids.contains(&group.id)) - .map(|group| (surviving_parent(group.parent), group.features.clone())) + .map(|group| (surviving_parent(group.parent), group.features.clone(), group.joints.clone())) .collect(); for group in &mut next.timeline_groups { if ids.contains(&group.id) { continue; } group.parent = surviving_parent(group.parent); - for (_, features) in moved_features.iter().filter(|(parent, _)| *parent == Some(group.id)) { + for (_, features, joints) in moved_features.iter().filter(|(parent, _, _)| *parent == Some(group.id)) { + group.joints.extend(joints.iter().copied()); group.features.extend(features.iter().copied()); } } @@ -507,9 +537,10 @@ fn rename_group(s: &mut Session, p: &Value) -> Result { fn move_to_group(s: &mut Session, p: &Value) -> Result { let cmd = "timeline.move_to_group"; let features = group_features(s, p, false, cmd)?; + let joints = group_joints(s, p, cmd)?; let groups = group_ids(s, p, false, cmd)?; - if features.is_empty() && groups.is_empty() { - return Err(bad(cmd, "list at least one feature or folder")); + if features.is_empty() && joints.is_empty() && groups.is_empty() { + return Err(bad(cmd, "list at least one feature, joint or folder")); } let target = match p.get("group") { Some(Value::Null) | None => None, @@ -522,8 +553,10 @@ fn move_to_group(s: &mut Session, p: &Value) -> Result { } let mut next = (*s.doc).clone(); for group in &mut next.timeline_groups { + group.joints.retain(|joint| !joints.contains(joint)); group.features.retain(|feature| !features.contains(feature)); if Some(group.id) == target { + group.joints.extend(joints.iter().copied()); group.features.extend(features.iter().copied()); } } @@ -535,7 +568,7 @@ fn move_to_group(s: &mut Session, p: &Value) -> Result { sort_group_features(&mut next); require_contiguous_groups(&next, cmd)?; *s.doc_mut() = next; - Ok(json!({"features": features, "groups": groups, "group": target})) + Ok(json!({"features": features, "joints": joints, "groups": groups, "group": target})) } fn move_many(s: &mut Session, p: &Value) -> Result { @@ -679,14 +712,18 @@ fn suppress(s: &mut Session, p: &Value) -> Result { let contents = group_feature_ids(&s.doc, &groups); let more: Vec = s.doc.features.iter().map(|f| f.id).filter(|id| contents.contains(id) && !ids.contains(id)).collect(); ids.extend(more); - if ids.is_empty() { - return Err(bad(cmd, "the timeline folders hold no features")); + let joints = group_joint_ids(&s.doc, &groups); + if ids.is_empty() && joints.is_empty() { + return Err(bad(cmd, "the timeline folders hold no features or joints")); } let want = match bool_(p, "suppressed") { Some(b) => b, None if p.get("suppressed").is_some_and(|v| !v.is_null()) => return Err(bad(cmd, "`suppressed` must be true or false")), // Toggle: one feature flips; several are all suppressed unless all already are. - None => !ids.iter().all(|id| s.doc.feature(*id).is_some_and(|f| f.suppressed)), + None => { + !(ids.iter().all(|id| s.doc.feature(*id).is_some_and(|f| f.suppressed)) + && joints.iter().all(|id| s.doc.assembly.joints.iter().any(|joint| joint.id == *id && joint.suppressed))) + } }; let keep = if want { counted_names_from(s, &ids) } else { Vec::new() }; // One command, so one undo step however many features it changes. @@ -700,10 +737,11 @@ fn suppress(s: &mut Session, p: &Value) -> Result { let f = doc.feature_mut(*id).ok_or_else(|| bad(cmd, format!("no feature {id}")))?; f.suppressed = want; } + super::joints::suppress_joints(s.doc_mut(), &joints, want); match ids.as_slice() { [id] if groups.is_empty() && p.get("features").is_none_or(Value::is_null) => Ok(json!({"feature": id, "suppressed": want})), _ if groups.is_empty() => Ok(json!({"features": ids, "suppressed": want})), - _ => Ok(json!({"features": ids, "groups": groups, "suppressed": want})), + _ => Ok(json!({"features": ids, "joints": joints, "groups": groups, "suppressed": want})), } } @@ -1063,6 +1101,11 @@ fn heavy_fields(kind: &FeatureKind) -> &'static [(&'static str, &'static str)] { fn inspect_feature(s: &mut Session, p: &Value) -> Result { let cmd = "timeline.inspect"; + if p.get("group").is_some() { + let id = timeline_group_id(s, p, cmd)?; + let group = s.doc.timeline_groups.iter().find(|group| group.id == id).ok_or_else(|| bad(cmd, "folder"))?; + return Ok(json!({"group": id, "name": group.name, "parent": group.parent, "features": group.features, "joints": group.joints})); + } let id = feature_id(s, p.get("feature"), cmd)?; let f = s.doc.feature(id).ok_or_else(|| bad(cmd, "feature"))?; let mut def = serde_json::to_value(f).map_err(|e| EngineError::Other(e.to_string()))?; diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs index 96cf19a2c..bbab9166e 100644 --- a/crates/engine/src/cmd/edit_tests.rs +++ b/crates/engine/src/cmd/edit_tests.rs @@ -1354,3 +1354,86 @@ fn a_move_before_a_long_history_of_one_body_fits_a_window_threads_stack() { .join(); assert!(moved.is_ok()); } + +#[test] +fn timeline_joint_folders_are_mixed_saved_and_undoable() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane":"XY", "name":"Profile"})); + run(&mut s, "component.create", json!({"name":"Part"})); + let joint = run(&mut s, "joint.as_built", json!({"type":"revolute", "a":0, "b":"Part", "name":"Hinge"}))["joint"].as_u64().unwrap(); + let folder = run(&mut s, "timeline.group", json!({"name":"Mixed", "features":["Profile"], "joints":["Hinge", joint]}))["group"].as_u64().unwrap(); + assert_eq!(s.doc.timeline_groups[0].joints, [joint]); + assert_eq!(s.doc.timeline_groups[0].features.len(), 1); + assert_eq!(run(&mut s, "timeline.inspect", json!({"group":folder}))["joints"], json!([joint])); + let saved = s.doc.to_json(); + let reopened = solidcraft_doc::Document::from_json(&saved).unwrap(); + assert_eq!(reopened.to_json(), saved); + let mut damaged: Value = serde_json::from_str(&saved).unwrap(); + damaged["timeline_groups"][0]["joints"] = json!([u64::MAX]); + assert!(solidcraft_doc::Document::from_json(&damaged.to_string()).is_err()); + damaged["timeline_groups"][0]["joints"] = json!([joint, joint]); + assert!(solidcraft_doc::Document::from_json(&damaged.to_string()).is_err()); + let destination = run(&mut s, "timeline.group", json!({"name":"Destination"}))["group"].as_u64().unwrap(); + run(&mut s, "timeline.move_to_group", json!({"joints":[joint], "group":destination})); + assert!(s.doc.timeline_groups[0].joints.is_empty()); + assert_eq!(s.doc.timeline_groups[1].joints, [joint]); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.timeline_groups[0].joints, [joint]); + // Both contents of a nested folder participate in the same toggle and undo. + run(&mut s, "timeline.move_to_group", json!({"groups":[folder], "group":destination})); + let before = s.doc.clone(); + run(&mut s, "timeline.suppress", json!({"groups":[destination]})); + assert!(s.doc.features[0].suppressed && s.doc.assembly.joints[0].suppressed); + run(&mut s, "timeline.suppress", json!({"groups":[destination]})); + assert!(!s.doc.features[0].suppressed && !s.doc.assembly.joints[0].suppressed); + run(&mut s, "edit.undo", json!({})); + assert!(s.doc.features[0].suppressed && s.doc.assembly.joints[0].suppressed); + run(&mut s, "edit.undo", json!({})); + assert_eq!(*s.doc, *before); + run(&mut s, "timeline.delete", json!({"groups":[destination]})); + assert!(s.doc.features.is_empty() && s.doc.assembly.joints.is_empty() && s.doc.timeline_groups.is_empty()); + run(&mut s, "edit.undo", json!({})); + assert_eq!(*s.doc, *before); + run(&mut s, "timeline.ungroup", json!({"group":folder})); + assert_eq!(s.doc.timeline_groups[0].joints, [joint], "contents promote to the surviving parent"); + run(&mut s, "timeline.ungroup", json!({"group":destination})); + assert!(s.doc.timeline_groups.is_empty()); + assert_eq!(s.doc.assembly.joints[0].id, joint); + let folder = run(&mut s, "timeline.group", json!({"joints":vec![joint; 10_000]}))["group"].as_u64().unwrap(); + assert_eq!(s.doc.timeline_groups[0].joints, [joint], "the 10000-entry cap is inclusive and deduplicated"); + run(&mut s, "timeline.move_to_group", json!({"joints":["Hinge"], "group":null})); + assert!(s.doc.timeline_groups[0].joints.is_empty()); + run(&mut s, "timeline.move_to_group", json!({"joints":["Hinge"], "group":folder})); + run(&mut s, "timeline.suppress", json!({"groups":[folder]})); + assert!(s.doc.assembly.joints[0].suppressed, "joint-only folders suppress too"); + run(&mut s, "joint.delete", json!({"joint":joint})); + assert!(s.doc.timeline_groups[0].joints.is_empty()); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.timeline_groups[0].joints, [joint]); + run(&mut s, "component.delete", json!({"component":"Part"})); + assert!(s.doc.assembly.joints.is_empty()); + assert!(s.doc.timeline_groups[0].joints.is_empty()); + assert!(solidcraft_doc::Document::from_json(&s.doc.to_json()).is_ok()); +} + +#[test] +fn timeline_joint_folders_reject_hostile_joint_references_atomically() { + let mut s = Session::default(); + run(&mut s, "component.create", json!({"name":"Part"})); + let joint = run(&mut s, "joint.as_built", json!({"type":"rigid", "a":0, "b":"Part"}))["joint"].as_u64().unwrap(); + let folder = run(&mut s, "timeline.group", json!({}))["group"].as_u64().unwrap(); + for command in ["timeline.group", "timeline.move_to_group"] { + for joints in + [json!([u64::MAX]), json!([-1]), json!([1e100]), json!(["missing"]), json!([{}]), json!([null]), json!("bad"), json!(vec![joint; 10_001])] + { + let before = s.doc.to_json(); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| s.execute(command, &json!({"joints":joints, "group":folder})))); + let error = result.unwrap().unwrap_err(); + assert!( + matches!(&error, crate::EngineError::BadParams { .. }), + "{command} must reject invalid joint references without an internal panic: {error}" + ); + assert_eq!(s.doc.to_json(), before); + } + } +} diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index 41148eb1c..0608885f1 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -1393,12 +1393,12 @@ fn edit(s: &mut Session, p: &Value) -> Result { if let Some(f) = bool_(p, "flip") { j.flip = f; } - if let Some(x) = bool_(p, "suppressed") { - j.suppressed = x; - } if let Some(n) = str_(p, "name").map(str::trim).filter(|n| !n.is_empty() && n.len() <= 128) { j.name = n.to_string(); } + if let Some(x) = bool_(p, "suppressed") { + suppress_joints(s.doc_mut(), &[id], x); + } // A relation whose type, offset, tilt or flip changes starts again from where its parts are. let reseat = kind.is_some() || offset.is_some() || angle.is_some() || p.get("flip").is_some(); if reseat { @@ -1413,6 +1413,25 @@ fn edit(s: &mut Session, p: &Value) -> Result { Ok(sol_json(&sol, p)) } +/// Shared mutation for individual joints and timeline folders; the caller resolves once. +pub(super) fn suppress_joints(doc: &mut solidcraft_doc::Document, ids: &[u64], suppressed: bool) { + let ids: std::collections::BTreeSet<_> = ids.iter().copied().collect(); + for joint in &mut doc.assembly.joints { + if ids.contains(&joint.id) { + joint.suppressed = suppressed; + } + } +} + +pub(super) fn delete_joints(doc: &mut solidcraft_doc::Document, ids: &[u64]) { + let ids: std::collections::BTreeSet<_> = ids.iter().copied().collect(); + doc.assembly.joints.retain(|joint| !ids.contains(&joint.id)); + doc.assembly.links.retain(|link| !ids.contains(&link.a) && !ids.contains(&link.b)); + for group in &mut doc.timeline_groups { + group.joints.retain(|id| !ids.contains(id)); + } +} + fn delete(s: &mut Session, p: &Value) -> Result { let cmd = "joint.delete"; if let Some(name) = str_(p, "origin") { @@ -1435,9 +1454,7 @@ fn delete(s: &mut Session, p: &Value) -> Result { return Ok(json!({"deleted_link": i})); } let id = joint_id(s, p.get("joint"), cmd)?; - let doc = s.doc_mut(); - doc.assembly.joints.retain(|j| j.id != id); - doc.assembly.links.retain(|l| l.a != id && l.b != id); + delete_joints(s.doc_mut(), &[id]); let sol = resolve(s); let mut out = sol_json(&sol, p); out["deleted"] = json!(id); diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index 8e35dd277..83c2926c6 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -1283,12 +1283,31 @@ fn joint_menu( } } +/// Membership is indexed once so a collapsed folder with hundreds of joints stays cheap. +fn timeline_joint_items(app: &SolveApp, ids: Option<&[u64]>) -> Vec<(u64, String, JointKind, bool)> { + let members: std::collections::BTreeSet = match ids { + Some(ids) => ids.iter().copied().collect(), + None => app.session.doc.timeline_groups.iter().flat_map(|group| group.joints.iter().copied()).collect(), + }; + app.session + .doc + .assembly + .joints + .iter() + .filter(|joint| members.contains(&joint.id) == ids.is_some()) + .map(|joint| (joint.id, joint.name.clone(), joint.kind, joint.suppressed)) + .collect() +} + /// Joints after the features in the timeline: double-click edits, the menu drives, suppresses /// or deletes. Returns the x after them. -pub fn timeline_joints(app: &mut SolveApp, ui: &mut egui::Ui, p: &egui::Painter, mut x: f32, r: egui::Rect) -> f32 { +pub fn timeline_joints(app: &mut SolveApp, ui: &mut egui::Ui, p: &egui::Painter, x: f32, r: egui::Rect) -> f32 { + timeline_joint_tiles(app, ui, p, x, r, None) +} + +pub(crate) fn timeline_joint_tiles(app: &mut SolveApp, ui: &mut egui::Ui, p: &egui::Painter, mut x: f32, r: egui::Rect, ids: Option<&[u64]>) -> f32 { let t = Tokens::get(); - let joints: Vec<(u64, String, JointKind, bool)> = - app.session.doc.assembly.joints.iter().map(|j| (j.id, j.name.clone(), j.kind, j.suppressed)).collect(); + let joints = timeline_joint_items(app, ids); if joints.is_empty() { return x; } @@ -1339,14 +1358,19 @@ pub fn timeline_joints(app: &mut SolveApp, ui: &mut egui::Ui, p: &egui::Painter, /// Named joint rows for the vertical feature-history layout. pub fn timeline_joints_vertical(app: &mut SolveApp, ui: &mut egui::Ui) { + timeline_joint_rows(app, ui, None); +} + +pub(crate) fn timeline_joint_rows(app: &mut SolveApp, ui: &mut egui::Ui, ids: Option<&[u64]>) { let t = Tokens::get(); - let joints: Vec<(u64, String, JointKind, bool)> = - app.session.doc.assembly.joints.iter().map(|joint| (joint.id, joint.name.clone(), joint.kind, joint.suppressed)).collect(); + let joints = timeline_joint_items(app, ids); if joints.is_empty() { return; } - ui.add_space(4.0); - ui.label(egui::RichText::new("JOINTS").size(crate::theme::Tokens::get().font_micro).semibold().color(t.text_dim)); + if ids.is_none() { + ui.add_space(4.0); + ui.label(egui::RichText::new("JOINTS").size(crate::theme::Tokens::get().font_micro).semibold().color(t.text_dim)); + } let mut open = None; let mut run = None; for (id, name, kind, suppressed) in joints { diff --git a/crates/ui-egui/src/history_rows.rs b/crates/ui-egui/src/history_rows.rs index 37ee998ff..410772201 100644 --- a/crates/ui-egui/src/history_rows.rs +++ b/crates/ui-egui/src/history_rows.rs @@ -208,7 +208,7 @@ mod tests { } fn folder(id: u64, features: &[u64], parent: Option) -> TimelineGroup { - TimelineGroup { id, name: format!("Folder{id}"), parent, features: features.to_vec() } + TimelineGroup { id, name: format!("Folder{id}"), parent, features: features.to_vec(), joints: vec![] } } /// The top-level rows as `(feature, slot, listed sketches as (sketch, reference))`. diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs index 581a7d634..07e040474 100644 --- a/crates/ui-egui/src/timeline.rs +++ b/crates/ui-egui/src/timeline.rs @@ -654,6 +654,109 @@ pub(crate) fn floating_rect(available: Rect) -> Rect { Container::floating_card(Surface::Panel).bottom_strip_rect(available, 40.0) } +#[derive(Clone, Debug)] +enum FolderTile { + Feature(usize), + Folder(u64), + Joints(Vec), +} + +/// Lay out each folder as a block, keeping feature order and placing its joints at its end. +fn folder_tiles(app: &SolveApp, features: &[u64]) -> Vec { + if app.session.doc.timeline_groups.is_empty() { + return (0..features.len()).map(FolderTile::Feature).collect(); + } + fn entries(app: &SolveApp, features: &[u64], parent: Option) -> Vec { + let groups = &app.session.doc.timeline_groups; + let mut entries: Vec<(usize, u64, FolderTile)> = features + .iter() + .enumerate() + .filter(|(_, id)| groups.iter().find(|group| group.features.contains(id)).map(|group| group.id) == parent) + .map(|(index, id)| (index, *id, FolderTile::Feature(index))) + .collect(); + for group in groups.iter().filter(|group| group.parent == parent) { + let mut pending = vec![group.id]; + let mut seen = std::collections::BTreeSet::new(); + let mut first = features.len(); + while let Some(id) = pending.pop() { + if !seen.insert(id) { + continue; + } + if let Some(group) = groups.iter().find(|group| group.id == id) { + first = first.min(features.iter().position(|id| group.features.contains(id)).unwrap_or(features.len())); + pending.extend(groups.iter().filter(|child| child.parent == Some(id)).map(|child| child.id)); + } + } + entries.push((first, group.id, FolderTile::Folder(group.id))); + } + entries.sort_by_key(|(index, id, _)| (*index, *id)); + entries.into_iter().map(|(_, _, tile)| tile).collect() + } + + let mut out = Vec::new(); + let mut pending = entries(app, features, None); + pending.reverse(); + let mut visited = std::collections::BTreeSet::new(); + while let Some(tile) = pending.pop() { + if let FolderTile::Folder(id) = tile { + if !visited.insert(id) { + continue; + } + out.push(FolderTile::Folder(id)); + if !app.tree.collapsed.contains(&format!("timeline_group:{id}")) { + if let Some(group) = app.session.doc.timeline_groups.iter().find(|group| group.id == id) { + pending.push(FolderTile::Joints(group.joints.clone())); + } + pending.extend(entries(app, features, Some(id)).into_iter().rev()); + } + } else { + out.push(tile); + } + } + out +} + +fn folder_tile(app: &mut SolveApp, ui: &mut egui::Ui, p: &egui::Painter, x: f32, r: Rect, id: u64) -> f32 { + let Some(group) = app.session.doc.timeline_groups.iter().find(|group| group.id == id).cloned() else { return x }; + let t = Tokens::get(); + let br = Rect::from_min_size(pos2(x, r.top() + 6.0), vec2(28.0, 28.0)); + let key = format!("timeline_group:{id}"); + let open = !app.tree.collapsed.contains(&key); + let resp = ui.interact(br, ui.id().with(("folder", id)), Sense::click()); + p.rect( + br, + t.radius_sm.saturating_sub(1), + if resp.hovered() { t.hover } else { t.timeline_item }, + t.control_border_stroke(t.border), + egui::StrokeKind::Inside, + ); + crate::icons::paint_icon(p, br.shrink(4.0), "folder", f32::from(t.icon.a()) / 255.0); + let mut pending = vec![id]; + let mut seen = std::collections::BTreeSet::new(); + let mut count = 0; + while let Some(id) = pending.pop() { + if !seen.insert(id) { + continue; + } + if let Some(group) = app.session.doc.timeline_groups.iter().find(|group| group.id == id) { + count += group.features.len() + group.joints.len(); + pending.extend(app.session.doc.timeline_groups.iter().filter(|child| child.parent == Some(id)).map(|child| child.id)); + } + } + p.text(br.right_bottom(), egui::Align2::RIGHT_BOTTOM, count.to_string(), egui::FontId::proportional(t.font_micro), t.text); + crate::scenario::publish_handle(&format!("timeline-folder:{}", group.name), br.center()); + crate::scenario::publish_handle(&format!("timeline-folder-fold:{}", group.name), br.center()); + if resp.clicked() { + if open { + app.tree.collapsed.insert(key); + } else { + app.tree.collapsed.remove(&key); + } + } + resp.on_hover_text(format!("{} ({count})", group.name)); + x + 32.0 +} + fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { let t = Tokens::get(); let accent = crate::theme::TabAccent::for_tab(&t, &app.ui.tab); @@ -739,7 +842,7 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { let drag_id = ui.id().with("tl_drag"); let mut drag: Option = ui.data(|d| d.get_temp(drag_id)); let pointer = ui.input(|i| i.pointer.hover_pos()); - let mut xs: Vec = Vec::new(); + let mut xs: Vec = vec![x; feats.len()]; let mut hovered: Option = None; let mut edit: Option = None; let mut marker_rect: Option = None; @@ -748,13 +851,47 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { // Each feature's result, found once for the strip: a search per chip made a long // timeline cost the square of its length every frame. let results = result_index(&app.session.model.results); - for (i, (id, name, icon, suppressed, ty, kind)) in feats.iter().enumerate() { + for tile in folder_tiles(app, &order) { + let i = match tile { + FolderTile::Folder(id) => { + if marker_rect.is_none() && app.tree.collapsed.contains(&format!("timeline_group:{id}")) { + let mut pending = vec![id]; + let mut seen = std::collections::BTreeSet::new(); + let mut contains_marker = false; + while let Some(id) = pending.pop() { + if !seen.insert(id) { + continue; + } + if let Some(group) = app.session.doc.timeline_groups.iter().find(|group| group.id == id) { + contains_marker |= order.get(marker).is_some_and(|feature| group.features.contains(feature)); + pending.extend( + app.session.doc.timeline_groups.iter().filter(|child| child.parent == Some(id)).map(|child| child.id), + ); + } + } + if contains_marker { + marker_rect = Some(Rect::from_min_size(pos2(x, r.top() + 5.0), vec2(t.space_12, r.height() - 10.0))); + x += t.space_16; + } + } + x = folder_tile(app, ui, &p, x, r, id); + continue; + } + FolderTile::Joints(ids) => { + x = crate::dialogs_assembly::timeline_joint_tiles(app, ui, &p, x, r, Some(&ids)); + continue; + } + FolderTile::Feature(index) => index, + }; + let Some((id, name, icon, suppressed, ty, kind)) = feats.get(i) else { continue }; let sketch_state = matches!(kind, TimelineKind::Sketch).then(|| sketch_states.get(*id)).flatten(); if i == marker { marker_rect = Some(Rect::from_min_size(pos2(x, r.top() + 5.0), vec2(t.space_12, r.height() - 10.0))); x += t.space_16; } - xs.push(x); + if let Some(slot) = xs.get_mut(i) { + *slot = x; + } let br = Rect::from_min_size(pos2(x, r.top() + 6.0), vec2(28.0, 28.0)); if reveal == Some(*id) { ui.scroll_to_rect(br, Some(egui::Align::Center)); @@ -868,6 +1005,11 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { }); x += 32.0; } + let mut previous = origin; + for slot in &mut xs { + *slot = (*slot).max(previous); + previous = *slot; + } let end = x; if marker >= feats.len() { marker_rect = Some(Rect::from_min_size(pos2(x, r.top() + 5.0), vec2(t.space_12, r.height() - 10.0))); @@ -973,6 +1115,45 @@ mod tests { use crate::scenario::Harness; + #[test] + fn joint_folder_hides_fifty_joint_tiles_in_both_history_layouts() { + use crate::scenario::handle_at; + for left in [false, true] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.timeline_left = left; + h.app.run("component.create", json!({"name":"Part"})).unwrap(); + let mut joints = Vec::new(); + for index in 0..50 { + joints.push( + h.app.run("joint.as_built", json!({"type":"rigid", "a":0, "b":"Part", "name":format!("Hinge{index}")})).unwrap()["joint"] + .as_u64() + .unwrap(), + ); + } + let folder = h.app.run("timeline.group", json!({"name":"Joints", "joints":joints})).unwrap()["group"].as_u64().unwrap(); + h.app.tree.collapsed.insert(format!("timeline_group:{folder}")); + h.frames(4); + assert!(handle_at("timeline-folder:Joints").is_some()); + assert_eq!(crate::scenario::handles("timeline-folder:").len(), 1); + assert!(crate::scenario::handles("timeline-joint:").is_empty()); + for index in 0..50 { + assert!(handle_at(&format!("timeline-joint:Hinge{index}")).is_none()); + } + h.step(&json!({"click":{"handle":"timeline-folder-fold:Joints"}})).unwrap(); + h.frames(4); + for index in 0..50 { + assert!(handle_at(&format!("timeline-joint:Hinge{index}")).is_some(), "joint {index} missing, left={left}"); + } + assert_eq!(crate::scenario::handles("timeline-joint:").len(), 50, "no trailing duplicates"); + h.step(&json!({"click":{"handle":"timeline-joint:Hinge0"}})).unwrap(); + assert_eq!(h.app.tree.picked_joints, [joints[0]]); + h.step(&json!({"click":{"handle":"timeline-folder-fold:Joints"}})).unwrap(); + h.frames(4); + assert!(handle_at("timeline-joint:Hinge0").is_none()); + } + } + #[test] fn history_status_translates_prefixes_and_both_diagnostics() { let diagnostic = "there is no body to cut or intersect in component 'Mount'; the tool may overlap 'Plate' in component 'Base' — activate that component or pick the body as a target"; diff --git a/crates/ui-egui/src/timeline_left.rs b/crates/ui-egui/src/timeline_left.rs index 8e262ca4a..3ef74922c 100644 --- a/crates/ui-egui/src/timeline_left.rs +++ b/crates/ui-egui/src/timeline_left.rs @@ -715,9 +715,13 @@ fn selection_actions(app: &mut SolveApp, ui: &mut egui::Ui, groups: &[solidcraft // The folders' own features and those of nested folders, as `timeline.suppress` and // `timeline.delete` take them with `groups` (#7219). let contents = folder_features(app, &selected_groups); - let all_suppressed = !contents.is_empty() && contents.iter().all(|id| app.session.doc.feature(*id).is_some_and(|f| f.suppressed)); + let joints = folder_joints(app, &selected_groups); + let has_contents = !contents.is_empty() || !joints.is_empty(); + let all_suppressed = has_contents + && contents.iter().all(|id| app.session.doc.feature(*id).is_some_and(|f| f.suppressed)) + && joints.iter().all(|id| app.session.doc.assembly.joints.iter().any(|joint| joint.id == *id && joint.suppressed)); let label = if all_suppressed { "Unsuppress Selected Folders" } else { "Suppress Selected Folders" }; - if crate::context_menu::button_enabled(ui, label, "suppress", !contents.is_empty()) + if crate::context_menu::button_enabled(ui, label, "suppress", has_contents) .on_hover_text(crate::i18n::tr("timeline.suppress_folders_tip")) .clicked() { @@ -782,6 +786,15 @@ fn folder_features(app: &SolveApp, roots: &[u64]) -> Vec { app.session.doc.features.iter().map(|feature| feature.id).filter(|feature| inside(*feature)).collect() } +fn folder_joints(app: &SolveApp, roots: &[u64]) -> Vec { + let groups = &app.session.doc.timeline_groups; + groups + .iter() + .filter(|group| roots.contains(&group.id) || roots.iter().any(|root| group_is_descendant(groups, group.id, *root))) + .flat_map(|group| group.joints.iter().copied()) + .collect() +} + fn group_is_descendant(groups: &[solidcraft_engine::doc::TimelineGroup], group: u64, ancestor: u64) -> bool { let mut current = groups.iter().find(|candidate| candidate.id == group).and_then(|candidate| candidate.parent); let mut steps = 0usize; @@ -798,6 +811,19 @@ fn group_is_descendant(groups: &[solidcraft_engine::doc::TimelineGroup], group: false } +/// A parent sorts immediately before its descendants, including folders with only joints. +fn group_path(groups: &[solidcraft_engine::doc::TimelineGroup], id: u64) -> Vec { + let mut path = Vec::new(); + let mut current = Some(id); + for _ in 0..groups.len() { + let Some(id) = current else { break }; + path.push(id); + current = groups.iter().find(|group| group.id == id).and_then(|group| group.parent); + } + path.reverse(); + path +} + fn group_depth(groups: &[solidcraft_engine::doc::TimelineGroup], id: u64) -> usize { let mut depth = 0; let mut current = groups.iter().find(|group| group.id == id).and_then(|group| group.parent); @@ -865,6 +891,23 @@ fn group_last_feature( direct.into_iter().chain(children).max() } +/// A folder with only joints shares its nearest feature-bearing ancestor's position. +fn group_position( + groups: &[solidcraft_engine::doc::TimelineGroup], + features: &[(u64, String, &'static str, bool, &'static str, TimelineKind)], + id: u64, +) -> Option { + let mut current = Some(id); + for _ in 0..groups.len() { + let id = current?; + if let Some(first) = group_first_feature(groups, features, id) { + return Some(first); + } + current = groups.iter().find(|group| group.id == id).and_then(|group| group.parent); + } + None +} + /// Whether Sketches: Under their feature is on (#6489). pub(crate) fn nests(app: &SolveApp) -> bool { app.preferences.history_sketches == crate::prefs::HistorySketches::UnderFeature @@ -897,8 +940,8 @@ fn visible_order( let mut order = Vec::new(); let mut shown = std::collections::BTreeSet::new(); for (index, (id, ..)) in features.iter().enumerate() { - let mut at_index: Vec<_> = groups.iter().filter(|group| group_first_feature(groups, features, group.id) == Some(index)).collect(); - at_index.sort_by_key(|group| (group_depth(groups, group.id), group.id)); + let mut at_index: Vec<_> = groups.iter().filter(|group| group_position(groups, features, group.id) == Some(index)).collect(); + at_index.sort_by_key(|group| group_path(groups, group.id)); for group in at_index { if group_ancestors_are_open(app, groups, group.id) && shown.insert(group.id) { order.push(TimelineItem::Group(group.id)); @@ -916,7 +959,7 @@ fn visible_order( } } let mut trailing: Vec<_> = groups.iter().filter(|group| !shown.contains(&group.id)).collect(); - trailing.sort_by_key(|group| (group_first_feature(groups, features, group.id).unwrap_or(usize::MAX), group_depth(groups, group.id), group.id)); + trailing.sort_by_key(|group| (group_position(groups, features, group.id).unwrap_or(usize::MAX), group_path(groups, group.id))); for group in trailing { if group_ancestors_are_open(app, groups, group.id) && shown.insert(group.id) { order.push(TimelineItem::Group(group.id)); @@ -1018,7 +1061,14 @@ fn vertical_group_row( crate::ui_kit::disclosure(ui.painter(), centre, open, t.text_dim); // A folder whose features are all suppressed looks like a suppressed feature. let contents = folder_features(app, &[group.id]); - let suppressed = !contents.is_empty() && contents.iter().all(|id| app.session.doc.feature(*id).is_some_and(|f| f.suppressed)); + let joints: Vec<_> = groups + .iter() + .filter(|candidate| candidate.id == group.id || group_is_descendant(groups, candidate.id, group.id)) + .flat_map(|group| group.joints.iter()) + .collect(); + let suppressed = (!contents.is_empty() || !joints.is_empty()) + && contents.iter().all(|id| app.session.doc.feature(*id).is_some_and(|f| f.suppressed)) + && joints.iter().all(|id| app.session.doc.assembly.joints.iter().any(|joint| joint.id == **id && joint.suppressed)); let mut painter = ui.painter().clone(); if suppressed { painter.multiply_opacity(0.42); @@ -1080,6 +1130,23 @@ fn vertical_group_row( open } +fn folder_joint_rows( + app: &mut SolveApp, + ui: &mut egui::Ui, + group: &solidcraft_engine::doc::TimelineGroup, + groups: &[solidcraft_engine::doc::TimelineGroup], +) { + if !group.joints.is_empty() && group_is_open(app, groups, group.id) { + ui.scope_builder(egui::UiBuilder::new().id_salt(("folder_joints", group.id)), |ui| { + ui.spacing_mut().item_spacing.x = 0.0; + ui.horizontal(|ui| { + ui.add_space((group_depth(groups, group.id) + 1) as f32 * FOLDER_INDENT); + ui.vertical(|ui| crate::dialogs_assembly::timeline_joint_rows(app, ui, Some(&group.joints))); + }); + }); + } +} + /// The fold-arrow column of a history row. With sketches listed under their features every row /// keeps it, so the icons of rows with and without a fold line up. const FOLD_COLUMN: f32 = 16.0; @@ -1152,7 +1219,7 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { let plan = drawn_rows(app, under_feature); let order = visible_order(app, &features, &groups, &plan); let first_indices: std::collections::BTreeMap> = - groups.iter().map(|group| (group.id, group_first_feature(&groups, &features, group.id))).collect(); + groups.iter().map(|group| (group.id, group_position(&groups, &features, group.id))).collect(); let end_indices: std::collections::BTreeMap = groups .iter() .map(|group| (group.id, group_last_feature(&groups, &features, group.id).map_or(features.len(), |index| index.saturating_add(1)))) @@ -1185,7 +1252,7 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { for (index, (id, ..)) in features.iter().enumerate() { let group_id = group_for(&groups, *id); let mut at_index: Vec<_> = groups.iter().filter(|group| first_indices.get(&group.id).copied().flatten() == Some(index)).collect(); - at_index.sort_by_key(|group| (group_depth(&groups, group.id), group.id)); + at_index.sort_by_key(|group| group_path(&groups, group.id)); let marker_before_group = index == marker && !at_index.is_empty(); if marker_before_group { let group = at_index.first().and_then(|group| group.parent); @@ -1211,6 +1278,9 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { &mut slots, &mut folder_drop_zones, ); + if group_first_feature(&groups, &features, group.id).is_none() { + folder_joint_rows(app, ui, group, &groups); + } rendered_group_header = true; } } @@ -1221,17 +1291,20 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { marker_y = vertical_marker(app, ui, &mut rows.drag); } // A sketch listed under a feature is drawn after that feature's row. - let Some(row) = plan.row_at(index) else { continue }; - if !group_open { - continue; + if group_open && let Some(row) = plan.row_at(index) { + slots.push(VerticalSlot { y: ui.cursor().top(), position: row.slot.min(index), group: group_id, indent_group }); + let indent = group_id.map(|id| (group_depth(&groups, id) + 1) as f32 * FOLDER_INDENT).unwrap_or(0.0); + feature_row(app, ui, &mut rows, index, indent, RowKind::Own); + previous_visible_group = group_id; + } + let mut ending: Vec<_> = groups.iter().filter(|group| group_last_feature(&groups, &features, group.id) == Some(index)).collect(); + ending.sort_by_key(|group| std::cmp::Reverse(group_depth(&groups, group.id))); + for group in ending { + folder_joint_rows(app, ui, group, &groups); } - slots.push(VerticalSlot { y: ui.cursor().top(), position: row.slot.min(index), group: group_id, indent_group }); - let indent = group_id.map(|id| (group_depth(&groups, id) + 1) as f32 * FOLDER_INDENT).unwrap_or(0.0); - feature_row(app, ui, &mut rows, index, indent, RowKind::Own); - previous_visible_group = group_id; } let mut trailing: Vec<_> = groups.iter().filter(|group| !shown_groups.contains(&group.id)).collect(); - trailing.sort_by_key(|group| (first_indices.get(&group.id).copied().flatten().unwrap_or(usize::MAX), group_depth(&groups, group.id), group.id)); + trailing.sort_by_key(|group| (first_indices.get(&group.id).copied().flatten().unwrap_or(usize::MAX), group_path(&groups, group.id))); for group in trailing { if group_ancestors_are_open(app, &groups, group.id) && shown_groups.insert(group.id) { vertical_group_row( @@ -1249,6 +1322,7 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { &mut slots, &mut folder_drop_zones, ); + folder_joint_rows(app, ui, group, &groups); } } slots.push(VerticalSlot { y: ui.cursor().top(), position: n, group: None, indent_group: previous_visible_group }); @@ -2258,10 +2332,10 @@ mod tests { let at_end = VerticalSlot { y: 60.0, position: 2, group: None, indent_group: Some(3) }; let folder_rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(200.0, 20.0)); let groups = vec![ - solidcraft_engine::doc::TimelineGroup { id: 1, name: "Outer".into(), parent: None, features: vec![] }, - solidcraft_engine::doc::TimelineGroup { id: 2, name: "Middle".into(), parent: Some(1), features: vec![] }, - solidcraft_engine::doc::TimelineGroup { id: 3, name: "Inner".into(), parent: Some(2), features: vec![] }, - solidcraft_engine::doc::TimelineGroup { id: 7, name: "Target".into(), parent: None, features: vec![] }, + solidcraft_engine::doc::TimelineGroup { id: 1, name: "Outer".into(), parent: None, features: vec![], joints: vec![] }, + solidcraft_engine::doc::TimelineGroup { id: 2, name: "Middle".into(), parent: Some(1), features: vec![], joints: vec![] }, + solidcraft_engine::doc::TimelineGroup { id: 3, name: "Inner".into(), parent: Some(2), features: vec![], joints: vec![] }, + solidcraft_engine::doc::TimelineGroup { id: 7, name: "Target".into(), parent: None, features: vec![], joints: vec![] }, ]; assert_eq!( @@ -2391,6 +2465,55 @@ mod tests { harness.frames(4); } + #[test] + fn joint_folder_rows_follow_their_nested_folder_before_its_sibling() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.timeline_left = true; + h.app.run("sketch.create", json!({"plane":"XY", "name":"Profile"})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.app.run("component.create", json!({"name":"Part"})).unwrap(); + for name in ["A", "B", "C"] { + h.app.run("joint.as_built", json!({"type":"rigid", "a":0, "b":"Part", "name":name})).unwrap(); + } + let outer = h.app.run("timeline.group", json!({"name":"Outer", "features":["Profile"]})).unwrap()["group"].as_u64().unwrap(); + let first = h.app.run("timeline.group", json!({"name":"First", "joints":["A"], "parent":outer})).unwrap()["group"].as_u64().unwrap(); + h.app.run("timeline.group", json!({"name":"Second", "joints":["C"], "parent":outer})).unwrap(); + h.app.run("timeline.group", json!({"name":"Nested", "joints":["B"], "parent":first})).unwrap(); + h.frames(4); + let y = |name| handle_at(name).unwrap().y; + assert!(y("timeline-folder:First") < y("timeline-joint:A")); + assert!(y("timeline-joint:A") < y("timeline-folder:Nested")); + assert!(y("timeline-folder:Nested") < y("timeline-joint:B")); + assert!(y("timeline-joint:B") < y("timeline-folder:Second")); + assert!(y("timeline-folder:Second") < y("timeline-joint:C")); + h.app.tree.collapsed.insert(format!("timeline_group:{first}")); + h.frames(4); + assert!(handle_at("timeline-joint:A").is_none() && handle_at("timeline-joint:B").is_none()); + assert!(handle_at("timeline-joint:C").is_some()); + } + + #[test] + fn joint_folder_menu_suppresses_and_deletes_joints_in_one_step() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.timeline_left = true; + h.app.run("component.create", json!({"name":"Part"})).unwrap(); + let joint = h.app.run("joint.as_built", json!({"type":"revolute", "a":0, "b":"Part", "name":"Hinge"})).unwrap()["joint"].as_u64().unwrap(); + h.app.run("timeline.group", json!({"name":"Folder", "joints":[joint]})).unwrap(); + h.frames(4); + folder_menu(&mut h, "Folder", "Suppress Selected Folders"); + assert!(h.app.session.doc.assembly.joints[0].suppressed); + folder_menu(&mut h, "Folder", "Unsuppress Selected Folders"); + assert!(!h.app.session.doc.assembly.joints[0].suppressed); + let before = h.app.session.doc.clone(); + folder_menu(&mut h, "Folder", "Delete Folders and Features…"); + assert!(h.app.session.doc.assembly.joints.is_empty()); + assert!(h.app.session.doc.timeline_groups.is_empty()); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(*h.app.session.doc, *before); + } + /// A folder's menu suppresses and unsuppresses every feature in it and in its nested folders, /// and deletes the folders with their features in one undo step (#7219). #[test] diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.md index ccf7a1808..3e3748b9e 100644 --- a/docs/book/src/guide/ui-tour.md +++ b/docs/book/src/guide/ui-tour.md @@ -139,6 +139,7 @@ selects it, and while the marker sits between a sketch and its feature, or the two are in different folders, the sketch keeps a row of its own. The timeline along the bottom always lists features in creation order. + Feature Folders can contain joints as well as features; closing a folder hides both behind one tile. - **Status bar** (off by default: Preferences › Interface › **Status bar**). A thin bar along the window's bottom edge, below the timeline. From the right: the design's units (click them to change the design's units, one undo step), the open sketch's state in its colour (under