diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index cff8ab07a..09ca9d750 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -3471,15 +3471,35 @@ impl Document { self.features.iter().find(|f| f.name.eq_ignore_ascii_case(r)) } + /// Resolve a textual timeline reference. An exact name wins even when it looks like an id. + /// Older scripts also pass ids as strings or use a different case for a unique name. + pub fn resolve_feature_name(&self, name: &str) -> Result<&Feature> { + if let Some(feature) = self.features.iter().find(|f| f.name == name) { + return Ok(feature); + } + if let Ok(id) = name.parse::() + && let Some(feature) = self.feature(id) + { + return Ok(feature); + } + let mut matches = self.features.iter().filter(|f| f.name.eq_ignore_ascii_case(name)); + let feature = matches.next().ok_or_else(|| DocError::Invalid(format!("no feature `{name}`")))?; + if matches.next().is_some() { + return Err(DocError::Invalid(format!("ambiguous feature `{name}`. Use its exact name or numeric id"))); + } + Ok(feature) + } + /// The feature a pattern or mirror seed names, resolved the way `replay()` resolved seed /// names before seeds were keyed by id (#1134): an exact name match on a feature that is /// not a sketch or a construction plane wins — a sketch and its extrude often share a - /// name, and the feature that makes geometry is the one to copy — else [`find_feature`]. + /// name, and the feature that makes geometry is the one to copy. Other references use + /// the timeline lookup. pub fn seed_feature(&self, name: &str) -> Option<&Feature> { self.features .iter() .find(|x| x.name == name && !matches!(x.kind, FeatureKind::Sketch { .. } | FeatureKind::ConstructionPlane { .. })) - .or_else(|| self.find_feature(name)) + .or_else(|| self.resolve_feature_name(name).ok()) } fn unique_name(&self, base: &str) -> String { diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 8ddb0f953..c8b1a29cd 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; use solidcraft_doc::{FeatureKind, PlaneRef}; use super::CommandSpec; -use crate::params::{bad, name_or_id_list, vec3}; +use crate::params::{bad, name_or_id_values, vec3}; use crate::{Result, Session}; pub static COMMANDS: &[CommandSpec] = &[ @@ -24,14 +24,11 @@ pub static COMMANDS: &[CommandSpec] = &[ fn copy(s: &mut Session, p: &Value) -> Result { let cmd = "timeline.copy"; // The features are named or numbered, and both kinds can sit in one list. - let keys = name_or_id_list(cmd, p, "features")?; + let keys = name_or_id_values(cmd, p, "features")?; if keys.is_empty() || keys.len() > 1000 { return Err(bad(cmd, "`features` must list 1…1000 features")); } - let mut ids = Vec::new(); - for k in &keys { - ids.push(s.doc.find_feature(k).map(|f| f.id).ok_or_else(|| bad(cmd, format!("no feature `{k}`")))?); - } + let ids = keys.iter().map(|key| super::edit::feature_id(s, Some(key), cmd)).collect::>>()?; // Keep timeline order so sketches come before the features that use them. let copied: Vec = s.doc.features.iter().filter(|f| ids.contains(&f.id)).cloned().collect(); let names: Vec = copied.iter().map(|f| f.name.clone()).collect(); diff --git a/crates/engine/src/cmd/delete.rs b/crates/engine/src/cmd/delete.rs index a867786f4..05b1cfd80 100644 --- a/crates/engine/src/cmd/delete.rs +++ b/crates/engine/src/cmd/delete.rs @@ -160,8 +160,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { done = true; } if !features.is_empty() { - let ids: Vec = features.iter().map(u64::to_string).collect(); - sub(s, "timeline.delete", json!({ "features": ids }))?; + sub(s, "timeline.delete", json!({ "features": features }))?; done = true; } // Bodies still there (not made by a feature deleted above) get a Remove feature. diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index f49e881d4..a52f3d82a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -6,7 +6,7 @@ use serde_json::{Value, json}; use solidcraft_doc::{Feature, FeatureKind}; use super::CommandSpec; -use crate::params::{bad, bool_, name_or_id_list, num, str_}; +use crate::params::{bad, bool_, name_or_id_values, num, str_}; use crate::{EngineError, Result, Sel, Session, Snapshot}; pub static COMMANDS: &[CommandSpec] = &[ @@ -179,47 +179,37 @@ fn compute_all(s: &mut Session, _p: &Value) -> Result { Ok(json!({"features": s.model.results.len(), "errors": errors})) } -fn feature_id(s: &Session, v: Option<&Value>, cmd: &str) -> Result { - let key = match v { - Some(Value::Number(n)) => n.to_string(), - Some(Value::String(x)) => x.clone(), - _ => return Err(bad(cmd, "`feature` must be an id or name")), - }; - s.doc.find_feature(&key).map(|f| f.id).ok_or_else(|| bad(cmd, format!("no feature `{key}`"))) +pub(super) fn feature_id(s: &Session, v: Option<&Value>, cmd: &str) -> Result { + match v { + Some(Value::Number(n)) => n.as_u64().and_then(|id| s.doc.feature(id)).map(|f| f.id).ok_or_else(|| bad(cmd, format!("no feature `{n}`"))), + Some(Value::String(name)) => s.doc.resolve_feature_name(name).map(|f| f.id).map_err(|e| bad(cmd, e.to_string())), + _ => Err(bad(cmd, "`feature` must be an id or name")), + } } fn delete(s: &mut Session, p: &Value) -> Result { let cmd = "timeline.delete"; - // The features are named or numbered, and both kinds can sit in one list. - let mut keys = name_or_id_list(cmd, p, "features")?; - if let Some(f) = p.get("feature") { - keys.push(match f { - Value::Number(n) => n.to_string(), - Value::String(x) => x.clone(), - _ => String::new(), - }); - } + // Resolve every key against the same timeline. A cascade or a repeated key must never + // redirect a later delete to another feature that happens to match after the first one. + let keys = name_or_id_values(cmd, p, "features")?; + let mut ids = keys.iter().chain(p.get("feature")).map(|v| feature_id(s, Some(v), cmd)).collect::>>()?; let groups = group_ids(s, p, false, cmd)?; - if keys.is_empty() && groups.is_empty() { + if ids.is_empty() && groups.is_empty() { return Err(bad(cmd, "`features` must list features, or `groups` timeline folders")); } // 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())); + ids.extend(s.doc.features.iter().filter(|f| contents.contains(&f.id)).map(|f| f.id)); // 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 { - if gone.is_empty() { - return Err(bad(cmd, format!("no feature `{k}`"))); - } - continue; - }; - gone.extend(s.doc_mut().delete_feature(id)?); + for id in ids { + if s.doc.feature(id).is_some() { + gone.extend(s.doc_mut().delete_feature(id)?); + } } if !folders.is_empty() { s.doc_mut().timeline_groups.retain(|group| !folders.contains(&group.id)); diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs index bbab9166e..79051e8c4 100644 --- a/crates/engine/src/cmd/edit_tests.rs +++ b/crates/engine/src/cmd/edit_tests.rs @@ -774,6 +774,45 @@ fn feature_names(s: &Session) -> Vec { s.doc.features.iter().map(|feature| feature.name.clone()).collect() } +#[test] +fn timeline_keys_distinguish_numeric_names_from_ids() { + let mut s = four_boxes(); + let id = s.doc.find_feature("Second").unwrap().id; + let named = s.doc.find_feature("Third").unwrap().id; + let key = id.to_string(); + run(&mut s, "timeline.rename", json!({"feature": named, "name": key})); + + assert_eq!(run(&mut s, "timeline.inspect", json!({"feature": key}))["id"], named); + assert_eq!(run(&mut s, "timeline.inspect", json!({"feature": id}))["id"], id); + assert_eq!(run(&mut s, "timeline.inspect", json!({"feature": named.to_string()}))["id"], named); + assert_eq!(run(&mut s, "timeline.copy", json!({"features": [key, id]}))["copied"], json!(["Second", key])); + + // Resolve the whole request before deleting: a repeated name must not turn into an id + // after the first deletion removes the feature with that name. + assert_eq!(run(&mut s, "timeline.delete", json!({"features": [key, key]}))["deleted"], json!([named])); + assert!(s.doc.feature(id).is_some()); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "selection.delete", json!({"items": [Sel::Feature { id }]})); + assert!(s.doc.feature(id).is_none()); + assert!(s.doc.feature(named).is_some()); +} + +#[test] +fn timeline_keys_prefer_exact_case_and_refuse_an_ambiguous_fallback() { + let mut s = four_boxes(); + let second = s.doc.find_feature("Second").unwrap().id; + let third = s.doc.find_feature("Third").unwrap().id; + run(&mut s, "timeline.rename", json!({"feature": third, "name": "second"})); + + let before = s.doc.clone(); + let error = s.execute("timeline.delete", &json!({"features": ["First", "SECOND"]})).unwrap_err().to_string(); + assert!(error.contains("ambiguous"), "{error}"); + assert_eq!(s.doc, before); + assert_eq!(run(&mut s, "timeline.inspect", json!({"feature": "Second"}))["id"], second); + assert_eq!(run(&mut s, "timeline.suppress", json!({"feature": "second"}))["feature"], third); + assert_eq!(run(&mut s, "timeline.inspect", json!({"feature": "FIRST"}))["name"], "First"); +} + /// `timeline.delete {groups}` deletes a folder with its features and nested folders in one undo /// step; other folders and features stay, and `timeline.ungroup` still keeps the features (#7219). #[test] diff --git a/crates/engine/src/params.rs b/crates/engine/src/params.rs index 10e6343a1..4fcfc97f6 100644 --- a/crates/engine/src/params.rs +++ b/crates/engine/src/params.rs @@ -146,21 +146,22 @@ pub fn string_list(cmd: &str, p: &Value, k: &str) -> Result> { /// named by its position as in [`string_list`]. The commands that take feature keys read them /// here, because their list is not a list of names (#6651). pub fn name_or_id_list(cmd: &str, p: &Value, k: &str) -> Result> { + Ok(name_or_id_values(cmd, p, k)?.iter().map(|v| v.as_str().map(str::to_owned).unwrap_or_else(|| v.to_string())).collect()) +} + +/// Keep the JSON types when a command distinguishes a numeric name from a numeric id. +pub(crate) fn name_or_id_values<'a>(cmd: &str, p: &'a Value, k: &str) -> Result<&'a [Value]> { match p.get(k) { - None | Some(Value::Null) => Ok(Vec::new()), - Some(Value::String(s)) => Ok(vec![s.clone()]), + None | Some(Value::Null) => Ok(&[]), + Some(v @ Value::String(_)) => Ok(std::slice::from_ref(v)), Some(Value::Array(a)) => { if a.len() > MAX_STRING_LIST { return Err(bad(cmd, format!("`{k}` must list at most {MAX_STRING_LIST} keys"))); } - a.iter() - .enumerate() - .map(|(i, v)| match v { - Value::String(s) => Ok(s.clone()), - Value::Number(n) if n.is_u64() => Ok(n.to_string()), - other => Err(bad(cmd, format!("`{k}` must list names or ids; the entry {} is {}", i + 1, json_brief(other)))), - }) - .collect() + if let Some((i, v)) = a.iter().enumerate().find(|(_, v)| !v.is_string() && !v.is_u64()) { + return Err(bad(cmd, format!("`{k}` must list names or ids; the entry {} is {}", i + 1, json_brief(v)))); + } + Ok(a) } Some(v) => Err(bad(cmd, format!("`{k}` must be a list of names or ids; it is {}", json_brief(v)))), } diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 4ad86e43c..7f20d7ab0 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -3089,7 +3089,7 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) { let blank = app.session.doc.sketch(sketch).is_ok_and(crate::sketch_palette::is_blank); let depth = app.session.undo.len(); app.finish_sketch(); - if blank && app.session.active_sketch.is_none() && app.run("timeline.delete", json!({ "feature": sketch.to_string() })).is_ok() { + if blank && app.session.active_sketch.is_none() && app.run("timeline.delete", json!({ "feature": sketch })).is_ok() { app.session.undo.truncate(depth + 1); } continue;