feat: a sketch text's height, place and angle can be expressions (#1453)
A sketch text's height, place (x and y) and angle can each be an expression over the design's parameters, and the text follows parameter changes, undo and reopening. Closes #1362. Co-authored-by: NOWN-DEV <NOWN-DEV@users.noreply.github.com>
This commit is contained in:
1 parent
e20cf1858a
commit
b6806b16cf
23 files changed
+751
-70
No files matched your search
@@ -3,7 +3,7 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_geom::Vec2;
|
||||
use solidcraft_sketch::{ConstraintKind, CurveKind, LinkKind, LinkSource, Sketch, TextAlign, TextStyle};
|
||||
use solidcraft_sketch::{ConstraintKind, CurveKind, LinkKind, LinkSource, Sketch, TextAlign, TextExprs, TextStyle};
|
||||
|
||||
/// The style parameters of `sketch.text` and `sketch.edit_text`.
|
||||
macro_rules! text_style_doc {
|
||||
@@ -21,6 +21,10 @@ use crate::{Result, Session};
|
||||
#[path = "sketch_text_move_tests.rs"]
|
||||
mod text_move_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "sketch_text_expr_tests.rs"]
|
||||
mod text_expr_tests;
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("sketch.line.midpoint", "Midpoint Line", midpoint_line)
|
||||
.at("SKETCH", "CREATE")
|
||||
@@ -91,7 +95,8 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.enabled(in_sketch)
|
||||
.params("curves: [line ids], value?: bool (default toggles): centerline line type (not in profiles; an axis)"),
|
||||
CommandSpec::new("sketch.text", "Text", text).at("SKETCH", "CREATE").icon("text").enabled(in_sketch).params(concat!(
|
||||
"text: string (\\n breaks lines), at: baseline start [x,y], height?: capital height mm (default 5), angle?: deg, 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: 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, \
|
||||
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!()
|
||||
)),
|
||||
@@ -99,7 +104,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, font?: family or file path (empty: the built-in font), ",
|
||||
"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), ",
|
||||
text_style_doc!(),
|
||||
" (each kept when left out); live?: bool: one frame of an interactive change (the sketch is solved, the features after it stay as they were until `sketch.drag_end`)",
|
||||
created_doc!()
|
||||
@@ -146,19 +151,47 @@ fn text_style(p: &Value, cmd: &str, old: TextStyle) -> Result<TextStyle> {
|
||||
}
|
||||
|
||||
/// What a text's `at` must be.
|
||||
const AT_MUST: &str = "`at` must be the baseline start [x, y]";
|
||||
const AT_MUST: &str = "`at` must be the baseline start [x, y], each a number or an expression";
|
||||
|
||||
/// The number given for `key`: `None` when it is left out or null, and an error when it is
|
||||
/// anything but a number (not read as left out).
|
||||
fn given_num(p: &Value, cmd: &str, key: &str, what: &str) -> Result<Option<f64>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(_) => num(p, key).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be {what}"))),
|
||||
/// One number of a text, from a command's parameter `key`. A number is that number (mm, or
|
||||
/// degrees for the angle). A string is an expression over the design's parameters: a bare number
|
||||
/// in it is in the design's units (degrees for the angle), and it is kept as an expression when
|
||||
/// it names a parameter, so that the text follows it; one that names none is the number it comes
|
||||
/// to. Returns the value (mm or radians) and the expression kept. Anything else is refused with
|
||||
/// `must`.
|
||||
fn text_number(doc: &solidcraft_doc::Document, v: &Value, cmd: &str, key: &str, must: &str, angle: bool) -> Result<(f64, Option<String>)> {
|
||||
use solidcraft_doc::expr::{self, Kind};
|
||||
let kind = if angle { Kind::Angle } else { Kind::Length };
|
||||
match v {
|
||||
Value::Number(n) => {
|
||||
let x = n.as_f64().and_then(crate::params::finite).ok_or_else(|| bad(cmd, must))?;
|
||||
Ok((if angle { x.to_radians() } else { x }, None))
|
||||
}
|
||||
Value::String(e) if !e.trim().is_empty() && e.len() <= 4096 => {
|
||||
let e = doc.with_design_unit(e.trim(), kind);
|
||||
match doc.eval(&e, kind) {
|
||||
Ok(x) => {
|
||||
let x = crate::params::finite(x).ok_or_else(|| bad(cmd, must))?;
|
||||
Ok((x, (!expr::references(&e).is_empty()).then_some(e)))
|
||||
}
|
||||
// Say what is wrong with it (an unknown parameter, a length where an angle goes).
|
||||
Err(error) => Err(bad(cmd, format!("{key}: {error}"))),
|
||||
}
|
||||
}
|
||||
_ => Err(bad(cmd, must)),
|
||||
}
|
||||
}
|
||||
|
||||
fn text_source(p: &Value, cmd: &str, old: Option<(String, Vec2, f64, f64, Option<String>, TextStyle)>) -> Result<LinkSource> {
|
||||
let (t0, at0, h0, a0, f0, s0) = old.unwrap_or((String::new(), Vec2::ZERO, 5.0, 0.0, None, TextStyle::default()));
|
||||
/// A text's values as `text_source` works on them: text, place, height, angle (radians), font,
|
||||
/// style and the expressions behind the numbers.
|
||||
type TextValues = (String, Vec2, f64, f64, Option<String>, TextStyle, TextExprs);
|
||||
|
||||
/// A text's source from a command's parameters: what is given replaces what `old` has (the
|
||||
/// defaults, for a new text); what is left out stays, an expression with its number. A number
|
||||
/// replaces an expression. An input that is not understood is refused, not ignored.
|
||||
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(),
|
||||
@@ -170,15 +203,27 @@ fn text_source(p: &Value, cmd: &str, old: Option<(String, Vec2, f64, f64, Option
|
||||
if text.chars().count() > solidcraft_sketch::MAX_TEXT_CHARS {
|
||||
return Err(bad(cmd, "text too long"));
|
||||
}
|
||||
let at = match p.get("at") {
|
||||
None | Some(Value::Null) => at0,
|
||||
Some(v) => crate::params::vec2(v).ok_or_else(|| bad(cmd, AT_MUST))?,
|
||||
};
|
||||
let height = given_num(p, cmd, "height", "a length in mm")?.unwrap_or(h0);
|
||||
match p.get("at") {
|
||||
None | Some(Value::Null) => {}
|
||||
Some(Value::Array(a)) => {
|
||||
let [x, y] = a.as_slice() else { return Err(bad(cmd, AT_MUST)) };
|
||||
(at.x, exprs.x) = text_number(doc, x, cmd, "`at` x", AT_MUST, false)?;
|
||||
(at.y, exprs.y) = text_number(doc, y, cmd, "`at` y", AT_MUST, false)?;
|
||||
}
|
||||
Some(v) => {
|
||||
at = crate::params::vec2(v).ok_or_else(|| bad(cmd, AT_MUST))?;
|
||||
(exprs.x, exprs.y) = (None, None);
|
||||
}
|
||||
}
|
||||
if let Some(v) = p.get("height").filter(|v| !v.is_null()) {
|
||||
(height, exprs.height) = text_number(doc, v, cmd, "`height`", "`height` must be a length in mm, or an expression", false)?;
|
||||
}
|
||||
if !(height > 1e-6 && height < 1e5) {
|
||||
return Err(bad(cmd, "`height` must be positive"));
|
||||
}
|
||||
let angle = given_num(p, cmd, "angle", "an angle in degrees")?.map_or(a0, f64::to_radians);
|
||||
if let Some(v) = p.get("angle").filter(|v| !v.is_null()) {
|
||||
(angle, exprs.angle) = text_number(doc, v, cmd, "`angle`", "`angle` must be an angle in degrees, or an expression", true)?;
|
||||
}
|
||||
let font = match p.get("font") {
|
||||
None | Some(Value::Null) => f0,
|
||||
Some(Value::String(f)) if f.trim().is_empty() => None,
|
||||
@@ -189,7 +234,19 @@ fn text_source(p: &Value, cmd: &str, old: Option<(String, Vec2, f64, f64, Option
|
||||
// An unknown font, an unreadable file or a style the font lacks is an error now, not a lost
|
||||
// link later; so is a font file outside an agent's folders (the font reader asks `vfs`).
|
||||
solidcraft_sketch::font_data_styled(font.as_deref(), style.bold, style.italic).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
Ok(LinkSource::Text { text, at, height, angle, font, style })
|
||||
Ok(LinkSource::Text { text, at, height, angle, font, style, exprs })
|
||||
}
|
||||
|
||||
/// The expressions behind a text's numbers, for a command's reply (`{"height": "plate_h / 10"}`).
|
||||
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)] {
|
||||
if let Some(e) = e {
|
||||
out.insert(key.into(), json!(e));
|
||||
}
|
||||
}
|
||||
(!out.is_empty()).then_some(Value::Object(out))
|
||||
}
|
||||
|
||||
fn text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -197,7 +254,7 @@ fn text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("at").is_none_or(Value::is_null) {
|
||||
return Err(bad(cmd, AT_MUST));
|
||||
}
|
||||
let src = text_source(p, cmd, None)?;
|
||||
let src = text_source(&s.doc, p, cmd, None)?;
|
||||
let id = s.active_sketch.ok_or_else(|| bad(cmd, "no sketch is being edited"))?;
|
||||
let mut doc = (*s.doc).clone();
|
||||
let mut sk = doc.sketch(id)?.clone();
|
||||
@@ -207,11 +264,16 @@ fn text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(cmd, "the text makes no outline"));
|
||||
}
|
||||
let guide = guide(&mut sk, &src);
|
||||
let exprs = text_exprs_json(&src);
|
||||
let l = sk.add_link(LinkKind::Text, src, &geom)?;
|
||||
let curves = ids_of(&sk, &sk.link_curves(&l));
|
||||
*doc.sketch_mut(id)? = sk;
|
||||
*s.doc_mut() = doc;
|
||||
Ok(json!({"link": l, "curves": curves, "guide": guide}))
|
||||
let mut out = json!({"link": l, "curves": curves, "guide": guide});
|
||||
if let Some(exprs) = exprs {
|
||||
out["exprs"] = exprs;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A text's path is its guide: the curve it follows becomes construction. Left as it was, it
|
||||
@@ -242,7 +304,7 @@ pub(super) fn text_link<'a>(sk: &'a Sketch, entity: &str) -> Option<&'a str> {
|
||||
|
||||
/// Transform a text source as a unit; generated outlines remain linked and editable.
|
||||
pub(super) fn move_text(sk: &mut Sketch, link: &str, translate: Vec2, rotation: f64, center: Vec2, copy: bool) -> Result<Vec<usize>> {
|
||||
let Some(LinkSource::Text { text, at, height, angle, font, style }) = sk.link(link).map(|l| l.source.clone()) else {
|
||||
let Some(LinkSource::Text { text, at, height, angle, font, style, mut exprs }) = sk.link(link).map(|l| l.source.clone()) else {
|
||||
return Err(bad("sketch.move", "the selected source is not text"));
|
||||
};
|
||||
if style.path.is_some() {
|
||||
@@ -250,10 +312,20 @@ pub(super) fn move_text(sk: &mut Sketch, link: &str, translate: Vec2, rotation:
|
||||
}
|
||||
let q = at - center;
|
||||
let (sin, cos) = rotation.sin_cos();
|
||||
let at = center + Vec2::new(q.x * cos - q.y * sin, q.x * sin + q.y * cos) + translate;
|
||||
let angle = angle + rotation;
|
||||
let moved = center + Vec2::new(q.x * cos - q.y * sin, q.x * sin + q.y * cos) + translate;
|
||||
// What the move changes is a number now, not the expression it was; the rest stays.
|
||||
if (moved.x - at.x).abs() > 1e-12 {
|
||||
exprs.x = None;
|
||||
}
|
||||
if (moved.y - at.y).abs() > 1e-12 {
|
||||
exprs.y = None;
|
||||
}
|
||||
if rotation.abs() > 1e-12 {
|
||||
exprs.angle = None;
|
||||
}
|
||||
let (at, angle) = (moved, angle + rotation);
|
||||
let geom = solidcraft_sketch::text_geometry_styled(font.as_deref(), &text, at, height, angle, &style, None)?;
|
||||
let source = LinkSource::Text { text, at, height, angle, font, style };
|
||||
let source = LinkSource::Text { text, at, height, angle, font, style, exprs };
|
||||
let link = if copy {
|
||||
sk.add_link(LinkKind::Text, source, &geom)?
|
||||
} else {
|
||||
@@ -271,7 +343,10 @@ fn edit_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = s.active_sketch.ok_or_else(|| bad(cmd, "no sketch is being edited"))?;
|
||||
let mut doc = (*s.doc).clone();
|
||||
let mut sk = doc.sketch(id)?.clone();
|
||||
let out = apply_text_edit(&mut sk, p)?;
|
||||
// The numbers its expressions give now (a parameter may have changed since the sketch was
|
||||
// last stored); one that cannot be evaluated is left as it was, to be replaced by this edit.
|
||||
let _ = doc.apply_text_values(&doc.param_values().0, &mut sk);
|
||||
let out = apply_text_edit(&mut sk, &doc, p)?;
|
||||
*doc.sketch_mut(id)? = sk;
|
||||
*s.doc_mut() = doc;
|
||||
Ok(out)
|
||||
@@ -282,13 +357,13 @@ fn edit_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn edit_text_live(s: &mut Session, p: &Value) -> Result<(Value, Option<crate::LiveEdit>)> {
|
||||
let cmd = "sketch.edit_text";
|
||||
let id = s.active_sketch.ok_or_else(|| bad(cmd, "no sketch is being edited"))?;
|
||||
let (out, report) = super::sketch::edit_solved(s, id, false, |sk, _| Ok((apply_text_edit(sk, p)?, super::sketch::Left::Unsolved)))?;
|
||||
let (out, report) = super::sketch::edit_solved(s, id, false, |sk, doc| Ok((apply_text_edit(sk, doc, p)?, super::sketch::Left::Unsolved)))?;
|
||||
Ok((out, report.map(|report| crate::LiveEdit { sketch: id, report })))
|
||||
}
|
||||
|
||||
/// `sketch.edit_text`'s change to its sketch: the text source's new values and its outlines
|
||||
/// regenerated from them.
|
||||
fn apply_text_edit(sk: &mut Sketch, p: &Value) -> Result<Value> {
|
||||
fn apply_text_edit(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value) -> Result<Value> {
|
||||
let cmd = "sketch.edit_text";
|
||||
let l = match (str_(p, "link"), str_(p, "entity")) {
|
||||
(Some(l), _) => l.to_string(),
|
||||
@@ -296,19 +371,24 @@ fn apply_text_edit(sk: &mut Sketch, p: &Value) -> Result<Value> {
|
||||
_ => return Err(bad(cmd, "give `link` or `entity`")),
|
||||
};
|
||||
let old = match sk.link(&l).map(|x| (x.kind, x.source.clone())) {
|
||||
Some((LinkKind::Text, LinkSource::Text { text, at, height, angle, font, style })) => (text, at, height, angle, font, style),
|
||||
Some((LinkKind::Text, LinkSource::Text { text, at, height, angle, font, style, exprs })) => (text, at, height, angle, font, style, exprs),
|
||||
_ => return Err(bad(cmd, format!("`{l}` is not text"))),
|
||||
};
|
||||
let src = text_source(p, cmd, Some(old))?;
|
||||
let src = text_source(doc, p, cmd, Some(old))?;
|
||||
let geom = sk.text_source_geometry(&src).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
if geom.is_empty() {
|
||||
return Err(bad(cmd, "the text makes no outline"));
|
||||
}
|
||||
let guide = guide(sk, &src);
|
||||
let exprs = text_exprs_json(&src);
|
||||
sk.set_link_source(&l, src.clone());
|
||||
sk.update_link(&l, &geom)?;
|
||||
let curves = ids_of(sk, &sk.link_curves(&l));
|
||||
Ok(json!({"link": l, "curves": curves, "guide": guide}))
|
||||
let mut out = json!({"link": l, "curves": curves, "guide": guide});
|
||||
if let Some(exprs) = exprs {
|
||||
out["exprs"] = exprs;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The curve ending at point `pi` and the direction leaving it there.
|
||||
|
||||
@@ -141,7 +141,7 @@ fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result<Value> {
|
||||
id,
|
||||
&mut sk,
|
||||
LinkKind::Text,
|
||||
LinkSource::Text { text, at, height, angle, font: None, style: Default::default() },
|
||||
LinkSource::Text { text, at, height, angle, font: None, style: Default::default(), exprs: Default::default() },
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
|
||||
@@ -180,6 +180,9 @@ pub(super) fn refresh(s: &Session, doc: &Document, id: u64, sk: &mut Sketch) ->
|
||||
}
|
||||
let doc = placed_candidate(s, doc);
|
||||
let (vals, _) = doc.param_values();
|
||||
// A text's outlines are rebuilt from its numbers: the ones its expressions give come first
|
||||
// (an expression that cannot be evaluated leaves the text as it was).
|
||||
let _ = doc.apply_text_values(&vals, sk);
|
||||
let st = s.model.state_before(id);
|
||||
let attachment = doc.feature(id).and_then(|feature| match &feature.kind {
|
||||
solidcraft_doc::FeatureKind::Sketch { plane, .. } => super::sketch::face::anchor(plane),
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
//! A sketch text's height, place and angle can be expressions of the design's parameters: the
|
||||
//! text keeps the expression, follows the parameters, and a number typed instead replaces it.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_geom::Vec2;
|
||||
use solidcraft_sketch::LinkSource;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => v,
|
||||
Err(e) => panic!("{id} {p}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Lower-left and upper-right corners of the outlines of the text in sketch `S`.
|
||||
fn text_box(s: &Session) -> (Vec2, Vec2) {
|
||||
let id = s.doc.find_feature("S").unwrap().id;
|
||||
let st = s.model.state();
|
||||
let sk = &st.sketch(id).unwrap().sketch;
|
||||
let (mut lo, mut hi) = (Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN));
|
||||
for q in sk.points.iter().filter(|q| q.link.is_some()) {
|
||||
lo = Vec2::new(lo.x.min(q.pos.x), lo.y.min(q.pos.y));
|
||||
hi = Vec2::new(hi.x.max(q.pos.x), hi.y.max(q.pos.y));
|
||||
}
|
||||
(lo, hi)
|
||||
}
|
||||
|
||||
fn no_trouble(s: &Session) {
|
||||
for r in &s.model.results {
|
||||
assert!(r.error.is_none() && r.warning.is_none(), "{}: {:?} {:?}", r.name, r.error, r.warning);
|
||||
}
|
||||
}
|
||||
|
||||
/// The numbers and expressions stored for the text `link` of sketch `S`.
|
||||
fn stored(s: &Session, link: &str) -> (Vec2, f64, f64, solidcraft_sketch::TextExprs) {
|
||||
let id = s.doc.find_feature("S").unwrap().id;
|
||||
let LinkSource::Text { at, height, angle, exprs, .. } = &s.doc.sketch(id).unwrap().link(link).unwrap().source else { panic!("not a text") };
|
||||
(*at, *height, *angle, exprs.clone())
|
||||
}
|
||||
|
||||
fn reopened(s: &Session) -> Session {
|
||||
Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_texts_height_and_place_typed_as_expressions_follow_their_parameters() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "parameters.add", json!({"name": "tall", "expression": "20 mm"}));
|
||||
run(&mut s, "parameters.add", json!({"name": "left", "expression": "30 mm"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
|
||||
// Capital letters without descenders: the outlines stand on the baseline, one height tall.
|
||||
let r = run(&mut s, "sketch.text", json!({"text": "LIVE", "at": ["left", 25], "height": "tall"}));
|
||||
let link = r["link"].as_str().unwrap().to_string();
|
||||
assert_eq!(r["exprs"], json!({"x": "left", "height": "tall"}), "{r}");
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
no_trouble(&s);
|
||||
let (lo, hi) = text_box(&s);
|
||||
assert!((lo.y - 25.0).abs() < 1e-9 && (hi.y - 45.0).abs() < 1e-6, "{lo:?} {hi:?}");
|
||||
// The first letter's side bearing is a fixed share of the height.
|
||||
let bearing = (lo.x - 30.0) / 20.0;
|
||||
assert!(bearing > 0.0 && bearing < 0.5, "{lo:?}");
|
||||
|
||||
// Smaller and further left: the outlines follow both parameters, and so do they after the
|
||||
// design is saved and opened again.
|
||||
run(&mut s, "parameters.change", json!({"name": "tall", "expression": "8 mm"}));
|
||||
run(&mut s, "parameters.change", json!({"name": "left", "expression": "5 mm"}));
|
||||
let check = |s: &Session, left: f64, tall: f64| {
|
||||
no_trouble(s);
|
||||
let (lo, hi) = text_box(s);
|
||||
assert!((lo.y - 25.0).abs() < 1e-9 && (hi.y - 25.0 - tall).abs() < 1e-6, "{lo:?} {hi:?}");
|
||||
assert!((lo.x - left - bearing * tall).abs() < 1e-6, "{lo:?}");
|
||||
};
|
||||
check(&s, 5.0, 8.0);
|
||||
let json = s.doc.to_json();
|
||||
assert!(json.contains("\"exprs\""), "the design file keeps the expressions");
|
||||
check(&reopened(&s), 5.0, 8.0);
|
||||
let (_, _, _, exprs) = stored(&s, &link);
|
||||
assert_eq!((exprs.x.as_deref(), exprs.y, exprs.height.as_deref(), exprs.angle), (Some("left"), None, Some("tall"), None));
|
||||
|
||||
// Editing the sketch afterwards keeps the text where its parameters put it.
|
||||
run(&mut s, "sketch.edit", json!({"sketch": "S"}));
|
||||
run(&mut s, "sketch.point", json!({"point": [200, 200]}));
|
||||
run(&mut s, "sketch.edit_text", json!({"link": link, "text": "LIVE"}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
check(&s, 5.0, 8.0);
|
||||
let (at, height, _, exprs) = stored(&s, &link);
|
||||
assert!((at.x - 5.0).abs() < 1e-9 && (height - 8.0).abs() < 1e-9 && exprs.height.as_deref() == Some("tall"), "{at:?} {height} {exprs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_texts_angle_can_be_an_expression_too() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "parameters.add", json!({"name": "turn", "expression": "0 deg"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
|
||||
let r = run(&mut s, "sketch.text", json!({"text": "LIVE", "at": [0, 0], "height": 10, "angle": "turn"}));
|
||||
let link = r["link"].as_str().unwrap().to_string();
|
||||
assert_eq!(r["exprs"], json!({"angle": "turn"}), "{r}");
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
let (lo, hi) = text_box(&s);
|
||||
assert!(hi.x - lo.x > hi.y - lo.y, "along the x axis: {lo:?} {hi:?}");
|
||||
run(&mut s, "parameters.change", json!({"name": "turn", "expression": "90 deg"}));
|
||||
no_trouble(&s);
|
||||
let (lo, hi) = text_box(&s);
|
||||
assert!(hi.y - lo.y > hi.x - lo.x && hi.x.abs() < 1e-9 && lo.x < -9.0, "upright, the letters run up the y axis: {lo:?} {hi:?}");
|
||||
assert_eq!(stored(&s, &link).3.angle.as_deref(), Some("turn"));
|
||||
// Reopened, the text stands as the parameter says.
|
||||
let (lo, hi) = text_box(&reopened(&s));
|
||||
assert!(hi.y - lo.y > hi.x - lo.x, "{lo:?} {hi:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parameters_a_text_uses_are_listed_renamed_and_kept() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "parameters.add", json!({"name": "tall", "expression": "12 mm"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
|
||||
let r = run(&mut s, "sketch.text", json!({"text": "LIVE", "at": [0, 0], "height": "tall * 2"}));
|
||||
let link = r["link"].as_str().unwrap().to_string();
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
let users = run(&mut s, "parameters.users", json!({"name": "tall"}));
|
||||
assert!(users.to_string().contains("Text height"), "{users}");
|
||||
assert!(users["drives"].to_string().contains("\"S\""), "{users}");
|
||||
let e = s.execute("parameters.delete", &json!({"name": "tall"})).unwrap_err().to_string();
|
||||
assert!(e.contains("Text height"), "{e}");
|
||||
run(&mut s, "parameters.rename", json!({"name": "tall", "new_name": "big"}));
|
||||
assert_eq!(stored(&s, &link).3.height.as_deref(), Some("big * 2"));
|
||||
no_trouble(&s);
|
||||
let (lo, hi) = text_box(&s);
|
||||
assert!((hi.y - lo.y - 24.0).abs() < 1e-6, "{lo:?} {hi:?}");
|
||||
run(&mut s, "parameters.change", json!({"name": "big", "expression": "5 mm"}));
|
||||
let (lo, hi) = text_box(&s);
|
||||
assert!((hi.y - lo.y - 10.0).abs() < 1e-6, "{lo:?} {hi:?}");
|
||||
// The edges of the dependency graph name it, too.
|
||||
let graph = run(&mut s, "parameters.graph", json!({}));
|
||||
assert!(graph["edges"].to_string().contains("big"), "{graph}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_replaces_an_expression_and_plain_numbers_save_as_before() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "parameters.add", json!({"name": "tall", "expression": "20 mm"}));
|
||||
run(&mut s, "parameters.add", json!({"name": "left", "expression": "30 mm"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
|
||||
// Numbers, and expressions naming no parameter, are numbers: nothing new is saved.
|
||||
let r = run(&mut s, "sketch.text", json!({"text": "A", "at": [3, "2 mm + 2 mm"], "height": "10 mm", "angle": "30 deg"}));
|
||||
let plain = r["link"].as_str().unwrap().to_string();
|
||||
assert!(r.get("exprs").is_none(), "{r}");
|
||||
let (at, height, angle, exprs) = stored(&s, &plain);
|
||||
assert!(at.dist(Vec2::new(3.0, 4.0)) < 1e-12 && (height - 10.0).abs() < 1e-12 && (angle - 30f64.to_radians()).abs() < 1e-12, "{at:?}");
|
||||
assert!(exprs.is_empty());
|
||||
assert!(!s.doc.to_json().contains("exprs"), "a design without expressions saves as before");
|
||||
|
||||
let r = run(&mut s, "sketch.text", json!({"text": "LIVE", "at": ["left", "left / 2"], "height": "tall"}));
|
||||
let link = r["link"].as_str().unwrap().to_string();
|
||||
// What an edit leaves out stays an expression; a number given replaces what it was.
|
||||
run(&mut s, "sketch.edit_text", json!({"link": link, "text": "LIVE!"}));
|
||||
assert_eq!(stored(&s, &link).3.height.as_deref(), Some("tall"));
|
||||
let r = run(&mut s, "sketch.edit_text", json!({"link": link, "height": 12}));
|
||||
assert_eq!(r["exprs"], json!({"x": "left", "y": "left / 2"}), "{r}");
|
||||
let (at, height, _, exprs) = stored(&s, &link);
|
||||
assert!((height - 12.0).abs() < 1e-12 && exprs.height.is_none() && at.dist(Vec2::new(30.0, 15.0)) < 1e-9, "{at:?} {height} {exprs:?}");
|
||||
run(&mut s, "sketch.edit_text", json!({"link": link, "at": [7, "left"]}));
|
||||
assert_eq!(run(&mut s, "sketch.edit_text", json!({"link": link}))["exprs"], json!({"y": "left"}));
|
||||
// Moving the text turns what moves into numbers; the height and the other coordinate stay.
|
||||
run(&mut s, "sketch.edit_text", json!({"link": link, "at": ["left", "left"], "height": "tall"}));
|
||||
let curve = s.doc.sketch(s.active_sketch.unwrap()).unwrap().link_curves(&link)[0];
|
||||
let curve = s.doc.sketch(s.active_sketch.unwrap()).unwrap().curves[curve].id.clone();
|
||||
run(&mut s, "sketch.move", json!({"entities": [curve], "translate": [10, 0]}));
|
||||
let (at, _, _, exprs) = stored(&s, &link);
|
||||
assert!((at.x - 40.0).abs() < 1e-9 && (at.y - 30.0).abs() < 1e-9, "{at:?}");
|
||||
assert_eq!((exprs.x, exprs.y.as_deref(), exprs.height.as_deref()), (None, Some("left"), Some("tall")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_expression_that_cannot_be_used_is_refused_and_changes_nothing() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "parameters.add", json!({"name": "turn", "expression": "30 deg"}));
|
||||
run(&mut s, "parameters.add", json!({"name": "tall", "expression": "20 mm"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
|
||||
let r = run(&mut s, "sketch.text", json!({"text": "A", "at": [0, 0]}));
|
||||
let link = r["link"].as_str().unwrap().to_string();
|
||||
let before = s.doc.to_json();
|
||||
let undo = s.undo.len();
|
||||
for (extra, error) in [
|
||||
(json!({"at": ["nope", 0]}), "`at` x"),
|
||||
(json!({"at": [0, "turn"]}), "`at` y"),
|
||||
(json!({"at": [0, "tall +"]}), "`at` y"),
|
||||
(json!({"height": "nope"}), "unknown parameter"),
|
||||
(json!({"height": "turn"}), "`height`"),
|
||||
(json!({"height": "tall - 30 mm"}), "`height` must be positive"),
|
||||
(json!({"height": "-3 mm"}), "`height` must be positive"),
|
||||
(json!({"height": "0 * tall"}), "`height` must be positive"),
|
||||
(json!({"height": ""}), "`height` must be a length"),
|
||||
(json!({"angle": "tall"}), "`angle`"),
|
||||
(json!({"angle": "5 mm"}), "`angle`"),
|
||||
(json!({"angle": "nope"}), "unknown parameter"),
|
||||
] {
|
||||
let mut create = json!({"text": "A", "at": [0, 0]});
|
||||
let mut edit = json!({"link": link});
|
||||
for (key, value) in extra.as_object().unwrap() {
|
||||
create[key] = value.clone();
|
||||
edit[key] = value.clone();
|
||||
}
|
||||
let e = s.execute("sketch.text", &create).unwrap_err().to_string();
|
||||
assert!(e.contains(error), "{create}: {e}");
|
||||
for live in [false, true] {
|
||||
edit["live"] = json!(live);
|
||||
let e = s.execute("sketch.edit_text", &edit).unwrap_err().to_string();
|
||||
assert!(e.contains(error), "{edit}: {e}");
|
||||
}
|
||||
assert_eq!(s.doc.to_json(), before, "{extra}");
|
||||
assert_eq!(s.undo.len(), undo, "{extra}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_that_leaves_a_text_no_height_is_an_error_of_its_sketch_not_a_crash() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "parameters.add", json!({"name": "tall", "expression": "12 mm"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
|
||||
run(&mut s, "sketch.text", json!({"text": "LIVE", "at": [0, 0], "height": "tall"}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
no_trouble(&s);
|
||||
run(&mut s, "parameters.change", json!({"name": "tall", "expression": "0 mm"}));
|
||||
let sketch = s.model.results.iter().find(|r| r.name == "S").unwrap();
|
||||
assert!(sketch.error.as_deref().is_some_and(|e| e.contains("height")), "{:?}", sketch.error);
|
||||
run(&mut s, "parameters.change", json!({"name": "tall", "expression": "6 mm"}));
|
||||
no_trouble(&s);
|
||||
let (lo, hi) = text_box(&s);
|
||||
assert!((hi.y - lo.y - 6.0).abs() < 1e-6, "{lo:?} {hi:?}");
|
||||
}
|
||||
|
||||
/// The height of the outlines of the texts in the sketch feature `id`.
|
||||
fn outline_height(s: &Session, id: u64) -> f64 {
|
||||
let st = s.model.state();
|
||||
let sk = &st.sketch(id).unwrap().sketch;
|
||||
let ys: Vec<f64> = sk.points.iter().filter(|q| q.link.is_some()).map(|q| q.pos.y).collect();
|
||||
ys.iter().cloned().fold(f64::MIN, f64::max) - ys.iter().cloned().fold(f64::MAX, f64::min)
|
||||
}
|
||||
|
||||
/// The first dimension's parameter of the sketch feature `id` and the expression of its text's height.
|
||||
fn dimension_and_expression(s: &Session, id: u64) -> (String, Option<String>) {
|
||||
let sk = s.doc.sketch(id).unwrap();
|
||||
let dimension = sk.constraints.iter().find_map(|c| c.param.clone()).expect("a dimension with a parameter");
|
||||
let LinkSource::Text { exprs, .. } = &sk.links.iter().find(|l| matches!(l.source, LinkSource::Text { .. })).unwrap().source else {
|
||||
panic!("not a text")
|
||||
};
|
||||
(dimension, exprs.height.clone())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cloned_components_text_follows_the_cloned_dimension_it_names_not_the_original() {
|
||||
let mut s = Session::default();
|
||||
let part = run(&mut s, "component.create", json!({"name": "Part"}))["component"].as_u64().unwrap();
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
|
||||
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [60, 20]}));
|
||||
run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": 60}));
|
||||
let original = s.doc.find_feature("S").unwrap().id;
|
||||
let own = s.doc.sketch(original).unwrap().constraints.iter().find_map(|c| c.param.clone()).expect("a dimension with a parameter");
|
||||
// The text's height is a quarter of the sketch's own dimension.
|
||||
run(&mut s, "sketch.text", json!({"text": "LIVE", "at": [5, 5], "height": format!("{own} / 4")}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
no_trouble(&s);
|
||||
assert!((outline_height(&s, original) - 15.0).abs() < 1e-6);
|
||||
|
||||
let copy = run(&mut s, "component.paste_new", json!({"component": part, "translate": [0, 50, 0]}))["component"].as_u64().unwrap();
|
||||
let clone = s.doc.features.iter().find(|f| f.component == copy && matches!(f.kind, solidcraft_doc::FeatureKind::Sketch { .. })).unwrap().id;
|
||||
let (theirs, expression) = dimension_and_expression(&s, clone);
|
||||
assert_ne!(theirs, own, "the copy's dimension is its own");
|
||||
assert_eq!(expression, Some(format!("{theirs} / 4")), "and so is the expression that uses it");
|
||||
no_trouble(&s);
|
||||
assert!((outline_height(&s, clone) - 15.0).abs() < 1e-6);
|
||||
run(&mut s, "parameters.change", json!({"name": theirs, "expression": "40"}));
|
||||
assert!((outline_height(&s, clone) - 10.0).abs() < 1e-6, "the copy follows its own dimension");
|
||||
assert!((outline_height(&s, original) - 15.0).abs() < 1e-6, "and the original stays");
|
||||
no_trouble(&s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_numbers_in_a_text_expression_are_in_the_designs_units() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));
|
||||
s.doc_mut().units = "in".into();
|
||||
let r = run(&mut s, "sketch.text", json!({"text": "A", "at": [0, 0], "height": "1"}));
|
||||
let (_, height, _, exprs) = stored(&s, r["link"].as_str().unwrap());
|
||||
// Numbers stay millimetres for programmatic callers; an expression is in the design's units.
|
||||
assert!((height - 25.4).abs() < 1e-9 && exprs.is_empty(), "{height}");
|
||||
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);
|
||||
}
|
||||
@@ -234,16 +234,17 @@ const TEXT: &str = "`text` must be a string";
|
||||
/// "H" drew the text 5 mm high, `at: ["H", 25]` put it at the origin. Each with its message.
|
||||
fn not_understood() -> Vec<(Value, &'static str)> {
|
||||
vec![
|
||||
(json!({"height":"H"}), HEIGHT),
|
||||
// A string is an expression now: one naming no parameter is refused as such.
|
||||
(json!({"height":"H"}), "unknown parameter `H`"),
|
||||
(json!({"height":true}), HEIGHT),
|
||||
(json!({"height":[10]}), HEIGHT),
|
||||
(json!({"height":1e10}), HEIGHT),
|
||||
(json!({"height":0}), "`height` must be positive"),
|
||||
(json!({"height":-3}), "`height` must be positive"),
|
||||
(json!({"angle":"A"}), ANGLE),
|
||||
(json!({"angle":"A"}), "unknown parameter `A`"),
|
||||
(json!({"angle":[15]}), ANGLE),
|
||||
(json!({"angle":1e10}), ANGLE),
|
||||
(json!({"at":["H",25]}), AT),
|
||||
(json!({"at":["H",25]}), "unknown parameter `H`"),
|
||||
(json!({"at":[1]}), AT),
|
||||
(json!({"at":[1,2,3]}), AT),
|
||||
(json!({"at":[1,null]}), AT),
|
||||
|
||||
Reference in new issue
Block a user