Skip to content

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

Parameters: the Filter box finds a name by the starts of its words, so toodia finds tooth_outward_flange_diameter (#11978) (#12695)

PaddleStrokea6c0e8a959e4
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 3c0ff6a6bf..2fb992d761 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -102,7 +102,7 @@ pub use eval::{
pub use eval::{EvalCache, KeptResults};
pub use expr::Expr;
pub use names::{BodyName, FeatureId, FeatureName, SketchId, copy_name};
-pub use params::{ParamRow, ParamUser, cycles};
+pub use params::{ParamRow, ParamUser, cycles, name_words_match};
pub use points::{Dir, FacePick, Position, plain};
pub use solidcraft_kernel as kernel;
pub use solidcraft_sketch as sketch;
diff --git a/crates/doc/src/params.rs b/crates/doc/src/params.rs
index 15ea16ca2f..63cbde1c01 100644
--- a/crates/doc/src/params.rs
+++ b/crates/doc/src/params.rs
@@ -1150,6 +1150,76 @@ fn csv_fields(record: &str) -> Result<Vec<String>> {
.collect()
}
+/// Whether `query` spells the starts of some words of `name`, in order, ignoring case: for
+/// `tooth_outward_flange_diameter`, `toodia`, `toofla`, `outdia` and `toofladia` all match
+/// (#11978). Words may be skipped but not reordered. Underscores, hyphens, spaces and other
+/// separators split `name` into words, and so do camelCase and letter-digit boundaries.
+/// Underscores, hyphens and spaces in `query` are ignored. A query with any other symbol (an
+/// expression such as `width *`) or with no letters or digits never matches here. This only adds
+/// to a plain substring search: callers keep that one too.
+pub fn name_words_match(name: &str, query: &str) -> bool {
+ if query.chars().any(|c| !(c.is_alphanumeric() || matches!(c, '_' | '-' | ' '))) {
+ return false;
+ }
+ let query: Vec<char> = query.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect();
+ let words = name_words(name);
+ // Every query character must come from some word, so a longer query can never match;
+ // this also bounds the work below by the name's length.
+ if query.is_empty() || query.len() > words.iter().map(Vec::len).sum::<usize>() {
+ return false;
+ }
+ // `reached[i]`: the first `i` query characters are spelled by word starts seen so far.
+ let mut reached = vec![false; query.len() + 1];
+ if let Some(first) = reached.first_mut() {
+ *first = true;
+ }
+ for word in &words {
+ // From the highest start down, so each word extends a match at most once.
+ for start in (0..query.len()).rev() {
+ if !reached.get(start).copied().unwrap_or(false) {
+ continue;
+ }
+ let rest = query.get(start..).unwrap_or_default();
+ for (k, _) in word.iter().zip(rest).take_while(|(a, b)| a == b).enumerate() {
+ if let Some(r) = reached.get_mut(start + k + 1) {
+ *r = true;
+ }
+ }
+ }
+ if reached.last().copied().unwrap_or(false) {
+ return true;
+ }
+ }
+ false
+}
+
+/// The words of a parameter name, in lower case: see [`name_words_match`].
+fn name_words(name: &str) -> Vec<Vec<char>> {
+ let mut words = Vec::new();
+ let mut word: Vec<char> = Vec::new();
+ let mut previous: Option<char> = None;
+ for c in name.chars() {
+ let split = match previous {
+ _ if !c.is_alphanumeric() => true,
+ Some(p) => (p.is_lowercase() && c.is_uppercase()) || p.is_numeric() != c.is_numeric(),
+ None => false,
+ };
+ if split && !word.is_empty() {
+ words.push(std::mem::take(&mut word));
+ }
+ if c.is_alphanumeric() {
+ word.extend(c.to_lowercase());
+ previous = Some(c);
+ } else {
+ previous = None;
+ }
+ }
+ if !word.is_empty() {
+ words.push(word);
+ }
+ words
+}
+
/// Parameters whose definitions depend on each other in a loop.
pub fn cycles(list: &[(String, String, Kind)]) -> BTreeSet<String> {
let refs: BTreeMap<&str, Vec<String>> = list.iter().map(|(n, e, _)| (n.as_str(), expr::references(e))).collect();
@@ -1236,3 +1306,47 @@ mod design_length_tests {
}
}
}
+
+#[cfg(test)]
+mod name_words_tests {
+ use super::name_words_match;
+
+ #[test]
+ fn the_starts_of_words_in_order_find_a_long_name() {
+ let name = "tooth_outward_flange_diameter";
+ for query in ["too", "dia", "toodia", "toofla", "outdia", "toofladia", "TooDia", "too_dia", "tooth outward", "toothoutwardflangediameter"] {
+ assert!(name_words_match(name, query), "{query}");
+ }
+ // Out of order, from inside a word, more than the words hold, or not a name at all.
+ for query in ["diatoo", "ooth", "toodiax", "toox", "", "_", "- ", "tooth *", "too.dia"] {
+ assert!(!name_words_match(name, query), "{query}");
+ }
+ }
+
+ #[test]
+ fn camel_case_hyphens_and_digits_split_words() {
+ assert!(name_words_match("boltHoleDepth", "bhd"));
+ assert!(name_words_match("boltHoleDepth", "holedep"));
+ assert!(name_words_match("rib-count-max", "rcm"));
+ assert!(name_words_match("hole2_depth", "h2d"));
+ assert!(name_words_match("Länge_Außen", "läau"));
+ assert!(!name_words_match("boltholedepth", "bhd"));
+ }
+
+ #[test]
+ fn a_later_word_can_take_over_part_of_a_match() {
+ // `ab` must not be taken whole from `abc` when the match needs `a` and then `bd...`.
+ assert!(name_words_match("abc_bd", "abd"));
+ assert!(name_words_match("aa_ab", "aab"));
+ }
+
+ #[test]
+ fn hostile_names_and_queries_never_panic() {
+ let long = "a_".repeat(5_000);
+ assert!(name_words_match(&long, &"a".repeat(5_000)));
+ assert!(!name_words_match(&long, &"a".repeat(5_001)));
+ for (name, query) in [("", "a"), ("\u{0}", "\u{0}"), ("İ", "i"), ("ß", "ss"), ("🙂_x", "x"), ("x", "🙂")] {
+ let _ = name_words_match(name, query);
+ }
+ }
+}
diff --git a/crates/engine/src/cmd/parameters.rs b/crates/engine/src/cmd/parameters.rs
index 79adc68691..583b0f1e2d 100644
--- a/crates/engine/src/cmd/parameters.rs
+++ b/crates/engine/src/cmd/parameters.rs
@@ -560,13 +560,16 @@ fn complete(s: &mut Session, p: &Value) -> Result<Value> {
let lower = word.to_ascii_lowercase();
let starts = |n: &str| word.is_empty() || n.to_ascii_lowercase().starts_with(&lower);
// A parameter matches wherever the word appears in its name (`side` finds
- // `cab_side_thickness`, #2757); functions, constants and units match from the start.
- let within = |n: &str| word.is_empty() || n.to_ascii_lowercase().contains(&lower);
+ // `cab_side_thickness`, #2757) or by the starts of its words in order (`toodia` finds
+ // `tooth_outward_flange_diameter`, #11978); functions, constants and units match from the
+ // start.
+ let contains = |n: &str| word.is_empty() || n.to_ascii_lowercase().contains(&lower);
+ let within = |n: &str| contains(n) || solidcraft_doc::name_words_match(n, &word);
let mut out: Vec<Value> = Vec::new();
let mut rows: Vec<solidcraft_doc::ParamRow> = s.doc.param_rows().into_iter().filter(|r| within(&r.name)).collect();
- // Names that start with the word, then the rest; within each, favourites, then user
- // parameters, then the others.
- rows.sort_by_key(|r| (!starts(&r.name), !r.favorite, r.source != "user"));
+ // Names that start with the word, then names that contain it, then names matched only by
+ // the starts of their words; within each, favourites, then user parameters, then the others.
+ rows.sort_by_key(|r| (!starts(&r.name), !contains(&r.name), !r.favorite, r.source != "user"));
for r in rows.into_iter().take(200) {
// The completion shows the parameter's own unit, so it reads `display_value`.
let v = r.display_value.or(r.value).map(|v| format!("{v:.4} {}", r.unit).trim().to_string()).unwrap_or_else(|| "error".into());
diff --git a/crates/engine/src/cmd/parameters_tests.rs b/crates/engine/src/cmd/parameters_tests.rs
index d277c696e1..8d79d33af8 100644
--- a/crates/engine/src/cmd/parameters_tests.rs
+++ b/crates/engine/src/cmd/parameters_tests.rs
@@ -350,6 +350,17 @@ fn completion_matches_parameters_anywhere_in_their_name() {
let c = run(&mut s, "parameters.complete", json!({"prefix": "THICK"}));
assert_eq!(texts(&c), ["cab_side_thickness"], "any case: {c}");
assert!(texts(&run(&mut s, "parameters.complete", json!({"prefix": "xyz"}))).is_empty());
+ // #11978: the starts of the name's words, in order, find it; out of order they don't.
+ let c = run(&mut s, "parameters.complete", json!({"prefix": "2 * cabthi"}));
+ assert_eq!(texts(&c), ["cab_side_thickness"], "{c}");
+ assert_eq!(texts(&run(&mut s, "parameters.complete", json!({"prefix": "doowid"}))), ["door_width"]);
+ assert!(texts(&run(&mut s, "parameters.complete", json!({"prefix": "thicab"}))).is_empty());
+ // A match by word starts alone comes after every name that contains the word, even a
+ // favourite: `inner_diameter` has no `id` in it.
+ run(&mut s, "parameters.add", json!({"name": "inner_diameter", "expression": "6 mm"}));
+ run(&mut s, "parameters.favorite", json!({"name": "inner_diameter", "favorite": true}));
+ let c = run(&mut s, "parameters.complete", json!({"prefix": "id"}));
+ assert_eq!(texts(&c), ["cab_side_thickness", "side", "door_width", "inner_diameter"], "{c}");
// Functions keep matching from the start: `in` is not `sin(`.
let c = run(&mut s, "parameters.complete", json!({"prefix": "in"}));
assert!(!c["suggestions"].as_array().unwrap().iter().any(|x| x["text"] == "sin("), "{c}");
diff --git a/crates/ui-egui/src/params_dialog.rs b/crates/ui-egui/src/params_dialog.rs
index 57cdd3c64b..85c77428db 100644
--- a/crates/ui-egui/src/params_dialog.rs
+++ b/crates/ui-egui/src/params_dialog.rs
@@ -113,13 +113,15 @@ struct Row {
impl Row {
/// Whether the Filter box's text (lower case) is in the row's name, expression, text,
/// comment or group. The expression lets a parameter's name find every one that uses it
- /// (#9706).
+ /// (#9706). The name also matches by the starts of its words, in order: `toodia` finds
+ /// `tooth_outward_flange_diameter` (#11978).
fn matches(&self, filter: &str) -> bool {
filter.is_empty()
|| [&self.name, &self.expression, &self.comment, &self.group]
.into_iter()
.chain(self.text.as_ref())
.any(|field| field.to_ascii_lowercase().contains(filter))
+ || solidcraft_engine::doc::name_words_match(&self.name, filter)
}
}
@@ -924,9 +926,19 @@ pub(crate) fn suggestions_for(ctx: &egui::Context, word: &str, explicit: bool) -
let offered = |s: &&Suggestion| (explicit || s.text.trim_end_matches('(') != word) && !(exact && s.kind == "unit");
let starts = |s: &&Suggestion| s.text.to_ascii_lowercase().starts_with(&w);
// A parameter is also offered for a word anywhere in its name (`side` finds
- // `cab_side_thickness`, #2757), after the names that start with it.
- let within = |s: &&Suggestion| !exact && s.kind == "parameter" && !starts(s) && s.text.to_ascii_lowercase().contains(&w);
- all.iter().filter(|s| starts(s) && offered(s)).chain(all.iter().filter(|s| within(s) && offered(s))).take(8).cloned().collect()
+ // `cab_side_thickness`, #2757), after the names that start with it, and then by the starts
+ // of its words in order (`toodia` finds `tooth_outward_flange_diameter`, #11978). That last
+ // group comes after the others, so it never pushes an earlier match out of the eight.
+ let parameter = |s: &&Suggestion| !exact && s.kind == "parameter" && !starts(s);
+ let within = |s: &&Suggestion| parameter(s) && s.text.to_ascii_lowercase().contains(&w);
+ let words = |s: &&Suggestion| parameter(s) && !within(s) && solidcraft_engine::doc::name_words_match(&s.text, word);
+ all.iter()
+ .filter(|s| starts(s) && offered(s))
+ .chain(all.iter().filter(|s| within(s) && offered(s)))
+ .chain(all.iter().filter(|s| words(s) && offered(s)))
+ .take(8)
+ .cloned()
+ .collect()
}
/// The named parameters, in the order the list offers them (favourites and the design's own
@@ -1346,13 +1358,21 @@ mod tests {
fn a_parameter_is_offered_for_any_part_of_its_name() {
let ctx = egui::Context::default();
let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
- for (name, e) in [("cab_side_thickness", "18 mm"), ("sides", "4")] {
+ for (name, e) in [("cab_side_thickness", "18 mm"), ("sides", "4"), ("inner_diameter", "6 mm")] {
let _ = app.run("parameters.add", json!({"name": name, "expression": e}));
}
+ // A favourite is listed first in the cache, but a match by word starts alone still
+ // comes after every name that contains the word (#11978).
+ let _ = app.run("parameters.favorite", json!({"name": "inner_diameter", "favorite": true}));
publish(&mut app, &ctx);
let texts = |w: &str| suggestions(&ctx, w).into_iter().map(|s| s.text).collect::<Vec<_>>();
assert_eq!(texts("side"), ["sides", "cab_side_thickness"]);
assert_eq!(texts("Thick"), ["cab_side_thickness"]);
+ // #11978: the starts of the name's words, in order.
+ assert_eq!(texts("cabthi"), ["cab_side_thickness"]);
+ assert_eq!(texts("sidthi"), ["cab_side_thickness"]);
+ assert!(texts("thicab").is_empty());
+ assert_eq!(texts("id"), ["cab_side_thickness", "sides", "inner_diameter"]);
assert!(!texts("in").iter().any(|t| t == "sin("), "functions match from the start");
}
@@ -1481,19 +1501,29 @@ mod tests {
}
/// #9706: the Filter box reads expressions too, so a parameter's name lists every parameter
- /// that uses it, and a value finds the parameter that holds it.
+ /// that uses it, and a value finds the parameter that holds it. #11978: the starts of a
+ /// name's words, in order, find it.
#[test]
fn the_filter_lists_the_parameters_that_use_a_name() {
let mut h = crate::scenario::Harness::new();
h.app.home.open = false;
h.call("ui.resize", json!({"width": 1600, "height": 1400}));
- for (name, expression) in [("width", "40 mm"), ("height", "width * 2"), ("depth", "5 mm")] {
+ for (name, expression) in [("width", "40 mm"), ("height", "width * 2"), ("depth", "5 mm"), ("tooth_outward_flange_diameter", "8 mm")] {
h.app.run("parameters.add", json!({"name": name, "expression": expression})).unwrap();
}
h.app.start("parameters.change");
h.frames(6);
- let all = ["width", "height", "depth"];
- for (filter, expected) in [("width", vec!["width", "height"]), ("WIDTH *", vec!["height"]), ("5 mm", vec!["depth"]), ("", all.to_vec())] {
+ let all = ["width", "height", "depth", "tooth_outward_flange_diameter"];
+ let tooth = vec!["tooth_outward_flange_diameter"];
+ for (filter, expected) in [
+ ("width", vec!["width", "height"]),
+ ("WIDTH *", vec!["height"]),
+ ("5 mm", vec!["depth"]),
+ ("toodia", tooth.clone()),
+ ("OutDia", tooth.clone()),
+ ("diatoo", vec![]),
+ ("", all.to_vec()),
+ ] {
h.app.params.as_mut().unwrap().filter = filter.into();
h.frames(4);
let shown: Vec<&str> = all.into_iter().filter(|n| crate::scenario::rect_of(&format!("dialog:table:user:{n}")).is_some()).collect();
diff --git a/docs/book/src/guide/parameters.md b/docs/book/src/guide/parameters.md
index 412627952c..c648ef2e44 100644
--- a/docs/book/src/guide/parameters.md
+++ b/docs/book/src/guide/parameters.md
@@ -46,6 +46,11 @@ In the MANAGE tab's PARAMETERS section, click **Parameters** to open the user an
parameter editor. The **Configurations** button in CONFIGURATIONS opens the configuration table;
**Configure** remains in the dropdown for configuring columns.
+The **Filter** box lists the parameters whose name, expression, comment or group contains what
+you type, in any case. It also finds a name by the starts of its words, in order: `toodia`,
+`toofla` and `outdia` all find `tooth_outward_flange_diameter`. Underscores, hyphens and
+camelCase (`boltHoleDepth`) separate the words. Autocomplete offers parameters the same way.
+
Press **Enter** in the new parameter's name, expression or comment field to add it.
Valid entries return focus to the name field for the next parameter; invalid entries remain
editable. In expression fields, type a parameter or dimension name for autocomplete,