Skip to content

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

Text parameters: a sketch text's words built from them follow every change (#727) (#6364)

NOWN-DEV826244bb2822
diff --git a/crates/doc/src/config.rs b/crates/doc/src/config.rs
index 369db695ca..fbd4f1b3a0 100644
--- a/crates/doc/src/config.rs
+++ b/crates/doc/src/config.rs
@@ -130,6 +130,7 @@ impl Document {
/// A column's current value in the design.
pub fn config_current(&self, c: &Column) -> Option<String> {
match c {
+ Column::Param(n) if self.text_param(n).is_some() => self.text_param(n).map(|p| p.text.clone()),
Column::Param(n) => self.all_param_exprs().into_iter().find(|(m, _, _)| m == n).map(|(_, e, kind)| {
// Feature literals are stored in base units, unlike newly typed bare
// row cells. Capture their unit explicitly before editing in an inch design.
@@ -262,6 +263,7 @@ impl Document {
}
self.configs.columns.iter().zip(&r.cells).all(|(c, v)| match c {
Column::Suppress(id) => suppression_cell(v).is_ok_and(|on| self.feature(*id).is_some_and(|f| f.suppressed == on)),
+ Column::Param(name) if self.text_param(name).is_some() => self.text_param(name).is_some_and(|p| p.text == crate::text_params::unquote(v)),
Column::Param(name) => {
let kind = self
.features
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index 5e45756867..17f44b0d2c 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -2518,6 +2518,9 @@ pub struct Document {
#[serde(default, skip_serializing_if = "crate::Metadata::is_empty")]
pub metadata: crate::Metadata,
pub params: Vec<Param>,
+ /// Named texts the words of sketch texts can be built from ([`crate::text_params`]).
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub text_params: Vec<crate::text_params::TextParam>,
pub features: Vec<Feature>,
/// Timeline marker: features at or after this index are rolled back (not evaluated).
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -2791,6 +2794,7 @@ impl Document {
units: default_units(),
metadata: Default::default(),
params: Vec::new(),
+ text_params: Vec::new(),
features: Vec::new(),
marker: None,
next_id: 1,
@@ -3474,6 +3478,12 @@ impl Document {
/// Add or change a parameter. Fails if the result would not evaluate. A new parameter
/// without a unit takes the unit of its value (mm, deg or none).
pub fn set_param(&mut self, name: &str, expr_s: &str, unit: Option<&str>, comment: Option<&str>) -> Result<()> {
+ // A text parameter: one with the text unit, or an existing one when no unit is given.
+ match (unit.map(crate::text_params::is_text_unit), self.text_param(name).is_some()) {
+ (Some(true), _) | (None, true) => return self.set_text_param(name, expr_s, comment),
+ (Some(false), true) => return Err(DocError::Invalid(format!("`{name}` is a text parameter"))),
+ _ => {}
+ }
if let Some(p) = Self::param_name_problem(name) {
return Err(DocError::Invalid(p));
}
@@ -3694,14 +3704,14 @@ impl Document {
Ok(())
}
- /// Give the texts of a sketch the numbers their expressions come to (in place): a text's
- /// height, place and angle that were typed as expressions. A text's outlines are rebuilt from
- /// its numbers when the sketch's links are refreshed, so this comes before that. A number
- /// typed as a number is left as it is.
+ /// Give the texts of a sketch the numbers and words their expressions come to (in place): a
+ /// text's height, place and angle that were typed as expressions, and its words built from
+ /// text parameters. A text's outlines are rebuilt from them when the sketch's links are
+ /// refreshed, so this comes before that. What was typed as such is left as it is.
pub fn apply_text_values(&self, vals: &std::collections::BTreeMap<String, expr::Value>, sk: &mut Sketch) -> Result<()> {
use crate::eval::val;
for link in &mut sk.links {
- let solidcraft_sketch::LinkSource::Text { at, height, angle, exprs, .. } = &mut link.source else { continue };
+ let solidcraft_sketch::LinkSource::Text { text, at, height, angle, exprs, .. } = &mut link.source else { continue };
let number = |e: &Option<String>, kind: Kind, what: &str| -> Result<Option<f64>> {
match e {
None => Ok(None),
@@ -3723,6 +3733,13 @@ impl Document {
if exprs.height.is_some() && !(*height > 1e-6 && *height < 1e5) {
return Err(DocError::Invalid("a text's height must be positive".into()));
}
+ if let Some(e) = &exprs.text {
+ let words = self.eval_words(e).map_err(|error| DocError::Expr(format!("text: {error}")))?;
+ if words.trim().is_empty() || words.chars().count() > solidcraft_sketch::MAX_TEXT_CHARS {
+ return Err(DocError::Invalid(format!("text: `{e}` gives no words, or too many")));
+ }
+ *text = words;
+ }
}
Ok(())
}
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index 3f60ccfc9d..ed7781df12 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -1178,19 +1178,20 @@ pub struct Model {
}
/// Parameters a feature uses directly (inputs, sketch dimensions and the expressions of a
-/// sketch's texts), sorted.
+/// sketch's texts, the text parameters of their words included), sorted.
fn param_names(f: &Feature) -> Vec<String> {
let mut names: Vec<String> = f.kind.expressions().iter().flat_map(|e| expr::references(e)).collect();
if let FeatureKind::Sketch { sketch, .. } = &f.kind {
names.extend(sketch.constraints.iter().filter_map(|c| c.param.clone()));
names.extend(sketch.text_exprs().into_iter().flat_map(|(_, e)| expr::references(e)));
+ names.extend(sketch.text_word_exprs().into_iter().flat_map(|e| crate::text_params::references(e)));
}
names.sort();
names.dedup();
names
}
-fn fingerprint(prev: u64, f: &Feature, vals: &BTreeMap<String, Value>, rolled_back: bool, steps: &StepDigests) -> u64 {
+fn fingerprint(doc: &Document, prev: u64, f: &Feature, vals: &BTreeMap<String, Value>, rolled_back: bool, steps: &StepDigests) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
prev.hash(&mut h);
rolled_back.hash(&mut h);
@@ -1198,13 +1199,14 @@ fn fingerprint(prev: u64, f: &Feature, vals: &BTreeMap<String, Value>, rolled_ba
hash_feature_json(f, steps, &mut h);
for n in param_names(f) {
n.hash(&mut h);
- match vals.get(&n) {
- Some(v) => {
+ match (vals.get(&n), doc.text_param(&n)) {
+ (Some(v), _) => {
v.v.to_bits().hash(&mut h);
v.len.hash(&mut h);
v.ang.hash(&mut h);
}
- None => 0u8.hash(&mut h),
+ (None, Some(p)) => p.text.hash(&mut h),
+ (None, None) => 0u8.hash(&mut h),
}
}
h.finish()
@@ -1381,7 +1383,7 @@ fn chain_fingerprint(
steps: &StepDigests,
st: Option<&ModelState>,
) -> u64 {
- let mut fp = fingerprint(prev, f, vals, rolled_back, steps) ^ placement_digest(doc, f, st);
+ let mut fp = fingerprint(doc, prev, f, vals, rolled_back, steps) ^ placement_digest(doc, f, st);
// Sheet metal features also depend on the rules (and the parameters they use).
if f.kind.is_sheet() {
let mut h = std::collections::hash_map::DefaultHasher::new();
@@ -1420,7 +1422,7 @@ fn context_digest(doc: &Document, vals: &BTreeMap<String, Value>) -> u64 {
for f in doc.features.iter().filter(|f| {
matches!(f.kind, FeatureKind::ConstructionPlane { .. } | FeatureKind::ConstructionAxis { .. } | FeatureKind::ConstructionPoint { .. })
}) {
- fingerprint(0, f, vals, false, &StepDigests::default()).hash(&mut h);
+ fingerprint(doc, 0, f, vals, false, &StepDigests::default()).hash(&mut h);
}
doc.units.hash(&mut h);
serde_json::to_string(&doc.sheet).unwrap_or_default().hash(&mut h);
@@ -1989,7 +1991,8 @@ impl Model {
Arc::make_mut(&mut state).reserved_body_names.clone_from(&reserved);
}
// The same feature on the same inputs: its earlier result.
- let key = cache_key(f, fp, fingerprint(0, f, &vals, false, &self.step_digests) ^ placement_digest(doc, f, Some(&state)), ctx, &state);
+ let key =
+ cache_key(f, fp, fingerprint(doc, 0, f, &vals, false, &self.step_digests) ^ placement_digest(doc, f, Some(&state)), ctx, &state);
let kept = self.kept.0.as_ref().filter(|_| !self.no_cache);
if !self.no_cache
&& let Some(c) = self.cache.lock().ok().and_then(|mut m| m.get(key)).or_else(|| kept.and_then(|k| k.get(key)))
diff --git a/crates/doc/src/format/pending/text-parameters.rs b/crates/doc/src/format/pending/text-parameters.rs
new file mode 100644
index 0000000000..eccf3318e3
--- /dev/null
+++ b/crates/doc/src/format/pending/text-parameters.rs
@@ -0,0 +1,5 @@
+//! Text parameters (`text_params`: name, text, comment) and the expression behind a sketch
+//! text's words (`exprs.text` of a text link, e.g. `Label + '-L'`), whose words are what it gave
+//! last. Older designs need no transformation: they have neither. The last release refuses the
+//! newer format number instead of opening a design whose texts would lose their link to the
+//! parameters.
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index ad82724a3a..95ad72841d 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -65,6 +65,7 @@ pub mod render_settings;
pub mod render_surface;
pub use project3d::iso_grid;
pub mod sheet;
+pub mod text_params;
pub use assembly::{
IDENTITY, MAX_PLACEMENT_DEPTH, MAX_PLACEMENTS, Mat, Occurrence, apply_point, apply_vector, is_identity, map_point_expr, mat_inverse, mat_mul,
diff --git a/crates/doc/src/model_cache.rs b/crates/doc/src/model_cache.rs
index dfcaf4974a..4b673dfe6c 100644
--- a/crates/doc/src/model_cache.rs
+++ b/crates/doc/src/model_cache.rs
@@ -636,7 +636,7 @@ impl Model {
let mut before = Arc::new(ModelState::default());
if let Ok(mut cache) = model.cache.lock() {
for (f, r) in doc.features.iter().zip(&model.results).filter(|(_, r)| !r.skipped && r.error.is_none()) {
- let local = fingerprint(0, f, &vals, false, &model.step_digests) ^ placement_digest(doc, f, Some(&before));
+ let local = fingerprint(doc, 0, f, &vals, false, &model.step_digests) ^ placement_digest(doc, f, Some(&before));
cache.put(
cache_key(f, r.fingerprint, local, ctx, &before),
CachedEval {
diff --git a/crates/doc/src/params.rs b/crates/doc/src/params.rs
index 114ec1833d..0fd89aa2e4 100644
--- a/crates/doc/src/params.rs
+++ b/crates/doc/src/params.rs
@@ -103,6 +103,9 @@ pub struct ParamRow {
/// Names this one's expression uses, and names whose expressions use this one.
pub uses: Vec<String>,
pub used_by: Vec<String>,
+ /// A text parameter's text (its unit is `text`, its value none).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub text: Option<String>,
}
fn unit_of(k: Kind) -> &'static str {
@@ -129,7 +132,7 @@ impl Document {
}
pub(crate) fn name_taken(&self, n: &str) -> bool {
- self.param(n).is_some() || self.features.iter().any(|f| f.param_names.iter().any(|x| x == n))
+ self.param(n).is_some() || self.text_param(n).is_some() || self.features.iter().any(|f| f.param_names.iter().any(|x| x == n))
}
/// The next free `dN` name.
@@ -289,6 +292,14 @@ impl Document {
if expression.len() > 4096 || expression.trim().is_empty() {
return Err(DocError::Expr("expression is empty or too long".into()));
}
+ if let Some(p) = next.text_params.iter_mut().find(|p| p.name == *name) {
+ let text = crate::text_params::unquote(expression);
+ if p.text != text {
+ changed.insert(name.clone());
+ }
+ p.text = text;
+ continue;
+ }
if let Some(p) = next.params.iter_mut().find(|p| p.name == *name) {
if p.expr != expression.trim() {
changed.insert(name.clone());
@@ -349,6 +360,7 @@ impl Document {
favorite: self.favorites.contains(&p.name),
uses: refs.get(&p.name).cloned().unwrap_or_default(),
used_by: used_by(&p.name),
+ text: None,
});
}
for f in &self.features {
@@ -369,9 +381,28 @@ impl Document {
favorite: self.favorites.contains(name),
uses: refs.get(name).cloned().unwrap_or_default(),
used_by: used_by(name),
+ text: None,
});
}
}
+ for p in &self.text_params {
+ let readers = self.features_reading_texts(&BTreeSet::from([p.name.clone()]));
+ rows.push(ParamRow {
+ name: p.name.clone(),
+ expression: p.text.clone(),
+ unit: crate::text_params::TEXT_UNIT.into(),
+ value: None,
+ error: None,
+ comment: p.comment.clone(),
+ source: "user",
+ feature: None,
+ input: None,
+ favorite: self.favorites.contains(&p.name),
+ uses: Vec::new(),
+ used_by: readers.iter().filter_map(|id| self.feature(*id)).map(|f| format!("Feature:{}", f.name)).collect(),
+ text: Some(p.text.clone()),
+ });
+ }
rows
}
@@ -498,6 +529,9 @@ impl Document {
}
return Ok(());
}
+ if unit.map_or(self.text_param(name).is_some(), crate::text_params::is_text_unit) {
+ return self.set_text_param(name, expr_s, comment);
+ }
if let Some(p) = Self::param_name_problem(name) {
return Err(DocError::Invalid(p));
}
@@ -709,6 +743,9 @@ impl Document {
out.push(ParamUser::Feature { feature: f.id, name: f.name.clone(), input: what.to_string() });
}
}
+ if sketch.text_word_exprs().iter().any(|e| crate::text_params::references(e).iter().any(|r| r == name)) {
+ out.push(ParamUser::Feature { feature: f.id, name: f.name.clone(), input: "Text".into() });
+ }
}
}
for (joint, input, e) in self.assembly.exprs() {
@@ -740,6 +777,9 @@ impl Document {
/// Remove a stored parameter; refused while something uses it (the error lists the users).
pub fn remove_param(&mut self, name: &str) -> Result<()> {
+ if self.text_param(name).is_some() {
+ return self.remove_text_param(name);
+ }
if self.param(name).is_none() {
if self.features.iter().any(|f| f.param_names.iter().any(|n| n == name)) {
return Err(DocError::Invalid(format!("`{name}` is a feature's input: delete or edit the feature instead")));
@@ -774,6 +814,12 @@ impl Document {
return Err(DocError::Invalid(format!("there is already a parameter `{new}`")));
}
let mut n = 0;
+ let text = self.text_param(old).is_some();
+ for p in &mut self.text_params {
+ if p.name == old {
+ p.name = new.to_string();
+ }
+ }
for p in &mut self.params {
if p.name == old {
p.name = new.to_string();
@@ -825,6 +871,13 @@ impl Document {
n += 1;
}
}
+ for e in sketch.text_word_exprs_mut() {
+ let r = crate::text_params::rename_reference(e, old, new);
+ if r != *e {
+ *e = r;
+ n += 1;
+ }
+ }
}
}
if self.favorites.remove(old) {
@@ -839,9 +892,11 @@ impl Document {
for rule in &mut self.configs.rules {
rule.rename_parameter(old, new);
}
+ // A text parameter's cells are texts, not expressions.
+ let texts: BTreeSet<String> = self.text_params.iter().map(|p| p.name.clone()).collect();
for r in &mut self.configs.rows {
for (column, cell) in self.configs.columns.iter().zip(&mut r.cells) {
- if matches!(column, crate::config::Column::Param(_)) {
+ if !text && matches!(column, crate::config::Column::Param(c) if !texts.contains(c)) {
*cell = expr::rename_reference(cell, old, new);
}
}
@@ -886,6 +941,10 @@ impl Document {
p.comment = comment.to_string();
return Ok(());
}
+ if let Some(p) = self.text_params.iter_mut().find(|p| p.name == name) {
+ p.comment = comment.to_string();
+ return Ok(());
+ }
if !self.name_taken(name) {
return Err(DocError::Unknown(format!("parameter `{name}`")));
}
@@ -907,6 +966,7 @@ impl Document {
names.extend(sketch.constraints.iter().filter_map(|c| c.param.clone()));
names.extend(sketch.text_exprs().into_iter().flat_map(|(_, e)| expr::references(e)));
names.extend(sketch.patterns.iter().filter_map(|p| p.count_expression.as_deref()).flat_map(expr::references));
+ names.extend(sketch.text_word_exprs().into_iter().flat_map(|e| crate::text_params::references(e)));
}
// Sheet metal and plastic features rebuild when their rules' parameters change (#4420).
if f.kind.is_sheet() {
@@ -948,6 +1008,7 @@ impl Document {
if let FeatureKind::Sketch { sketch, .. } = &f.kind {
hit |= sketch.constraints.iter().any(|c| c.param.as_ref().is_some_and(|p| affected.contains(p)));
hit |= sketch.text_exprs().iter().any(|(_, e)| expr::references(e).iter().any(|r| affected.contains(r)));
+ hit |= sketch.text_word_exprs().iter().any(|e| crate::text_params::references(e).iter().any(|r| affected.contains(r)));
}
if hit {
out.push(f.id);
diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rs
index 02d2586907..dd662d1ac1 100644
--- a/crates/doc/src/project.rs
+++ b/crates/doc/src/project.rs
@@ -688,7 +688,11 @@ fn refresh_links_in(
}
sk.set_link_source(&l.id, r.source);
let _ = sk.set_link_wires(&l.id, &r.wires);
+ // Words built from text parameters change shape when the parameters do: that
+ // rebuild is the text following them, not a reference that changed under it.
+ let words_follow = matches!(&l.source, LinkSource::Text { exprs, .. } if exprs.text.is_some());
match sk.update_link(&l.id, &r.geom) {
+ Ok(true) if words_follow => {}
Ok(true) => warn.push(format!("projected {} changed shape and was rebuilt", l.source.describe())),
Ok(false) if r.moved => warn.push(format!("projected {} was re-found on the nearest geometry", l.source.describe())),
Ok(false) => {}
diff --git a/crates/doc/src/text_params.rs b/crates/doc/src/text_params.rs
new file mode 100644
index 0000000000..2338acb9d4
--- /dev/null
+++ b/crates/doc/src/text_params.rs
@@ -0,0 +1,252 @@
+//! Text parameters: named texts (`Label` = `TAG-1`) that the words of a sketch text can be built
+//! from, by an expression that joins them and quoted texts with `+` (`Label + '-L'`). They are
+//! kept apart from the number parameters: a text has no unit and no number expression reads it.
+//! A parameter edit or a configuration row that sets one relabels every text built from it, and
+//! the features that use those texts follow in the same rebuild.
+
+use serde::{Deserialize, Serialize};
+
+use crate::{DocError, Document, FeatureKind, MAX_PARAMS, Result};
+
+/// The unit that marks a text parameter where parameters are listed, added or imported.
+pub const TEXT_UNIT: &str = "text";
+
+/// Longest text a text parameter holds, and longest words expression.
+const MAX_LEN: usize = 4096;
+
+/// A named text.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct TextParam {
+ pub name: String,
+ pub text: String,
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub comment: String,
+}
+
+/// Is `unit` the text unit?
+pub fn is_text_unit(unit: &str) -> bool {
+ unit.trim() == TEXT_UNIT
+}
+
+/// A text as typed for a text parameter: inside matching quotes, what they hold (a quote doubled
+/// inside stands for one); else the text itself, without surrounding spaces.
+pub fn unquote(s: &str) -> String {
+ let t = s.trim();
+ for q in ['\'', '"'] {
+ if t.len() >= 2 && t.starts_with(q) && t.ends_with(q) {
+ let inner = t.get(1..t.len() - 1).unwrap_or_default();
+ let doubled = format!("{q}{q}");
+ // Only a text whose inner quotes all come in pairs is one quoted text.
+ if inner.replace(&doubled, "").contains(q) {
+ break;
+ }
+ return inner.replace(&doubled, &q.to_string());
+ }
+ }
+ t.to_string()
+}
+
+enum Term {
+ Text(String),
+ Name(String),
+}
+
+/// The terms of a words expression with their byte ranges: quoted texts (single or double
+/// quotes, a quote doubled inside stands for one) and parameter names, joined by `+`.
+fn terms(s: &str) -> Result<Vec<(Term, usize, usize)>> {
+ if s.len() > MAX_LEN {
+ return Err(DocError::Expr("text expression too long".into()));
+ }
+ let cs: Vec<(usize, char)> = s.char_indices().collect();
+ let at = |i: usize| cs.get(i).map_or(s.len(), |x| x.0);
+ let mut out = Vec::new();
+ let mut i = 0;
+ let mut want_term = true;
+ while let Some(&(_, c)) = cs.get(i) {
+ if c.is_whitespace() {
+ i += 1;
+ } else if !want_term {
+ if c != '+' {
+ return Err(DocError::Expr(format!("unexpected `{c}`: a text expression joins quoted texts and text parameters with +")));
+ }
+ want_term = true;
+ i += 1;
+ } else if c == '\'' || c == '"' {
+ let start = i;
+ let mut text = String::new();
+ i += 1;
+ loop {
+ match cs.get(i).map(|x| x.1) {
+ None => return Err(DocError::Expr(format!("a text in quotes ({c}) is not closed"))),
+ Some(d) if d == c && cs.get(i + 1).is_some_and(|x| x.1 == c) => {
+ text.push(c);
+ i += 2;
+ }
+ Some(d) if d == c => {
+ i += 1;
+ break;
+ }
+ Some(d) => {
+ text.push(d);
+ i += 1;
+ }
+ }
+ }
+ out.push((Term::Text(text), at(start), at(i)));
+ want_term = false;
+ } else if c.is_alphabetic() || c == '_' {
+ let start = i;
+ while cs.get(i).is_some_and(|x| x.1.is_alphanumeric() || x.1 == '_') {
+ i += 1;
+ }
+ out.push((Term::Name(s.get(at(start)..at(i)).unwrap_or_default().to_string()), at(start), at(i)));
+ want_term = false;
+ } else {
+ return Err(DocError::Expr(format!("unexpected `{c}`: a text expression joins quoted texts and text parameters with +")));
+ }
+ }
+ if want_term {
+ let what = if out.is_empty() { "the text expression is empty" } else { "the text expression ends with +" };
+ return Err(DocError::Expr(what.into()));
+ }
+ Ok(out)
+}
+
+/// The parameters a words expression names (none when it does not parse).
+pub fn references(s: &str) -> Vec<String> {
+ let mut out: Vec<String> = Vec::new();
+ for (t, _, _) in terms(s).unwrap_or_default() {
+ if let Term::Name(n) = t
+ && !out.contains(&n)
+ {
+ out.push(n);
+ }
+ }
+ out
+}
+
+/// The words expression with every reference to `old` renamed to `new` (quoted texts kept).
+pub fn rename_reference(s: &str, old: &str, new: &str) -> String {
+ let Ok(terms) = terms(s) else { return s.to_string() };
+ let mut out = String::with_capacity(s.len());
+ let mut last = 0;
+ for (t, a, b) in terms {
+ if matches!(&t, Term::Name(n) if n == old) {
+ out.push_str(s.get(last..a).unwrap_or_default());
+ out.push_str(new);
+ last = b;
+ }
+ }
+ out.push_str(s.get(last..).unwrap_or_default());
+ out
+}
+
+/// The words an expression comes to, each parameter's text from `lookup`.
+pub fn eval(s: &str, lookup: &dyn Fn(&str) -> Result<String>) -> Result<String> {
+ let mut out = String::new();
+ for (t, _, _) in terms(s)? {
+ match t {
+ Term::Text(text) => out.push_str(&text),
+ Term::Name(n) => out.push_str(&lookup(&n)?),
+ }
+ if out.len() > MAX_LEN {
+ return Err(DocError::Expr("the text is too long".into()));
+ }
+ }
+ Ok(out)
+}
+
+impl Document {
+ pub fn text_param(&self, name: &str) -> Option<&TextParam> {
+ self.text_params.iter().find(|p| p.name == name)
+ }
+
+ /// The words a words expression comes to in this design.
+ pub fn eval_words(&self, e: &str) -> Result<String> {
+ eval(e, &|n| match self.text_param(n) {
+ Some(p) => Ok(p.text.clone()),
+ None if self.name_taken(n) => Err(DocError::Expr(format!("`{n}` is a number parameter: a text's words take text parameters"))),
+ None => Err(DocError::Expr(format!("unknown text parameter `{n}`"))),
+ })
+ }
+
+ /// Set text parameter `name` to `text` (as typed: [`unquote`]), adding it when new.
+ pub fn set_text_param(&mut self, name: &str, text: &str, comment: Option<&str>) -> Result<()> {
+ if let Some(p) = Self::param_name_problem(name) {
+ return Err(DocError::Invalid(p));
+ }
+ if text.len() > MAX_LEN {
+ return Err(DocError::Expr("text too long".into()));
+ }
+ if comment.is_some_and(|c| c.len() > 4096) {
+ return Err(DocError::Invalid("comment too long".into()));
+ }
+ let text = unquote(text);
+ if let Some(p) = self.text_params.iter_mut().find(|p| p.name == name) {
+ p.text = text;
+ if let Some(c) = comment {
+ p.comment = c.to_string();
+ }
+ return Ok(());
+ }
+ if self.name_taken(name) {
+ return Err(DocError::Invalid(format!("`{name}` is a number parameter")));
+ }
+ if self.params.len() + self.text_params.len() >= MAX_PARAMS {
+ return Err(DocError::Invalid("too many parameters".into()));
+ }
+ self.text_params.push(TextParam { name: name.to_string(), text, comment: comment.unwrap_or_default().to_string() });
+ Ok(())
+ }
+
+ /// Remove text parameter `name`; refused while a text uses it.
+ pub(crate) fn remove_text_param(&mut self, name: &str) -> Result<()> {
+ let users = self.param_users(name);
+ if !users.is_empty() {
+ let list: Vec<String> = users.iter().map(crate::ParamUser::describe).collect();
+ return Err(DocError::Invalid(format!("`{name}` is used by {}", list.join(", "))));
+ }
+ self.text_params.retain(|p| p.name != name);
+ self.favorites.remove(name);
+ Ok(())
+ }
+
+ /// The sketches whose texts' words read one of `names`.
+ pub(crate) fn features_reading_texts(&self, names: &std::collections::BTreeSet<String>) -> Vec<u64> {
+ self.features
+ .iter()
+ .filter(|f| match &f.kind {
+ FeatureKind::Sketch { sketch, .. } => sketch.text_word_exprs().iter().any(|e| references(e).iter().any(|r| names.contains(r))),
+ _ => false,
+ })
+ .map(|f| f.id)
+ .collect()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn words_expressions_join_quoted_texts_and_parameters() {
+ let look = |n: &str| match n {
+ "Label" => Ok("TAG-1".to_string()),
+ _ => Err(DocError::Expr(format!("unknown text parameter `{n}`"))),
+ };
+ assert_eq!(eval("Label + '-L'", &look).unwrap(), "TAG-1-L");
+ assert_eq!(eval("\"it's \" + Label", &look).unwrap(), "it's TAG-1");
+ assert_eq!(eval("'it''s'", &look).unwrap(), "it's");
+ assert_eq!(eval("'a+b' + 'c'", &look).unwrap(), "a+bc");
+ for bad in ["", "Label +", "+ 'a'", "Label 'a'", "'open", "Label - 'a'", "Other"] {
+ assert!(eval(bad, &look).is_err(), "{bad}");
+ }
+ assert_eq!(references("Label + 'Label' + Other + Label"), ["Label", "Other"]);
+ assert_eq!(rename_reference("Label+'Label-' + Label", "Label", "Tag"), "Tag+'Label-' + Tag");
+ assert_eq!(unquote(" 'A B' "), "A B");
+ assert_eq!(unquote("\"it''s\""), "it''s");
+ assert_eq!(unquote("'it''s'"), "it's");
+ assert_eq!(unquote("'a' + 'b'"), "'a' + 'b'");
+ assert_eq!(unquote("TAG-1"), "TAG-1");
+ }
+}
diff --git a/crates/engine/src/cmd/config.rs b/crates/engine/src/cmd/config.rs
index 023242ed05..2a6792674e 100644
--- a/crates/engine/src/cmd/config.rs
+++ b/crates/engine/src/cmd/config.rs
@@ -98,7 +98,7 @@ fn column_of(s: &Session, p: &Value, cmd: &str) -> Result<Column> {
}
}
if let Some(n) = str_(p, "param") {
- if !s.doc.all_param_exprs().iter().any(|(m, _, _)| m == n) {
+ if !s.doc.all_param_exprs().iter().any(|(m, _, _)| m == n) && s.doc.text_param(n).is_none() {
return Err(bad(cmd, format!("no parameter `{n}`")));
}
return Ok(Column::Param(n.to_string()));
diff --git a/crates/engine/src/cmd/parameters.rs b/crates/engine/src/cmd/parameters.rs
index 26a6359ebb..c2ebe6c534 100644
--- a/crates/engine/src/cmd/parameters.rs
+++ b/crates/engine/src/cmd/parameters.rs
@@ -11,7 +11,8 @@ use crate::{EngineError, Result, Session};
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("parameters.change", "Change Parameters", change_param).at("SOLID", "MODIFY").icon("params").params(
- "name, expression (number or text), unit?: mm|cm|m|in|ft|deg|rad|\"\" (new parameters default to their value's unit), comment?, \
+ "name, expression (number or text), unit?: mm|cm|m|in|ft|deg|rad|\"\"|text (new parameters default to their value's unit; \
+ a text parameter's expression is its text, quotes round it optional: sketch texts' words are built from it), comment?, \
favorite?: bool, new_name?: rename (references follow); or delete: name; or changes: {name: expression, …} (existing \
parameters, checked together and rebuilt once, all or nothing) → changed?: {name: value} (with changes), recomputed: features rebuilt, \
restored: features whose earlier result for the same inputs was reused (e.g. a value set back), switched?: [{feature, name, suppressed}] \
@@ -22,7 +23,9 @@ pub static COMMANDS: &[CommandSpec] = &[
"favorites?: bool (only favourites), filter?: all|user|sketch|feature|favorites → parameters (name, expression, unit, value in its unit, \
source, feature/input, comment, favorite, uses, used_by, error) and cycles",
),
- CommandSpec::new("parameters.add", "Add User Parameter", add).icon("new").params("name, expression, unit?, comment?, favorite?: bool"),
+ CommandSpec::new("parameters.add", "Add User Parameter", add)
+ .icon("new")
+ .params("name, expression, unit?: as parameters.change (text: a text parameter, its expression the text), comment?, favorite?: bool"),
CommandSpec::new("parameters.rename", "Rename Parameter", rename)
.icon("rename")
.params("name, new_name (expressions, feature inputs and dimensions that use it follow)"),
@@ -53,7 +56,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.icon("params")
.noundo()
.doc_only()
- .params("expression, kind?: length|angle|unitless (or unit?: mm|in|deg…) → ok, value (mm/rad), display_value, references, error"),
+ .params("expression, kind?: length|angle|unitless (or unit?: mm|in|deg…; text: the text a text parameter would hold, as `text`) → ok, value (mm/rad), display_value, references, error"),
CommandSpec::new("parameters.complete", "Complete Expression", complete)
.icon("params")
.noundo()
@@ -79,7 +82,7 @@ fn failing(s: &Session) -> Vec<Value> {
}
pub(super) fn known(s: &Session, name: &str) -> bool {
- s.doc.param(name).is_some() || s.doc.features.iter().any(|f| f.param_names.iter().any(|n| n == name))
+ s.doc.param(name).is_some() || s.doc.text_param(name).is_some() || s.doc.features.iter().any(|f| f.param_names.iter().any(|n| n == name))
}
fn change_param(s: &mut Session, p: &Value) -> Result<Value> {
@@ -132,6 +135,9 @@ fn change_param(s: &mut Session, p: &Value) -> Result<Value> {
}
out["name"] = json!(name);
out["expression"] = json!(e);
+ if let Some(t) = s.doc.text_param(&name) {
+ out["text"] = json!(t.text);
+ }
out["value"] = json!(vals.get(&name).map(|v| v.v));
out["display_value"] = json!(s.doc.param_display_value(&vals, &name));
out["recomputed"] = json!(s.model.last_recomputed);
@@ -217,6 +223,9 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
s.doc_mut().set_favorite(&name, f)?;
}
let (vals, _) = s.doc.param_values();
+ if let Some(t) = s.doc.text_param(&name) {
+ return Ok(json!({"name": name, "unit": solidcraft_doc::text_params::TEXT_UNIT, "text": t.text, "value": null}));
+ }
Ok(
json!({"name": name, "unit": s.doc.param(&name).map(|x| x.unit.clone()), "value": vals.get(&name).map(|v| v.v), "display_value": s.doc.param_display_value(&vals, &name)}),
)
@@ -335,6 +344,10 @@ fn evaluate(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "expr.evaluate";
let e = expr_arg(p, "expression").ok_or_else(|| bad(cmd, "`expression` must be text or a number"))?;
let unit = str_(p, "unit");
+ // A text parameter's expression is its text.
+ if unit.is_some_and(solidcraft_doc::text_params::is_text_unit) {
+ return Ok(json!({"ok": true, "kind": "text", "text": solidcraft_doc::text_params::unquote(&e), "references": []}));
+ }
if let Some(u) = unit
&& expr::unit_info(u).is_none()
{
diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs
index babba325fa..dfa0d9328c 100644
--- a/crates/engine/src/cmd/sketch_create.rs
+++ b/crates/engine/src/cmd/sketch_create.rs
@@ -101,7 +101,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.enabled(in_sketch)
.params("curves: [line ids], value?: bool (default toggles): infinite line type (#1359): construction geometry drawn across the whole view through the line's two points; off, a normal line"),
CommandSpec::new("sketch.text", "Text", text).at("SKETCH", "CREATE").icon("sketch_text").enabled(in_sketch).params(concat!(
- "text: string (\\n breaks lines), at: baseline start [x,y], height?: capital height mm (default 5), angle?: deg; at's x and y, height and angle each take a number or an expression over the design's parameters as a string (\"plate_width / 2\", \"label_size\"): the text keeps the expression, follows the parameters, and returns it in `exprs`; an expression naming no parameter is the number it comes to, a bare number in one is in the design's units, \
+ "text: string (\\n breaks lines), or text_expression: the words built from text parameters (parameters.add with unit text) and quoted texts joined by + (\"Label + '-L'\"): the text keeps it, its words follow the parameters (a parameter edit or a configuration row relabels it) and `exprs` returns it as `text`; at: baseline start [x,y], height?: capital height mm (default 5), angle?: deg; at's x and y, height and angle each take a number or an expression over the design's parameters as a string (\"plate_width / 2\", \"label_size\"): the text keeps the expression, follows the parameters, and returns it in `exprs`; an expression naming no parameter is the number it comes to, a bare number in one is in the design's units, \
font?: an installed font's family or full name, or a .ttf/.otf file path (~ and %VAR% expand; default: the built-in Liberation Sans), ",
text_style_doc!(),
created_doc!()
@@ -110,7 +110,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.enabled(in_sketch)
.live(edit_text_live)
.params(concat!(
- "link: the text's link id (or entity: one of its curves), text?, at?, height?, angle?: deg (numbers or expressions as in sketch.text; a number replaces an expression, and so does moving the text), font?: family or file path (empty: the built-in font), ",
+ "link: the text's link id (or entity: one of its curves), text? or text_expression? (as in sketch.text; typed words replace the expression), at?, height?, angle?: deg (numbers or expressions as in sketch.text; a number replaces an expression, and so does moving the text), font?: family or file path (empty: the built-in font), ",
text_style_doc!(),
" (each kept when left out); or edits: [{link or entity, text?, at?, …}]: several texts changed together, the design rebuilt once \
(all or nothing; returns edits: each one's result); live?: bool: one frame of an interactive change (the sketch is solved, the features after it stay as they were until `sketch.drag_end`)",
@@ -199,10 +199,20 @@ type TextValues = (String, Vec2, f64, f64, Option<String>, TextStyle, TextExprs)
fn text_source(doc: &solidcraft_doc::Document, p: &Value, cmd: &str, old: Option<TextValues>) -> Result<LinkSource> {
let (t0, mut at, mut height, mut angle, f0, s0, mut exprs) =
old.unwrap_or((String::new(), Vec2::ZERO, 5.0, 0.0, None, TextStyle::default(), TextExprs::default()));
- let text = match p.get("text") {
- None | Some(Value::Null) => t0,
- Some(Value::String(t)) => t.clone(),
- Some(_) => return Err(bad(cmd, "`text` must be a string")),
+ let text = match (p.get("text").filter(|v| !v.is_null()), p.get("text_expression").filter(|v| !v.is_null())) {
+ (Some(_), Some(_)) => return Err(bad(cmd, "give `text` or `text_expression`, not both")),
+ (None, None) => t0,
+ (Some(Value::String(t)), None) => {
+ exprs.text = None;
+ t.clone()
+ }
+ (None, Some(Value::String(e))) => {
+ let words = doc.eval_words(e.trim()).map_err(|error| bad(cmd, format!("`text_expression`: {error}")))?;
+ exprs.text = Some(e.trim().to_string());
+ words
+ }
+ (Some(_), None) => return Err(bad(cmd, "`text` must be a string")),
+ (None, Some(_)) => return Err(bad(cmd, "`text_expression` must be a string")),
};
if text.trim().is_empty() {
return Err(bad(cmd, "`text` must not be empty"));
@@ -248,7 +258,7 @@ fn text_source(doc: &solidcraft_doc::Document, p: &Value, cmd: &str, old: Option
fn text_exprs_json(src: &LinkSource) -> Option<Value> {
let LinkSource::Text { exprs, .. } = src else { return None };
let mut out = serde_json::Map::new();
- for (key, e) in [("x", &exprs.x), ("y", &exprs.y), ("height", &exprs.height), ("angle", &exprs.angle)] {
+ for (key, e) in [("x", &exprs.x), ("y", &exprs.y), ("height", &exprs.height), ("angle", &exprs.angle), ("text", &exprs.text)] {
if let Some(e) = e {
out.insert(key.into(), json!(e));
}
diff --git a/crates/engine/src/cmd/sketch_text_expr_tests.rs b/crates/engine/src/cmd/sketch_text_expr_tests.rs
index 334e7320b9..5a8749d65e 100644
--- a/crates/engine/src/cmd/sketch_text_expr_tests.rs
+++ b/crates/engine/src/cmd/sketch_text_expr_tests.rs
@@ -289,3 +289,111 @@ fn bare_numbers_in_a_text_expression_are_in_the_designs_units() {
let r = run(&mut s, "sketch.text", json!({"text": "A", "at": [0, 0], "height": 2}));
assert!((stored(&s, r["link"].as_str().unwrap()).1 - 2.0).abs() < 1e-12);
}
+
+/// A 100 x 30 x 10 mm block with a text cut 1 mm into its face, its words given by `words`
+/// (`{"text": …}` or `{"text_expression": …}`). The text's sketch is `S`; the reply is
+/// `sketch.text`'s.
+fn block_with_text(s: &mut Session, words: Value) -> Value {
+ run(s, "sketch.create", json!({"plane": "XY"}));
+ run(s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [100, 30]}));
+ run(s, "sketch.finish", json!({}));
+ run(s, "solid.extrude", json!({"distance": -10}));
+ run(s, "sketch.create", json!({"plane": "XY", "name": "S"}));
+ let mut p = json!({"at": [5, 10], "height": 8});
+ for (k, v) in words.as_object().unwrap() {
+ p[k] = v.clone();
+ }
+ let r = run(s, "sketch.text", p);
+ run(s, "sketch.finish", json!({}));
+ run(s, "solid.extrude", json!({"distance": -1, "operation": "cut"}));
+ r
+}
+
+fn volume(s: &mut Session) -> f64 {
+ run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap()
+}
+
+/// The words of the text `link` of sketch `S`, as evaluated.
+fn words(s: &Session, link: &str) -> String {
+ let id = s.doc.find_feature("S").unwrap().id;
+ let st = s.model.state();
+ let LinkSource::Text { text, .. } = &st.sketch(id).unwrap().sketch.link(link).unwrap().source else { panic!("not a text") };
+ text.clone()
+}
+
+/// The expression of the words of the text `link` of sketch `S` (null: typed words).
+fn word_expr(s: &Session, link: &str) -> Value {
+ serde_json::to_value(stored(s, link).3).unwrap()["text"].clone()
+}
+
+/// A text's words can be an expression of text parameters (`Label + '-L'`): a parameter edit,
+/// or a configuration row that sets the parameter, relabels the text, and a cut of the text
+/// follows in the same rebuild, as if its words had been typed.
+#[test]
+fn a_texts_words_follow_its_text_parameters_and_so_does_its_cut() {
+ let typed = |words: &str| {
+ let mut s = Session::default();
+ block_with_text(&mut s, json!({"text": words}));
+ no_trouble(&s);
+ volume(&mut s)
+ };
+ let same = |a: f64, b: f64, what: &str| assert!((a - b).abs() < 1e-6, "{what}: {a} against {b} typed");
+ let mut s = Session::default();
+ let r = run(&mut s, "parameters.add", json!({"name": "Label", "expression": "IT", "unit": "text"}));
+ assert_eq!((r["unit"].as_str(), r["text"].as_str()), (Some("text"), Some("IT")), "{r}");
+ let r = block_with_text(&mut s, json!({"text_expression": "Label + '-L'"}));
+ let link = r["link"].as_str().unwrap().to_string();
+ assert_eq!(r["exprs"], json!({"text": "Label + '-L'"}), "{r}");
+ no_trouble(&s);
+ assert_eq!(words(&s, &link), "IT-L");
+ same(volume(&mut s), typed("IT-L"), "IT-L");
+
+ // A parameter edit relabels; the cut follows in the same rebuild, and after a save.
+ run(&mut s, "parameters.change", json!({"name": "Label", "expression": "WWM"}));
+ no_trouble(&s);
+ assert_eq!(words(&s, &link), "WWM-L");
+ let wide = typed("WWM-L");
+ same(volume(&mut s), wide, "WWM-L");
+ let mut again = reopened(&s);
+ no_trouble(&again);
+ same(volume(&mut again), wide, "WWM-L reopened");
+
+ // A configuration row sets it like any parameter.
+ run(&mut s, "config.configure", json!({"params": ["Label"]}));
+ run(&mut s, "config.row", json!({"name": "Short", "values": {"Label": "I"}}));
+ run(&mut s, "config.row", json!({"name": "Wide", "values": {"Label": "WWM"}}));
+ run(&mut s, "config.activate", json!({"row": "Short"}));
+ no_trouble(&s);
+ assert_eq!(words(&s, &link), "I-L");
+ same(volume(&mut s), typed("I-L"), "row Short");
+ run(&mut s, "config.activate", json!({"row": "Wide"}));
+ same(volume(&mut s), wide, "row Wide");
+
+ // Listed with its text; a rename follows into the expression; deleting it is refused while
+ // the text uses it.
+ let list = run(&mut s, "parameters.list", json!({}));
+ let row = list["parameters"].as_array().unwrap().iter().find(|r| r["name"] == "Label").cloned().unwrap();
+ assert_eq!((row["unit"].as_str(), row["text"].as_str()), (Some("text"), Some("WWM")), "{row}");
+ run(&mut s, "parameters.rename", json!({"name": "Label", "new_name": "Tag"}));
+ assert_eq!(word_expr(&s, &link), json!("Tag + '-L'"));
+ let users = run(&mut s, "parameters.users", json!({"name": "Tag"}));
+ assert!(users["drives"].to_string().contains("\"S\""), "{users}");
+ let e = s.execute("parameters.delete", &json!({"name": "Tag"})).unwrap_err().to_string();
+ assert!(e.contains("Text"), "{e}");
+ no_trouble(&s);
+ same(volume(&mut s), wide, "after the rename");
+
+ // Words typed as a text replace the expression.
+ run(&mut s, "sketch.edit", json!({"sketch": "S"}));
+ run(&mut s, "sketch.edit_text", json!({"link": link, "text": "OK"}));
+ run(&mut s, "sketch.finish", json!({}));
+ assert_eq!((words(&s, &link).as_str(), word_expr(&s, &link)), ("OK", Value::Null));
+
+ // An expression naming no text parameter, or a number parameter, is refused.
+ run(&mut s, "parameters.add", json!({"name": "W", "expression": "10 mm"}));
+ run(&mut s, "sketch.edit", json!({"sketch": "S"}));
+ for (bad, says) in [("Nope + 'x'", "Nope"), ("W", "W"), ("Tag +", "")] {
+ let e = s.execute("sketch.edit_text", &json!({"link": link, "text_expression": bad})).unwrap_err().to_string();
+ assert!(e.contains(says), "{bad}: {e}");
+ }
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 7adfa00fbe..10a60850de 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -1432,6 +1432,7 @@ fn same_but_features(a: &Document, b: &Document) -> bool {
units,
metadata,
params,
+ text_params,
features: _,
marker,
next_id,
@@ -1465,6 +1466,7 @@ fn same_but_features(a: &Document, b: &Document) -> bool {
&& *units == b.units
&& *metadata == b.metadata
&& *params == b.params
+ && *text_params == b.text_params
&& *marker == b.marker
&& *next_id == b.next_id
&& *reserved_body_names == b.reserved_body_names
diff --git a/crates/sketch/src/link.rs b/crates/sketch/src/link.rs
index 72414f93e7..ca5a576261 100644
--- a/crates/sketch/src/link.rs
+++ b/crates/sketch/src/link.rs
@@ -91,7 +91,8 @@ pub enum LinkSource {
}
/// The expressions behind a text's numbers that were typed as expressions: its place (`x`, `y`),
-/// its height and its angle. A number without an expression is the number typed. The numbers
+/// its height and its angle; and behind its words (`text`), an expression of the design's text
+/// parameters. A number or text without an expression is the one typed. The numbers and words
/// of `LinkSource::Text` are what the expressions gave last: the document evaluates them against
/// its parameters before the text's outlines are rebuilt (`Document::apply_text_values`), and
/// the sketch crate, which knows no parameters, only keeps them.
@@ -105,6 +106,9 @@ pub struct TextExprs {
pub height: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub angle: Option<String>,
+ /// The words: text parameters and quoted texts joined by `+` (`Label + '-L'`).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub text: Option<String>,
}
impl TextExprs {
@@ -112,7 +116,8 @@ impl TextExprs {
*self == TextExprs::default()
}
- /// The expressions set, each with what it sets.
+ /// The expressions of numbers set, each with what it sets (the words' expression is of
+ /// texts, not numbers: [`TextExprs::text`]).
pub fn list(&self) -> Vec<(&'static str, &String)> {
[("Text X", &self.x), ("Text Y", &self.y), ("Text height", &self.height), ("Text angle", &self.angle)]
.into_iter()
@@ -560,6 +565,28 @@ impl Sketch {
.collect()
}
+ /// The expressions of the words of the sketch's texts (of text parameters).
+ pub fn text_word_exprs(&self) -> Vec<&String> {
+ self.links
+ .iter()
+ .filter_map(|l| match &l.source {
+ LinkSource::Text { exprs, .. } => exprs.text.as_ref(),
+ _ => None,
+ })
+ .collect()
+ }
+
+ /// Mutable view of [`Sketch::text_word_exprs`], for renaming the parameters they refer to.
+ pub fn text_word_exprs_mut(&mut self) -> Vec<&mut String> {
+ self.links
+ .iter_mut()
+ .filter_map(|l| match &mut l.source {
+ LinkSource::Text { exprs, .. } => exprs.text.as_mut(),
+ _ => None,
+ })
+ .collect()
+ }
+
/// Mutable view of [`Sketch::text_exprs`], for renaming the parameters they refer to.
pub fn text_exprs_mut(&mut self) -> Vec<&mut String> {
self.links
diff --git a/crates/ui-egui/src/params_dialog.rs b/crates/ui-egui/src/params_dialog.rs
index 9b1b65df5d..4790ded689 100644
--- a/crates/ui-egui/src/params_dialog.rs
+++ b/crates/ui-egui/src/params_dialog.rs
@@ -21,7 +21,7 @@ use crate::ui_kit::{self, Column};
/// can't be picked (#3216).
pub(crate) const IMPORT_TYPES: &[&str] = &["csv", "json"];
-const UNITS: [&str; 9] = ["mm", "cm", "m", "in", "ft", "deg", "rad", "", "um"];
+const UNITS: [&str; 10] = ["mm", "cm", "m", "in", "ft", "deg", "rad", "", "um", "text"];
/// Dialog state (what is being typed; the parameters themselves live in the document).
#[derive(Default)]
@@ -99,6 +99,8 @@ struct Row {
source: String,
group: String,
favorite: bool,
+ /// A text parameter's text.
+ text: Option<String>,
}
fn rows(app: &mut SolveApp) -> Vec<Row> {
@@ -134,6 +136,7 @@ fn rows(app: &mut SolveApp) -> Vec<Row> {
error: r.get("error").and_then(Value::as_str).map(str::to_string),
comment: s(r, "comment"),
favorite: r.get("favorite").and_then(Value::as_bool).unwrap_or(false),
+ text: r.get("text").and_then(Value::as_str).map(str::to_string),
source,
group,
name,
@@ -146,7 +149,7 @@ fn show_value(r: &Row) -> String {
match r.value {
Some(v) if r.unit.is_empty() => format!("{v:.4}"),
Some(v) => format!("{v:.4} {}", r.unit),
- None => "—".into(),
+ None => r.text.clone().unwrap_or_else(|| "—".into()),
}
}
@@ -365,6 +368,9 @@ fn model_group(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog, grou
/// Live check of an expression typed for a parameter of this unit: Ok(shown value) or the message.
fn check(app: &mut SolveApp, e: &str, unit: &str) -> Result<String, String> {
let r = app.session.execute("expr.evaluate", &json!({"expression": e, "unit": unit})).map_err(|e| e.to_string())?;
+ if let Some(text) = r["text"].as_str() {
+ return Ok(text.to_string());
+ }
if r["ok"].as_bool().unwrap_or(false) {
let v = r["display_value"].as_f64().unwrap_or(0.0);
Ok(if unit.is_empty() { format!("{v:.4}") } else { format!("{v:.4} {unit}") })