Skip to content

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

Sketch text: number parameters in the words, and = for a formula in Edit Text (#9281) (#9386)

phanoob634f0a2308e8
diff --git a/assets/locales/pending/sketch-text-formula.json b/assets/locales/pending/sketch-text-formula.json
new file mode 100644
index 0000000000..7d0d73b794
--- /dev/null
+++ b/assets/locales/pending/sketch-text-formula.json
@@ -0,0 +1,9 @@
+{
+ "en": { "sketch_text.formula": "Start with = to build the words from parameters: ='W' + number(Width)" },
+ "ar": { "sketch_text.formula": "ابدأ بـ = لتكوين النص من المعاملات: ='W' + number(Width)" },
+ "fr": { "sketch_text.formula": "Commencez par = pour composer le texte avec des paramètres : ='L' + number(Largeur)" },
+ "he": { "sketch_text.formula": "התחילו ב־= כדי לבנות את הטקסט מפרמטרים: ='W' + number(Width)" },
+ "ja": { "sketch_text.formula": "= で始めるとパラメーターから文字列を組み立てられます: ='W' + number(Width)" },
+ "vi": { "sketch_text.formula": "Bắt đầu bằng = để tạo chữ từ các tham số: ='W' + number(Width)" },
+ "zh": { "sketch_text.formula": "以 = 开头即可用参数组成文字:='W' + number(Width)" }
+}
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index 3c53b5e6dc..fb24e12542 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -4022,7 +4022,7 @@ impl Document {
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}")))?;
+ let words = self.eval_words(e, vals).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")));
}
diff --git a/crates/doc/src/text_params.rs b/crates/doc/src/text_params.rs
index 7fb35bb1d9..53866b029c 100644
--- a/crates/doc/src/text_params.rs
+++ b/crates/doc/src/text_params.rs
@@ -3,9 +3,17 @@
//! 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.
+//!
+//! The words can show a number parameter's value too (#9281): `'Width: ' + Width` reads
+//! `Width: 85 mm`, a length in the design's units, an angle in degrees (`30°`), up to three
+//! decimals without trailing zeros. `number(Width)` is the number alone (`85`) and
+//! `number(Width, 2)` gives it two decimals (`85.00`).
use serde::{Deserialize, Serialize};
+use std::collections::BTreeMap;
+
+use crate::expr::Value;
use crate::{DocError, Document, FeatureKind, MAX_PARAMS, Result};
/// The unit that marks a text parameter where parameters are listed, added or imported.
@@ -49,8 +57,29 @@ pub fn unquote(s: &str) -> String {
enum Term {
Text(String),
Name(String),
+ /// `number(name)` or `number(name, decimals)`, with the name's byte range.
+ Number {
+ name: String,
+ at: (usize, usize),
+ decimals: Option<u8>,
+ },
+}
+
+/// How the words show a number parameter.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Show {
+ /// As named: its value and unit, up to three decimals.
+ Named,
+ /// In `number(...)`: the number alone, with these decimals or up to three.
+ Number(Option<u8>),
}
+/// The function that shows a number parameter's value without its unit.
+const NUMBER: &str = "number";
+
+/// Most decimals `number(name, decimals)` takes.
+const MAX_DECIMALS: u8 = 8;
+
/// 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)>> {
@@ -96,10 +125,16 @@ fn terms(s: &str) -> Result<Vec<(Term, usize, usize)>> {
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;
+ i = word_end(&cs, i);
+ let word = s.get(at(start)..at(i)).unwrap_or_default().to_string();
+ let open = skip_blanks(&cs, i);
+ if word == NUMBER && cs.get(open).is_some_and(|x| x.1 == '(') {
+ let (term, end) = number_call(s, &cs, open + 1)?;
+ i = end;
+ out.push((term, at(start), at(i)));
+ } else {
+ out.push((Term::Name(word), at(start), at(i)));
}
- 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 +")));
@@ -112,11 +147,88 @@ fn terms(s: &str) -> Result<Vec<(Term, usize, usize)>> {
Ok(out)
}
+fn word_end(cs: &[(usize, char)], mut i: usize) -> usize {
+ while cs.get(i).is_some_and(|x| x.1.is_alphanumeric() || x.1 == '_') {
+ i += 1;
+ }
+ i
+}
+
+fn skip_blanks(cs: &[(usize, char)], mut i: usize) -> usize {
+ while cs.get(i).is_some_and(|x| x.1.is_whitespace()) {
+ i += 1;
+ }
+ i
+}
+
+/// `number(` has been read up to `i`: the name, optional decimals and `)`; the term and where
+/// it ends.
+fn number_call(s: &str, cs: &[(usize, char)], i: usize) -> Result<(Term, usize)> {
+ let at = |i: usize| cs.get(i).map_or(s.len(), |x| x.0);
+ let usage = || DocError::Expr("number() takes a number parameter and, if wanted, its decimals: number(Width, 2)".into());
+ let start = skip_blanks(cs, i);
+ if !cs.get(start).is_some_and(|x| x.1.is_alphabetic() || x.1 == '_') {
+ return Err(usage());
+ }
+ let end = word_end(cs, start);
+ let name = s.get(at(start)..at(end)).unwrap_or_default().to_string();
+ let mut i = skip_blanks(cs, end);
+ let mut decimals = None;
+ if cs.get(i).is_some_and(|x| x.1 == ',') {
+ let from = skip_blanks(cs, i + 1);
+ let mut to = from;
+ while cs.get(to).is_some_and(|x| x.1.is_ascii_digit()) {
+ to += 1;
+ }
+ let digits = s.get(at(from)..at(to)).unwrap_or_default();
+ let n: u8 = digits.parse().map_err(|_| usage())?;
+ if n > MAX_DECIMALS {
+ return Err(DocError::Expr(format!("number() shows at most {MAX_DECIMALS} decimals")));
+ }
+ decimals = Some(n);
+ i = skip_blanks(cs, to);
+ }
+ if !cs.get(i).is_some_and(|x| x.1 == ')') {
+ return Err(usage());
+ }
+ Ok((Term::Number { name, at: (at(start), at(end)), decimals }, i + 1))
+}
+
+/// A number parameter's value as the words show it: `v` in millimetres, radians or no unit
+/// (`len`, `ang`: its dimension), lengths in `units`.
+pub fn show_number(v: f64, len: i8, ang: i8, units: &str, show: Show) -> Result<String> {
+ let (value, unit) = match (len, ang) {
+ (0, 0) => (v, ""),
+ (1, 0) => {
+ let (scale, name) = crate::display_units::unit_scale(units);
+ (v * scale, name)
+ }
+ (0, 1) => (v.to_degrees(), "°"),
+ _ => return Err(DocError::Expr("a text shows lengths, angles and plain numbers only".into())),
+ };
+ if !value.is_finite() || value.abs() > 1e12 {
+ return Err(DocError::Expr("the number is out of range for a text".into()));
+ }
+ let digits = match show {
+ Show::Number(Some(d)) => format!("{value:.*}", usize::from(d)),
+ Show::Named | Show::Number(None) => {
+ let t = format!("{value:.3}");
+ let t = t.trim_end_matches('0').trim_end_matches('.');
+ if t == "-0" { "0".to_string() } else { t.to_string() }
+ }
+ };
+ Ok(match (show, unit) {
+ (Show::Number(_), _) | (_, "") => digits,
+ (Show::Named, "°") => format!("{digits}°"),
+ (Show::Named, unit) => format!("{digits} {unit}"),
+ })
+}
+
/// 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
+ if let Term::Name(n) | Term::Number { name: n, .. } = t
&& !out.contains(&n)
{
out.push(n);
@@ -131,23 +243,27 @@ pub fn rename_reference(s: &str, old: &str, new: &str) -> 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;
- }
+ let at = match &t {
+ Term::Name(n) if n == old => (a, b),
+ Term::Number { name, at, .. } if name == old => *at,
+ _ => continue,
+ };
+ out.push_str(s.get(last..at.0).unwrap_or_default());
+ out.push_str(new);
+ last = at.1;
}
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> {
+pub fn eval(s: &str, lookup: &dyn Fn(&str, Show) -> 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)?),
+ Term::Name(n) => out.push_str(&lookup(&n, Show::Named)?),
+ Term::Number { name, decimals, .. } => out.push_str(&lookup(&name, Show::Number(decimals))?),
}
if out.len() > MAX_LEN {
return Err(DocError::Expr("the text is too long".into()));
@@ -161,12 +277,14 @@ impl Document {
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}`"))),
+ /// The words a words expression comes to in this design, number parameters from `vals`.
+ pub fn eval_words(&self, e: &str, vals: &BTreeMap<String, Value>) -> Result<String> {
+ eval(e, &|n, show| match (self.text_param(n), vals.get(n)) {
+ (Some(_), _) if show != Show::Named => Err(DocError::Expr(format!("`{n}` is a text parameter: number() takes a number parameter"))),
+ (Some(p), _) => Ok(p.text.clone()),
+ (None, Some(v)) => show_number(v.v, v.len, v.ang, &self.units, show).map_err(|error| DocError::Expr(format!("`{n}`: {error}"))),
+ (None, None) if self.name_taken(n) => Err(DocError::Expr(format!("`{n}` has no value"))),
+ (None, None) => Err(DocError::Expr(format!("unknown parameter `{n}`"))),
})
}
@@ -230,7 +348,7 @@ mod tests {
#[test]
fn words_expressions_join_quoted_texts_and_parameters() {
- let look = |n: &str| match n {
+ let look = |n: &str, _: Show| match n {
"Label" => Ok("TAG-1".to_string()),
_ => Err(DocError::Expr(format!("unknown text parameter `{n}`"))),
};
@@ -249,4 +367,30 @@ mod tests {
assert_eq!(unquote("'a' + 'b'"), "'a' + 'b'");
assert_eq!(unquote("TAG-1"), "TAG-1");
}
+
+ /// #9281: a number parameter in the words shows its value; `number()` drops the unit and
+ /// can fix the decimals; a rename reaches inside `number()`.
+ #[test]
+ fn number_parameters_show_their_value_in_the_words() {
+ let look = |n: &str, show: Show| match n {
+ "Width" => show_number(85.0, 1, 0, "mm", show),
+ "Gap" => show_number(12.7, 1, 0, "in", show),
+ "Tilt" => show_number(30f64.to_radians(), 0, 1, "mm", show),
+ "Count" => show_number(4.0, 0, 0, "mm", show),
+ "Area" => show_number(1.0, 2, 0, "mm", show),
+ _ => Err(DocError::Expr(format!("unknown parameter `{n}`"))),
+ };
+ assert_eq!(eval("'Width: ' + Width", &look).unwrap(), "Width: 85 mm");
+ assert_eq!(eval("Gap", &look).unwrap(), "0.5 in");
+ assert_eq!(eval("Tilt + ' / ' + Count", &look).unwrap(), "30° / 4");
+ assert_eq!(eval("number(Width) + 'x' + number( Width , 2 )", &look).unwrap(), "85x85.00");
+ assert_eq!(eval("number(Tilt, 1)", &look).unwrap(), "30.0");
+ for bad in ["number(Width", "number()", "number(Width, x)", "number(Width, 9)", "number(Width 2)", "Area", "number('a')"] {
+ assert!(eval(bad, &look).is_err(), "{bad}");
+ }
+ assert_eq!(references("number(Width, 1) + Count"), ["Width", "Count"]);
+ assert_eq!(rename_reference("number(Width, 1) + Width + 'Width'", "Width", "W"), "number(W, 1) + W + 'Width'");
+ assert_eq!(show_number(-0.0001, 1, 0, "mm", Show::Named).unwrap(), "0 mm");
+ assert!(show_number(f64::NAN, 0, 0, "mm", Show::Named).is_err());
+ }
}
diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs
index 38d8e53878..39758b08f5 100644
--- a/crates/engine/src/cmd/sketch_create.rs
+++ b/crates/engine/src/cmd/sketch_create.rs
@@ -116,7 +116,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), 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, \
+ "text: string (\\n breaks lines), or text_expression: the words built from text parameters (parameters.add with unit text), number parameters and quoted texts joined by + (\"Label + '-L'\", \"'W' + Width\"; a number parameter shows its value in the design's units, \"85 mm\", an angle in degrees, \"30°\"; number(Width) is the number alone and number(Width, 2) has 2 decimals): 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!()
@@ -222,7 +222,7 @@ fn text_source(doc: &solidcraft_doc::Document, p: &Value, cmd: &str, old: Option
t.clone()
}
(None, Some(Value::String(e))) => {
- let words = doc.eval_words(e.trim()).map_err(|error| bad(cmd, format!("`text_expression`: {error}")))?;
+ let words = doc.eval_words(e.trim(), &doc.param_values().0).map_err(|error| bad(cmd, format!("`text_expression`: {error}")))?;
exprs.text = Some(e.trim().to_string());
words
}
diff --git a/crates/engine/src/cmd/sketch_text_expr_tests.rs b/crates/engine/src/cmd/sketch_text_expr_tests.rs
index 5a8749d65e..779a14a659 100644
--- a/crates/engine/src/cmd/sketch_text_expr_tests.rs
+++ b/crates/engine/src/cmd/sketch_text_expr_tests.rs
@@ -389,11 +389,55 @@ fn a_texts_words_follow_its_text_parameters_and_so_does_its_cut() {
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"}));
+ // An expression naming an unknown parameter, or a text parameter in number(), is refused.
run(&mut s, "sketch.edit", json!({"sketch": "S"}));
- for (bad, says) in [("Nope + 'x'", "Nope"), ("W", "W"), ("Tag +", "")] {
+ for (bad, says) in [("Nope + 'x'", "Nope"), ("number(Tag)", "Tag"), ("Tag +", "")] {
let e = s.execute("sketch.edit_text", &json!({"link": link, "text_expression": bad})).unwrap_err().to_string();
assert!(e.contains(says), "{bad}: {e}");
}
}
+
+/// #9281: a number parameter in a text's words shows its value in the design's units
+/// (`number()` without the unit, with chosen decimals); a parameter edit rewrites the words
+/// and the cut follows in the same rebuild, also after a save; a rename reaches the words and
+/// deleting the parameter is refused while the text shows it.
+#[test]
+fn a_texts_words_show_a_number_parameter_and_follow_it() {
+ 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();
+ run(&mut s, "parameters.add", json!({"name": "Width", "expression": "85 mm"}));
+ run(&mut s, "parameters.add", json!({"name": "Tilt", "expression": "30 deg"}));
+ let r = block_with_text(&mut s, json!({"text_expression": "'W' + number(Width)"}));
+ let link = r["link"].as_str().unwrap().to_string();
+ no_trouble(&s);
+ assert_eq!(words(&s, &link), "W85");
+ same(volume(&mut s), typed("W85"), "W85");
+
+ run(&mut s, "parameters.change", json!({"name": "Width", "expression": "90 mm"}));
+ no_trouble(&s);
+ assert_eq!(words(&s, &link), "W90");
+ let wide = typed("W90");
+ same(volume(&mut s), wide, "W90");
+ let mut again = reopened(&s);
+ no_trouble(&again);
+ same(volume(&mut again), wide, "W90 reopened");
+
+ run(&mut s, "sketch.edit", json!({"sketch": "S"}));
+ run(&mut s, "sketch.edit_text", json!({"link": link, "text_expression": "number(Width, 1) + ' / ' + Tilt"}));
+ run(&mut s, "sketch.finish", json!({}));
+ no_trouble(&s);
+ assert_eq!(words(&s, &link), "90.0 / 30°");
+
+ run(&mut s, "parameters.rename", json!({"name": "Width", "new_name": "Span"}));
+ assert_eq!(word_expr(&s, &link), json!("number(Span, 1) + ' / ' + Tilt"));
+ let e = s.execute("parameters.delete", &json!({"name": "Span"})).unwrap_err().to_string();
+ assert!(e.contains("Text"), "{e}");
+ no_trouble(&s);
+ assert_eq!(words(&s, &link), "90.0 / 30°");
+}
diff --git a/crates/ui-egui/src/sketch_text.rs b/crates/ui-egui/src/sketch_text.rs
index 6cf025a5a5..9089df35e2 100644
--- a/crates/ui-egui/src/sketch_text.rs
+++ b/crates/ui-egui/src/sketch_text.rs
@@ -28,6 +28,9 @@ const ANGLE: usize = 3;
const ANGLE_END: usize = 4;
const LINE_SPACING: usize = 5;
+/// Starts the words' expression in the Text field (`='W' + number(Width)`, #9281).
+const FORMULA: char = '=';
+
/// No input is active: a click on the canvas picks no path until the Path chip is clicked.
const NO_INPUT: usize = usize::MAX;
@@ -36,8 +39,11 @@ const NO_INPUT: usize = usize::MAX;
pub struct Tx {
sketch: u64,
pub(crate) link: String,
+ /// The words as typed, or `=` and the expression they follow.
pub(crate) text: String,
initial_text: String,
+ /// The saved words follow an expression: an untouched Text field keeps it.
+ initial_formula: bool,
/// The font as typed: an installed font's family name or a font file's path; empty is the built-in font.
pub(crate) font: String,
initial_font: String,
@@ -70,8 +76,8 @@ pub struct Tx {
shown: Option<Source>,
}
-/// A text source as the dialog sees it: text, font (empty: built-in), its values, its style and
-/// the expressions behind its values.
+/// A text source as the dialog sees it: text (`=` and its expression when the words follow one),
+/// font (empty: built-in), its values, its style and the expressions behind its values.
type Source = (String, String, [f64; FIELDS], TextStyle, [Option<String>; FIELDS]);
/// What the Text tool puts down, ready to be typed over.
@@ -222,8 +228,15 @@ fn source(app: &SolveApp, sketch: u64, link: &str) -> Option<Source> {
let source = sk.link(link).filter(|source| source.kind == LinkKind::Text)?;
let LinkSource::Text { text, at, height, angle, font, style, exprs } = &source.source else { return None };
let values = [at.x, at.y, *height, *angle, style.letter_spacing, style.line_spacing];
+ let text = exprs.text.as_ref().map_or_else(|| text.clone(), |e| format!("{FORMULA}{e}"));
let exprs = [exprs.x.clone(), exprs.y.clone(), exprs.height.clone(), exprs.angle.clone(), None, None];
- Some((text.clone(), font.clone().unwrap_or_default(), values, style.clone(), exprs))
+ Some((text, font.clone().unwrap_or_default(), values, style.clone(), exprs))
+}
+
+/// Whether the saved words of `link` follow an expression.
+fn formula_saved(app: &SolveApp, sketch: u64, link: &str) -> bool {
+ let source = app.session.doc.sketch(sketch).ok().and_then(|sk| sk.link(link).map(|l| l.source.clone()));
+ matches!(source, Some(LinkSource::Text { exprs, .. }) if exprs.text.is_some())
}
/// The fields as shown: a value, or the expression behind it.
@@ -281,6 +294,7 @@ fn kind_for(app: &SolveApp, entity: &str) -> Option<Kind> {
let (scale, unit) = crate::prefs::unit_scale(&app.session.doc.units);
let values = fields(&original, &exprs, unit, scale);
let mut tx = Tx {
+ initial_formula: formula_saved(app, sketch, &link),
sketch,
link,
initial_text: text.clone(),
@@ -468,6 +482,7 @@ pub(crate) fn refresh(app: &SolveApp, k: &mut Tx) -> bool {
k.text = text.clone();
}
k.initial_text = text;
+ k.initial_formula = formula_saved(app, k.sketch, &k.link);
}
if font != k.initial_font {
if k.font == k.initial_font {
@@ -486,7 +501,7 @@ pub(crate) fn rows(ui: &mut egui::Ui, k: &mut Tx, inputs: &mut [SelInput], activ
if ui.memory(|m| m.has_focus(id)) {
enter |= ui.input_mut(|i| !i.modifiers.shift && i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
}
- let response = ui_kit::multiline_text_field(ui, "Text", id, &mut k.text);
+ let response = ui_kit::multiline_text_field(ui, "Text", id, &mut k.text).on_hover_text(crate::i18n::tr("sketch_text.formula"));
crate::scenario::publish_handle("dialog:Text", response.rect.center());
if k.focus {
response.request_focus();
@@ -678,11 +693,18 @@ fn edit_params(app: &SolveApp, k: &Tx) -> Result<Value, String> {
TextAlign::Right => "right",
};
let mut params = json!({
- "link": k.link, "text": k.text, "at": [sent_x, sent_y], "height": sent_height,
+ "link": k.link, "at": [sent_x, sent_y], "height": sent_height,
"bold": k.style.bold, "italic": k.style.italic, "align": align,
"letter_spacing": letter_spacing, "line_spacing": line_spacing,
"path": k.style.path.clone().unwrap_or_default(), "reverse": k.style.reverse,
});
+ // `=` starts the words' expression; an untouched text keeps what it was, so a typed text that
+ // happens to start with `=` stays typed.
+ let untouched = k.text == k.initial_text;
+ match k.text.trim_start().strip_prefix(FORMULA).filter(|_| !untouched || k.initial_formula) {
+ Some(e) => params["text_expression"] = json!(e.trim()),
+ None => params["text"] = json!(k.text),
+ }
// Omitting an unchanged angle keeps its exact saved radians (or its expression).
if k.values.get(ANGLE) != k.initial.get(ANGLE) {
params["angle"] = sent_angle;
@@ -1159,6 +1181,60 @@ mod tests {
assert!(editing(&h.app), "the dialog stays open on a field that cannot be used");
}
+ fn words_of(h: &Harness, link: &str) -> String {
+ let sid = h.app.session.active_sketch.unwrap();
+ let LinkSource::Text { text, .. } = h.app.session.doc.sketch(sid).unwrap().link(link).unwrap().source.clone() else { panic!("text source") };
+ text
+ }
+
+ /// #9281: a Text starting with `=` is the words' expression: OK keeps it; reopened, the field
+ /// shows it with its `=` and an untouched OK keeps it; typed words replace it; a typed text
+ /// that happens to start with `=` stays typed; the rebuilt design's words follow the parameter.
+ #[test]
+ fn a_text_starting_with_equals_builds_its_words_from_parameters() {
+ let (mut h, link, _) = setup();
+ let formula = |h: &mut Harness| {
+ h.app.start("sketch.edit_text");
+ h.frames(3);
+ replace(h, "dialog:Text", "='W' + number(Width)");
+ ok(h);
+ assert!(!editing(&h.app), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone()));
+ assert_eq!(exprs_of(h, &link).text.as_deref(), Some("'W' + number(Width)"));
+ };
+ let reopen = |h: &mut Harness| {
+ select_text(h, &link);
+ h.app.start("sketch.edit_text");
+ h.frames(3);
+ };
+ h.app.run("parameters.add", json!({"name":"Width","expression":"85 mm"})).unwrap();
+ formula(&mut h);
+ assert_eq!(words_of(&h, &link), "W85");
+
+ reopen(&mut h);
+ assert_eq!(tx(&h.app).text, "='W' + number(Width)");
+ ok(&mut h);
+ assert_eq!(exprs_of(&h, &link).text.as_deref(), Some("'W' + number(Width)"));
+
+ reopen(&mut h);
+ replace(&mut h, "dialog:Text", "Plain");
+ ok(&mut h);
+ assert_eq!((exprs_of(&h, &link).text, words_of(&h, &link).as_str()), (None, "Plain"));
+
+ h.app.run("sketch.edit_text", json!({"link": link, "text": "=5"})).unwrap();
+ reopen(&mut h);
+ ok(&mut h);
+ assert_eq!((exprs_of(&h, &link).text, words_of(&h, &link).as_str()), (None, "=5"));
+
+ select_text(&mut h, &link);
+ formula(&mut h);
+ let sid = h.app.session.active_sketch.unwrap();
+ h.app.run("sketch.finish", json!({})).unwrap();
+ h.app.run("parameters.change", json!({"name":"Width","expression":"90 mm"})).unwrap();
+ let state = h.app.session.model.state();
+ let LinkSource::Text { text, .. } = &state.sketch(sid).unwrap().sketch.link(&link).unwrap().source else { panic!("text source") };
+ assert_eq!(text, "W90");
+ }
+
#[test]
fn fields_take_expressions_with_units_and_parameters() {
let (mut h, link, _) = setup();