From b70c8609c981a2bef08d32abd71c40d7fea09caa Mon Sep 17 00:00:00 2001 From: eldrir Date: Tue, 13 Oct 2026 08:05:50 -0400 Subject: [PATCH 01/41] Properties: describe and set every text, mtext and dimension property properties.describe lists the Properties palette's rows for a selection: General for every object; Text and Geometry for TEXT and MTEXT; Misc, Lines & Arrows, Text, Fit, Primary Units, Alternate Units and Tolerances for dimensions. Each row carries the properties.set key that changes it, the value the objects share (or *VARIES*), the value in the drawing's units, whether it can be edited (a fixed-height text style makes a dimension's text height read-only and says so), and for dimensions whether the dimension overrides its style there. A mixed selection gets the General group; `type` limits the description to one object type. properties.set takes those keys: TEXT style, justify (keeping the point the text is placed by), oblique, positionX/Y/Z and the second point of aligned and fit text; MTEXT style, justify, lineSpacing, lineSpacingDistance and lineSpacingStyle, position; dimension style variables by field or DIM* name as overrides of each dimension, clearOverrides, clear, textRotation, textPositionX/Y, prefix and suffix. The reply lists the keys no selected object took. Editing a dimension style or a text style now redraws the dimensions read from files that use it (they kept drawing, and saving, the *D block they were read with), and renaming a text style follows a dimension's own text style override. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/props.rs | 362 ++------- crates/engine/src/cmd/props/set.rs | 594 ++++++++++++++ crates/engine/src/lib.rs | 1 + crates/engine/src/properties.rs | 745 ++++++++++++++++++ crates/engine/tests/it/main.rs | 2 + crates/engine/tests/it/properties_describe.rs | 155 ++++ .../tests/it/properties_set_text_dims.rs | 247 ++++++ crates/ui-egui/src/i18n/ar.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/pt_br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/zh.tsv | 1 + docs/mcp.md | 8 + 20 files changed, 1837 insertions(+), 289 deletions(-) create mode 100644 crates/engine/src/cmd/props/set.rs create mode 100644 crates/engine/src/properties.rs create mode 100644 crates/engine/tests/it/properties_describe.rs create mode 100644 crates/engine/tests/it/properties_set_text_dims.rs diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 018e2dbf6..e12dedc99 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -6,8 +6,10 @@ mod chprop; mod dash_units; mod matchprop; mod rename; +mod set; pub use matchprop::MatchProps; +use set::run_set; use cadcraft_color::Color; use cadcraft_doc::{EntityKind, Lineweight, Transparency}; @@ -21,7 +23,14 @@ use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; pub fn specs() -> Vec { vec![ CommandSpec::new("properties", "Properties", run_get).menu(&["Modify", "Properties"]).alias(&["pr", "props", "ch"]).params("{handles?} → properties of the selection").noundo(), - CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, thickness?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, ; dimensions: textOverride, dimStyle, textHeight, arrowSize, dimScale, precision (per-dimension overrides)}"), + CommandSpec::new("properties.set", "Set Properties", run_set).params( + "{handles?, layer?, color?, linetype?, lineweight?, ltscale?, thickness?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, annotative?, \ + , text: style?, justify?, oblique?, positionX/Y/Z?, alignmentX/Y?, \ + mtext: style?, justify?, lineSpacing?, lineSpacingDistance?, lineSpacingStyle?: atLeast | exactly, positionX/Y/Z?, \ + dimension: dimStyle?, textOverride?, textRotation?, textPositionX/Y?, prefix?, suffix?, altPrefix?, altSuffix?, dimScale?, precision?, \ + , clearOverrides?, clear?: [variable]} \ + → {changed, ignored: keys no selected object took} (the keys are those of `properties.describe` rows)", + ), CommandSpec::new("chprop", "Change Properties", chprop::run_chprop) .params("as properties.set, leaving out objects on locked layers → {changed, locked} (the command line asks Color, LAyer, LType, ltScale, LWeight, Thickness and TRansparency in turn)") .interactive(|_| Ok(Box::new(chprop::ChpropM::new()))), @@ -29,6 +38,13 @@ pub fn specs() -> Vec { .alias(&["-ch"]) .params("{handles?, point?: [x, y], elevation?} → {changed, ignored, differingZ, detachedHatches, locked}: the point moves the nearer end of each line to it (level or plumb with the other end under ORTHOMODE) and, when it is the one object, passes a circle through it or places a text, attribute definition or block reference at it (`ignored` otherwise); `elevation` sets the z of objects whose points share one (`differingZ` otherwise); objects on locked layers are left out (the command line asks Specify change point or [Properties], then about each circle, text, attribute definition and block reference in turn)") .interactive(|_| Ok(Box::new(change::ChangeM::new()))), + CommandSpec::new("properties.describe", "Describe Properties", run_describe) + .params( + "{handles?, type?: one of the `types` names, to describe only those objects} → {types: [{type, count}], filter?, count, \ + groups: [{name, rows: [{key, label, kind, value, varies, display, editable, note?, overridden?, options?: [{value, label}], quick?}]}]} \ + (each row's `key` is the `properties.set` key that changes it; text, mtext and dimensions have their own groups)", + ) + .noundo(), CommandSpec::new("matchprop", "Match Properties", matchprop::run_matchprop) .menu(&["Modify", "Match Properties"]) .alias(&["ma", "painter"]) @@ -172,10 +188,13 @@ fn parse_color(v: &Value) -> Option { /// A transparency as JSON, in the form `properties.set` takes: "ByLayer", "ByBlock" or a percentage. pub(super) fn transparency_value(t: Transparency) -> Value { - match t { - Transparency::Percent(p) => json!(p), - other => json!(other.name()), - } + crate::properties::transparency_value(t) +} + +fn run_describe(s: &mut Session, p: &Value) -> Result { + let hs = targets(s, p)?; + let d = s.doc()?; + Ok(serde_json::to_value(crate::properties::describe(d, &hs, str_param(p, "type"))).unwrap_or(Value::Null)) } /// "ByLayer", "ByBlock" or a percentage 0..=90 (a number, or a string such as "50" or "50%"). @@ -189,290 +208,6 @@ fn parse_transparency(v: &Value) -> Option { (pct.is_finite() && (0.0..=90.0).contains(&pct)).then(|| Transparency::Percent(pct.round() as u8)) } -fn set_xy(p: &mut Vec3, v: &Value) { - if let Some(q) = point_value(v) { - p.x = q.x; - p.y = q.y; - } -} - -fn run_set(s: &mut Session, p: &Value) -> Result { - let hs = targets(s, p)?; - if hs.is_empty() { - return Err(bad("properties.set", "nothing selected")); - } - let color = p.get("color").map(|c| parse_color(c).ok_or_else(|| bad("properties.set", "bad colour"))).transpose()?; - let transparency = p - .get("transparency") - .map(|v| parse_transparency(v).ok_or_else(|| bad("properties.set", "transparency must be ByLayer, ByBlock or a percentage from 0 to 90"))) - .transpose()?; - let thickness = p - .get("thickness") - .map(|v| v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad("properties.set", "thickness must be a finite number"))) - .transpose()?; - let lw = p.get("lineweight").map(|v| super::layer::parse_lw(v).ok_or_else(|| bad("properties.set", "bad lineweight"))).transpose()?; - let d = s.doc_mut()?; - // An explicit object linetype must be ByLayer, ByBlock or a loaded definition (as `linetype current` requires). - let linetype = str_param(p, "linetype") - .map(|n| { - if n.eq_ignore_ascii_case("ByLayer") || n.eq_ignore_ascii_case("ByBlock") { - Ok(n.to_string()) - } else { - d.linetype(n).map(|t| t.name.clone()).ok_or_else(|| bad("properties.set", format!("linetype `{n}` is not loaded"))) - } - }) - .transpose()?; - if let Some(l) = str_param(p, "layer") { - d.ensure_layer(l); - } - let dim_style = str_param(p, "dimStyle") - .map(|n| d.dim_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("dimension style `{n}` not found")))) - .transpose()?; - let dim_over = dim_overrides(p)?; - let anno_scale = d.current_anno_scale(); - let common = CommonEntityProperties { anno_scale: &anno_scale, color, linetype: linetype.as_deref(), lineweight: lw, transparency, thickness }; - for h in &hs { - d.modify_entity(*h, |e| { - set_common_properties(e, p, &common); - apply_kind_properties(e, p, dim_style.as_ref(), &dim_over); - })?; - } - Ok(json!({ "changed": hs.len() })) -} - -fn apply_kind_properties( - entity: &mut cadcraft_doc::Entity, - params: &Value, - dim_style: Option<&String>, - dim_overrides: &serde_json::Map, -) { - let num = |key: &str| params.get(key).and_then(Value::as_f64).filter(|value| value.is_finite()); - match &mut entity.kind { - EntityKind::Line(l) => { - if let Some(v) = params.get("start") { - set_xy(&mut l.a, v); - } - if let Some(v) = params.get("end") { - set_xy(&mut l.b, v); - } - // Length / angle keep the start point and move the end point. - let (a, b) = (l.a.xy(), l.b.xy()); - let len = num("length").filter(|x| *x > 0.0 && *x < 1e15).unwrap_or_else(|| a.dist(b)); - let ang = num("angle").map(f64::to_radians).unwrap_or_else(|| a.angle_to(b)); - if num("length").is_some() || num("angle").is_some() { - let e = cadcraft_geom::Vec2::polar(a, len, ang); - if e.is_finite() { - l.b.x = e.x; - l.b.y = e.y; - } - } - } - EntityKind::Circle(c) => { - if let Some(v) = params.get("center") { - set_xy(&mut c.center, v); - } - if let Some(r) = num("radius").filter(|r| *r > 0.0) { - c.radius = r; - } - if let Some(dm) = num("diameter").filter(|r| *r > 0.0) { - c.radius = dm / 2.0; - } - if let Some(cf) = num("circumference").filter(|x| *x > 0.0) { - c.radius = cf / cadcraft_geom::TAU; - } - if let Some(a) = num("area").filter(|x| *x > 0.0) { - c.radius = (a / cadcraft_geom::PI).sqrt(); - } - } - EntityKind::Arc(a) => { - if let Some(v) = params.get("center") { - set_xy(&mut a.center, v); - } - if let Some(r) = num("radius").filter(|r| *r > 0.0) { - a.radius = r; - } - if let Some(x) = num("startAngle") { - a.start = cadcraft_geom::norm_angle(x.to_radians()); - } - if let Some(x) = num("endAngle") { - a.end = cadcraft_geom::norm_angle(x.to_radians()); - } - } - EntityKind::Text(t) => { - if let Some(v) = str_param(params, "text") { - t.value = v.to_string(); - } - if let Some(x) = num("height").filter(|x| *x > 0.0) { - t.height = x; - } - if let Some(x) = num("rotation") { - t.rotation = x.to_radians(); - } - if let Some(x) = num("widthFactor").filter(|x| *x > 0.0) { - t.width_factor = x; - } - // The position is the point the text is placed by: moving it moves the text. - if let Some(to) = params.get("position").and_then(point_value) { - let d = to - t.justify_point(); - for q in std::iter::once(&mut t.insert).chain(t.align_pt.as_mut()) { - q.x += d.x; - q.y += d.y; - } - } - } - EntityKind::MText(t) => { - if let Some(v) = str_param(params, "text") { - t.contents = v.replace('\n', "\\P"); - } - if let Some(x) = num("height").filter(|x| *x > 0.0) { - t.height = x; - } - if let Some(x) = num("width").filter(|x| *x >= 0.0) { - t.width = x; - } - if let Some(x) = num("rotation") { - t.rotation = x.to_radians(); - } - } - EntityKind::LwPolyline(pl) => { - if let Some(x) = num("width").filter(|x| *x >= 0.0) { - pl.const_width = x; - } - if let Some(c) = params.get("closed").and_then(Value::as_bool) { - pl.closed = c; - } - } - EntityKind::Insert(insert) => set_insert_properties(insert, params), - EntityKind::Dimension(dimension) => set_dimension_properties(dimension, params, dim_style, dim_overrides), - EntityKind::Hatch(hatch) => set_hatch_properties(hatch, params), - _ => {} - } -} - -fn set_insert_properties(insert: &mut cadcraft_doc::Insert, params: &Value) { - let number = |key: &str| params.get(key).and_then(Value::as_f64).filter(|value| value.is_finite()); - - if let Some(x) = number("rotation") { - let turn = x.to_radians() - insert.rotation; - insert.rotation = x.to_radians(); - // The attached text turns with the reference, around its insertion point (as ROTATE does). - let base = insert.insert.xy(); - for a in &mut insert.attribs { - let t = &mut a.text; - for q in std::iter::once(&mut t.insert).chain(t.align_pt.as_mut()) { - let r = q.xy().rotate_about(base, turn); - q.x = r.x; - q.y = r.y; - } - t.rotation = cadcraft_geom::norm_angle(t.rotation + turn); - if let Some(ml) = &mut a.multiline { - let r = ml.mtext.insert.xy().rotate_about(base, turn); - ml.mtext.insert.x = r.x; - ml.mtext.insert.y = r.y; - ml.mtext.rotation = cadcraft_geom::norm_angle(ml.mtext.rotation + turn); - } - } - } - if let Some(x) = number("scale").filter(|x| *x != 0.0) { - // A new positive scale carries the attached attribute text with it, like SCALE about the insertion point. - if x > 0.0 && insert.scale.x > 0.0 { - let m = cadcraft_geom::Mat3::scale_about(insert.insert.xy(), x / insert.scale.x); - for a in &mut insert.attribs { - let mut k = EntityKind::Text(a.text.clone()); - k.transform(&m); - if let EntityKind::Text(t) = k { - a.text = t; - } - a.transform_multiline(&m); - } - } - insert.scale = Vec3::new(x, x, x); - } -} - -fn set_dimension_properties( - dimension: &mut cadcraft_doc::Dimension, - params: &Value, - style: Option<&String>, - overrides: &serde_json::Map, -) { - if let Some(v) = str_param(params, "textOverride") { - dimension.text = v.to_string(); - dimension.block = None; - } - if let Some(st) = style { - dimension.style.clone_from(st); - dimension.block = None; - } - if !overrides.is_empty() { - dimension.overrides.extend(overrides.clone()); - dimension.block = None; - } -} - -fn set_hatch_properties(hatch: &mut cadcraft_doc::Hatch, params: &Value) { - let number = |key: &str| params.get(key).and_then(Value::as_f64).filter(|value| value.is_finite()); - - if let Some(v) = str_param(params, "pattern") { - if !hatch.pattern.eq_ignore_ascii_case(v) { - hatch.pattern_lines = super::hatch::lines_for(v); - } - hatch.pattern = v.to_ascii_uppercase(); - // The old pattern's definition lines no longer apply. - hatch.pattern_lines.clear(); - hatch.solid = hatch.pattern == "SOLID"; - if !hatch.solid { - // A named pattern replaces the gradient fill; the renderer draws the gradient first when it is set. - hatch.gradient = None; - } - } - if let Some(x) = number("scale").filter(|x| *x > 0.0) { - hatch.scale = x; - } - if let Some(x) = number("angle") { - hatch.angle = x.to_radians(); - } -} - -struct CommonEntityProperties<'a> { - anno_scale: &'a cadcraft_doc::AnnoScale, - color: Option, - linetype: Option<&'a str>, - lineweight: Option, - transparency: Option, - thickness: Option, -} - -fn set_common_properties(entity: &mut cadcraft_doc::Entity, params: &Value, common: &CommonEntityProperties<'_>) { - if let Some(annotative) = params.get("annotative").and_then(Value::as_bool) { - cadcraft_doc::set_annotative(entity, annotative, common.anno_scale); - } - if let Some(layer) = str_param(params, "layer") { - entity.common.layer = layer.to_string(); - } - if let Some(color) = common.color { - entity.common.color = color; - } - if let Some(linetype) = common.linetype { - entity.common.linetype = linetype.to_string(); - } - if let Some(lineweight) = common.lineweight { - entity.common.lineweight = lineweight; - } - if let Some(scale) = params.get("ltscale").and_then(Value::as_f64).filter(|scale| *scale > 0.0) { - entity.common.ltscale = scale; - } - if let Some(transparency) = common.transparency { - entity.common.transparency = transparency; - } - if let Some(thickness) = common.thickness { - entity.common.thickness = thickness; - } - if let Some(visible) = params.get("visible").and_then(Value::as_bool) { - entity.common.visible = visible; - } -} - fn run_color(s: &mut Session, p: &Value) -> Result { let c = p.get("color").and_then(parse_color).ok_or_else(|| bad("color", "`color` is required"))?; set_current_color(s.doc_mut()?, c); @@ -747,6 +482,11 @@ fn run_style(s: &mut Session, p: &Value) -> Result { } } } + // Dimensions whose text uses the style drop the geometry they were read with: their text + // changes with it. + let text_style_of: std::collections::HashMap = + d.dim_styles.iter().map(|st| (st.name.to_ascii_lowercase(), st.text_style.clone())).collect(); + regen_dims(d, |dm| dim_text_style(dm, &text_style_of).eq_ignore_ascii_case(&name))?; if bool_or(p, "current", true) { d.header.set_str("TEXTSTYLE", &name); } @@ -817,6 +557,7 @@ fn run_style_rename(s: &mut Session, p: &Value) -> Result { EntityKind::AttDef(a) => a.text.style.eq_ignore_ascii_case(&from), EntityKind::Insert(i) => i.attribs.iter().any(|a| a.text.style.eq_ignore_ascii_case(&from)), EntityKind::MLeader(m) => m.text.iter().any(|t| t.style.eq_ignore_ascii_case(&from)), + EntityKind::Dimension(dm) => dm.overrides.iter().any(|(k, v)| is_text_style_override(k, v, &from)), _ => false, }; let repoint = |k: &mut EntityKind| match k { @@ -825,6 +566,8 @@ fn run_style_rename(s: &mut Session, p: &Value) -> Result { EntityKind::AttDef(a) => fix(&mut a.text.style), EntityKind::Insert(i) => i.attribs.iter_mut().for_each(|a| fix(&mut a.text.style)), EntityKind::MLeader(m) => m.text.iter_mut().for_each(|t| fix(&mut t.style)), + // A dimension's own text style (a DIMTXSTY override). + EntityKind::Dimension(dm) => dm.overrides.iter_mut().filter(|(k, v)| is_text_style_override(k, v, &from)).for_each(|(_, v)| *v = json!(to)), _ => {} }; let mut hs: Vec = d.model.iter().filter(|e| uses(&e.kind)).map(|e| e.handle).collect(); @@ -889,6 +632,9 @@ fn run_dimstyle(s: &mut Session, p: &Value) -> Result { src.iter().filter(|(k, _)| !matches!(k.as_str(), "name" | "current")).map(|(k, v)| (k.clone(), v.clone())).collect(); rejected = st.apply_fields(&fields); } + // Dimensions with the style drop the geometry they were read with, so they show the edit + // (as AutoCAD updates every dimension that uses a style; their overrides still win). + regen_dims(d, |dm| dm.style.eq_ignore_ascii_case(&name))?; if bool_or(p, "current", true) { d.header.set_str("DIMSTYLE", &name); } @@ -931,6 +677,44 @@ fn run_dimstyle_current(s: &mut Session, p: &Value) -> Result { Ok(dimstyles_json(d)) } +/// Dimensions (in model space, layouts and block definitions) that `uses` matches drop the +/// geometry block they were read with, so they are drawn and saved from their style again. +fn regen_dims(d: &mut cadcraft_doc::Drawing, uses: impl Fn(&cadcraft_doc::Dimension) -> bool) -> Result<()> { + let stale = |e: &cadcraft_doc::Entity| matches!(&e.kind, EntityKind::Dimension(dm) if dm.block.is_some() && uses(dm)); + let regen = |e: &mut cadcraft_doc::Entity| { + if let EntityKind::Dimension(dm) = &mut e.kind { + dm.block = None; + } + }; + let mut hs: Vec = d.model.iter().filter(|e| stale(e)).map(|e| e.handle).collect(); + hs.extend(d.layouts.iter().flat_map(|l| l.entities.iter().filter(|e| stale(e)).map(|e| e.handle))); + for h in hs { + d.modify_entity(h, regen)?; + } + for block in d.blocks.values_mut() { + let hs: Vec = block.entities.iter().filter(|e| stale(e)).map(|e| e.handle).collect(); + if !hs.is_empty() { + let b = std::sync::Arc::make_mut(block); + for h in hs { + b.entities.modify(h, regen); + } + } + } + Ok(()) +} + +/// The text style a dimension's text is drawn with: its DIMTXSTY override, else its style's +/// (`text_style_of`: lower-case dimension style name → text style). +fn dim_text_style(dm: &cadcraft_doc::Dimension, text_style_of: &std::collections::HashMap) -> String { + let own = dm.overrides.iter().find(|(k, _)| cadcraft_doc::DimStyle::field_name(k) == Some("textStyle")).and_then(|(_, v)| v.as_str()); + own.map(str::to_string).or_else(|| text_style_of.get(&dm.style.to_ascii_lowercase()).cloned()).unwrap_or_else(|| "Standard".into()) +} + +/// Whether a dimension override `k: v` names text style `style`. +fn is_text_style_override(k: &str, v: &Value, style: &str) -> bool { + cadcraft_doc::DimStyle::field_name(k) == Some("textStyle") && v.as_str().is_some_and(|n| n.eq_ignore_ascii_case(style)) +} + fn dims_using(d: &cadcraft_doc::Drawing, name: &str) -> Vec<(cadcraft_doc::Space, cadcraft_doc::Handle)> { let mut out = Vec::new(); for space in std::iter::once(cadcraft_doc::Space::Model).chain(d.layouts.iter().map(|l| cadcraft_doc::Space::Paper(l.name.clone()))) { diff --git a/crates/engine/src/cmd/props/set.rs b/crates/engine/src/cmd/props/set.rs new file mode 100644 index 000000000..e2742010d --- /dev/null +++ b/crates/engine/src/cmd/props/set.rs @@ -0,0 +1,594 @@ +//! `properties.set`: change properties of the selected objects, the way the Properties palette +//! edits them. Keys that no selected object takes come back in `ignored`. + +use std::collections::{BTreeSet, HashMap}; + +use cadcraft_doc::{DimStyle, Drawing, HAlign, Handle, Text, VAlign}; +use cadcraft_geom::Vec2; + +use super::*; +use crate::properties::{LINE_PITCH, is_dim_linetype, join_post, split_post}; + +fn set_xy(p: &mut Vec3, v: &Value) { + if let Some(q) = point_value(v) { + p.x = q.x; + p.y = q.y; + } +} + +/// Keys `properties.set` handles itself; the rest that name a dimension style variable (a field +/// such as `textHeight` or a DIM* name such as `DIMTXT`) set per-dimension overrides. +const SET_KEYS: &[&str] = &[ + "handles", + "handle", + "layer", + "color", + "linetype", + "lineweight", + "ltscale", + "thickness", + "transparency", + "visible", + "annotative", + "dimStyle", + "textOverride", + "textRotation", + "textPositionX", + "textPositionY", + "clearOverrides", + "clear", + "prefix", + "suffix", + "altPrefix", + "altSuffix", +]; + +/// The dimension style variables of a call, checked once: canonical field names with their +/// values, and the keys they were given as. Unusable values are left out (and so `ignored`). +struct DimVars { + fields: Vec<(&'static str, Value)>, + keys: Vec, +} + +impl DimVars { + fn new(d: &Drawing, p: &Value) -> Result { + // Text height, arrow size, overall scale (`dimScale`) and precision are refused, not + // ignored, when unusable, and the last two have names of their own (#1473). + let checked = super::dim_overrides(p)?; + let mut given = serde_json::Map::new(); + for (k, v) in p.as_object().into_iter().flatten() { + if SET_KEYS.contains(&k.as_str()) { + continue; + } + let Some(field) = DimStyle::field_name(k).filter(|f| !matches!(*f, "name" | "annotative")) else { continue }; + let v = match (field, v.as_str()) { + // A text style or linetype that doesn't exist would fall back without a word. + ("textStyle", Some(n)) => { + json!(d.text_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("text style `{n}` not found")))?) + } + (f, Some(n)) if is_dim_linetype(f) => { + if n.is_empty() || n.eq_ignore_ascii_case("ByBlock") { + json!("") + } else { + json!(d.linetype(n).map(|t| t.name.clone()).ok_or_else(|| bad("properties.set", format!("linetype `{n}` is not loaded")))?) + } + } + _ => v.clone(), + }; + given.insert(k.clone(), v); + } + let rejected = DimStyle::default().apply_fields(&given); + let mut out = DimVars { fields: Vec::new(), keys: Vec::new() }; + for (k, v) in given { + if rejected.contains(&k) { + continue; + } + if let Some(f) = DimStyle::field_name(&k) { + out.fields.push((f, v)); + out.keys.push(k); + } + } + for (key, field) in [("dimScale", "scale"), ("precision", "decimals")] { + if let Some(v) = checked.get(field) { + out.fields.push((field, v.clone())); + out.keys.push(key.to_string()); + } + } + Ok(out) + } +} + +/// What some edits need to know about objects before they change. +#[derive(Default)] +struct Prepared { + /// TEXT made aligned or fit: where its baseline ends (its width along its rotation). + ends: HashMap, + /// Dimensions: where their text is drawn now. + text_pos: HashMap, + /// Dimensions: the DIMPOST and DIMAPOST templates they draw with. + posts: HashMap, +} + +impl Prepared { + fn new(d: &Drawing, p: &Value, hs: &[Handle]) -> Self { + let mut out = Prepared::default(); + let two_points = str_param(p, "justify").and_then(crate::cmd::draw::justify).is_some_and(|(h, _)| matches!(h, HAlign::Aligned | HAlign::Fit)); + let moves_text = p.get("textPositionX").is_some() || p.get("textPositionY").is_some(); + let posts = ["prefix", "suffix", "altPrefix", "altSuffix"].iter().any(|k| p.get(*k).is_some()); + if !(two_points || moves_text || posts) { + return out; + } + for h in hs { + let Some(e) = d.entity(*h) else { continue }; + match &e.kind { + EntityKind::Text(t) if two_points => { + let font = cadcraft_fonts::TextFont::resolve(&d.text_style(&t.style).cloned().unwrap_or_default().font); + let w = cadcraft_fonts::text_width(&font, &t.value, t.height, t.width_factor); + let w = if w.is_finite() && w > 1e-9 { w } else { t.height.max(1e-9) }; + out.ends.insert(*h, Vec2::polar(t.justify_point(), w, t.rotation)); + } + EntityKind::Dimension(dm) => { + if moves_text { + out.text_pos.insert(*h, cadcraft_render::dimension_in(d, dm).text_pos); + } + if posts { + let st = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides); + out.posts.insert(*h, (st.post, st.alt_post)); + } + } + _ => {} + } + } + out + } +} + +/// Give TEXT a justification. It keeps the point it is placed by, so the text moves (as +/// AutoCAD's Properties Justify does); aligned and fit text then ends at `end`. +fn set_justify(t: &mut Text, h: HAlign, v: VAlign, end: Option) { + let at = t.justify_point(); + let z = t.insert.z; + let was_two_points = matches!(t.halign, HAlign::Aligned | HAlign::Fit) && t.align_pt.is_some(); + let two_points = matches!(h, HAlign::Aligned | HAlign::Fit); + t.halign = h; + t.valign = if two_points { VAlign::Baseline } else { v }; + if two_points { + // Between aligned and fit the two points stay. + if !was_two_points { + t.insert = at.to3(z); + t.align_pt = Some(end.unwrap_or_else(|| Vec2::polar(at, t.height.max(1e-9), t.rotation)).to3(z)); + } + } else if (h, v) == (HAlign::Left, VAlign::Baseline) { + t.insert = at.to3(z); + t.align_pt = None; + } else { + t.insert = at.to3(z); + t.align_pt = Some(at.to3(z)); + } +} + +/// Move TEXT by `d` (both of its points). +fn shift(t: &mut Text, d: Vec2) { + for q in std::iter::once(&mut t.insert).chain(t.align_pt.as_mut()) { + q.x += d.x; + q.y += d.y; + } +} + +/// Set a per-dimension override, replacing the same variable under another spelling (a DIM* +/// name read from a file). +fn set_override(dm: &mut cadcraft_doc::Dimension, field: &'static str, v: Value) { + dm.overrides.retain(|k, _| DimStyle::field_name(k) != Some(field)); + dm.overrides.insert(field.to_string(), v); +} + +pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { + let hs = targets(s, p)?; + if hs.is_empty() { + return Err(bad("properties.set", "nothing selected")); + } + let color = p.get("color").map(|c| parse_color(c).ok_or_else(|| bad("properties.set", "bad colour"))).transpose()?; + let transparency = p + .get("transparency") + .map(|v| parse_transparency(v).ok_or_else(|| bad("properties.set", "transparency must be ByLayer, ByBlock or a percentage from 0 to 90"))) + .transpose()?; + let thickness = p + .get("thickness") + .map(|v| v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad("properties.set", "thickness must be a finite number"))) + .transpose()?; + let lw = p.get("lineweight").map(|v| crate::cmd::layer::parse_lw(v).ok_or_else(|| bad("properties.set", "bad lineweight"))).transpose()?; + let d = s.doc_mut()?; + // An explicit object linetype must be ByLayer, ByBlock or a loaded definition (as `linetype current` requires). + let linetype = str_param(p, "linetype") + .map(|n| { + if n.eq_ignore_ascii_case("ByLayer") || n.eq_ignore_ascii_case("ByBlock") { + Ok(n.to_string()) + } else { + d.linetype(n).map(|t| t.name.clone()).ok_or_else(|| bad("properties.set", format!("linetype `{n}` is not loaded"))) + } + }) + .transpose()?; + if let Some(l) = str_param(p, "layer") { + d.ensure_layer(l); + } + let dim_style = str_param(p, "dimStyle") + .map(|n| d.dim_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("dimension style `{n}` not found")))) + .transpose()?; + let text_style = str_param(p, "style") + .map(|n| d.text_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("text style `{n}` not found")))) + .transpose()?; + let dim_vars = DimVars::new(d, p)?; + let prep = Prepared::new(d, p, &hs); + let anno_scale = d.current_anno_scale(); + let mut used: BTreeSet<&str> = BTreeSet::new(); + for h in &hs { + let h = *h; + d.modify_entity(h, |e| { + // Annotative: Yes supports the current annotation scale; No drops every scale. + if let Some(a) = p.get("annotative").and_then(Value::as_bool) + && cadcraft_doc::can_be_annotative(&e.kind) + { + cadcraft_doc::set_annotative(e, a, &anno_scale); + if let EntityKind::Dimension(dm) = &mut e.kind { + dm.block = None; + } + used.insert("annotative"); + } + if let Some(l) = str_param(p, "layer") { + e.common.layer = l.to_string(); + used.insert("layer"); + } + if let Some(c) = color { + e.common.color = c; + used.insert("color"); + } + if let Some(lt) = &linetype { + e.common.linetype.clone_from(lt); + used.insert("linetype"); + } + if let Some(w) = lw { + e.common.lineweight = w; + used.insert("lineweight"); + } + if let Some(x) = p.get("ltscale").and_then(Value::as_f64).filter(|x| *x > 0.0 && x.is_finite()) { + e.common.ltscale = x; + used.insert("ltscale"); + } + if let Some(t) = transparency { + e.common.transparency = t; + used.insert("transparency"); + } + if let Some(th) = thickness { + e.common.thickness = th; + used.insert("thickness"); + } + if let Some(v) = p.get("visible").and_then(Value::as_bool) { + e.common.visible = v; + used.insert("visible"); + } + let num = |k: &str| p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()); + match &mut e.kind { + EntityKind::Line(l) => { + if let Some(v) = p.get("start") { + set_xy(&mut l.a, v); + used.insert("start"); + } + if let Some(v) = p.get("end") { + set_xy(&mut l.b, v); + used.insert("end"); + } + // Length / angle keep the start point and move the end point. + let (a, b) = (l.a.xy(), l.b.xy()); + let length = num("length").filter(|x| *x > 0.0 && *x < 1e15); + let len = length.unwrap_or_else(|| a.dist(b)); + let ang = num("angle").map(f64::to_radians).unwrap_or_else(|| a.angle_to(b)); + if length.is_some() || num("angle").is_some() { + let e = Vec2::polar(a, len, ang); + if e.is_finite() { + l.b.x = e.x; + l.b.y = e.y; + if length.is_some() { + used.insert("length"); + } + if num("angle").is_some() { + used.insert("angle"); + } + } + } + } + EntityKind::Circle(c) => { + if let Some(v) = p.get("center") { + set_xy(&mut c.center, v); + used.insert("center"); + } + if let Some(r) = num("radius").filter(|r| *r > 0.0) { + c.radius = r; + used.insert("radius"); + } + if let Some(dm) = num("diameter").filter(|r| *r > 0.0) { + c.radius = dm / 2.0; + used.insert("diameter"); + } + if let Some(cf) = num("circumference").filter(|x| *x > 0.0) { + c.radius = cf / cadcraft_geom::TAU; + used.insert("circumference"); + } + if let Some(a) = num("area").filter(|x| *x > 0.0) { + c.radius = (a / cadcraft_geom::PI).sqrt(); + used.insert("area"); + } + } + EntityKind::Arc(a) => { + if let Some(v) = p.get("center") { + set_xy(&mut a.center, v); + used.insert("center"); + } + if let Some(r) = num("radius").filter(|r| *r > 0.0) { + a.radius = r; + used.insert("radius"); + } + if let Some(x) = num("startAngle") { + a.start = cadcraft_geom::norm_angle(x.to_radians()); + used.insert("startAngle"); + } + if let Some(x) = num("endAngle") { + a.end = cadcraft_geom::norm_angle(x.to_radians()); + used.insert("endAngle"); + } + } + EntityKind::Text(t) => { + if let Some(v) = str_param(p, "text") { + t.value = v.to_string(); + used.insert("text"); + } + if let Some(st) = &text_style { + t.style.clone_from(st); + used.insert("style"); + } + if let Some(x) = num("height").filter(|x| *x > 0.0) { + t.height = x; + used.insert("height"); + } + if let Some(x) = num("rotation") { + t.rotation = x.to_radians(); + used.insert("rotation"); + } + if let Some(x) = num("widthFactor").filter(|x| *x > 0.0) { + t.width_factor = x; + used.insert("widthFactor"); + } + if let Some(x) = num("oblique").filter(|x| x.abs() <= 85.0) { + t.oblique = x.to_radians(); + used.insert("oblique"); + } + if let Some((ha, va)) = str_param(p, "justify").and_then(crate::cmd::draw::justify) { + set_justify(t, ha, va, prep.ends.get(&h).copied()); + used.insert("justify"); + } + // The position is the point the text is placed by: moving it moves the text. + if let Some(to) = p.get("position").and_then(point_value) { + shift(t, to - t.justify_point()); + used.insert("position"); + } + let (x, y) = (num("positionX"), num("positionY")); + if x.is_some() || y.is_some() { + let at = t.justify_point(); + shift(t, Vec2::new(x.unwrap_or(at.x), y.unwrap_or(at.y)) - at); + used.extend(["positionX", "positionY"].into_iter().filter(|k| num(k).is_some())); + } + if let Some(z) = num("positionZ") { + t.insert.z = z; + if let Some(a) = &mut t.align_pt { + a.z = z; + } + used.insert("positionZ"); + } + // Aligned and fit text: the second point alone (the text refits between them). + if matches!(t.halign, HAlign::Aligned | HAlign::Fit) + && let Some(a) = &mut t.align_pt + { + if let Some(x) = num("alignmentX") { + a.x = x; + used.insert("alignmentX"); + } + if let Some(y) = num("alignmentY") { + a.y = y; + used.insert("alignmentY"); + } + } + } + EntityKind::MText(t) => { + if let Some(v) = str_param(p, "text") { + t.contents = v.replace('\n', "\\P"); + used.insert("text"); + } + if let Some(st) = &text_style { + t.style.clone_from(st); + used.insert("style"); + } + if let Some(x) = num("height").filter(|x| *x > 0.0) { + t.height = x; + used.insert("height"); + } + if let Some(x) = num("width").filter(|x| *x >= 0.0) { + t.width = x; + used.insert("width"); + } + if let Some(x) = num("rotation") { + t.rotation = x.to_radians(); + used.insert("rotation"); + } + // The attachment point stays where it is; the text moves around it. + if let Some(n) = str_param(p, "justify").and_then(crate::cmd::mtext_opts::attach_code) { + t.attach = n; + used.insert("justify"); + } + // MTEXT's Line spacing option takes factors from 0.25 to 4. + let factor = |f: f64| f.is_finite() && (0.25 - 1e-9..=4.0 + 1e-9).contains(&f); + if let Some(x) = num("lineSpacing").filter(|x| factor(*x)) { + t.line_spacing = x; + used.insert("lineSpacing"); + } + if let Some(f) = num("lineSpacingDistance").map(|x| x / (t.height * LINE_PITCH)).filter(|f| factor(*f)) { + t.line_spacing = f; + used.insert("lineSpacingDistance"); + } + // "atLeast", "At least", "exactly"… + let spacing = str_param(p, "lineSpacingStyle") + .map(|v| v.chars().filter(char::is_ascii_alphabetic).collect::().to_ascii_lowercase()); + if let Some(exact) = match spacing.as_deref() { + Some("atleast") => Some(false), + Some("exactly") => Some(true), + _ => None, + } { + t.line_spacing_exact = exact; + used.insert("lineSpacingStyle"); + } + if let Some(to) = p.get("position").and_then(point_value) { + t.insert.x = to.x; + t.insert.y = to.y; + used.insert("position"); + } + for (k, slot) in [("positionX", &mut t.insert.x), ("positionY", &mut t.insert.y), ("positionZ", &mut t.insert.z)] { + if let Some(v) = num(k) { + *slot = v; + used.insert(k); + } + } + } + EntityKind::LwPolyline(pl) => { + if let Some(x) = num("width").filter(|x| *x >= 0.0) { + pl.const_width = x; + used.insert("width"); + } + if let Some(c) = p.get("closed").and_then(Value::as_bool) { + pl.closed = c; + used.insert("closed"); + } + } + EntityKind::Insert(i) => { + if let Some(x) = num("rotation") { + let turn = x.to_radians() - i.rotation; + i.rotation = x.to_radians(); + // The attached text turns with the reference, around its insertion point (as ROTATE does). + let base = i.insert.xy(); + for a in &mut i.attribs { + let t = &mut a.text; + for q in std::iter::once(&mut t.insert).chain(t.align_pt.as_mut()) { + let r = q.xy().rotate_about(base, turn); + q.x = r.x; + q.y = r.y; + } + t.rotation = cadcraft_geom::norm_angle(t.rotation + turn); + if let Some(ml) = &mut a.multiline { + let r = ml.mtext.insert.xy().rotate_about(base, turn); + ml.mtext.insert.x = r.x; + ml.mtext.insert.y = r.y; + ml.mtext.rotation = cadcraft_geom::norm_angle(ml.mtext.rotation + turn); + } + } + used.insert("rotation"); + } + if let Some(x) = num("scale").filter(|x| *x != 0.0) { + // A new positive scale carries the attached attribute text with it, like SCALE about the insertion point. + if x > 0.0 && i.scale.x > 0.0 { + let m = cadcraft_geom::Mat3::scale_about(i.insert.xy(), x / i.scale.x); + for a in &mut i.attribs { + let mut k = EntityKind::Text(a.text.clone()); + k.transform(&m); + if let EntityKind::Text(t) = k { + a.text = t; + } + a.transform_multiline(&m); + } + } + i.scale = Vec3::new(x, x, x); + used.insert("scale"); + } + } + EntityKind::Dimension(dm) => { + let before = dm.clone(); + if let Some(v) = str_param(p, "textOverride") { + dm.text = v.to_string(); + used.insert("textOverride"); + } + if let Some(st) = &dim_style { + dm.style.clone_from(st); + used.insert("dimStyle"); + } + // Overrides: clear first, then set (as DIMOVERRIDE does). + if p.get("clearOverrides").and_then(Value::as_bool) == Some(true) { + dm.overrides.clear(); + used.insert("clearOverrides"); + } + if let Some(names) = p.get("clear").and_then(Value::as_array) { + for f in names.iter().filter_map(Value::as_str).filter_map(DimStyle::field_name) { + dm.overrides.retain(|k, _| DimStyle::field_name(k) != Some(f)); + } + used.insert("clear"); + } + for (f, v) in &dim_vars.fields { + set_override(dm, f, v.clone()); + } + used.extend(dim_vars.keys.iter().map(String::as_str)); + if let Some(x) = num("textRotation") { + dm.text_rotation = x.to_radians(); + used.insert("textRotation"); + } + let (x, y) = (num("textPositionX"), num("textPositionY")); + if x.is_some() || y.is_some() { + let at = prep.text_pos.get(&h).copied().unwrap_or_else(|| dm.text_mid.xy()); + dm.text_mid.x = x.unwrap_or(at.x); + dm.text_mid.y = y.unwrap_or(at.y); + dm.user_text_pos = true; + used.extend(["textPositionX", "textPositionY"].into_iter().filter(|k| num(k).is_some())); + } + if let Some((post, alt)) = prep.posts.get(&h) { + for (field, template, keys) in [("post", post, ["prefix", "suffix"]), ("altPost", alt, ["altPrefix", "altSuffix"])] { + let (pre, suf) = (str_param(p, keys[0]), str_param(p, keys[1])); + if pre.is_some() || suf.is_some() { + let (pre0, suf0) = split_post(template); + set_override(dm, field, json!(join_post(pre.unwrap_or(&pre0), suf.unwrap_or(&suf0)))); + used.extend(keys.into_iter().filter(|k| str_param(p, k).is_some())); + } + } + } + // The geometry block read from a file no longer matches: draw and save it anew. + if *dm != before { + dm.block = None; + } + } + EntityKind::Hatch(h) => { + if let Some(v) = str_param(p, "pattern") { + if !h.pattern.eq_ignore_ascii_case(v) { + h.pattern_lines = crate::cmd::hatch::lines_for(v); + } + h.pattern = v.to_ascii_uppercase(); + // The old pattern's definition lines no longer apply. + h.pattern_lines.clear(); + h.solid = h.pattern == "SOLID"; + if !h.solid { + // A named pattern replaces the gradient fill; the renderer draws the gradient first when it is set. + h.gradient = None; + } + used.insert("pattern"); + } + if let Some(x) = num("scale").filter(|x| *x > 0.0) { + h.scale = x; + used.insert("scale"); + } + if let Some(x) = num("angle") { + h.angle = x.to_radians(); + used.insert("angle"); + } + } + _ => {} + } + })?; + } + let ignored: Vec<&str> = p + .as_object() + .map(|o| o.keys().map(String::as_str).filter(|k| !matches!(*k, "handles" | "handle") && !used.contains(k)).collect()) + .unwrap_or_default(); + Ok(json!({ "changed": hs.len(), "ignored": ignored })) +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ccb93ef4f..c6ea97960 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -26,6 +26,7 @@ pub mod lisp; pub mod mtext_edit; pub mod pointmod; pub mod prompt; +pub mod properties; mod recent; pub mod sample; pub mod select; diff --git a/crates/engine/src/properties.rs b/crates/engine/src/properties.rs new file mode 100644 index 000000000..a117007a0 --- /dev/null +++ b/crates/engine/src/properties.rs @@ -0,0 +1,745 @@ +//! What the Properties palette shows for a selection: groups of rows, each with the +//! `properties.set` key that changes it, the value the objects share (or *VARIES*), how the +//! value reads in the drawing's units, and whether it can be edited. `properties.describe` +//! returns the same description, so the palette, Quick Properties and agents read one list. +//! +//! Text, MText and Dimension have their own groups; other objects have the General group only +//! (the palette draws their rows itself). Dimension rows are the dimension style variables, +//! valued as the dimension draws them (its style with its overrides); setting one stores a +//! per-dimension override, as AutoCAD's Properties palette does (DIMOVERRIDE). + +use std::collections::HashSet; + +use cadcraft_doc::{DimKind, DimStyle, Dimension, Drawing, Entity, EntityKind, HAlign, Handle, Lineweight, MText, Text, Transparency, VAlign}; +use serde::Serialize; +use serde_json::{Value, json}; + +use crate::units; + +/// What a row shows when the described objects don't share a value. +pub const VARIES: &str = "*VARIES*"; + +/// MTEXT line pitch per unit of text height at line spacing factor 1 (the layout's 5/3 in +/// `cadcraft_fonts`): Line space distance = factor × text height × `LINE_PITCH`. +pub const LINE_PITCH: f64 = 5.0 / 3.0; + +/// Above this many dimensions, their measurement and text position aren't worked out (each +/// needs the dimension's geometry); the rows show *VARIES*. +const GEOMETRY_CAP: usize = 256; + +/// The Properties of a selection. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct Description { + /// The object types selected and how many of each, in the order first selected. + pub types: Vec, + /// The type the description is limited to; `None`: every selected object. + #[serde(skip_serializing_if = "Option::is_none")] + pub filter: Option<&'static str>, + /// How many objects the rows describe. + pub count: usize, + pub groups: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct TypeCount { + #[serde(rename = "type")] + pub name: &'static str, + pub count: usize, +} + +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct Group { + pub name: &'static str, + pub rows: Vec, +} + +/// One property of the described objects. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Row { + /// The `properties.set` key that changes it. + pub key: &'static str, + pub label: &'static str, + pub kind: Kind, + /// The value every described object has; `null` when they differ. + pub value: Value, + pub varies: bool, + /// The value as shown: lengths in the drawing's units (LUNITS/LUPREC), angles in its angle + /// units (AUNITS/AUPREC), choices by their label; *VARIES* when the objects differ. + pub display: String, + pub editable: bool, + /// Why the row can't be edited, or what decides its value. + #[serde(skip_serializing_if = "Option::is_none")] + pub note: Option, + /// Dimension rows: a described dimension overrides its style here. + #[serde(skip_serializing_if = "is_false")] + pub overridden: bool, + /// The values a choice or style row can take. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub options: Vec, + /// One of the rows Quick Properties shows. + #[serde(skip_serializing_if = "is_false")] + pub quick: bool, +} + +fn is_false(b: &bool) -> bool { + !*b +} + +impl Row { + fn quick(mut self) -> Self { + self.quick = true; + self + } + fn read_only(mut self) -> Self { + self.editable = false; + self + } +} + +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct Choice { + pub value: Value, + pub label: String, +} + +impl Choice { + fn new(value: Value, label: impl Into) -> Self { + Choice { value, label: label.into() } + } +} + +/// How a row's value is entered and shown. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Kind { + /// One line of text. + Text, + /// MTEXT contents, inline formatting codes included. + Contents, + /// A plain number (factors, scales). + Number, + /// A length in drawing units. + Distance, + /// An angle in degrees. + Angle, + Bool, + /// One of `options`. + Choice, + Color, + Layer, + Linetype, + Lineweight, + Transparency, + TextStyle, + DimStyle, +} + +/// A transparency as `properties.set` takes it: "ByLayer", "ByBlock" or a percentage. +pub fn transparency_value(t: Transparency) -> Value { + match t { + Transparency::Percent(p) => json!(p), + other => json!(other.name()), + } +} + +/// The Properties of the objects `handles` (model space and layouts), limited to the objects +/// of type `filter` (a name from [`Description::types`]) when it names one. Handles that don't +/// name an object are left out. +pub fn describe(d: &Drawing, handles: &[Handle], filter: Option<&str>) -> Description { + let mut seen = HashSet::new(); + let all: Vec<&Entity> = handles.iter().filter(|h| seen.insert(**h)).filter_map(|h| d.entity(*h).map(|e| &**e)).collect(); + let mut types: Vec = Vec::new(); + for e in &all { + let name = e.kind.type_name(); + match types.iter_mut().find(|t| t.name == name) { + Some(t) => t.count += 1, + None => types.push(TypeCount { name, count: 1 }), + } + } + let filter = filter.and_then(|f| types.iter().find(|t| t.name.eq_ignore_ascii_case(f.trim())).map(|t| t.name)); + let ents: Vec<&Entity> = all.into_iter().filter(|e| filter.is_none_or(|f| e.kind.type_name() == f)).collect(); + let c = Ctx::new(d); + let mut groups = Vec::new(); + if !ents.is_empty() { + groups.push(general(&c, &ents)); + let texts: Vec<&Text> = ents.iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t) } else { None }).collect(); + let mtexts: Vec<&MText> = ents.iter().filter_map(|e| if let EntityKind::MText(t) = &e.kind { Some(t) } else { None }).collect(); + let dims: Vec<&Dimension> = ents.iter().filter_map(|e| if let EntityKind::Dimension(t) = &e.kind { Some(t) } else { None }).collect(); + // Type groups only when every described object is of that type (AutoCAD shows the + // common properties of a mixed selection). + if texts.len() == ents.len() { + groups.extend(text_groups(&c, &ents, &texts)); + } else if mtexts.len() == ents.len() { + groups.extend(mtext_groups(&c, &ents, &mtexts)); + } else if dims.len() == ents.len() { + groups.extend(dimension_groups(&c, &ents, &dims)); + } + } + Description { types, filter, count: ents.len(), groups } +} + +/// Unit settings and the drawing, for formatting rows. +struct Ctx<'a> { + d: &'a Drawing, + lunits: i64, + luprec: i64, + aunits: i64, + auprec: i64, +} + +impl<'a> Ctx<'a> { + fn new(d: &'a Drawing) -> Self { + let h = &d.header; + Ctx { d, lunits: h.i64("LUNITS", 2), luprec: h.i64("LUPREC", 4), aunits: h.i64("AUNITS", 0), auprec: h.i64("AUPREC", 0) } + } + + fn distance(&self, v: f64) -> String { + units::format_distance(v, self.lunits, self.luprec) + } + + /// `deg` in the drawing's angle units. + fn angle(&self, deg: f64) -> String { + units::format_angle(deg.to_radians(), self.aunits, self.auprec) + } + + fn show(&self, kind: Kind, v: &Value, options: &[Choice]) -> String { + match kind { + Kind::Distance => v.as_f64().map(|x| self.distance(x)).unwrap_or_default(), + Kind::Number => v.as_f64().map(|x| format!("{x:.4}")).unwrap_or_default(), + Kind::Angle => v.as_f64().map(|x| self.angle(x)).unwrap_or_default(), + Kind::Bool => (if v.as_bool() == Some(true) { "Yes" } else { "No" }).to_string(), + Kind::Choice => options.iter().find(|o| o.value == *v).map(|o| o.label.clone()).unwrap_or_else(|| plain(v)), + _ => plain(v), + } + } + + /// A row valued by `values` (one per described object). + fn row(&self, key: &'static str, label: &'static str, kind: Kind, values: impl IntoIterator) -> Row { + self.choice(key, label, kind, Vec::new(), values) + } + + /// A row with options (a choice, or a style picked from the drawing's styles). + fn choice(&self, key: &'static str, label: &'static str, kind: Kind, options: Vec, values: impl IntoIterator) -> Row { + let mut it = values.into_iter(); + let first = it.next().unwrap_or(Value::Null); + let varies = it.any(|v| v != first); + let (value, display) = if varies { (Value::Null, VARIES.to_string()) } else { (first.clone(), self.show(kind, &first, &options)) }; + Row { key, label, kind, value, varies, display, editable: true, note: None, overridden: false, options, quick: false } + } + + fn text_styles(&self) -> Vec { + self.d.text_styles.iter().map(|t| Choice::new(json!(t.name), t.name.clone())).collect() + } + + fn dim_styles(&self) -> Vec { + self.d.dim_styles.iter().map(|t| Choice::new(json!(t.name), t.name.clone())).collect() + } +} + +/// A value as plain text: strings as they are, numbers and booleans as JSON writes them. +fn plain(v: &Value) -> String { + match v { + Value::String(s) => s.clone(), + Value::Null => String::new(), + other => other.to_string(), + } +} + +fn general(c: &Ctx, ents: &[&Entity]) -> Group { + let rows = vec![ + c.row("color", "Color", Kind::Color, ents.iter().map(|e| json!(e.common.color.name()))), + c.row("layer", "Layer", Kind::Layer, ents.iter().map(|e| json!(e.common.layer))).quick(), + c.row("linetype", "Linetype", Kind::Linetype, ents.iter().map(|e| json!(e.common.linetype))), + c.row("ltscale", "Linetype scale", Kind::Number, ents.iter().map(|e| json!(e.common.ltscale))), + c.row("lineweight", "Lineweight", Kind::Lineweight, ents.iter().map(|e| json!(e.common.lineweight.name()))), + c.row("transparency", "Transparency", Kind::Transparency, ents.iter().map(|e| transparency_value(e.common.transparency))), + ]; + Group { name: "General", rows } +} + +fn annotative(c: &Ctx, ents: &[&Entity]) -> Row { + c.row("annotative", "Annotative", Kind::Bool, ents.iter().map(|e| json!(cadcraft_doc::is_annotative(e)))).quick() +} + +/// TEXT justifications as `properties.set` takes them, with their labels. +pub const TEXT_JUSTIFY: &[(&str, &str)] = &[ + ("Left", "Left"), + ("Center", "Center"), + ("Right", "Right"), + ("Align", "Aligned"), + ("Middle", "Middle"), + ("Fit", "Fit"), + ("TL", "Top left"), + ("TC", "Top center"), + ("TR", "Top right"), + ("ML", "Middle left"), + ("MC", "Middle center"), + ("MR", "Middle right"), + ("BL", "Bottom left"), + ("BC", "Bottom center"), + ("BR", "Bottom right"), +]; + +/// MTEXT attachments 1–9 as `properties.set` takes them, with their labels. +pub const MTEXT_JUSTIFY: &[(&str, &str)] = &[ + ("TL", "Top left"), + ("TC", "Top center"), + ("TR", "Top right"), + ("ML", "Middle left"), + ("MC", "Middle center"), + ("MR", "Middle right"), + ("BL", "Bottom left"), + ("BC", "Bottom center"), + ("BR", "Bottom right"), +]; + +fn options(list: &[(&str, &str)]) -> Vec { + list.iter().map(|(v, l)| Choice::new(json!(v), *l)).collect() +} + +/// The justification code of a TEXT (one of [`TEXT_JUSTIFY`]). +pub fn text_justify(t: &Text) -> &'static str { + match (t.halign, t.valign) { + (HAlign::Aligned, _) => "Align", + (HAlign::Fit, _) => "Fit", + (HAlign::Middle, _) => "Middle", + (HAlign::Left, VAlign::Baseline) => "Left", + (HAlign::Center, VAlign::Baseline) => "Center", + (HAlign::Right, VAlign::Baseline) => "Right", + (HAlign::Left, VAlign::Top) => "TL", + (HAlign::Center, VAlign::Top) => "TC", + (HAlign::Right, VAlign::Top) => "TR", + (HAlign::Left, VAlign::Middle) => "ML", + (HAlign::Center, VAlign::Middle) => "MC", + (HAlign::Right, VAlign::Middle) => "MR", + (HAlign::Left, VAlign::Bottom) => "BL", + (HAlign::Center, VAlign::Bottom) => "BC", + (HAlign::Right, VAlign::Bottom) => "BR", + } +} + +/// The justification code of an MTEXT attachment (1–9; anything else reads as top left). +pub fn mtext_justify(attach: u8) -> &'static str { + MTEXT_JUSTIFY.get(usize::from(attach.max(1)) - 1).map_or("TL", |(code, _)| *code) +} + +fn text_groups(c: &Ctx, ents: &[&Entity], texts: &[&Text]) -> Vec { + let mut text = vec![ + c.row("text", "Contents", Kind::Text, texts.iter().map(|t| json!(t.value))).quick(), + c.choice("style", "Style", Kind::TextStyle, c.text_styles(), texts.iter().map(|t| json!(t.style))).quick(), + annotative(c, ents), + c.choice("justify", "Justify", Kind::Choice, options(TEXT_JUSTIFY), texts.iter().map(|t| json!(text_justify(t)))).quick(), + c.row("height", "Height", Kind::Distance, texts.iter().map(|t| json!(t.height))).quick(), + c.row("rotation", "Rotation", Kind::Angle, texts.iter().map(|t| json!(t.rotation.to_degrees()))).quick(), + c.row("widthFactor", "Width factor", Kind::Number, texts.iter().map(|t| json!(t.width_factor))), + c.row("oblique", "Obliquing", Kind::Angle, texts.iter().map(|t| json!(t.oblique.to_degrees()))), + ]; + // Aligned and fit text sit between two points: the second is the text alignment point. + let second: Option> = + texts.iter().map(|t| if matches!(t.halign, HAlign::Aligned | HAlign::Fit) { t.align_pt } else { None }).collect(); + if let Some(pts) = second { + text.push(c.row("alignmentX", "Text alignment X", Kind::Distance, pts.iter().map(|p| json!(p.x)))); + text.push(c.row("alignmentY", "Text alignment Y", Kind::Distance, pts.iter().map(|p| json!(p.y)))); + } + // The position is the point the text is placed by (see `Text::justify_point`). + let geometry = vec![ + c.row("positionX", "Position X", Kind::Distance, texts.iter().map(|t| json!(t.justify_point().x))), + c.row("positionY", "Position Y", Kind::Distance, texts.iter().map(|t| json!(t.justify_point().y))), + c.row("positionZ", "Position Z", Kind::Distance, texts.iter().map(|t| json!(t.insert.z))), + ]; + vec![Group { name: "Text", rows: text }, Group { name: "Geometry", rows: geometry }] +} + +fn mtext_groups(c: &Ctx, ents: &[&Entity], mts: &[&MText]) -> Vec { + let spacing = vec![Choice::new(json!("atLeast"), "At least"), Choice::new(json!("exactly"), "Exactly")]; + let columns = |t: &MText| match &t.columns { + None => "None".to_string(), + Some(col) => match col.kind { + cadcraft_doc::MTextColumnType::Static => format!("Static ({})", col.count.max(1)), + cadcraft_doc::MTextColumnType::Dynamic => "Dynamic".to_string(), + }, + }; + let text = vec![ + c.row("text", "Contents", Kind::Contents, mts.iter().map(|t| json!(t.contents))).quick(), + c.choice("style", "Style", Kind::TextStyle, c.text_styles(), mts.iter().map(|t| json!(t.style))).quick(), + annotative(c, ents), + c.choice("justify", "Justify", Kind::Choice, options(MTEXT_JUSTIFY), mts.iter().map(|t| json!(mtext_justify(t.attach)))).quick(), + c.row("height", "Text height", Kind::Distance, mts.iter().map(|t| json!(t.height))).quick(), + c.row("rotation", "Rotation", Kind::Angle, mts.iter().map(|t| json!(t.rotation.to_degrees()))).quick(), + c.row("lineSpacing", "Line space factor", Kind::Number, mts.iter().map(|t| json!(t.line_spacing))), + c.row("lineSpacingDistance", "Line space distance", Kind::Distance, mts.iter().map(|t| json!(t.line_spacing * t.height * LINE_PITCH))), + c.choice( + "lineSpacingStyle", + "Line space style", + Kind::Choice, + spacing, + mts.iter().map(|t| json!(if t.line_spacing_exact { "exactly" } else { "atLeast" })), + ), + c.row("width", "Defined width", Kind::Distance, mts.iter().map(|t| json!(t.width))), + c.row("columns", "Columns", Kind::Text, mts.iter().map(|t| json!(columns(t)))).read_only(), + ]; + let geometry = vec![ + c.row("positionX", "Position X", Kind::Distance, mts.iter().map(|t| json!(t.insert.x))), + c.row("positionY", "Position Y", Kind::Distance, mts.iter().map(|t| json!(t.insert.y))), + c.row("positionZ", "Position Z", Kind::Distance, mts.iter().map(|t| json!(t.insert.z))), + ]; + vec![Group { name: "Text", rows: text }, Group { name: "Geometry", rows: geometry }] +} + +/// How a dimension style variable is entered. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DimPropKind { + Distance, + Number, + /// Degrees. + Angle, + Bool, + /// Numbers with labels. + Choice(&'static [(i64, &'static str)]), + /// Decimal places 0–8. + Precision, + Color, + TextStyle, + /// A linetype name; "" (and "ByBlock") is ByBlock. + Linetype, + /// Hundredths of a millimetre, or -1 ByLayer, -2 ByBlock, -3 Default. + Lineweight, + /// An arrowhead name ("" is closed filled). + Arrow, + /// The decimal separator. + Separator, +} + +/// A dimension style variable as a Properties row. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DimProp { + /// The [`DimStyle`] field (camelCase), which is also the `properties.set` key. + pub field: &'static str, + pub group: &'static str, + pub label: &'static str, + pub kind: DimPropKind, + /// Shown in the Properties palette (the rest belong to the style dialog only). + pub palette: bool, +} + +const fn prop(field: &'static str, group: &'static str, label: &'static str, kind: DimPropKind) -> DimProp { + DimProp { field, group, label, kind, palette: true } +} + +const fn style_only(field: &'static str, group: &'static str, label: &'static str, kind: DimPropKind) -> DimProp { + DimProp { field, group, label, kind, palette: false } +} + +/// The groups dimension rows come in, in order (after Misc). +pub const DIM_GROUPS: &[&str] = &["Lines & Arrows", "Text", "Fit", "Primary Units", "Alternate Units", "Tolerances"]; + +const TEXT_POS_HOR: &[(i64, &str)] = &[(0, "Centered"), (1, "At Ext Line 1"), (2, "At Ext Line 2"), (3, "Over Ext Line 1"), (4, "Over Ext Line 2")]; +const TEXT_POS_VERT: &[(i64, &str)] = &[(0, "Centered"), (1, "Above"), (2, "Outside"), (3, "JIS"), (4, "Below")]; +const FIT: &[(i64, &str)] = &[(0, "Text and arrows"), (1, "Arrows"), (2, "Text"), (3, "Best fit")]; +const TEXT_MOVE: &[(i64, &str)] = &[(0, "Keep dim line with text"), (1, "Move text, add leader"), (2, "Move text, no leader")]; +const LINEAR_UNITS: &[(i64, &str)] = + &[(1, "Scientific"), (2, "Decimal"), (3, "Engineering"), (4, "Architectural"), (5, "Fractional"), (6, "Windows desktop")]; +const ALT_UNITS: &[(i64, &str)] = &[ + (1, "Scientific"), + (2, "Decimal"), + (3, "Engineering"), + (4, "Architectural stacked"), + (5, "Fractional stacked"), + (6, "Architectural"), + (7, "Fractional"), + (8, "Windows desktop"), +]; +const ANGLE_FORMAT: &[(i64, &str)] = &[(0, "Decimal degrees"), (1, "Degrees Minutes Seconds"), (2, "Gradians"), (3, "Radians")]; +const FRACTION_FORMAT: &[(i64, &str)] = &[(0, "Horizontal"), (1, "Diagonal"), (2, "Not stacked")]; +const TOL_POS: &[(i64, &str)] = &[(0, "Bottom"), (1, "Middle"), (2, "Top")]; +const ARC_SYMBOL: &[(i64, &str)] = &[(0, "Before text"), (1, "Above text"), (2, "None")]; + +/// Every modeled dimension style variable as a row, grouped as AutoCAD's Properties palette +/// groups dimension properties. The rows not shown in the palette are style settings only. +pub const DIM_PROPS: &[DimProp] = &[ + // Lines & Arrows + prop("arrowBlock1", "Lines & Arrows", "Arrow 1", DimPropKind::Arrow), + prop("arrowBlock2", "Lines & Arrows", "Arrow 2", DimPropKind::Arrow), + style_only("arrowBlock", "Lines & Arrows", "Arrowheads", DimPropKind::Arrow), + prop("arrowSize", "Lines & Arrows", "Arrow size", DimPropKind::Distance), + prop("tickSize", "Lines & Arrows", "Tick size", DimPropKind::Distance), + prop("dimLineColor", "Lines & Arrows", "Dim line color", DimPropKind::Color), + prop("dimLinetype", "Lines & Arrows", "Dim line linetype", DimPropKind::Linetype), + prop("dimLineweight", "Lines & Arrows", "Dim line lineweight", DimPropKind::Lineweight), + prop("dimLineExtend", "Lines & Arrows", "Dim line ext", DimPropKind::Distance), + prop("suppressDim1", "Lines & Arrows", "Suppress dim line 1", DimPropKind::Bool), + prop("suppressDim2", "Lines & Arrows", "Suppress dim line 2", DimPropKind::Bool), + prop("extLineColor", "Lines & Arrows", "Ext line color", DimPropKind::Color), + prop("extLinetype1", "Lines & Arrows", "Ext line 1 linetype", DimPropKind::Linetype), + prop("extLinetype2", "Lines & Arrows", "Ext line 2 linetype", DimPropKind::Linetype), + prop("extLineweight", "Lines & Arrows", "Ext line lineweight", DimPropKind::Lineweight), + prop("extExtend", "Lines & Arrows", "Ext line ext", DimPropKind::Distance), + prop("extOffset", "Lines & Arrows", "Ext line offset", DimPropKind::Distance), + prop("fixedExt", "Lines & Arrows", "Ext line fixed", DimPropKind::Bool), + prop("fixedExtLength", "Lines & Arrows", "Ext line fixed length", DimPropKind::Distance), + prop("suppressExt1", "Lines & Arrows", "Suppress ext line 1", DimPropKind::Bool), + prop("suppressExt2", "Lines & Arrows", "Suppress ext line 2", DimPropKind::Bool), + prop("centerMark", "Lines & Arrows", "Center mark size", DimPropKind::Distance), + prop("jogAngle", "Lines & Arrows", "Jog angle", DimPropKind::Angle), + prop("arcSymbol", "Lines & Arrows", "Arc length symbol", DimPropKind::Choice(ARC_SYMBOL)), + style_only("leaderArrowBlock", "Lines & Arrows", "Leader arrow", DimPropKind::Arrow), + style_only("baselineSpacing", "Lines & Arrows", "Baseline spacing", DimPropKind::Distance), + // Text + prop("textColor", "Text", "Text color", DimPropKind::Color), + prop("textHeight", "Text", "Text height", DimPropKind::Distance), + prop("textGap", "Text", "Text offset", DimPropKind::Distance), + prop("textOutsideHorizontal", "Text", "Text outside align", DimPropKind::Bool), + prop("textJust", "Text", "Text pos hor", DimPropKind::Choice(TEXT_POS_HOR)), + prop("textAbove", "Text", "Text pos vert", DimPropKind::Choice(TEXT_POS_VERT)), + prop("textStyle", "Text", "Text style", DimPropKind::TextStyle), + prop("textInsideHorizontal", "Text", "Text inside align", DimPropKind::Bool), + style_only("textVerticalPos", "Text", "Text vertical position", DimPropKind::Number), + // Fit + prop("forceLineInside", "Fit", "Dim line forced", DimPropKind::Bool), + prop("suppressOutsideArrows", "Fit", "Suppress arrows outside", DimPropKind::Bool), + prop("scale", "Fit", "Dim scale overall", DimPropKind::Number), + prop("fit", "Fit", "Fit", DimPropKind::Choice(FIT)), + prop("textInside", "Fit", "Text inside", DimPropKind::Bool), + prop("textMove", "Fit", "Text movement", DimPropKind::Choice(TEXT_MOVE)), + // Primary Units + prop("decimalSeparator", "Primary Units", "Decimal separator", DimPropKind::Separator), + prop("round", "Primary Units", "Dim roundoff", DimPropKind::Distance), + prop("linearFactor", "Primary Units", "Dim scale linear", DimPropKind::Number), + prop("linearUnit", "Primary Units", "Dim units", DimPropKind::Choice(LINEAR_UNITS)), + prop("decimals", "Primary Units", "Precision", DimPropKind::Precision), + prop("fractionFormat", "Primary Units", "Fraction format", DimPropKind::Choice(FRACTION_FORMAT)), + prop("angularUnit", "Primary Units", "Angle format", DimPropKind::Choice(ANGLE_FORMAT)), + prop("angularDecimals", "Primary Units", "Angle precision", DimPropKind::Precision), + style_only("post", "Primary Units", "Prefix and suffix", DimPropKind::Number), + style_only("zeroSuppression", "Primary Units", "Zero suppression", DimPropKind::Number), + style_only("angularZeroSuppression", "Primary Units", "Angular zero suppression", DimPropKind::Number), + // Alternate Units + prop("alt", "Alternate Units", "Alt enabled", DimPropKind::Bool), + prop("altUnit", "Alternate Units", "Alt format", DimPropKind::Choice(ALT_UNITS)), + prop("altDecimals", "Alternate Units", "Alt precision", DimPropKind::Precision), + prop("altFactor", "Alternate Units", "Alt scale factor", DimPropKind::Number), + prop("altRound", "Alternate Units", "Alt round", DimPropKind::Number), + style_only("altPost", "Alternate Units", "Alt prefix and suffix", DimPropKind::Number), + style_only("altZeroSuppression", "Alternate Units", "Alt zero suppression", DimPropKind::Number), + // Tolerances + prop("tolerance", "Tolerances", "Tolerances", DimPropKind::Bool), + prop("limits", "Tolerances", "Limits", DimPropKind::Bool), + prop("tolPlus", "Tolerances", "Tolerance limit upper", DimPropKind::Number), + prop("tolMinus", "Tolerances", "Tolerance limit lower", DimPropKind::Number), + prop("tolDecimals", "Tolerances", "Tolerance precision", DimPropKind::Precision), + prop("tolScale", "Tolerances", "Tolerance text height", DimPropKind::Number), + prop("tolJust", "Tolerances", "Tolerance pos vert", DimPropKind::Choice(TOL_POS)), + style_only("tolZeroSuppression", "Tolerances", "Tolerance zero suppression", DimPropKind::Number), +]; + +/// The arrowheads drawn in code, by the DIMBLK name stored for them and their label. +pub const ARROWHEADS: &[(&str, &str)] = &[ + ("", "Closed filled"), + ("_CLOSEDBLANK", "Closed blank"), + ("_CLOSED", "Closed"), + ("_DOT", "Dot"), + ("_ARCHTICK", "Architectural tick"), + ("_OBLIQUE", "Oblique"), + ("_OPEN", "Open"), + ("_ORIGIN", "Origin indicator"), + ("_ORIGIN2", "Origin indicator 2"), + ("_OPEN90", "Right angle"), + ("_OPEN30", "Open 30"), + ("_DOTSMALL", "Dot small"), + ("_DOTBLANK", "Dot blank"), + ("_SMALL", "Small"), + ("_BOXBLANK", "Box blank"), + ("_BOXFILLED", "Box filled"), + ("_DATUMBLANK", "Datum triangle"), + ("_DATUMFILLED", "Datum triangle filled"), + ("_INTEGRAL", "Integral"), + ("_NONE", "None"), +]; + +/// The row for dimension style field `field`, if it has one. +pub fn dim_prop(field: &str) -> Option<&'static DimProp> { + DIM_PROPS.iter().find(|p| p.field.eq_ignore_ascii_case(field)) +} + +/// The dimension style fields whose value is a linetype name ("" is ByBlock). +pub fn is_dim_linetype(field: &str) -> bool { + matches!(field, "dimLinetype" | "extLinetype1" | "extLinetype2") +} + +impl DimPropKind { + fn row_kind(self, c: &Ctx) -> (Kind, Vec) { + match self { + DimPropKind::Distance => (Kind::Distance, Vec::new()), + DimPropKind::Number => (Kind::Number, Vec::new()), + DimPropKind::Angle => (Kind::Angle, Vec::new()), + DimPropKind::Bool => (Kind::Bool, Vec::new()), + DimPropKind::Choice(list) => (Kind::Choice, list.iter().map(|(v, l)| Choice::new(json!(v), *l)).collect()), + DimPropKind::Precision => ( + Kind::Choice, + (0..=8u8).map(|n| Choice::new(json!(n), if n == 0 { "0".into() } else { format!("0.{}", "0".repeat(usize::from(n))) })).collect(), + ), + DimPropKind::Color => (Kind::Color, Vec::new()), + DimPropKind::TextStyle => (Kind::TextStyle, c.text_styles()), + DimPropKind::Linetype => (Kind::Linetype, Vec::new()), + DimPropKind::Lineweight => { + let mut o = vec![Choice::new(json!(-2), "ByBlock"), Choice::new(json!(-1), "ByLayer"), Choice::new(json!(-3), "Default")]; + o.extend(Lineweight::STANDARD.iter().map(|w| Choice::new(json!(w), Lineweight::Mm100(*w).name()))); + (Kind::Choice, o) + } + DimPropKind::Arrow => (Kind::Choice, ARROWHEADS.iter().map(|(v, l)| Choice::new(json!(v), *l)).collect()), + DimPropKind::Separator => { + (Kind::Choice, [(".", "Period"), (",", "Comma"), (" ", "Space")].iter().map(|(v, l)| Choice::new(json!(v), *l)).collect()) + } + } + } +} + +/// `name` normalized as the renderer reads arrowhead names ("_DOT", "dot" and "Dot" alike). +fn arrow_key(name: &str) -> String { + name.trim().trim_start_matches('_').chars().filter(char::is_ascii_alphanumeric).collect::().to_ascii_lowercase() +} + +/// A dimension style field's value as the row shows and `properties.set` takes it. +fn dim_value(p: &DimProp, st: &Value) -> Value { + let v = st.get(p.field).cloned().unwrap_or(Value::Null); + match p.kind { + DimPropKind::Color => serde_json::from_value::(v).map(|c| json!(c.name())).unwrap_or(Value::Null), + DimPropKind::Linetype => match v.as_str() { + Some("") | None => json!("ByBlock"), + Some(_) => v, + }, + DimPropKind::Arrow => { + // Per-end arrowheads left empty use DIMBLK. + let name = v.as_str().filter(|s| !s.is_empty() || p.field == "arrowBlock").map(str::to_string); + let name = name.unwrap_or_else(|| st.get("arrowBlock").and_then(Value::as_str).unwrap_or_default().to_string()); + // A drawn arrowhead reads as its standard name; a block of the user's stays as it is. + match ARROWHEADS.iter().find(|(n, _)| arrow_key(n) == arrow_key(&name) || (n.is_empty() && arrow_key(&name) == "closedfilled")) { + Some((n, _)) => json!(n), + None => json!(name), + } + } + _ => v, + } +} + +/// Whether dimension `dm` overrides style field `field`. +fn overrides(dm: &Dimension, field: &str) -> bool { + dm.overrides.keys().any(|k| DimStyle::field_name(k) == Some(field)) +} + +/// The prefix and suffix of a DIMPOST/DIMAPOST template: around `<>`, or the whole template +/// as a suffix when it has no `<>` (as the renderer reads it). +pub fn split_post(template: &str) -> (String, String) { + match template.split_once("<>") { + Some((pre, post)) => (pre.to_string(), post.to_string()), + None => (String::new(), template.to_string()), + } +} + +/// A DIMPOST/DIMAPOST template from a prefix and a suffix. +pub fn join_post(prefix: &str, suffix: &str) -> String { + if prefix.is_empty() { suffix.to_string() } else { format!("{prefix}<>{suffix}") } +} + +/// The measurement as the dimension writes it (its own units and precision). +fn measurement_text(dm: &Dimension, st: &DimStyle, meas: f64) -> String { + match dm.kind { + DimKind::Angular | DimKind::Angular3P => format!("{:.*}°", usize::from(st.angular_decimals.min(8)), meas.to_degrees()), + _ => cadcraft_render::format_linear_value(meas, st), + } +} + +fn dimension_groups(c: &Ctx, ents: &[&Entity], dims: &[&Dimension]) -> Vec { + let styles: Vec = dims.iter().map(|dm| c.d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides)).collect(); + let values: Vec = styles.iter().map(|st| serde_json::to_value(st).unwrap_or(Value::Null)).collect(); + // Measurement and text position need each dimension's geometry. + let geometry: Option> = + (dims.len() <= GEOMETRY_CAP).then(|| dims.iter().map(|dm| cadcraft_render::dimension_in(c.d, dm)).collect()); + let mut groups = vec![Group { + name: "Misc", + rows: vec![ + c.choice("dimStyle", "Dim style", Kind::DimStyle, c.dim_styles(), dims.iter().map(|dm| json!(dm.style))).quick(), + annotative(c, ents), + ], + }]; + for &name in DIM_GROUPS { + let mut rows: Vec = Vec::new(); + for p in DIM_PROPS.iter().filter(|p| p.group == name && p.palette) { + let (kind, options) = p.kind.row_kind(c); + let mut r = c.choice(p.field, p.label, kind, options, values.iter().map(|v| dim_value(p, v))); + r.overridden = dims.iter().any(|dm| overrides(dm, p.field)); + if p.field == "textHeight" { + fixed_height(c, &mut r, &styles); + } + rows.push(r); + } + match name { + "Text" => { + let (xs, ys): (Vec, Vec) = match &geometry { + Some(g) => g.iter().map(|g| (json!(g.text_pos.x), json!(g.text_pos.y))).unzip(), + None => (vec![Value::Null, json!(VARIES)], vec![Value::Null, json!(VARIES)]), + }; + rows.push(c.row("textPositionX", "Text position X", Kind::Distance, xs)); + rows.push(c.row("textPositionY", "Text position Y", Kind::Distance, ys)); + rows.push(c.row("textRotation", "Text rotation", Kind::Angle, dims.iter().map(|dm| json!(dm.text_rotation.to_degrees())))); + let measured: Vec<(Value, String)> = match &geometry { + Some(g) => g + .iter() + .zip(dims) + .zip(&styles) + .map(|((g, dm), st)| { + let angular = matches!(dm.kind, DimKind::Angular | DimKind::Angular3P); + (json!(if angular { g.measurement.to_degrees() } else { g.measurement }), measurement_text(dm, st, g.measurement)) + }) + .collect(), + None => vec![(Value::Null, String::new()), (json!(VARIES), String::new())], + }; + // A length, or an angle in degrees, shown as the dimension writes it. + let mut m = c.row("measurement", "Measurement", Kind::Number, measured.iter().map(|(v, _)| v.clone())).read_only().quick(); + if !m.varies { + m.display = measured.first().map(|(_, s)| s.clone()).unwrap_or_default(); + } + rows.push(m); + rows.push(c.row("textOverride", "Text override", Kind::Text, dims.iter().map(|dm| json!(dm.text))).quick()); + } + "Primary Units" => { + let (pre, suf): (Vec, Vec) = styles.iter().map(|st| split_post(&st.post)).map(|(p, s)| (json!(p), json!(s))).unzip(); + let at = rows.iter().position(|r| r.key == "round").unwrap_or(rows.len()); + rows.insert(at, c.row("prefix", "Dim prefix", Kind::Text, pre)); + let at = rows.iter().position(|r| r.key == "linearUnit").unwrap_or(rows.len()); + rows.insert(at, c.row("suffix", "Dim suffix", Kind::Text, suf)); + } + "Alternate Units" => { + let (pre, suf): (Vec, Vec) = + styles.iter().map(|st| split_post(&st.alt_post)).map(|(p, s)| (json!(p), json!(s))).unzip(); + rows.push(c.row("altPrefix", "Alt prefix", Kind::Text, pre)); + rows.push(c.row("altSuffix", "Alt suffix", Kind::Text, suf)); + } + _ => {} + } + groups.push(Group { name, rows }); + } + groups +} + +/// A fixed-height text style decides the dimension text height whatever DIMTXT says (as in +/// AutoCAD); the row says so instead of taking edits that change nothing. +fn fixed_height(c: &Ctx, r: &mut Row, styles: &[DimStyle]) { + let fixed: Vec> = styles + .iter() + .map(|st| c.d.text_style(&st.text_style).filter(|ts| ts.height > 0.0 && ts.height.is_finite()).map(|ts| (ts.name.as_str(), ts.height))) + .collect(); + let Some(&Some((name, h))) = fixed.iter().find(|f| f.is_some()) else { return }; + if fixed.iter().all(|f| *f == Some((name, h))) { + r.value = json!(h); + r.varies = false; + r.display = c.distance(h); + r.editable = false; + r.note = + Some(format!("Set by text style \"{name}\", which has a fixed height. Give the style a height of 0 to use the dimension text height.")); + } else { + r.editable = fixed.iter().any(Option::is_none); + r.note = Some("Some of these dimensions take their text height from a fixed-height text style.".into()); + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 3a1537bee..277a54710 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -112,6 +112,8 @@ mod polyface_explode; mod post_command_passes; mod prompt_keywords; mod prompt_or_once; +mod properties_describe; +mod properties_set_text_dims; mod props_bad_lineweight; mod props_insert_scale_attribs; mod purge_mlinestyles; diff --git a/crates/engine/tests/it/properties_describe.rs b/crates/engine/tests/it/properties_describe.rs new file mode 100644 index 000000000..2189c0342 --- /dev/null +++ b/crates/engine/tests/it/properties_describe.rs @@ -0,0 +1,155 @@ +//! `properties.describe`: the Properties palette's rows for text, mtext and dimensions, with +//! shared values, *VARIES*, units, and the reason a dimension's text height can't be edited. + +use cadcraft_engine::Session; +use serde_json::{Value, json}; + +fn handle(r: &Value) -> String { + r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string() +} + +fn last(s: &Session) -> String { + s.doc().unwrap().model.last().unwrap().handle.hex() +} + +fn describe(s: &mut Session, p: Value) -> Value { + s.execute("properties.describe", &p).unwrap() +} + +/// The row `key` in group `group`. +fn row<'a>(desc: &'a Value, group: &str, key: &str) -> &'a Value { + let g = desc["groups"].as_array().unwrap().iter().find(|g| g["name"] == group).unwrap_or_else(|| panic!("no group {group}: {desc}")); + g["rows"].as_array().unwrap().iter().find(|r| r["key"] == key).unwrap_or_else(|| panic!("no row {key} in {group}: {g}")) +} + +fn group_names(desc: &Value) -> Vec { + desc["groups"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap().to_string()).collect() +} + +#[test] +fn text_rows_share_values_and_vary() { + let mut s = Session::new(); + let a = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "A", "height": 2.5 })).unwrap()); + let b = handle(&s.execute("text", &json!({ "at": [0, 5], "text": "B", "height": 1, "justify": "MC" })).unwrap()); + let one = describe(&mut s, json!({ "handles": [a] })); + assert_eq!(group_names(&one), ["General", "Text", "Geometry"]); + let h = row(&one, "Text", "height"); + assert_eq!((h["value"].as_f64(), h["display"].as_str(), h["kind"].as_str()), (Some(2.5), Some("2.5000"), Some("distance"))); + assert_eq!(row(&one, "Text", "justify")["display"], "Left"); + assert_eq!(row(&one, "Text", "style")["value"], "Standard"); + assert!(row(&one, "Text", "style")["options"].as_array().unwrap().iter().any(|o| o["value"] == "Standard")); + assert_eq!(row(&one, "Text", "text")["value"], "A"); + + let both = describe(&mut s, json!({ "handles": [a, b] })); + assert_eq!(both["count"], 2); + let h = row(&both, "Text", "height"); + assert_eq!((h["varies"].as_bool(), h["display"].as_str(), h["value"].is_null()), (Some(true), Some("*VARIES*"), true)); + // Both are rotated 0 and in the same style. + assert_eq!(row(&both, "Text", "rotation")["varies"], false); + assert_eq!(row(&both, "Text", "style")["display"], "Standard"); + assert_eq!(row(&both, "Text", "justify")["varies"], true); +} + +#[test] +fn mixed_selections_show_general_rows_unless_filtered() { + let mut s = Session::new(); + let t = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "A", "height": 1 })).unwrap()); + s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap(); + let c = last(&s); + let mixed = describe(&mut s, json!({ "handles": [t, c] })); + assert_eq!(group_names(&mixed), ["General"]); + assert_eq!(mixed["types"], json!([{ "type": "Text", "count": 1 }, { "type": "Circle", "count": 1 }])); + assert_eq!(row(&mixed, "General", "layer")["value"], "0"); + let texts = describe(&mut s, json!({ "handles": [t, c], "type": "text" })); + assert_eq!((texts["filter"].as_str(), texts["count"].as_u64()), (Some("Text"), Some(1))); + assert_eq!(group_names(&texts), ["General", "Text", "Geometry"]); + // An unknown filter describes everything. + assert_eq!(describe(&mut s, json!({ "handles": [t, c], "type": "nope" }))["count"], 2); + // Nothing selected, or handles that name nothing: no rows. + assert_eq!(describe(&mut s, json!({ "handles": [] }))["groups"], json!([])); + assert_eq!(describe(&mut s, json!({ "handles": ["FFFFFF"] }))["count"], 0); +} + +#[test] +fn mtext_rows() { + let mut s = Session::new(); + let r = s.execute("mtext", &json!({ "at": [0, 0], "text": "one\\Ptwo", "height": 3, "width": 40, "justify": "MC", "lineSpacing": 1.5 })).unwrap(); + let m = handle(&r); + let d = describe(&mut s, json!({ "handles": [m] })); + assert_eq!(group_names(&d), ["General", "Text", "Geometry"]); + assert_eq!(row(&d, "Text", "justify")["value"], "MC"); + assert_eq!(row(&d, "Text", "justify")["display"], "Middle center"); + assert_eq!(row(&d, "Text", "text")["kind"], "contents"); + assert_eq!(row(&d, "Text", "lineSpacing")["value"], 1.5); + // Line space distance: factor × height × 5/3. + let dist = row(&d, "Text", "lineSpacingDistance")["value"].as_f64().unwrap(); + assert!((dist - 1.5 * 3.0 * 5.0 / 3.0).abs() < 1e-9, "{dist}"); + assert_eq!(row(&d, "Text", "lineSpacingStyle")["value"], "atLeast"); + assert_eq!(row(&d, "Text", "width")["value"], 40.0); + let cols = row(&d, "Text", "columns"); + assert_eq!((cols["display"].as_str(), cols["editable"].as_bool()), (Some("None"), Some(false))); +} + +#[test] +fn dimension_rows_come_from_the_style_and_its_overrides() { + let mut s = Session::new(); + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + let dm = last(&s); + let d = describe(&mut s, json!({ "handles": [dm] })); + assert_eq!(group_names(&d), ["General", "Misc", "Lines & Arrows", "Text", "Fit", "Primary Units", "Alternate Units", "Tolerances"]); + let th = row(&d, "Text", "textHeight"); + assert_eq!((th["value"].as_f64(), th["editable"].as_bool(), th.get("overridden")), (Some(0.18), Some(true), None)); + assert_eq!(row(&d, "Misc", "dimStyle")["value"], "Standard"); + assert_eq!(row(&d, "Text", "textAbove")["display"], "Centered"); + assert_eq!(row(&d, "Primary Units", "decimals")["display"], "0.0000"); + assert_eq!(row(&d, "Lines & Arrows", "arrowBlock1")["display"], "Closed filled"); + assert_eq!(row(&d, "Lines & Arrows", "dimLineColor")["value"], "ByBlock"); + let m = row(&d, "Text", "measurement"); + assert_eq!((m["editable"].as_bool(), m["display"].as_str()), (Some(false), Some("10.0000"))); + assert_eq!(row(&d, "Text", "textOverride")["value"], ""); + + // A Properties edit is an override of this dimension; the row says so. + let r = s.execute("properties.set", &json!({ "handles": [dm], "textHeight": 0.3 })).unwrap(); + assert_eq!(r["ignored"], json!([])); + let d = describe(&mut s, json!({ "handles": [dm] })); + let th = row(&d, "Text", "textHeight"); + assert_eq!((th["value"].as_f64(), th["overridden"].as_bool()), (Some(0.3), Some(true))); + // The style itself is unchanged. + let st = s.execute("dimstyle.list", &json!({ "name": "Standard" })).unwrap(); + assert_eq!(st["variables"]["DIMTXT"], 0.18); +} + +#[test] +fn a_fixed_height_text_style_decides_dimension_text_height() { + let mut s = Session::new(); + s.execute("style", &json!({ "name": "Fixed", "height": 0.5, "current": false })).unwrap(); + s.execute("dimstyle", &json!({ "name": "FixedDims", "textStyle": "Fixed" })).unwrap(); + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + let dm = last(&s); + let d = describe(&mut s, json!({ "handles": [dm] })); + let th = row(&d, "Text", "textHeight"); + assert_eq!((th["editable"].as_bool(), th["display"].as_str()), (Some(false), Some("0.5000"))); + assert!(th["note"].as_str().unwrap().contains("Fixed"), "{th}"); +} + +#[test] +fn rows_show_lengths_in_the_drawing_units() { + let mut s = Session::new(); + s.execute("setvar", &json!({ "name": "LUNITS", "value": 4 })).unwrap(); + let t = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "A", "height": 18 })).unwrap()); + let d = describe(&mut s, json!({ "handles": [t] })); + assert_eq!(row(&d, "Text", "height")["display"], "1'-6\""); + assert_eq!(row(&d, "Text", "height")["value"], 18.0); +} + +#[test] +fn hostile_requests_never_panic() { + let mut s = Session::new(); + let t = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "A", "height": 1 })).unwrap()); + for p in [json!({}), json!({ "handles": "x" }), json!({ "handles": [t, t, t] }), json!({ "handles": [t], "type": 5 }), json!({ "type": "Text" })] + { + let _ = s.execute("properties.describe", &p); + } + // Duplicates count once. + assert_eq!(describe(&mut s, json!({ "handles": [t, t] }))["count"], 1); +} diff --git a/crates/engine/tests/it/properties_set_text_dims.rs b/crates/engine/tests/it/properties_set_text_dims.rs new file mode 100644 index 000000000..609dea2a6 --- /dev/null +++ b/crates/engine/tests/it/properties_set_text_dims.rs @@ -0,0 +1,247 @@ +//! `properties.set` for text, mtext and dimensions: the edits the Properties palette makes, keys +//! nobody took coming back as `ignored`, and style edits reaching dimensions read from files. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{EntityKind, HAlign, Handle, MText, Text}; +use serde_json::{Value, json}; + +fn handle(r: &Value) -> String { + r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string() +} + +fn last(s: &Session) -> String { + s.doc().unwrap().model.last().unwrap().handle.hex() +} + +fn set(s: &mut Session, h: &str, p: Value) -> Value { + let mut p = p; + p["handles"] = json!([h]); + s.execute("properties.set", &p).unwrap() +} + +fn text(s: &Session, h: &str) -> Text { + match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind { + EntityKind::Text(t) => t.clone(), + k => panic!("not text: {k:?}"), + } +} + +fn mtext(s: &Session, h: &str) -> MText { + match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind { + EntityKind::MText(t) => t.clone(), + k => panic!("not mtext: {k:?}"), + } +} + +fn dim(s: &Session, h: &str) -> cadcraft_engine::doc::Dimension { + match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind { + EntityKind::Dimension(d) => d.clone(), + k => panic!("not a dimension: {k:?}"), + } +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn text_style_justify_oblique_and_position() { + let mut s = Session::new(); + s.execute("style", &json!({ "name": "Notes", "current": false })).unwrap(); + let t = handle(&s.execute("text", &json!({ "at": [5, 5], "text": "Hello", "height": 2 })).unwrap()); + let r = set(&mut s, &t, json!({ "style": "notes", "oblique": 15, "bogus": 1 })); + assert_eq!(r["ignored"], json!(["bogus"])); + assert_eq!(text(&s, &t).style, "Notes"); + assert!(near(text(&s, &t).oblique.to_degrees(), 15.0)); + // A style that doesn't exist is refused; an oblique past 85 degrees is ignored. + assert!(s.execute("properties.set", &json!({ "handles": [t], "style": "Nope" })).is_err()); + assert_eq!(set(&mut s, &t, json!({ "oblique": 90 }))["ignored"], json!(["oblique"])); + + // Justify keeps the point the text is placed by: the text moves around it. + set(&mut s, &t, json!({ "justify": "MC" })); + let j = text(&s, &t); + assert_eq!((j.halign, j.justify_point().x, j.justify_point().y), (HAlign::Center, 5.0, 5.0)); + // Position X moves the text along X only. + set(&mut s, &t, json!({ "positionX": 20 })); + let j = text(&s, &t); + assert_eq!((j.justify_point().x, j.justify_point().y), (20.0, 5.0)); + // Fit puts the second point at the end of the text, along its rotation. + set(&mut s, &t, json!({ "justify": "Fit" })); + let f = text(&s, &t); + let end = f.align_pt.unwrap(); + assert!(f.halign == HAlign::Fit && near(f.insert.x, 20.0) && end.x > 20.0 && near(end.y, 5.0), "{f:?}"); + // The second point alone (the text refits between them). + set(&mut s, &t, json!({ "alignmentX": 40 })); + assert!(near(text(&s, &t).align_pt.unwrap().x, 40.0) && near(text(&s, &t).insert.x, 20.0)); + // Back to left: one point, where the fit text started. + set(&mut s, &t, json!({ "justify": "Left" })); + let l = text(&s, &t); + assert!(l.align_pt.is_none() && near(l.insert.x, 20.0)); + // Alignment points belong to aligned and fit text only. + assert_eq!(set(&mut s, &t, json!({ "alignmentX": 1 }))["ignored"], json!(["alignmentX"])); +} + +#[test] +fn mtext_style_justify_and_line_spacing() { + let mut s = Session::new(); + s.execute("style", &json!({ "name": "Notes", "current": false })).unwrap(); + let m = handle(&s.execute("mtext", &json!({ "at": [0, 10], "text": "one\\Ptwo", "height": 3, "width": 40 })).unwrap()); + set(&mut s, &m, json!({ "style": "Notes", "justify": "MC", "lineSpacing": 2, "lineSpacingStyle": "Exactly" })); + let t = mtext(&s, &m); + assert_eq!((t.style.as_str(), t.attach, t.line_spacing, t.line_spacing_exact), ("Notes", 5, 2.0, true)); + // The attachment point stays put. + assert!(near(t.insert.x, 0.0) && near(t.insert.y, 10.0)); + // MTEXT's factors run from 0.25 to 4. + assert_eq!(set(&mut s, &m, json!({ "lineSpacing": 10 }))["ignored"], json!(["lineSpacing"])); + // A distance between lines sets the factor: factor × height × 5/3. + set(&mut s, &m, json!({ "lineSpacingDistance": 7.5 })); + assert!(near(mtext(&s, &m).line_spacing, 1.5)); + set(&mut s, &m, json!({ "lineSpacingStyle": "atLeast", "positionX": 4, "positionY": 6 })); + let t = mtext(&s, &m); + assert!(!t.line_spacing_exact && near(t.insert.x, 4.0) && near(t.insert.y, 6.0)); +} + +#[test] +fn dimension_variables_become_overrides_of_each_dimension() { + let mut s = Session::new(); + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + let dm = last(&s); + set(&mut s, &dm, json!({ "textHeight": 0.3 })); + assert_eq!(dim(&s, &dm).overrides.get("textHeight"), Some(&json!(0.3))); + let geometry = |s: &Session| cadcraft_engine::render::dimension_in(s.doc().unwrap(), &dim(s, &dm)); + assert!(near(geometry(&s).text_height, 0.3)); + // A DIM* name replaces the override under its field name. + set(&mut s, &dm, json!({ "DIMTXT": 0.25, "DIMGAP": 0.05 })); + let o = dim(&s, &dm).overrides; + assert_eq!((o.len(), o.get("textHeight"), o.get("textGap")), (2, Some(&json!(0.25)), Some(&json!(0.05)))); + // Clear one, then all. + set(&mut s, &dm, json!({ "clear": ["DIMGAP"] })); + assert_eq!(dim(&s, &dm).overrides.keys().collect::>(), ["textHeight"]); + set(&mut s, &dm, json!({ "clearOverrides": true })); + assert!(dim(&s, &dm).overrides.is_empty()); + assert!(near(geometry(&s).text_height, 0.18)); + // Bad values and unknown text styles don't become overrides. + // An unusable text height is refused (as Properties' dimension rows refuse it, #1473). + assert!(s.execute("properties.set", &json!({ "handles": [dm], "textHeight": -1 })).is_err()); + assert!(s.execute("properties.set", &json!({ "handles": [dm], "textStyle": "Nope" })).is_err()); + assert!(dim(&s, &dm).overrides.is_empty()); +} + +#[test] +fn dimension_text_rows() { + let mut s = Session::new(); + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + let dm = last(&s); + set(&mut s, &dm, json!({ "prefix": "~", "suffix": " mm", "textRotation": 30, "textPositionX": 2 })); + let d = dim(&s, &dm); + assert_eq!(d.overrides.get("post"), Some(&json!("~<> mm"))); + assert!(near(d.text_rotation.to_degrees(), 30.0)); + assert!(d.user_text_pos && near(d.text_mid.x, 2.0)); + let g = cadcraft_engine::render::dimension_in(s.doc().unwrap(), &d); + assert!(g.value.starts_with('~') && g.value.ends_with(" mm"), "{}", g.value); + // A suffix alone keeps the prefix. + set(&mut s, &dm, json!({ "suffix": "" })); + assert_eq!(dim(&s, &dm).overrides.get("post"), Some(&json!("~<>"))); +} + +#[test] +fn edits_of_a_dimension_read_from_a_file_redraw_it() { + let mut s = Session::new(); + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + // Read back from DXF, a dimension draws the block it was saved with. + let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap(); + s.open_drawing(back, "dims", None); + let dm = last(&s); + assert!(dim(&s, &dm).block.is_some()); + // Nothing changed: the block stays. + set(&mut s, &dm, json!({ "clear": [], "color": "ByLayer" })); + assert!(dim(&s, &dm).block.is_some()); + set(&mut s, &dm, json!({ "textHeight": 0.4 })); + assert!(dim(&s, &dm).block.is_none()); +} + +#[test] +fn style_edits_redraw_dimensions_read_from_a_file() { + let mut s = Session::new(); + s.execute("style", &json!({ "name": "DimText", "current": false })).unwrap(); + s.execute("dimstyle", &json!({ "name": "Plan", "textStyle": "DimText" })).unwrap(); + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + s.execute("dimstyle", &json!({ "name": "Other" })).unwrap(); + s.execute("dimlinear", &json!({ "p1": [0, 10], "p2": [10, 10], "at": [5, 13] })).unwrap(); + let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap(); + s.open_drawing(back, "dims", None); + let dims: Vec<(String, cadcraft_engine::doc::Dimension)> = s + .doc() + .unwrap() + .model + .iter() + .filter_map(|e| if let EntityKind::Dimension(d) = &e.kind { Some((e.handle.hex(), d.clone())) } else { None }) + .collect(); + let plan = dims.iter().find(|(_, d)| d.style == "Plan").unwrap().0.clone(); + let other = dims.iter().find(|(_, d)| d.style == "Other").unwrap().0.clone(); + assert!(dim(&s, &plan).block.is_some() && dim(&s, &other).block.is_some()); + // Editing a dimension style redraws the dimensions that use it, and only those. + s.execute("dimstyle", &json!({ "name": "Plan", "DIMTXT": 0.5, "current": false })).unwrap(); + assert!(dim(&s, &plan).block.is_none() && dim(&s, &other).block.is_some()); + let g = cadcraft_engine::render::dimension_in(s.doc().unwrap(), &dim(&s, &plan)); + assert!(near(g.text_height, 0.5)); + // Editing a text style redraws the dimensions whose text uses it. + let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap(); + s.open_drawing(back, "dims", None); + let plan = s.doc().unwrap().model.iter().find(|e| matches!(&e.kind, EntityKind::Dimension(d) if d.style == "Plan")).unwrap().handle.hex(); + assert!(dim(&s, &plan).block.is_some()); + s.execute("style", &json!({ "name": "DimText", "widthFactor": 0.8, "current": false })).unwrap(); + assert!(dim(&s, &plan).block.is_none()); +} + +#[test] +fn renaming_a_text_style_follows_dimension_overrides() { + let mut s = Session::new(); + s.execute("style", &json!({ "name": "Old", "current": false })).unwrap(); + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + let dm = last(&s); + set(&mut s, &dm, json!({ "textStyle": "Old" })); + s.execute("style.rename", &json!({ "from": "Old", "to": "New" })).unwrap(); + assert_eq!(dim(&s, &dm).overrides.get("textStyle"), Some(&json!("New"))); +} + +#[test] +fn hostile_values_never_panic() { + let mut s = Session::new(); + let t = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "A", "height": 1 })).unwrap()); + let m = handle(&s.execute("mtext", &json!({ "at": [0, 5], "text": "B", "height": 1 })).unwrap()); + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + let dm = last(&s); + for v in [json!(null), json!("x"), json!(1e308), json!(-1e308), json!([1, 2]), json!({ "a": 1 }), json!(true)] { + let mut p = json!({ "handles": [t, m, dm] }); + for k in [ + "justify", + "oblique", + "positionX", + "positionZ", + "alignmentX", + "lineSpacing", + "lineSpacingDistance", + "lineSpacingStyle", + "textRotation", + "textPositionX", + "prefix", + "suffix", + "altPrefix", + "clear", + "clearOverrides", + "DIMTXT", + "DIMBLK1", + "DIMCLRT", + "DIMLWD", + "DIMLTYPE", + ] { + p[k] = v.clone(); + } + let _ = s.execute("properties.set", &p); + let _ = s.execute("properties.describe", &json!({ "handles": [t, m, dm] })); + } + // Every dimension still draws. + let g = cadcraft_engine::render::dimension_in(s.doc().unwrap(), &dim(&s, &dm)); + assert!(g.text_height.is_finite()); +} diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index cf5741cdd..20b6078fe 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -906,6 +906,7 @@ Set Current Viewport تعيين إطار العرض الحالي Set Layer Properties تعيين خصائص الطبقة Set Properties تعيين الخصائص + Describe Properties وصف الخصائص Set Table Cell تعيين خلية الجدول Set Table Cell Style تعيين نمط خلية الجدول Set Variable تعيين متغير diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 67a6e90f6..345be9b98 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -840,6 +840,7 @@ Set Current Viewport Nastavit aktuální výřez Set Layer Properties Nastavit vlastnosti hladiny Set Properties Nastavit vlastnosti + Describe Properties Popsat vlastnosti Set Table Cell Nastavit buňku tabulky Set Table Cell Style Nastavit styl buňky tabulky Set Variable Nastavit proměnnou diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 0925cb6af..0cdb2db24 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -729,6 +729,7 @@ Set Current Text Style Textstil als aktuell festlegen Set Layer Properties Layer-Eigenschaften festlegen Set Properties Eigenschaften festlegen + Describe Properties Eigenschaften beschreiben Set Table Cell Tabellenzelle festlegen Set Variable Variable festlegen Set View Ansicht festlegen diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f0e6471ee..235eab1bc 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -933,6 +933,7 @@ Set Current Text Style Establecer estilo de texto actual Set Layer Properties Establecer propiedades de capa Set Properties Establecer propiedades + Describe Properties Describir propiedades Set Table Cell Establecer celda de tabla Set Variable Establecer variable Set View Establecer vista diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 2f391809e..6b830b4db 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -723,6 +723,7 @@ Set Current Text Style Définir le style de texte courant Set Layer Properties Définir les propriétés du calque Set Properties Définir les propriétés + Describe Properties Décrire les propriétés Set Table Cell Définir la cellule de tableau Set Variable Définir la variable Set View Définir la vue diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b298e1c98..77cdeea83 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -847,6 +847,7 @@ menu Modify Edita Set Current Viewport Imposta finestra corrente Set Layer Properties Imposta proprietà layer Set Properties Imposta proprietà + Describe Properties Descrivi proprietà Set Table Cell Imposta cella tabella Set Table Cell Style Imposta stile cella tabella Set Variable Imposta variabile diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 3f01bb695..eec025830 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -837,6 +837,7 @@ Set Current Viewport 현재 뷰포트 설정 Set Layer Properties 도면층 특성 설정 Set Properties 특성 설정 + Describe Properties 특성 설명 Set Table Cell 표 셀 설정 Set Table Cell Style 표 셀 스타일 설정 Set Variable 변수 설정 diff --git a/crates/ui-egui/src/i18n/pt_br.tsv b/crates/ui-egui/src/i18n/pt_br.tsv index 3d1791c1b..c387ecea1 100644 --- a/crates/ui-egui/src/i18n/pt_br.tsv +++ b/crates/ui-egui/src/i18n/pt_br.tsv @@ -928,6 +928,7 @@ Set Current Text Style Definir estilo de texto atual Set Layer Properties Definir propriedades da camada Set Properties Definir propriedades + Describe Properties Descrever propriedades Set Table Cell Definir célula da tabela Set Variable Definir variável Set View Definir vista diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f1a5124f0..f963a875e 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -723,6 +723,7 @@ Set Current Text Style Сделать текстовый стиль текущим Set Layer Properties Задать свойства слоя Set Properties Задать свойства + Describe Properties Описать свойства Set Table Cell Задать ячейку таблицы Set Variable Задать переменную Set View Задать вид diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index d67d39c03..955242c4e 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -926,6 +926,7 @@ Set Current Text Style Gör textstil aktuell Set Layer Properties Ange lageregenskaper Set Properties Ange egenskaper + Describe Properties Beskriv egenskaper Set Table Cell Ange tabellcell Set Variable Ange variabel Set View Ange vy diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 821f30c1b..91be500de 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -862,6 +862,7 @@ Set Current Viewport Зробити видовий екран поточним Set Layer Properties Задати властивості шару Set Properties Задати властивості + Describe Properties Описати властивості Set Table Cell Задати комірку таблиці Set Table Cell Style Задати стиль комірки таблиці Set Variable Задати змінну diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index a07b4f027..e65053cdd 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -726,6 +726,7 @@ Set Current Text Style 设置当前文字样式 Set Layer Properties 设置图层特性 Set Properties 设置特性 + Describe Properties 描述特性 Set Table Cell 设置表格单元格 Set Variable 设置变量 Set View 设置视图 diff --git a/docs/mcp.md b/docs/mcp.md index ecdc53d09..7b9cc0a34 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -67,5 +67,13 @@ point, an unknown command) returns a result with `isError: true` and the message 4. `inspect_drawing {}` — verify counts and geometry. 5. `render {}` — look at it. +To change properties the way the Properties palette does, `execute {"command": +"properties.describe", "params": {"handles": ["2F"]}}` lists the palette's rows for those +objects: each row's `key` (what `properties.set` takes), its value (or `varies`), the value as +shown in the drawing's units, and whether it can be edited (with a `note` when not). Then +`execute {"command": "properties.set", "params": {"handles": ["2F"], "textHeight": 0.25}}` +changes it; on a dimension, style variables such as `textHeight` (or `DIMTXT`) become overrides of +that dimension, and the reply's `ignored` lists keys no selected object took. + The end-to-end test in `crates/mcp/src/tests.rs` runs a session like this and checks the result only through MCP. From a551f206e8af6149aab782a4fcf6e3c31047189f Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Mon, 19 Oct 2026 12:48:41 -0400 Subject: [PATCH 02/41] Review fixes: hatch pattern lines, closed-filled ends, measurements, layer after checks From CodeRabbit's review of #954: - A Properties pattern edit follows HATCHEDIT: a library pattern drops the hatch's own lines, a loaded .pat pattern brings its lines, and any other name keeps them (the moved code cleared them unconditionally). - Closed filled chosen for Arrow 1 or Arrow 2 is stored as _CLOSEDFILLED: an empty per-end arrowhead draws DIMBLK's, so "" changed nothing under a tick. - The Measurement row writes angles in the dimension's angle format (DIMAUNIT, DIMADEC, DIMAZIN) as the renderer does, and equal measurements written differently (units, precision) show *VARIES*. - Text height with fixed-height text styles of different heights shows *VARIES* instead of the dimensions' shared DIMTXT. - properties.set creates a new layer only after every check, so a refused call leaves no layer behind. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/hatch.rs | 2 +- crates/engine/src/cmd/props/set.rs | 23 ++++++++++----- crates/engine/src/properties.rs | 21 ++++++++++++-- crates/engine/tests/it/properties_describe.rs | 29 +++++++++++++++++++ .../tests/it/properties_set_text_dims.rs | 19 ++++++++++++ crates/engine/tests/lin_pat_files.rs | 17 +++++++++++ 6 files changed, 99 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index a362a3502..954b940d4 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -2,7 +2,7 @@ mod patfile; pub use patfile::{PatternChoice, pattern_choices}; -pub(super) use patfile::{lines_for, run_patterns}; +pub(super) use patfile::{run_patterns, user_pattern}; use cadcraft_color::Color; use cadcraft_doc::{Drawing, Entity, EntityKind, Gradient, Handle, Hatch, HatchLoop, Space, entity_bounds}; diff --git a/crates/engine/src/cmd/props/set.rs b/crates/engine/src/cmd/props/set.rs index e2742010d..098bbc177 100644 --- a/crates/engine/src/cmd/props/set.rs +++ b/crates/engine/src/cmd/props/set.rs @@ -73,6 +73,9 @@ impl DimVars { json!(d.linetype(n).map(|t| t.name.clone()).ok_or_else(|| bad("properties.set", format!("linetype `{n}` is not loaded")))?) } } + // Closed filled is `""` among the arrowheads, but an empty per-end arrowhead draws + // DIMBLK's: chosen for one end, it's named. + ("arrowBlock1" | "arrowBlock2", Some("")) => json!("_CLOSEDFILLED"), _ => v.clone(), }; given.insert(k.clone(), v); @@ -208,9 +211,6 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { } }) .transpose()?; - if let Some(l) = str_param(p, "layer") { - d.ensure_layer(l); - } let dim_style = str_param(p, "dimStyle") .map(|n| d.dim_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("dimension style `{n}` not found")))) .transpose()?; @@ -218,6 +218,11 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { .map(|n| d.text_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("text style `{n}` not found")))) .transpose()?; let dim_vars = DimVars::new(d, p)?; + // A failed call changes nothing (a command's error doesn't undo what it did), so the layer + // comes after every check. + if let Some(l) = str_param(p, "layer") { + d.ensure_layer(l); + } let prep = Prepared::new(d, p, &hs); let anno_scale = d.current_anno_scale(); let mut used: BTreeSet<&str> = BTreeSet::new(); @@ -560,16 +565,18 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { } EntityKind::Hatch(h) => { if let Some(v) = str_param(p, "pattern") { - if !h.pattern.eq_ignore_ascii_case(v) { - h.pattern_lines = crate::cmd::hatch::lines_for(v); - } h.pattern = v.to_ascii_uppercase(); - // The old pattern's definition lines no longer apply. - h.pattern_lines.clear(); h.solid = h.pattern == "SOLID"; if !h.solid { // A named pattern replaces the gradient fill; the renderer draws the gradient first when it is set. h.gradient = None; + // As HATCHEDIT: a library pattern is drawn from the library, a loaded .pat + // pattern brings its lines, and any other name is the hatch's own and keeps them. + if cadcraft_doc::library::pattern(&h.pattern).is_some() { + h.pattern_lines.clear(); + } else if let Some(user) = crate::cmd::hatch::user_pattern(&h.pattern) { + h.pattern_lines = user.lines; + } } used.insert("pattern"); } diff --git a/crates/engine/src/properties.rs b/crates/engine/src/properties.rs index a117007a0..b360ee48a 100644 --- a/crates/engine/src/properties.rs +++ b/crates/engine/src/properties.rs @@ -645,7 +645,10 @@ pub fn join_post(prefix: &str, suffix: &str) -> String { /// The measurement as the dimension writes it (its own units and precision). fn measurement_text(dm: &Dimension, st: &DimStyle, meas: f64) -> String { match dm.kind { - DimKind::Angular | DimKind::Angular3P => format!("{:.*}°", usize::from(st.angular_decimals.min(8)), meas.to_degrees()), + // As the renderer writes angles: DIMAUNIT, DIMADEC, and DIMAZIN's leading and trailing zeros. + DimKind::Angular | DimKind::Angular3P => { + cadcraft_render::units::format_angle(meas, st.angular_unit, st.angular_decimals, (st.angular_zero_suppression & 3) * 4) + } _ => cadcraft_render::format_linear_value(meas, st), } } @@ -697,8 +700,12 @@ fn dimension_groups(c: &Ctx, ents: &[&Entity], dims: &[&Dimension]) -> Vec = fixed.iter().zip(styles).map(|(f, st)| f.map_or(st.text_height, |(_, h)| h)).collect(); + let first = heights.first().copied().unwrap_or_default(); + if heights.iter().all(|h| *h == first) { + (r.value, r.varies, r.display) = (json!(first), false, c.distance(first)); + } else { + (r.value, r.varies, r.display) = (Value::Null, true, VARIES.to_string()); + } r.editable = fixed.iter().any(Option::is_none); r.note = Some("Some of these dimensions take their text height from a fixed-height text style.".into()); } diff --git a/crates/engine/tests/it/properties_describe.rs b/crates/engine/tests/it/properties_describe.rs index 2189c0342..193f669ea 100644 --- a/crates/engine/tests/it/properties_describe.rs +++ b/crates/engine/tests/it/properties_describe.rs @@ -130,6 +130,35 @@ fn a_fixed_height_text_style_decides_dimension_text_height() { let th = row(&d, "Text", "textHeight"); assert_eq!((th["editable"].as_bool(), th["display"].as_str()), (Some(false), Some("0.5000"))); assert!(th["note"].as_str().unwrap().contains("Fixed"), "{th}"); + // Fixed heights that differ vary, whatever their DIMTXT says. + s.execute("style", &json!({ "name": "Large", "height": 0.75, "current": false })).unwrap(); + s.execute("dimstyle", &json!({ "name": "LargeDims", "textStyle": "Large" })).unwrap(); + s.execute("dimlinear", &json!({ "p1": [0, 10], "p2": [10, 10], "at": [5, 13] })).unwrap(); + let large = last(&s); + let d = describe(&mut s, json!({ "handles": [dm, large] })); + let th = row(&d, "Text", "textHeight"); + assert_eq!((th["editable"].as_bool(), th["display"].as_str()), (Some(false), Some("*VARIES*"))); +} + +#[test] +fn measurements_read_as_each_dimension_writes_them() { + let mut s = Session::new(); + let shown = + |s: &mut Session, hs: Value| row(&describe(s, json!({ "handles": hs })), "Text", "measurement")["display"].as_str().unwrap().to_string(); + s.execute("dimangular", &json!({ "vertex": [0, 0], "p1": [10, 0], "p2": [0, 10], "at": [3, 3] })).unwrap(); + let angle = last(&s); + assert_eq!(shown(&mut s, json!([angle])), "90°"); + // In the dimension's angle format. + s.execute("properties.set", &json!({ "handles": [angle], "angularUnit": 3, "angularDecimals": 2 })).unwrap(); + assert_eq!(shown(&mut s, json!([angle])), "1.57r"); + // The same length written at two precisions varies. + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + let a = last(&s); + s.execute("dimlinear", &json!({ "p1": [0, 20], "p2": [10, 20], "at": [5, 23] })).unwrap(); + let b = last(&s); + assert_eq!(shown(&mut s, json!([a, b])), "10.0000"); + s.execute("properties.set", &json!({ "handles": [b], "precision": 1 })).unwrap(); + assert_eq!(shown(&mut s, json!([a, b])), "*VARIES*"); } #[test] diff --git a/crates/engine/tests/it/properties_set_text_dims.rs b/crates/engine/tests/it/properties_set_text_dims.rs index 609dea2a6..e15c13744 100644 --- a/crates/engine/tests/it/properties_set_text_dims.rs +++ b/crates/engine/tests/it/properties_set_text_dims.rs @@ -125,6 +125,25 @@ fn dimension_variables_become_overrides_of_each_dimension() { assert!(s.execute("properties.set", &json!({ "handles": [dm], "textHeight": -1 })).is_err()); assert!(s.execute("properties.set", &json!({ "handles": [dm], "textStyle": "Nope" })).is_err()); assert!(dim(&s, &dm).overrides.is_empty()); + // A refused call makes no layer either. + assert!(s.execute("properties.set", &json!({ "handles": [dm], "layer": "Notes", "dimStyle": "Nope" })).is_err()); + assert!(s.doc().unwrap().layer("Notes").is_none()); +} + +#[test] +fn closed_filled_for_one_end_is_drawn_whatever_dimblk_says() { + let mut s = Session::new(); + s.execute("dimstyle", &json!({ "name": "Ticks", "arrowBlock": "_ARCHTICK" })).unwrap(); + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + let dm = last(&s); + // Closed filled is "" among the arrowheads; for one end it's named, as "" there is DIMBLK's. + set(&mut s, &dm, json!({ "arrowBlock1": "" })); + assert_eq!(dim(&s, &dm).overrides.get("arrowBlock1"), Some(&json!("_CLOSEDFILLED"))); + let rows = s.execute("properties.describe", &json!({ "handles": [dm] })).unwrap(); + let arrow = |key: &str| { + rows["groups"].as_array().unwrap().iter().flat_map(|g| g["rows"].as_array().unwrap()).find(|r| r["key"] == key).unwrap()["value"].clone() + }; + assert_eq!((arrow("arrowBlock1"), arrow("arrowBlock2")), (json!(""), json!("_ARCHTICK"))); } #[test] diff --git a/crates/engine/tests/lin_pat_files.rs b/crates/engine/tests/lin_pat_files.rs index 91f99062e..7a4aa6852 100644 --- a/crates/engine/tests/lin_pat_files.rs +++ b/crates/engine/tests/lin_pat_files.rs @@ -128,6 +128,23 @@ fn hatch_uses_a_pattern_from_a_pat_file_and_keeps_its_definition() { assert!(hatches(&s).pop().unwrap().pattern_lines.is_empty()); } +#[test] +fn properties_pattern_edits_keep_a_pat_files_definition() { + let mut s = Session::new(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap(); + s.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "ANSI31", "patternText": PAT })).unwrap(); + let hx = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle.hex(); + // As HATCHEDIT: a loaded pattern brings its lines, and they stay. + s.execute("properties.set", &json!({ "handles": [hx], "pattern": "MYSTEPS" })).unwrap(); + let h = hatches(&s).pop().unwrap(); + assert_eq!((h.pattern.as_str(), h.pattern_lines.len()), ("MYSTEPS", 1)); + // The same name again keeps them, and a library pattern drops them. + s.execute("properties.set", &json!({ "handles": [hx], "pattern": "mysteps" })).unwrap(); + assert_eq!(hatches(&s).pop().unwrap().pattern_lines[0].dashes, [0.25, -0.25]); + s.execute("properties.set", &json!({ "handles": [hx], "pattern": "ANSI37" })).unwrap(); + assert!(hatches(&s).pop().unwrap().pattern_lines.is_empty()); +} + #[test] fn hatch_pattern_prompt_takes_a_pat_file_name() { let dir = TempDir::new("lin-pat"); From c1c97ed00e2ec2f1e07a44d14f2fb6475973152e Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Fri, 23 Oct 2026 20:43:52 -0400 Subject: [PATCH 03/41] Review fixes: SOLID drops the gradient, all objects checked first, Align rotation, DIMPOST rows From CodeRabbit's second to fourth reviews of #954, and codyvogt (from #1371's): - The Properties pattern edit and HATCHEDIT share one helper (hatch::set_pattern) and one rule for the names a hatch takes: SOLID drops a gradient fill too, a blank name changes nothing (it's reported as ignored), and a name no pattern has is refused, as HATCHEDIT refuses it (a hatch's own name matches in any case). - properties.set refuses a call that names an object that isn't there before it edits any, so a bad handle late in the list no longer leaves the earlier objects edited. - A prefix or suffix edit goes into the DIMPOST/DIMAPOST the dimension has after the call's other edits (its new style, cleared overrides), not the ones it had before. - The prefix and suffix rows are marked overridden when DIMPOST or DIMAPOST is, and their "Use the style's value" clears that variable. - Rotating aligned or fit TEXT turns its baseline's second point with it (the renderer takes their direction from the two points). - Justify Align or Fit measures the baseline from the text as the call leaves it (its new contents, style, height, width factor and rotation). - `scale` is an insert's or hatch's scale only; it no longer also becomes a DIMSCALE override of a dimension in the selection (that's `dimScale`). - A text style that only a dimension's text style override names is in use, so style.delete refuses it (a rename follows those overrides already). - Editing a text or dimension style redraws the dimensions read from a file only when the style changed: making it current keeps their geometry. - docs/mcp.md's example finds the dimension's handle with query_entities before it describes and sets it. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/hatch.rs | 3 +- crates/engine/src/cmd/hatch/edit.rs | 58 ++++++---- crates/engine/src/cmd/props.rs | 32 ++++-- crates/engine/src/cmd/props/set.rs | 90 ++++++++++------ crates/engine/src/properties.rs | 15 ++- .../tests/it/properties_set_text_dims.rs | 100 ++++++++++++++++++ docs/mcp.md | 7 +- 7 files changed, 239 insertions(+), 66 deletions(-) diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index 954b940d4..2082346bd 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -1,8 +1,9 @@ //! HATCH, GRADIENT, BOUNDARY, REGION: boundaries from pick points or selected closed objects. mod patfile; +pub(super) use edit::{set_pattern, takes_pattern}; +pub(super) use patfile::run_patterns; pub use patfile::{PatternChoice, pattern_choices}; -pub(super) use patfile::{run_patterns, user_pattern}; use cadcraft_color::Color; use cadcraft_doc::{Drawing, Entity, EntityKind, Gradient, Handle, Hatch, HatchLoop, Space, entity_bounds}; diff --git a/crates/engine/src/cmd/hatch/edit.rs b/crates/engine/src/cmd/hatch/edit.rs index c0f5c7440..3f4b9ba0b 100644 --- a/crates/engine/src/cmd/hatch/edit.rs +++ b/crates/engine/src/cmd/hatch/edit.rs @@ -143,21 +143,8 @@ fn separate(s: &mut Session, handle: Handle) -> Result> { /// Pattern, scale and angle (degrees) from the parameters. fn properties(h: &mut Hatch, p: &Value) { - if let Some(v) = str_param(p, "pattern").map(str::trim).filter(|v| !v.is_empty()) { - h.pattern = v.to_ascii_uppercase(); - h.solid = h.pattern == "SOLID"; - // A named pattern, SOLID included, replaces the gradient fill; the renderer draws the - // gradient first when it is set. - h.gradient = None; - if !h.solid { - // A library pattern is drawn from the library; a loaded .pat pattern brings its lines; - // any other name is the hatch's own and keeps its definition. - if cadcraft_doc::library::pattern(&h.pattern).is_some() { - h.pattern_lines.clear(); - } else if let Some(user) = super::patfile::user_pattern(&h.pattern) { - h.pattern_lines = user.lines; - } - } + if let Some(v) = str_param(p, "pattern") { + set_pattern(h, v); } if let Some(x) = p.get("scale").and_then(Value::as_f64).filter(|x| x.is_finite() && *x > 0.0) { h.scale = x; @@ -167,6 +154,43 @@ fn properties(h: &mut Hatch, p: &Value) { } } +/// Whether the pattern called `up` (upper case) is defined: SOLID, one CADCraft defines, or a +/// loaded .pat pattern. +fn defined_pattern(up: &str) -> bool { + up == "SOLID" || cadcraft_doc::library::pattern(up).is_some() || super::patfile::user_pattern(up).is_some() +} + +/// Whether `h` can take the pattern called `name`: a defined one, or the hatch's own (a pattern +/// read from a file keeps its definition). +pub(crate) fn takes_pattern(h: &Hatch, name: &str) -> bool { + let up = name.trim().to_ascii_uppercase(); + defined_pattern(&up) || h.pattern.eq_ignore_ascii_case(&up) +} + +/// Give `h` the pattern called `name` (HATCHEDIT's and Properties' pattern edit); false, and +/// nothing changes, for a blank name or one the hatch can't take ([`takes_pattern`]). +pub(crate) fn set_pattern(h: &mut Hatch, name: &str) -> bool { + let name = name.trim(); + if name.is_empty() || !takes_pattern(h, name) { + return false; + } + h.pattern = name.to_ascii_uppercase(); + h.solid = h.pattern == "SOLID"; + // A named pattern, SOLID included, replaces the gradient fill; the renderer draws the + // gradient first when it is set. + h.gradient = None; + if !h.solid { + // A library pattern is drawn from the library; a loaded .pat pattern brings its lines; + // any other name is the hatch's own and keeps its definition. + if cadcraft_doc::library::pattern(&h.pattern).is_some() { + h.pattern_lines.clear(); + } else if let Some(user) = super::patfile::user_pattern(&h.pattern) { + h.pattern_lines = user.lines; + } + } + true +} + /// HATCHEDIT's `gradient`: the fields to change, all checked before any hatch is touched. struct GradientEdit { name: Option<&'static str>, @@ -389,9 +413,7 @@ pub(super) fn run_hatchedit(s: &mut Session, p: &Value) -> Result { // Like the prompt: a pattern must be one CADCraft defines, SOLID, or the hatches' own (a // pattern read from a file keeps its definition). if let Some(up) = str_param(p, "pattern").map(|v| v.trim().to_ascii_uppercase()).filter(|v| !v.is_empty()) - && up != "SOLID" - && cadcraft_doc::library::pattern(&up).is_none() - && super::patfile::user_pattern(&up).is_none() + && !defined_pattern(&up) { let d = s.doc()?; let own = hs.iter().all(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Hatch(x)) if x.pattern == up)); diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index e12dedc99..94032e380 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -447,6 +447,8 @@ fn run_style(s: &mut Session, p: &Value) -> Result { return Err(bad("style", "bad style name")); } let d = s.doc_mut()?; + // As it was (none for a new style), so dimensions are redrawn only when it changes. + let before = d.text_style(&name).cloned(); let idx = match d.text_styles.iter().position(|t| t.name.eq_ignore_ascii_case(&name)) { Some(i) => i, None => { @@ -482,11 +484,13 @@ fn run_style(s: &mut Session, p: &Value) -> Result { } } } - // Dimensions whose text uses the style drop the geometry they were read with: their text - // changes with it. - let text_style_of: std::collections::HashMap = - d.dim_styles.iter().map(|st| (st.name.to_ascii_lowercase(), st.text_style.clone())).collect(); - regen_dims(d, |dm| dim_text_style(dm, &text_style_of).eq_ignore_ascii_case(&name))?; + // Dimensions whose text uses the style drop the geometry they were read with when it + // changed: their text changes with it. Only making it current keeps that geometry. + if before.as_ref() != d.text_styles.get(idx) { + let text_style_of: std::collections::HashMap = + d.dim_styles.iter().map(|st| (st.name.to_ascii_lowercase(), st.text_style.clone())).collect(); + regen_dims(d, |dm| dim_text_style(dm, &text_style_of).eq_ignore_ascii_case(&name))?; + } if bool_or(p, "current", true) { d.header.set_str("TEXTSTYLE", &name); } @@ -521,6 +525,13 @@ pub(super) fn text_styles_in_use(d: &cadcraft_doc::Drawing) -> Vec { EntityKind::AttDef(a) => out.push(a.text.style.clone()), EntityKind::Insert(i) => out.extend(i.attribs.iter().map(|a| a.text.style.clone())), EntityKind::MLeader(m) => out.extend(m.text.iter().map(|t| t.style.clone())), + // A dimension's own text style (a DIMTXSTY override), which a rename follows too. + EntityKind::Dimension(dm) => out.extend( + dm.overrides + .iter() + .filter(|(k, _)| cadcraft_doc::DimStyle::field_name(k) == Some("textStyle")) + .filter_map(|(_, v)| v.as_str().map(str::to_string)), + ), _ => {} } } @@ -618,6 +629,8 @@ fn run_dimstyle(s: &mut Session, p: &Value) -> Result { return Err(bad("dimstyle", "bad style name")); } let d = s.doc_mut()?; + // As it was (none for a new style), so dimensions are redrawn only when it changes. + let before = d.dim_style(&name).cloned(); let base = d.dim_style(&d.header.str("DIMSTYLE", "Standard")).cloned().unwrap_or_default(); let idx = match d.dim_styles.iter().position(|t| t.name.eq_ignore_ascii_case(&name)) { Some(i) => i, @@ -632,9 +645,12 @@ fn run_dimstyle(s: &mut Session, p: &Value) -> Result { src.iter().filter(|(k, _)| !matches!(k.as_str(), "name" | "current")).map(|(k, v)| (k.clone(), v.clone())).collect(); rejected = st.apply_fields(&fields); } - // Dimensions with the style drop the geometry they were read with, so they show the edit - // (as AutoCAD updates every dimension that uses a style; their overrides still win). - regen_dims(d, |dm| dm.style.eq_ignore_ascii_case(&name))?; + // Dimensions with the style drop the geometry they were read with when it changed, so they + // show the edit (as AutoCAD updates every dimension that uses a style; their overrides still + // win). Only making it current keeps that geometry. + if before.as_ref() != d.dim_styles.get(idx) { + regen_dims(d, |dm| dm.style.eq_ignore_ascii_case(&name))?; + } if bool_or(p, "current", true) { d.header.set_str("DIMSTYLE", &name); } diff --git a/crates/engine/src/cmd/props/set.rs b/crates/engine/src/cmd/props/set.rs index 098bbc177..3b3703daa 100644 --- a/crates/engine/src/cmd/props/set.rs +++ b/crates/engine/src/cmd/props/set.rs @@ -41,6 +41,8 @@ const SET_KEYS: &[&str] = &[ "suffix", "altPrefix", "altSuffix", + // An insert's or hatch's scale; a dimension's overall scale is `dimScale` (or DIMSCALE). + "scale", ]; /// The dimension style variables of a call, checked once: canonical field names with their @@ -108,8 +110,9 @@ struct Prepared { ends: HashMap, /// Dimensions: where their text is drawn now. text_pos: HashMap, - /// Dimensions: the DIMPOST and DIMAPOST templates they draw with. - posts: HashMap, + /// The DIMPOST and DIMAPOST templates of each dimension style (by lowercase name), when a + /// prefix or suffix is edited: a dimension's are worked out after its other edits. + posts: Option>, } impl Prepared { @@ -125,23 +128,28 @@ impl Prepared { let Some(e) = d.entity(*h) else { continue }; match &e.kind { EntityKind::Text(t) if two_points => { - let font = cadcraft_fonts::TextFont::resolve(&d.text_style(&t.style).cloned().unwrap_or_default().font); - let w = cadcraft_fonts::text_width(&font, &t.value, t.height, t.width_factor); - let w = if w.is_finite() && w > 1e-9 { w } else { t.height.max(1e-9) }; - out.ends.insert(*h, Vec2::polar(t.justify_point(), w, t.rotation)); + // The text as this call leaves it: its contents, style, height, width factor + // and rotation, where the call sets them too. + let num = |k: &str| p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()); + let style = str_param(p, "style").and_then(|n| d.text_style(n)).map_or(t.style.as_str(), |s| s.name.as_str()); + let value = str_param(p, "text").unwrap_or(&t.value); + let height = num("height").filter(|x| *x > 0.0).unwrap_or(t.height); + let width_factor = num("widthFactor").filter(|x| *x > 0.0).unwrap_or(t.width_factor); + let rotation = num("rotation").map_or(t.rotation, f64::to_radians); + let font = cadcraft_fonts::TextFont::resolve(&d.text_style(style).cloned().unwrap_or_default().font); + let w = cadcraft_fonts::text_width(&font, value, height, width_factor); + let w = if w.is_finite() && w > 1e-9 { w } else { height.max(1e-9) }; + out.ends.insert(*h, Vec2::polar(t.justify_point(), w, rotation)); } - EntityKind::Dimension(dm) => { - if moves_text { - out.text_pos.insert(*h, cadcraft_render::dimension_in(d, dm).text_pos); - } - if posts { - let st = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides); - out.posts.insert(*h, (st.post, st.alt_post)); - } + EntityKind::Dimension(dm) if moves_text => { + out.text_pos.insert(*h, cadcraft_render::dimension_in(d, dm).text_pos); } _ => {} } } + if posts { + out.posts = Some(d.dim_styles.iter().map(|st| (st.name.to_ascii_lowercase(), (st.post.clone(), st.alt_post.clone()))).collect()); + } out } } @@ -218,8 +226,17 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { .map(|n| d.text_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("text style `{n}` not found")))) .transpose()?; let dim_vars = DimVars::new(d, p)?; + if let Some(h) = hs.iter().find(|h| d.entity(**h).is_none()) { + return Err(bad("properties.set", format!("no object {}", h.hex()))); + } + // A pattern must be one each hatch can take, as HATCHEDIT refuses others. + if let Some(v) = str_param(p, "pattern").filter(|v| !v.trim().is_empty()) + && hs.iter().any(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Hatch(x)) if !crate::cmd::hatch::takes_pattern(x, v))) + { + return Err(bad("properties.set", format!("unknown pattern {}", v.trim().to_ascii_uppercase()))); + } // A failed call changes nothing (a command's error doesn't undo what it did), so the layer - // comes after every check. + // comes after every check, and every object is there before any is edited. if let Some(l) = str_param(p, "layer") { d.ensure_layer(l); } @@ -356,6 +373,13 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { } if let Some(x) = num("rotation") { t.rotation = x.to_radians(); + // Aligned and fit text run along their baseline's two ends: it turns too. + if matches!(t.halign, HAlign::Aligned | HAlign::Fit) + && let Some(end) = t.align_pt + { + let e = Vec2::polar(t.insert.xy(), t.insert.xy().dist(end.xy()), t.rotation); + t.align_pt = Some(Vec3::new(e.x, e.y, end.z)); + } used.insert("rotation"); } if let Some(x) = num("widthFactor").filter(|x| *x > 0.0) { @@ -527,7 +551,13 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { used.insert("clearOverrides"); } if let Some(names) = p.get("clear").and_then(Value::as_array) { - for f in names.iter().filter_map(Value::as_str).filter_map(DimStyle::field_name) { + // Prefix and suffix rows reset DIMPOST (DIMAPOST), the variable they're halves of. + let field = |n: &str| match n { + "prefix" | "suffix" => Some("post"), + "altPrefix" | "altSuffix" => Some("altPost"), + n => DimStyle::field_name(n), + }; + for f in names.iter().filter_map(Value::as_str).filter_map(field) { dm.overrides.retain(|k, _| DimStyle::field_name(k) != Some(f)); } used.insert("clear"); @@ -548,8 +578,14 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { dm.user_text_pos = true; used.extend(["textPositionX", "textPositionY"].into_iter().filter(|k| num(k).is_some())); } - if let Some((post, alt)) = prep.posts.get(&h) { - for (field, template, keys) in [("post", post, ["prefix", "suffix"]), ("altPost", alt, ["altPrefix", "altSuffix"])] { + if let Some(styles) = &prep.posts { + // The templates the dimension draws with after the edits above (its style, + // cleared and new overrides), which the prefix or suffix edit goes into. + let (post, alt) = styles.get(&dm.style.to_ascii_lowercase()).cloned().unwrap_or_default(); + let st = DimStyle { post, alt_post: alt, ..DimStyle::default() }.with_overrides(&dm.overrides); + for (field, template, keys) in + [("post", &st.post, ["prefix", "suffix"]), ("altPost", &st.alt_post, ["altPrefix", "altSuffix"])] + { let (pre, suf) = (str_param(p, keys[0]), str_param(p, keys[1])); if pre.is_some() || suf.is_some() { let (pre0, suf0) = split_post(template); @@ -564,20 +600,10 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { } } EntityKind::Hatch(h) => { - if let Some(v) = str_param(p, "pattern") { - h.pattern = v.to_ascii_uppercase(); - h.solid = h.pattern == "SOLID"; - if !h.solid { - // A named pattern replaces the gradient fill; the renderer draws the gradient first when it is set. - h.gradient = None; - // As HATCHEDIT: a library pattern is drawn from the library, a loaded .pat - // pattern brings its lines, and any other name is the hatch's own and keeps them. - if cadcraft_doc::library::pattern(&h.pattern).is_some() { - h.pattern_lines.clear(); - } else if let Some(user) = crate::cmd::hatch::user_pattern(&h.pattern) { - h.pattern_lines = user.lines; - } - } + // HATCHEDIT's pattern edit (a blank name changes nothing, so it's ignored). + if let Some(v) = str_param(p, "pattern") + && crate::cmd::hatch::set_pattern(h, v) + { used.insert("pattern"); } if let Some(x) = num("scale").filter(|x| *x > 0.0) { diff --git a/crates/engine/src/properties.rs b/crates/engine/src/properties.rs index b360ee48a..425d5f645 100644 --- a/crates/engine/src/properties.rs +++ b/crates/engine/src/properties.rs @@ -95,6 +95,10 @@ impl Row { self.editable = false; self } + fn overridden_if(mut self, overridden: bool) -> Self { + self.overridden = overridden; + self + } } #[derive(Clone, Debug, PartialEq, Serialize)] @@ -713,15 +717,18 @@ fn dimension_groups(c: &Ctx, ents: &[&Entity], dims: &[&Dimension]) -> Vec { let (pre, suf): (Vec, Vec) = styles.iter().map(|st| split_post(&st.post)).map(|(p, s)| (json!(p), json!(s))).unzip(); let at = rows.iter().position(|r| r.key == "round").unwrap_or(rows.len()); - rows.insert(at, c.row("prefix", "Dim prefix", Kind::Text, pre)); + // Prefix and suffix are DIMPOST's two halves: overridden with it, and reset with it. + let posted = dims.iter().any(|dm| overrides(dm, "post")); + rows.insert(at, c.row("prefix", "Dim prefix", Kind::Text, pre).overridden_if(posted)); let at = rows.iter().position(|r| r.key == "linearUnit").unwrap_or(rows.len()); - rows.insert(at, c.row("suffix", "Dim suffix", Kind::Text, suf)); + rows.insert(at, c.row("suffix", "Dim suffix", Kind::Text, suf).overridden_if(posted)); } "Alternate Units" => { let (pre, suf): (Vec, Vec) = styles.iter().map(|st| split_post(&st.alt_post)).map(|(p, s)| (json!(p), json!(s))).unzip(); - rows.push(c.row("altPrefix", "Alt prefix", Kind::Text, pre)); - rows.push(c.row("altSuffix", "Alt suffix", Kind::Text, suf)); + let posted = dims.iter().any(|dm| overrides(dm, "altPost")); + rows.push(c.row("altPrefix", "Alt prefix", Kind::Text, pre).overridden_if(posted)); + rows.push(c.row("altSuffix", "Alt suffix", Kind::Text, suf).overridden_if(posted)); } _ => {} } diff --git a/crates/engine/tests/it/properties_set_text_dims.rs b/crates/engine/tests/it/properties_set_text_dims.rs index e15c13744..ed0f18aac 100644 --- a/crates/engine/tests/it/properties_set_text_dims.rs +++ b/crates/engine/tests/it/properties_set_text_dims.rs @@ -161,6 +161,104 @@ fn dimension_text_rows() { // A suffix alone keeps the prefix. set(&mut s, &dm, json!({ "suffix": "" })); assert_eq!(dim(&s, &dm).overrides.get("post"), Some(&json!("~<>"))); + // Together with other edits, the prefix goes into what those leave: here no suffix override. + set(&mut s, &dm, json!({ "suffix": " mm" })); + set(&mut s, &dm, json!({ "clearOverrides": true, "prefix": "=" })); + assert_eq!(dim(&s, &dm).overrides.get("post"), Some(&json!("=<>"))); + // The prefix and suffix rows are DIMPOST's halves: overridden with it, reset with it. + let rows = s.execute("properties.describe", &json!({ "handles": [dm] })).unwrap(); + let prefix = + rows["groups"].as_array().unwrap().iter().flat_map(|g| g["rows"].as_array().unwrap()).find(|r| r["key"] == "prefix").unwrap().clone(); + assert_eq!(prefix["overridden"], true, "{prefix}"); + set(&mut s, &dm, json!({ "clear": ["prefix"] })); + assert!(dim(&s, &dm).overrides.get("post").is_none()); +} + +#[test] +fn rotating_aligned_text_turns_its_baseline() { + let mut s = Session::new(); + let t = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "Wide", "height": 1 })).unwrap()); + set(&mut s, &t, json!({ "justify": "Align" })); + let long = text(&s, &t).align_pt.unwrap().x; + assert!(long > 0.0); + set(&mut s, &t, json!({ "rotation": 90 })); + let end = text(&s, &t).align_pt.unwrap(); + assert!(near(end.x, 0.0) && near(end.y, long), "{end:?}"); +} + +#[test] +fn justify_in_one_call_with_other_edits_takes_them_in() { + // Fit with new contents measures the new text; with a rotation, the baseline runs along it. + let mut s = Session::new(); + let short = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "A", "height": 1 })).unwrap()); + let long = handle(&s.execute("text", &json!({ "at": [0, 5], "text": "Much longer", "height": 1 })).unwrap()); + set(&mut s, &long, json!({ "justify": "Fit" })); + set(&mut s, &short, json!({ "text": "Much longer", "justify": "Fit", "rotation": 90 })); + let (a, b) = (text(&s, &short), text(&s, &long)); + let len = |t: &Text| t.insert.xy().dist(t.align_pt.unwrap().xy()); + assert!(near(len(&a), len(&b)), "{} {}", len(&a), len(&b)); + let end = a.align_pt.unwrap(); + assert!(near(end.x, 0.0) && end.y > 0.0, "{end:?}"); +} + +#[test] +fn scale_is_no_dimension_override() { + // `scale` is an insert's or hatch's; a dimension's overall scale is `dimScale`. + let mut s = Session::new(); + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + let dm = last(&s); + assert_eq!(set(&mut s, &dm, json!({ "scale": 2 }))["ignored"], json!(["scale"])); + assert!(dim(&s, &dm).overrides.is_empty()); +} + +#[test] +fn making_a_style_current_keeps_the_dimensions_read_from_a_file() { + let mut s = Session::new(); + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap(); + s.open_drawing(back, "dims", None); + let dm = last(&s); + assert!(dim(&s, &dm).block.is_some()); + // No field changes: the geometry the file stored stays. + s.execute("dimstyle", &json!({ "name": "Standard" })).unwrap(); + s.execute("style", &json!({ "name": "Standard" })).unwrap(); + assert!(dim(&s, &dm).block.is_some()); + // A change redraws it. + s.execute("dimstyle", &json!({ "name": "Standard", "DIMTXT": 0.3 })).unwrap(); + assert!(dim(&s, &dm).block.is_none()); +} + +#[test] +fn hatch_pattern_edits_go_as_hatchedits_do() { + let mut s = Session::new(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap(); + s.execute("gradient", &json!({ "points": [[5, 5]], "color1": "1", "color2": "3" })).unwrap(); + let h = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle.hex(); + let hatch = |s: &Session| match &s.doc().unwrap().entity(Handle::parse_hex(&h).unwrap()).unwrap().kind { + EntityKind::Hatch(x) => x.clone(), + k => panic!("not a hatch: {k:?}"), + }; + assert!(hatch(&s).gradient.is_some()); + // SOLID is a plain fill, not the gradient. + set(&mut s, &h, json!({ "pattern": "SOLID" })); + assert!(hatch(&s).solid && hatch(&s).gradient.is_none()); + // A blank name changes nothing. + assert_eq!(set(&mut s, &h, json!({ "pattern": " " }))["ignored"], json!(["pattern"])); + assert_eq!(hatch(&s).pattern, "SOLID"); + // A name no pattern has is refused, as HATCHEDIT refuses it; a defined one is taken. + assert!(s.execute("properties.set", &json!({ "handles": [h], "pattern": "ANSI3" })).is_err()); + assert_eq!(hatch(&s).pattern, "SOLID"); + set(&mut s, &h, json!({ "pattern": "ansi31" })); + assert_eq!(hatch(&s).pattern, "ANSI31"); +} + +#[test] +fn an_object_that_is_not_there_refuses_the_whole_call() { + let mut s = Session::new(); + let t = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "A", "height": 1 })).unwrap()); + assert!(s.execute("properties.set", &json!({ "handles": [t, "FFFFF"], "height": 3, "layer": "Notes" })).is_err()); + assert_eq!(text(&s, &t).height, 1.0); + assert!(s.doc().unwrap().layer("Notes").is_none()); } #[test] @@ -222,6 +320,8 @@ fn renaming_a_text_style_follows_dimension_overrides() { set(&mut s, &dm, json!({ "textStyle": "Old" })); s.execute("style.rename", &json!({ "from": "Old", "to": "New" })).unwrap(); assert_eq!(dim(&s, &dm).overrides.get("textStyle"), Some(&json!("New"))); + // A style only a dimension override names is in use: it can't be deleted. + assert!(s.execute("style.delete", &json!({ "name": "New" })).is_err()); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 7b9cc0a34..291fddc1e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -67,9 +67,10 @@ point, an unknown command) returns a result with `isError: true` and the message 4. `inspect_drawing {}` — verify counts and geometry. 5. `render {}` — look at it. -To change properties the way the Properties palette does, `execute {"command": -"properties.describe", "params": {"handles": ["2F"]}}` lists the palette's rows for those -objects: each row's `key` (what `properties.set` takes), its value (or `varies`), the value as +To change properties the way the Properties palette does, find the object's handle first, for +example the dimension from step 3 with `query_entities {"type": "Dimension"}` (say its `handle` +is `"2F"`). Then `execute {"command": "properties.describe", "params": {"handles": ["2F"]}}` +lists the palette's rows for those objects: each row's `key` (what `properties.set` takes), its value (or `varies`), the value as shown in the drawing's units, and whether it can be edited (with a `note` when not). Then `execute {"command": "properties.set", "params": {"handles": ["2F"], "textHeight": 0.25}}` changes it; on a dimension, style variables such as `textHeight` (or `DIMTXT`) become overrides of From b99ea8905e02ca27cdf633394f3c4fcdcb1c8f16 Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Wed, 28 Oct 2026 16:09:32 -0400 Subject: [PATCH 04/41] properties.set: one function per kind of object, within #2239's clippy limits #2239 denies a cognitive complexity over 30 and wildcard imports. properties.set's per-object edit (complexity 90) becomes one function per kind of object (line, circle, arc, text and its position, mtext and its line spacing, insert, dimension and its prefix and suffix, hatch) and one for the properties every object has; what the call checked before any object changes travels in a `Call`. set.rs and props.rs import by name. Nothing changes in behavior. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/props.rs | 3 +- crates/engine/src/cmd/props/set.rs | 802 ++++++++++++++++------------- 2 files changed, 439 insertions(+), 366 deletions(-) diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 94032e380..c3437b060 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -13,10 +13,9 @@ use set::run_set; use cadcraft_color::Color; use cadcraft_doc::{EntityKind, Lineweight, Transparency}; -use cadcraft_geom::Vec3; use serde_json::{Value, json}; -use super::{CommandSpec, always, bad, bool_or, f64_req, find_command, ok, point_req, point_value, str_param, targets}; +use super::{CommandSpec, always, bad, bool_or, f64_req, find_command, ok, point_req, str_param, targets}; use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; diff --git a/crates/engine/src/cmd/props/set.rs b/crates/engine/src/cmd/props/set.rs index 3b3703daa..4ada1986c 100644 --- a/crates/engine/src/cmd/props/set.rs +++ b/crates/engine/src/cmd/props/set.rs @@ -3,11 +3,18 @@ use std::collections::{BTreeSet, HashMap}; -use cadcraft_doc::{DimStyle, Drawing, HAlign, Handle, Text, VAlign}; -use cadcraft_geom::Vec2; +use cadcraft_color::Color; +use cadcraft_doc::{ + AnnoScale, Arc, Circle, DimStyle, Dimension, Drawing, Entity, EntityKind, HAlign, Handle, Hatch, Insert, Line, Lineweight, MText, Text, + Transparency, VAlign, +}; +use cadcraft_geom::{Vec2, Vec3}; +use serde_json::{Value, json}; -use super::*; +use super::{parse_color, parse_transparency}; +use crate::cmd::{bad, point_value, str_param, targets}; use crate::properties::{LINE_PITCH, is_dim_linetype, join_post, split_post}; +use crate::{Result, Session}; fn set_xy(p: &mut Vec3, v: &Value) { if let Some(q) = point_value(v) { @@ -193,6 +200,32 @@ fn set_override(dm: &mut cadcraft_doc::Dimension, field: &'static str, v: Value) dm.overrides.insert(field.to_string(), v); } +/// A `properties.set` call, checked before any object changes: the values every object takes, +/// and what the edits need to know beforehand. +struct Call<'a> { + p: &'a Value, + color: Option, + transparency: Option, + thickness: Option, + lineweight: Option, + linetype: Option, + dim_style: Option, + text_style: Option, + dim_vars: DimVars, + prep: Prepared, + anno_scale: AnnoScale, +} + +/// The keys some object took. +type Used<'c> = BTreeSet<&'c str>; + +impl Call<'_> { + /// A finite number under `k`. + fn num(&self, k: &str) -> Option { + self.p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()) + } +} + pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { let hs = targets(s, p)?; if hs.is_empty() { @@ -207,7 +240,8 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { .get("thickness") .map(|v| v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad("properties.set", "thickness must be a finite number"))) .transpose()?; - let lw = p.get("lineweight").map(|v| crate::cmd::layer::parse_lw(v).ok_or_else(|| bad("properties.set", "bad lineweight"))).transpose()?; + let lineweight = + p.get("lineweight").map(|v| crate::cmd::layer::parse_lw(v).ok_or_else(|| bad("properties.set", "bad lineweight"))).transpose()?; let d = s.doc_mut()?; // An explicit object linetype must be ByLayer, ByBlock or a loaded definition (as `linetype current` requires). let linetype = str_param(p, "linetype") @@ -242,379 +276,34 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { } let prep = Prepared::new(d, p, &hs); let anno_scale = d.current_anno_scale(); - let mut used: BTreeSet<&str> = BTreeSet::new(); + let c = Call { p, color, transparency, thickness, lineweight, linetype, dim_style, text_style, dim_vars, prep, anno_scale }; + let mut used = Used::new(); for h in &hs { let h = *h; d.modify_entity(h, |e| { - // Annotative: Yes supports the current annotation scale; No drops every scale. - if let Some(a) = p.get("annotative").and_then(Value::as_bool) - && cadcraft_doc::can_be_annotative(&e.kind) - { - cadcraft_doc::set_annotative(e, a, &anno_scale); - if let EntityKind::Dimension(dm) = &mut e.kind { - dm.block = None; - } - used.insert("annotative"); - } - if let Some(l) = str_param(p, "layer") { - e.common.layer = l.to_string(); - used.insert("layer"); - } - if let Some(c) = color { - e.common.color = c; - used.insert("color"); - } - if let Some(lt) = &linetype { - e.common.linetype.clone_from(lt); - used.insert("linetype"); - } - if let Some(w) = lw { - e.common.lineweight = w; - used.insert("lineweight"); - } - if let Some(x) = p.get("ltscale").and_then(Value::as_f64).filter(|x| *x > 0.0 && x.is_finite()) { - e.common.ltscale = x; - used.insert("ltscale"); - } - if let Some(t) = transparency { - e.common.transparency = t; - used.insert("transparency"); - } - if let Some(th) = thickness { - e.common.thickness = th; - used.insert("thickness"); - } - if let Some(v) = p.get("visible").and_then(Value::as_bool) { - e.common.visible = v; - used.insert("visible"); - } - let num = |k: &str| p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()); + common(e, &c, &mut used); match &mut e.kind { - EntityKind::Line(l) => { - if let Some(v) = p.get("start") { - set_xy(&mut l.a, v); - used.insert("start"); - } - if let Some(v) = p.get("end") { - set_xy(&mut l.b, v); - used.insert("end"); - } - // Length / angle keep the start point and move the end point. - let (a, b) = (l.a.xy(), l.b.xy()); - let length = num("length").filter(|x| *x > 0.0 && *x < 1e15); - let len = length.unwrap_or_else(|| a.dist(b)); - let ang = num("angle").map(f64::to_radians).unwrap_or_else(|| a.angle_to(b)); - if length.is_some() || num("angle").is_some() { - let e = Vec2::polar(a, len, ang); - if e.is_finite() { - l.b.x = e.x; - l.b.y = e.y; - if length.is_some() { - used.insert("length"); - } - if num("angle").is_some() { - used.insert("angle"); - } - } - } - } - EntityKind::Circle(c) => { - if let Some(v) = p.get("center") { - set_xy(&mut c.center, v); - used.insert("center"); - } - if let Some(r) = num("radius").filter(|r| *r > 0.0) { - c.radius = r; - used.insert("radius"); - } - if let Some(dm) = num("diameter").filter(|r| *r > 0.0) { - c.radius = dm / 2.0; - used.insert("diameter"); - } - if let Some(cf) = num("circumference").filter(|x| *x > 0.0) { - c.radius = cf / cadcraft_geom::TAU; - used.insert("circumference"); - } - if let Some(a) = num("area").filter(|x| *x > 0.0) { - c.radius = (a / cadcraft_geom::PI).sqrt(); - used.insert("area"); - } - } - EntityKind::Arc(a) => { - if let Some(v) = p.get("center") { - set_xy(&mut a.center, v); - used.insert("center"); - } - if let Some(r) = num("radius").filter(|r| *r > 0.0) { - a.radius = r; - used.insert("radius"); - } - if let Some(x) = num("startAngle") { - a.start = cadcraft_geom::norm_angle(x.to_radians()); - used.insert("startAngle"); - } - if let Some(x) = num("endAngle") { - a.end = cadcraft_geom::norm_angle(x.to_radians()); - used.insert("endAngle"); - } - } + EntityKind::Line(l) => line(l, &c, &mut used), + EntityKind::Circle(ci) => circle(ci, &c, &mut used), + EntityKind::Arc(a) => arc(a, &c, &mut used), EntityKind::Text(t) => { - if let Some(v) = str_param(p, "text") { - t.value = v.to_string(); - used.insert("text"); - } - if let Some(st) = &text_style { - t.style.clone_from(st); - used.insert("style"); - } - if let Some(x) = num("height").filter(|x| *x > 0.0) { - t.height = x; - used.insert("height"); - } - if let Some(x) = num("rotation") { - t.rotation = x.to_radians(); - // Aligned and fit text run along their baseline's two ends: it turns too. - if matches!(t.halign, HAlign::Aligned | HAlign::Fit) - && let Some(end) = t.align_pt - { - let e = Vec2::polar(t.insert.xy(), t.insert.xy().dist(end.xy()), t.rotation); - t.align_pt = Some(Vec3::new(e.x, e.y, end.z)); - } - used.insert("rotation"); - } - if let Some(x) = num("widthFactor").filter(|x| *x > 0.0) { - t.width_factor = x; - used.insert("widthFactor"); - } - if let Some(x) = num("oblique").filter(|x| x.abs() <= 85.0) { - t.oblique = x.to_radians(); - used.insert("oblique"); - } - if let Some((ha, va)) = str_param(p, "justify").and_then(crate::cmd::draw::justify) { - set_justify(t, ha, va, prep.ends.get(&h).copied()); - used.insert("justify"); - } - // The position is the point the text is placed by: moving it moves the text. - if let Some(to) = p.get("position").and_then(point_value) { - shift(t, to - t.justify_point()); - used.insert("position"); - } - let (x, y) = (num("positionX"), num("positionY")); - if x.is_some() || y.is_some() { - let at = t.justify_point(); - shift(t, Vec2::new(x.unwrap_or(at.x), y.unwrap_or(at.y)) - at); - used.extend(["positionX", "positionY"].into_iter().filter(|k| num(k).is_some())); - } - if let Some(z) = num("positionZ") { - t.insert.z = z; - if let Some(a) = &mut t.align_pt { - a.z = z; - } - used.insert("positionZ"); - } - // Aligned and fit text: the second point alone (the text refits between them). - if matches!(t.halign, HAlign::Aligned | HAlign::Fit) - && let Some(a) = &mut t.align_pt - { - if let Some(x) = num("alignmentX") { - a.x = x; - used.insert("alignmentX"); - } - if let Some(y) = num("alignmentY") { - a.y = y; - used.insert("alignmentY"); - } - } - } - EntityKind::MText(t) => { - if let Some(v) = str_param(p, "text") { - t.contents = v.replace('\n', "\\P"); - used.insert("text"); - } - if let Some(st) = &text_style { - t.style.clone_from(st); - used.insert("style"); - } - if let Some(x) = num("height").filter(|x| *x > 0.0) { - t.height = x; - used.insert("height"); - } - if let Some(x) = num("width").filter(|x| *x >= 0.0) { - t.width = x; - used.insert("width"); - } - if let Some(x) = num("rotation") { - t.rotation = x.to_radians(); - used.insert("rotation"); - } - // The attachment point stays where it is; the text moves around it. - if let Some(n) = str_param(p, "justify").and_then(crate::cmd::mtext_opts::attach_code) { - t.attach = n; - used.insert("justify"); - } - // MTEXT's Line spacing option takes factors from 0.25 to 4. - let factor = |f: f64| f.is_finite() && (0.25 - 1e-9..=4.0 + 1e-9).contains(&f); - if let Some(x) = num("lineSpacing").filter(|x| factor(*x)) { - t.line_spacing = x; - used.insert("lineSpacing"); - } - if let Some(f) = num("lineSpacingDistance").map(|x| x / (t.height * LINE_PITCH)).filter(|f| factor(*f)) { - t.line_spacing = f; - used.insert("lineSpacingDistance"); - } - // "atLeast", "At least", "exactly"… - let spacing = str_param(p, "lineSpacingStyle") - .map(|v| v.chars().filter(char::is_ascii_alphabetic).collect::().to_ascii_lowercase()); - if let Some(exact) = match spacing.as_deref() { - Some("atleast") => Some(false), - Some("exactly") => Some(true), - _ => None, - } { - t.line_spacing_exact = exact; - used.insert("lineSpacingStyle"); - } - if let Some(to) = p.get("position").and_then(point_value) { - t.insert.x = to.x; - t.insert.y = to.y; - used.insert("position"); - } - for (k, slot) in [("positionX", &mut t.insert.x), ("positionY", &mut t.insert.y), ("positionZ", &mut t.insert.z)] { - if let Some(v) = num(k) { - *slot = v; - used.insert(k); - } - } + text(t, &c, h, &mut used); + text_position(t, &c, &mut used); } + EntityKind::MText(t) => mtext(t, &c, &mut used), EntityKind::LwPolyline(pl) => { - if let Some(x) = num("width").filter(|x| *x >= 0.0) { + if let Some(x) = c.num("width").filter(|x| *x >= 0.0) { pl.const_width = x; used.insert("width"); } - if let Some(c) = p.get("closed").and_then(Value::as_bool) { - pl.closed = c; + if let Some(closed) = p.get("closed").and_then(Value::as_bool) { + pl.closed = closed; used.insert("closed"); } } - EntityKind::Insert(i) => { - if let Some(x) = num("rotation") { - let turn = x.to_radians() - i.rotation; - i.rotation = x.to_radians(); - // The attached text turns with the reference, around its insertion point (as ROTATE does). - let base = i.insert.xy(); - for a in &mut i.attribs { - let t = &mut a.text; - for q in std::iter::once(&mut t.insert).chain(t.align_pt.as_mut()) { - let r = q.xy().rotate_about(base, turn); - q.x = r.x; - q.y = r.y; - } - t.rotation = cadcraft_geom::norm_angle(t.rotation + turn); - if let Some(ml) = &mut a.multiline { - let r = ml.mtext.insert.xy().rotate_about(base, turn); - ml.mtext.insert.x = r.x; - ml.mtext.insert.y = r.y; - ml.mtext.rotation = cadcraft_geom::norm_angle(ml.mtext.rotation + turn); - } - } - used.insert("rotation"); - } - if let Some(x) = num("scale").filter(|x| *x != 0.0) { - // A new positive scale carries the attached attribute text with it, like SCALE about the insertion point. - if x > 0.0 && i.scale.x > 0.0 { - let m = cadcraft_geom::Mat3::scale_about(i.insert.xy(), x / i.scale.x); - for a in &mut i.attribs { - let mut k = EntityKind::Text(a.text.clone()); - k.transform(&m); - if let EntityKind::Text(t) = k { - a.text = t; - } - a.transform_multiline(&m); - } - } - i.scale = Vec3::new(x, x, x); - used.insert("scale"); - } - } - EntityKind::Dimension(dm) => { - let before = dm.clone(); - if let Some(v) = str_param(p, "textOverride") { - dm.text = v.to_string(); - used.insert("textOverride"); - } - if let Some(st) = &dim_style { - dm.style.clone_from(st); - used.insert("dimStyle"); - } - // Overrides: clear first, then set (as DIMOVERRIDE does). - if p.get("clearOverrides").and_then(Value::as_bool) == Some(true) { - dm.overrides.clear(); - used.insert("clearOverrides"); - } - if let Some(names) = p.get("clear").and_then(Value::as_array) { - // Prefix and suffix rows reset DIMPOST (DIMAPOST), the variable they're halves of. - let field = |n: &str| match n { - "prefix" | "suffix" => Some("post"), - "altPrefix" | "altSuffix" => Some("altPost"), - n => DimStyle::field_name(n), - }; - for f in names.iter().filter_map(Value::as_str).filter_map(field) { - dm.overrides.retain(|k, _| DimStyle::field_name(k) != Some(f)); - } - used.insert("clear"); - } - for (f, v) in &dim_vars.fields { - set_override(dm, f, v.clone()); - } - used.extend(dim_vars.keys.iter().map(String::as_str)); - if let Some(x) = num("textRotation") { - dm.text_rotation = x.to_radians(); - used.insert("textRotation"); - } - let (x, y) = (num("textPositionX"), num("textPositionY")); - if x.is_some() || y.is_some() { - let at = prep.text_pos.get(&h).copied().unwrap_or_else(|| dm.text_mid.xy()); - dm.text_mid.x = x.unwrap_or(at.x); - dm.text_mid.y = y.unwrap_or(at.y); - dm.user_text_pos = true; - used.extend(["textPositionX", "textPositionY"].into_iter().filter(|k| num(k).is_some())); - } - if let Some(styles) = &prep.posts { - // The templates the dimension draws with after the edits above (its style, - // cleared and new overrides), which the prefix or suffix edit goes into. - let (post, alt) = styles.get(&dm.style.to_ascii_lowercase()).cloned().unwrap_or_default(); - let st = DimStyle { post, alt_post: alt, ..DimStyle::default() }.with_overrides(&dm.overrides); - for (field, template, keys) in - [("post", &st.post, ["prefix", "suffix"]), ("altPost", &st.alt_post, ["altPrefix", "altSuffix"])] - { - let (pre, suf) = (str_param(p, keys[0]), str_param(p, keys[1])); - if pre.is_some() || suf.is_some() { - let (pre0, suf0) = split_post(template); - set_override(dm, field, json!(join_post(pre.unwrap_or(&pre0), suf.unwrap_or(&suf0)))); - used.extend(keys.into_iter().filter(|k| str_param(p, k).is_some())); - } - } - } - // The geometry block read from a file no longer matches: draw and save it anew. - if *dm != before { - dm.block = None; - } - } - EntityKind::Hatch(h) => { - // HATCHEDIT's pattern edit (a blank name changes nothing, so it's ignored). - if let Some(v) = str_param(p, "pattern") - && crate::cmd::hatch::set_pattern(h, v) - { - used.insert("pattern"); - } - if let Some(x) = num("scale").filter(|x| *x > 0.0) { - h.scale = x; - used.insert("scale"); - } - if let Some(x) = num("angle") { - h.angle = x.to_radians(); - used.insert("angle"); - } - } + EntityKind::Insert(i) => insert(i, &c, &mut used), + EntityKind::Dimension(dm) => dimension(dm, &c, h, &mut used), + EntityKind::Hatch(ha) => hatch(ha, &c, &mut used), _ => {} } })?; @@ -625,3 +314,388 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { .unwrap_or_default(); Ok(json!({ "changed": hs.len(), "ignored": ignored })) } + +/// The properties every object has: annotative, layer, color, linetype, lineweight, linetype +/// scale, transparency, thickness and visibility. +fn common<'c>(e: &mut Entity, c: &'c Call<'_>, used: &mut Used<'c>) { + let p = c.p; + // Annotative: Yes supports the current annotation scale; No drops every scale. + if let Some(a) = p.get("annotative").and_then(Value::as_bool) + && cadcraft_doc::can_be_annotative(&e.kind) + { + cadcraft_doc::set_annotative(e, a, &c.anno_scale); + if let EntityKind::Dimension(dm) = &mut e.kind { + dm.block = None; + } + used.insert("annotative"); + } + if let Some(l) = str_param(p, "layer") { + e.common.layer = l.to_string(); + used.insert("layer"); + } + if let Some(color) = c.color { + e.common.color = color; + used.insert("color"); + } + if let Some(lt) = &c.linetype { + e.common.linetype.clone_from(lt); + used.insert("linetype"); + } + if let Some(w) = c.lineweight { + e.common.lineweight = w; + used.insert("lineweight"); + } + if let Some(x) = p.get("ltscale").and_then(Value::as_f64).filter(|x| *x > 0.0 && x.is_finite()) { + e.common.ltscale = x; + used.insert("ltscale"); + } + if let Some(t) = c.transparency { + e.common.transparency = t; + used.insert("transparency"); + } + if let Some(th) = c.thickness { + e.common.thickness = th; + used.insert("thickness"); + } + if let Some(v) = p.get("visible").and_then(Value::as_bool) { + e.common.visible = v; + used.insert("visible"); + } +} + +fn line(l: &mut Line, c: &Call<'_>, used: &mut Used<'_>) { + if let Some(v) = c.p.get("start") { + set_xy(&mut l.a, v); + used.insert("start"); + } + if let Some(v) = c.p.get("end") { + set_xy(&mut l.b, v); + used.insert("end"); + } + // Length / angle keep the start point and move the end point. + let (a, b) = (l.a.xy(), l.b.xy()); + let length = c.num("length").filter(|x| *x > 0.0 && *x < 1e15); + let len = length.unwrap_or_else(|| a.dist(b)); + let ang = c.num("angle").map(f64::to_radians).unwrap_or_else(|| a.angle_to(b)); + if length.is_some() || c.num("angle").is_some() { + let e = Vec2::polar(a, len, ang); + if e.is_finite() { + l.b.x = e.x; + l.b.y = e.y; + if length.is_some() { + used.insert("length"); + } + if c.num("angle").is_some() { + used.insert("angle"); + } + } + } +} + +fn circle(ci: &mut Circle, c: &Call<'_>, used: &mut Used<'_>) { + if let Some(v) = c.p.get("center") { + set_xy(&mut ci.center, v); + used.insert("center"); + } + if let Some(r) = c.num("radius").filter(|r| *r > 0.0) { + ci.radius = r; + used.insert("radius"); + } + if let Some(dm) = c.num("diameter").filter(|r| *r > 0.0) { + ci.radius = dm / 2.0; + used.insert("diameter"); + } + if let Some(cf) = c.num("circumference").filter(|x| *x > 0.0) { + ci.radius = cf / cadcraft_geom::TAU; + used.insert("circumference"); + } + if let Some(a) = c.num("area").filter(|x| *x > 0.0) { + ci.radius = (a / cadcraft_geom::PI).sqrt(); + used.insert("area"); + } +} + +fn arc(a: &mut Arc, c: &Call<'_>, used: &mut Used<'_>) { + if let Some(v) = c.p.get("center") { + set_xy(&mut a.center, v); + used.insert("center"); + } + if let Some(r) = c.num("radius").filter(|r| *r > 0.0) { + a.radius = r; + used.insert("radius"); + } + if let Some(x) = c.num("startAngle") { + a.start = cadcraft_geom::norm_angle(x.to_radians()); + used.insert("startAngle"); + } + if let Some(x) = c.num("endAngle") { + a.end = cadcraft_geom::norm_angle(x.to_radians()); + used.insert("endAngle"); + } +} + +/// TEXT's contents, style, size, angles and justification. +fn text(t: &mut Text, c: &Call<'_>, h: Handle, used: &mut Used<'_>) { + let p = c.p; + if let Some(v) = str_param(p, "text") { + t.value = v.to_string(); + used.insert("text"); + } + if let Some(st) = &c.text_style { + t.style.clone_from(st); + used.insert("style"); + } + if let Some(x) = c.num("height").filter(|x| *x > 0.0) { + t.height = x; + used.insert("height"); + } + if let Some(x) = c.num("rotation") { + t.rotation = x.to_radians(); + // Aligned and fit text run along their baseline's two ends: it turns too. + if matches!(t.halign, HAlign::Aligned | HAlign::Fit) + && let Some(end) = t.align_pt + { + let e = Vec2::polar(t.insert.xy(), t.insert.xy().dist(end.xy()), t.rotation); + t.align_pt = Some(Vec3::new(e.x, e.y, end.z)); + } + used.insert("rotation"); + } + if let Some(x) = c.num("widthFactor").filter(|x| *x > 0.0) { + t.width_factor = x; + used.insert("widthFactor"); + } + if let Some(x) = c.num("oblique").filter(|x| x.abs() <= 85.0) { + t.oblique = x.to_radians(); + used.insert("oblique"); + } + if let Some((ha, va)) = str_param(p, "justify").and_then(crate::cmd::draw::justify) { + set_justify(t, ha, va, c.prep.ends.get(&h).copied()); + used.insert("justify"); + } +} + +/// Where TEXT is: its position (the point it's placed by), and an aligned or fit text's second +/// point. +fn text_position(t: &mut Text, c: &Call<'_>, used: &mut Used<'_>) { + // The position is the point the text is placed by: moving it moves the text. + if let Some(to) = c.p.get("position").and_then(point_value) { + shift(t, to - t.justify_point()); + used.insert("position"); + } + let (x, y) = (c.num("positionX"), c.num("positionY")); + if x.is_some() || y.is_some() { + let at = t.justify_point(); + shift(t, Vec2::new(x.unwrap_or(at.x), y.unwrap_or(at.y)) - at); + used.extend(["positionX", "positionY"].into_iter().filter(|k| c.num(k).is_some())); + } + if let Some(z) = c.num("positionZ") { + t.insert.z = z; + if let Some(a) = &mut t.align_pt { + a.z = z; + } + used.insert("positionZ"); + } + // Aligned and fit text: the second point alone (the text refits between them). + if matches!(t.halign, HAlign::Aligned | HAlign::Fit) + && let Some(a) = &mut t.align_pt + { + if let Some(x) = c.num("alignmentX") { + a.x = x; + used.insert("alignmentX"); + } + if let Some(y) = c.num("alignmentY") { + a.y = y; + used.insert("alignmentY"); + } + } +} + +fn mtext(t: &mut MText, c: &Call<'_>, used: &mut Used<'_>) { + let p = c.p; + if let Some(v) = str_param(p, "text") { + t.contents = v.replace('\n', "\\P"); + used.insert("text"); + } + if let Some(st) = &c.text_style { + t.style.clone_from(st); + used.insert("style"); + } + if let Some(x) = c.num("height").filter(|x| *x > 0.0) { + t.height = x; + used.insert("height"); + } + if let Some(x) = c.num("width").filter(|x| *x >= 0.0) { + t.width = x; + used.insert("width"); + } + if let Some(x) = c.num("rotation") { + t.rotation = x.to_radians(); + used.insert("rotation"); + } + // The attachment point stays where it is; the text moves around it. + if let Some(n) = str_param(p, "justify").and_then(crate::cmd::mtext_opts::attach_code) { + t.attach = n; + used.insert("justify"); + } + mtext_spacing(t, c, used); + if let Some(to) = p.get("position").and_then(point_value) { + t.insert.x = to.x; + t.insert.y = to.y; + used.insert("position"); + } + for (k, slot) in [("positionX", &mut t.insert.x), ("positionY", &mut t.insert.y), ("positionZ", &mut t.insert.z)] { + if let Some(v) = c.num(k) { + *slot = v; + used.insert(k); + } + } +} + +/// MTEXT's line spacing: a factor, a distance, or its style. +fn mtext_spacing(t: &mut MText, c: &Call<'_>, used: &mut Used<'_>) { + // MTEXT's Line spacing option takes factors from 0.25 to 4. + let factor = |f: f64| f.is_finite() && (0.25 - 1e-9..=4.0 + 1e-9).contains(&f); + if let Some(x) = c.num("lineSpacing").filter(|x| factor(*x)) { + t.line_spacing = x; + used.insert("lineSpacing"); + } + if let Some(f) = c.num("lineSpacingDistance").map(|x| x / (t.height * LINE_PITCH)).filter(|f| factor(*f)) { + t.line_spacing = f; + used.insert("lineSpacingDistance"); + } + // "atLeast", "At least", "exactly"… + let spacing = str_param(c.p, "lineSpacingStyle").map(|v| v.chars().filter(char::is_ascii_alphabetic).collect::().to_ascii_lowercase()); + if let Some(exact) = match spacing.as_deref() { + Some("atleast") => Some(false), + Some("exactly") => Some(true), + _ => None, + } { + t.line_spacing_exact = exact; + used.insert("lineSpacingStyle"); + } +} + +fn insert(i: &mut Insert, c: &Call<'_>, used: &mut Used<'_>) { + if let Some(x) = c.num("rotation") { + let turn = x.to_radians() - i.rotation; + i.rotation = x.to_radians(); + // The attached text turns with the reference, around its insertion point (as ROTATE does). + let base = i.insert.xy(); + for a in &mut i.attribs { + let t = &mut a.text; + for q in std::iter::once(&mut t.insert).chain(t.align_pt.as_mut()) { + let r = q.xy().rotate_about(base, turn); + q.x = r.x; + q.y = r.y; + } + t.rotation = cadcraft_geom::norm_angle(t.rotation + turn); + if let Some(ml) = &mut a.multiline { + let r = ml.mtext.insert.xy().rotate_about(base, turn); + ml.mtext.insert.x = r.x; + ml.mtext.insert.y = r.y; + ml.mtext.rotation = cadcraft_geom::norm_angle(ml.mtext.rotation + turn); + } + } + used.insert("rotation"); + } + if let Some(x) = c.num("scale").filter(|x| *x != 0.0) { + // A new positive scale carries the attached attribute text with it, like SCALE about the insertion point. + if x > 0.0 && i.scale.x > 0.0 { + let m = cadcraft_geom::Mat3::scale_about(i.insert.xy(), x / i.scale.x); + for a in &mut i.attribs { + let mut k = EntityKind::Text(a.text.clone()); + k.transform(&m); + if let EntityKind::Text(t) = k { + a.text = t; + } + a.transform_multiline(&m); + } + } + i.scale = Vec3::new(x, x, x); + used.insert("scale"); + } +} + +fn dimension<'c>(dm: &mut Dimension, c: &'c Call<'_>, h: Handle, used: &mut Used<'c>) { + let p = c.p; + let before = dm.clone(); + if let Some(v) = str_param(p, "textOverride") { + dm.text = v.to_string(); + used.insert("textOverride"); + } + if let Some(st) = &c.dim_style { + dm.style.clone_from(st); + used.insert("dimStyle"); + } + // Overrides: clear first, then set (as DIMOVERRIDE does). + if p.get("clearOverrides").and_then(Value::as_bool) == Some(true) { + dm.overrides.clear(); + used.insert("clearOverrides"); + } + if let Some(names) = p.get("clear").and_then(Value::as_array) { + // Prefix and suffix rows reset DIMPOST (DIMAPOST), the variable they're halves of. + let field = |n: &str| match n { + "prefix" | "suffix" => Some("post"), + "altPrefix" | "altSuffix" => Some("altPost"), + n => DimStyle::field_name(n), + }; + for f in names.iter().filter_map(Value::as_str).filter_map(field) { + dm.overrides.retain(|k, _| DimStyle::field_name(k) != Some(f)); + } + used.insert("clear"); + } + for (f, v) in &c.dim_vars.fields { + set_override(dm, f, v.clone()); + } + used.extend(c.dim_vars.keys.iter().map(String::as_str)); + if let Some(x) = c.num("textRotation") { + dm.text_rotation = x.to_radians(); + used.insert("textRotation"); + } + let (x, y) = (c.num("textPositionX"), c.num("textPositionY")); + if x.is_some() || y.is_some() { + let at = c.prep.text_pos.get(&h).copied().unwrap_or_else(|| dm.text_mid.xy()); + dm.text_mid.x = x.unwrap_or(at.x); + dm.text_mid.y = y.unwrap_or(at.y); + dm.user_text_pos = true; + used.extend(["textPositionX", "textPositionY"].into_iter().filter(|k| c.num(k).is_some())); + } + dimension_posts(dm, c, used); + // The geometry block read from a file no longer matches: draw and save it anew. + if *dm != before { + dm.block = None; + } +} + +/// A dimension's prefix and suffix edits, which go into the DIMPOST and DIMAPOST templates it +/// draws with after the call's other edits (its style, cleared and new overrides). +fn dimension_posts(dm: &mut Dimension, c: &Call<'_>, used: &mut Used<'_>) { + let Some(styles) = &c.prep.posts else { return }; + let (post, alt) = styles.get(&dm.style.to_ascii_lowercase()).cloned().unwrap_or_default(); + let st = DimStyle { post, alt_post: alt, ..DimStyle::default() }.with_overrides(&dm.overrides); + for (field, template, keys) in [("post", &st.post, ["prefix", "suffix"]), ("altPost", &st.alt_post, ["altPrefix", "altSuffix"])] { + let (pre, suf) = (str_param(c.p, keys[0]), str_param(c.p, keys[1])); + if pre.is_some() || suf.is_some() { + let (pre0, suf0) = split_post(template); + set_override(dm, field, json!(join_post(pre.unwrap_or(&pre0), suf.unwrap_or(&suf0)))); + used.extend(keys.into_iter().filter(|k| str_param(c.p, k).is_some())); + } + } +} + +fn hatch(ha: &mut Hatch, c: &Call<'_>, used: &mut Used<'_>) { + // HATCHEDIT's pattern edit (a blank name changes nothing, so it's ignored). + if let Some(v) = str_param(c.p, "pattern") + && crate::cmd::hatch::set_pattern(ha, v) + { + used.insert("pattern"); + } + if let Some(x) = c.num("scale").filter(|x| *x > 0.0) { + ha.scale = x; + used.insert("scale"); + } + if let Some(x) = c.num("angle") { + ha.angle = x.to_radians(); + used.insert("angle"); + } +} From 56892037919cc8f43c2a767f1cffe2f5b06d7dcd Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Sat, 31 Oct 2026 00:34:46 -0400 Subject: [PATCH 05/41] Dimensions: an explicit text rotation sizes the dimension line's gap A linear or aligned dimension broke its line around the text as DIMTIH and DIMTOH turn it, and only then applied an explicit text rotation (DIMTEDIT Angle, or Text rotation in the Properties palette). Text turned along a vertical dimension line drew over the line, which left a gap only the height of horizontal text, whatever the text offset (DIMGAP). The gap, the fit check and the text's clearance now take the text as turned. Found by testing #1042 (Dievartis). A test checks that no part of the dimension line crosses text turned along it. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/dim/linear.rs | 20 +++++++++++++++++--- crates/render/src/dim/tests.rs | 15 +++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/crates/render/src/dim/linear.rs b/crates/render/src/dim/linear.rs index da1b2a746..3dc740186 100644 --- a/crates/render/src/dim/linear.rs +++ b/crates/render/src/dim/linear.rs @@ -77,7 +77,7 @@ fn prepare_linear(config: &DimConfig<'_>, g: &mut DimGeometry, text_mid: Vec2) - let axis = Vec2::from_angle(angle); (text_width * axis.dot(u).abs() + text_height * axis.perp().dot(u).abs()) / 2.0 }; - let inside_angle = if st.text_inside_horizontal { 0.0 } else { along_angle }; + let inside_angle = text_angle(config, st.text_inside_horizontal, along_angle); let tvp = if st.text_above == 0 && st.text_vertical_pos.is_finite() { st.text_vertical_pos } else { 0.0 }; let centred = st.text_above == 0 && tvp.abs() < 0.7; let text_need = if centred { 2.0 * (extent(inside_angle) + config.gap) } else { 2.0 * extent(inside_angle) }; @@ -129,6 +129,20 @@ fn prepare_linear(config: &DimConfig<'_>, g: &mut DimGeometry, text_mid: Vec2) - } } +/// The text's angle: an explicit text rotation (DIMTEDIT Angle, the Properties palette's Text +/// rotation) turns it, so the dimension line leaves room for the text as turned; otherwise +/// horizontal (DIMTIH inside, DIMTOH outside) or `along` the line. +fn text_angle(config: &DimConfig<'_>, horizontal: bool, along: f64) -> f64 { + let rotation = config.dimension.text_rotation; + if rotation != 0.0 && rotation.is_finite() { + rotation + } else if horizontal { + 0.0 + } else { + along + } +} + fn position_linear_text(config: &DimConfig<'_>, state: &mut LinearDimState) { let st = config.style; let along_angle = readable(state.u.angle()); @@ -136,8 +150,8 @@ fn position_linear_text(config: &DimConfig<'_>, state: &mut LinearDimState) { let axis = Vec2::from_angle(angle); (state.text_width * axis.dot(state.u).abs() + state.text_height * axis.perp().dot(state.u).abs()) / 2.0 }; - let inside_angle = if st.text_inside_horizontal { 0.0 } else { along_angle }; - state.angle = if state.text_outside { if st.text_outside_horizontal { 0.0 } else { along_angle } } else { inside_angle }; + let inside_angle = text_angle(config, st.text_inside_horizontal, along_angle); + state.angle = if state.text_outside { text_angle(config, st.text_outside_horizontal, along_angle) } else { inside_angle }; state.half_extent = extent(state.angle); state.along_center = if state.text_outside { state.f2 + state.u * (2.0 * config.arrow_size.max(config.tick_size) + config.gap + state.half_extent) diff --git a/crates/render/src/dim/tests.rs b/crates/render/src/dim/tests.rs index 15001c6b7..ff32f6242 100644 --- a/crates/render/src/dim/tests.rs +++ b/crates/render/src/dim/tests.rs @@ -201,6 +201,21 @@ fn text_alignment_vertical_dimension() { assert!((a.text_angle - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "aligned: {}", a.text_angle); } +#[test] +fn explicit_text_rotation_widens_the_dimension_line_gap() { + // A vertical dimension's text, horizontal by DIMTIH, turned along the line (DIMTEDIT Angle, + // the Properties palette's Text rotation): the line's gap fits the text as turned. + let mut d = lin((0.0, 0.0), (0.0, 40.0), (5.0, 0.0), std::f64::consts::FRAC_PI_2); + d.text_rotation = std::f64::consts::FRAC_PI_2; + let g = dimension_geometry(&d, &DimStyle::default(), 1.0); + let text = bbox(&g.text); + assert!(text.height() > 2.0 * text.width(), "turned along the line: {text:?}"); + for l in g.lines_of(LineRole::Dim) { + let b = bbox(std::slice::from_ref(l)); + assert!(b.max.y <= text.min.y + 1e-9 || b.min.y >= text.max.y - 1e-9, "the dimension line {l:?} crosses the text {text:?}"); + } +} + #[test] fn justification_moves_text() { let d = lin((0.0, 0.0), (10.0, 0.0), (0.0, 5.0), 0.0); From 5c24bc3dcfeab831ff09adbae1ba484cce172993 Mon Sep 17 00:00:00 2001 From: eldrir Date: Tue, 13 Oct 2026 12:04:40 -0400 Subject: [PATCH 06/41] Properties palette: text, mtext and dimension rows from properties.describe The palette draws the groups the engine describes for text, mtext and dimensions after its own General group, so a dimension's text height (and every other dimension style setting) is edited there as an override of the selected dimensions, and TEXT and MTEXT get their style, justification, obliquing, line spacing and position rows. Several objects of one type edit together, with *VARIES* where they differ. Rows read values as the command line does (distances in any unit format, angles in the drawing's angle units); unreadable text and values the engine refuses are reported. An overridden dimension row has its label in the accent color, and right-clicking it puts the style's value back. A fixed-height text style's height shows read-only with the reason. A few engine labels are renamed to translate cleanly and fit the label column; every label the engine gives the palette has a Ukrainian row, and `cargo xtask i18n` reports any that go missing. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/properties.rs | 47 ++-- crates/engine/tests/it/properties_describe.rs | 17 ++ crates/ui-egui/src/i18n/tests.rs | 38 ++++ crates/ui-egui/src/i18n/uk.tsv | 143 ++++++++++++ crates/ui-egui/src/palettes.rs | 58 ++--- crates/ui-egui/src/palettes/described.rs | 215 ++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + .../ui-egui/tests/it/properties_described.rs | 172 ++++++++++++++ 8 files changed, 630 insertions(+), 61 deletions(-) create mode 100644 crates/ui-egui/src/palettes/described.rs create mode 100644 crates/ui-egui/tests/it/properties_described.rs diff --git a/crates/engine/src/properties.rs b/crates/engine/src/properties.rs index 425d5f645..db0d37438 100644 --- a/crates/engine/src/properties.rs +++ b/crates/engine/src/properties.rs @@ -127,6 +127,10 @@ pub enum Kind { Distance, /// An angle in degrees. Angle, + /// A direction (a text's rotation): `value` is in degrees counterclockwise from +X, as + /// `properties.set` takes it; `display` shows it as the drawing measures directions, from + /// ANGBASE in the ANGDIR sense (#1275). + Direction, Bool, /// One of `options`. Choice, @@ -190,12 +194,20 @@ struct Ctx<'a> { luprec: i64, aunits: i64, auprec: i64, + angles: units::AngleSettings, } impl<'a> Ctx<'a> { fn new(d: &'a Drawing) -> Self { let h = &d.header; - Ctx { d, lunits: h.i64("LUNITS", 2), luprec: h.i64("LUPREC", 4), aunits: h.i64("AUNITS", 0), auprec: h.i64("AUPREC", 0) } + Ctx { + d, + lunits: h.i64("LUNITS", 2), + luprec: h.i64("LUPREC", 4), + aunits: h.i64("AUNITS", 0), + auprec: h.i64("AUPREC", 0), + angles: units::AngleSettings::from_header(h), + } } fn distance(&self, v: f64) -> String { @@ -212,6 +224,7 @@ impl<'a> Ctx<'a> { Kind::Distance => v.as_f64().map(|x| self.distance(x)).unwrap_or_default(), Kind::Number => v.as_f64().map(|x| format!("{x:.4}")).unwrap_or_default(), Kind::Angle => v.as_f64().map(|x| self.angle(x)).unwrap_or_default(), + Kind::Direction => v.as_f64().map(|x| self.angle(self.angles.shown(x.to_radians()).to_degrees())).unwrap_or_default(), Kind::Bool => (if v.as_bool() == Some(true) { "Yes" } else { "No" }).to_string(), Kind::Choice => options.iter().find(|o| o.value == *v).map(|o| o.label.clone()).unwrap_or_else(|| plain(v)), _ => plain(v), @@ -271,7 +284,7 @@ pub const TEXT_JUSTIFY: &[(&str, &str)] = &[ ("Left", "Left"), ("Center", "Center"), ("Right", "Right"), - ("Align", "Aligned"), + ("Align", "Align"), ("Middle", "Middle"), ("Fit", "Fit"), ("TL", "Top left"), @@ -333,9 +346,9 @@ fn text_groups(c: &Ctx, ents: &[&Entity], texts: &[&Text]) -> Vec { c.row("text", "Contents", Kind::Text, texts.iter().map(|t| json!(t.value))).quick(), c.choice("style", "Style", Kind::TextStyle, c.text_styles(), texts.iter().map(|t| json!(t.style))).quick(), annotative(c, ents), - c.choice("justify", "Justify", Kind::Choice, options(TEXT_JUSTIFY), texts.iter().map(|t| json!(text_justify(t)))).quick(), + c.choice("justify", "Justification", Kind::Choice, options(TEXT_JUSTIFY), texts.iter().map(|t| json!(text_justify(t)))).quick(), c.row("height", "Height", Kind::Distance, texts.iter().map(|t| json!(t.height))).quick(), - c.row("rotation", "Rotation", Kind::Angle, texts.iter().map(|t| json!(t.rotation.to_degrees()))).quick(), + c.row("rotation", "Rotation", Kind::Direction, texts.iter().map(|t| json!(t.rotation.to_degrees()))).quick(), c.row("widthFactor", "Width factor", Kind::Number, texts.iter().map(|t| json!(t.width_factor))), c.row("oblique", "Obliquing", Kind::Angle, texts.iter().map(|t| json!(t.oblique.to_degrees()))), ]; @@ -368,9 +381,9 @@ fn mtext_groups(c: &Ctx, ents: &[&Entity], mts: &[&MText]) -> Vec { c.row("text", "Contents", Kind::Contents, mts.iter().map(|t| json!(t.contents))).quick(), c.choice("style", "Style", Kind::TextStyle, c.text_styles(), mts.iter().map(|t| json!(t.style))).quick(), annotative(c, ents), - c.choice("justify", "Justify", Kind::Choice, options(MTEXT_JUSTIFY), mts.iter().map(|t| json!(mtext_justify(t.attach)))).quick(), + c.choice("justify", "Justification", Kind::Choice, options(MTEXT_JUSTIFY), mts.iter().map(|t| json!(mtext_justify(t.attach)))).quick(), c.row("height", "Text height", Kind::Distance, mts.iter().map(|t| json!(t.height))).quick(), - c.row("rotation", "Rotation", Kind::Angle, mts.iter().map(|t| json!(t.rotation.to_degrees()))).quick(), + c.row("rotation", "Rotation", Kind::Direction, mts.iter().map(|t| json!(t.rotation.to_degrees()))).quick(), c.row("lineSpacing", "Line space factor", Kind::Number, mts.iter().map(|t| json!(t.line_spacing))), c.row("lineSpacingDistance", "Line space distance", Kind::Distance, mts.iter().map(|t| json!(t.line_spacing * t.height * LINE_PITCH))), c.choice( @@ -455,7 +468,7 @@ const ALT_UNITS: &[(i64, &str)] = &[ (8, "Windows desktop"), ]; const ANGLE_FORMAT: &[(i64, &str)] = &[(0, "Decimal degrees"), (1, "Degrees Minutes Seconds"), (2, "Gradians"), (3, "Radians")]; -const FRACTION_FORMAT: &[(i64, &str)] = &[(0, "Horizontal"), (1, "Diagonal"), (2, "Not stacked")]; +const FRACTION_FORMAT: &[(i64, &str)] = &[(0, "Horizontal stacking"), (1, "Diagonal stacking"), (2, "Not stacked")]; const TOL_POS: &[(i64, &str)] = &[(0, "Bottom"), (1, "Middle"), (2, "Top")]; const ARC_SYMBOL: &[(i64, &str)] = &[(0, "Before text"), (1, "Above text"), (2, "None")]; @@ -472,8 +485,8 @@ pub const DIM_PROPS: &[DimProp] = &[ prop("dimLinetype", "Lines & Arrows", "Dim line linetype", DimPropKind::Linetype), prop("dimLineweight", "Lines & Arrows", "Dim line lineweight", DimPropKind::Lineweight), prop("dimLineExtend", "Lines & Arrows", "Dim line ext", DimPropKind::Distance), - prop("suppressDim1", "Lines & Arrows", "Suppress dim line 1", DimPropKind::Bool), - prop("suppressDim2", "Lines & Arrows", "Suppress dim line 2", DimPropKind::Bool), + prop("suppressDim1", "Lines & Arrows", "Hide dim line 1", DimPropKind::Bool), + prop("suppressDim2", "Lines & Arrows", "Hide dim line 2", DimPropKind::Bool), prop("extLineColor", "Lines & Arrows", "Ext line color", DimPropKind::Color), prop("extLinetype1", "Lines & Arrows", "Ext line 1 linetype", DimPropKind::Linetype), prop("extLinetype2", "Lines & Arrows", "Ext line 2 linetype", DimPropKind::Linetype), @@ -481,9 +494,9 @@ pub const DIM_PROPS: &[DimProp] = &[ prop("extExtend", "Lines & Arrows", "Ext line ext", DimPropKind::Distance), prop("extOffset", "Lines & Arrows", "Ext line offset", DimPropKind::Distance), prop("fixedExt", "Lines & Arrows", "Ext line fixed", DimPropKind::Bool), - prop("fixedExtLength", "Lines & Arrows", "Ext line fixed length", DimPropKind::Distance), - prop("suppressExt1", "Lines & Arrows", "Suppress ext line 1", DimPropKind::Bool), - prop("suppressExt2", "Lines & Arrows", "Suppress ext line 2", DimPropKind::Bool), + prop("fixedExtLength", "Lines & Arrows", "Ext line length", DimPropKind::Distance), + prop("suppressExt1", "Lines & Arrows", "Hide ext line 1", DimPropKind::Bool), + prop("suppressExt2", "Lines & Arrows", "Hide ext line 2", DimPropKind::Bool), prop("centerMark", "Lines & Arrows", "Center mark size", DimPropKind::Distance), prop("jogAngle", "Lines & Arrows", "Jog angle", DimPropKind::Angle), prop("arcSymbol", "Lines & Arrows", "Arc length symbol", DimPropKind::Choice(ARC_SYMBOL)), @@ -501,7 +514,7 @@ pub const DIM_PROPS: &[DimProp] = &[ style_only("textVerticalPos", "Text", "Text vertical position", DimPropKind::Number), // Fit prop("forceLineInside", "Fit", "Dim line forced", DimPropKind::Bool), - prop("suppressOutsideArrows", "Fit", "Suppress arrows outside", DimPropKind::Bool), + prop("suppressOutsideArrows", "Fit", "Suppress arrows", DimPropKind::Bool), prop("scale", "Fit", "Dim scale overall", DimPropKind::Number), prop("fit", "Fit", "Fit", DimPropKind::Choice(FIT)), prop("textInside", "Fit", "Text inside", DimPropKind::Bool), @@ -529,10 +542,10 @@ pub const DIM_PROPS: &[DimProp] = &[ // Tolerances prop("tolerance", "Tolerances", "Tolerances", DimPropKind::Bool), prop("limits", "Tolerances", "Limits", DimPropKind::Bool), - prop("tolPlus", "Tolerances", "Tolerance limit upper", DimPropKind::Number), - prop("tolMinus", "Tolerances", "Tolerance limit lower", DimPropKind::Number), + prop("tolPlus", "Tolerances", "Upper tolerance", DimPropKind::Number), + prop("tolMinus", "Tolerances", "Lower tolerance", DimPropKind::Number), prop("tolDecimals", "Tolerances", "Tolerance precision", DimPropKind::Precision), - prop("tolScale", "Tolerances", "Tolerance text height", DimPropKind::Number), + prop("tolScale", "Tolerances", "Tolerance height", DimPropKind::Number), prop("tolJust", "Tolerances", "Tolerance pos vert", DimPropKind::Choice(TOL_POS)), style_only("tolZeroSuppression", "Tolerances", "Tolerance zero suppression", DimPropKind::Number), ]; @@ -545,7 +558,7 @@ pub const ARROWHEADS: &[(&str, &str)] = &[ ("_DOT", "Dot"), ("_ARCHTICK", "Architectural tick"), ("_OBLIQUE", "Oblique"), - ("_OPEN", "Open"), + ("_OPEN", "Open arrow"), ("_ORIGIN", "Origin indicator"), ("_ORIGIN2", "Origin indicator 2"), ("_OPEN90", "Right angle"), diff --git a/crates/engine/tests/it/properties_describe.rs b/crates/engine/tests/it/properties_describe.rs index 193f669ea..e5be2de68 100644 --- a/crates/engine/tests/it/properties_describe.rs +++ b/crates/engine/tests/it/properties_describe.rs @@ -182,3 +182,20 @@ fn hostile_requests_never_panic() { // Duplicates count once. assert_eq!(describe(&mut s, json!({ "handles": [t, t] }))["count"], 1); } + +#[test] +fn rotations_show_as_the_drawing_measures_directions() { + let mut s = Session::new(); + s.execute("text", &json!({ "at": [0, 0], "text": "N", "height": 1, "rotation": 2.22729505553431 })).unwrap(); + // Clockwise from north (ANGBASE 90, ANGDIR 1): AutoCAD shows the text turned 2.23° as 87.77 + // (#1275); the value stays from +X counterclockwise, as properties.set takes it. + for (name, value) in [("ANGDIR", json!(1)), ("ANGBASE", json!(90)), ("AUPREC", json!(2))] { + s.execute("setvar", &json!({ "name": name, "value": value })).unwrap(); + } + let h = last(&s); + let desc = describe(&mut s, json!({ "handles": [h] })); + let r = row(&desc, "Text", "rotation"); + assert_eq!(r["kind"], "direction"); + assert_eq!(r["display"], "87.77"); + assert!((r["value"].as_f64().unwrap() - 2.22729505553431).abs() < 1e-9); +} diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index f9f41c798..73f3907bc 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -59,6 +59,7 @@ fn translation_gaps() { for language in translated() { let mut missing: BTreeSet = missing_commands_menus_tools_and_snap_labels(language.code).into_iter().collect(); missing.extend(missing_marked_ui_literals(language.code)); + missing.extend(missing_property_labels(language.code)); if missing.is_empty() { println!("{}: nothing missing", language.code); continue; @@ -70,6 +71,43 @@ fn translation_gaps() { } } +/// The labels the engine gives the Properties palette (`properties.describe`) for text, fit +/// text, mtext and dimensions: group names, row labels and the labels of choices. Part of the +/// report above. +fn missing_property_labels(language: &str) -> Vec { + use cadcraft_engine::properties::{Kind, describe}; + let catalog = catalog(language).unwrap(); + let mut s = Session::new(); + for (cmd, p) in [ + ("text", json!({ "at": [0, 0], "text": "A", "height": 1 })), + ("text", json!({ "at": [0, 5], "text": "B", "height": 1, "justify": "Fit" })), + ("mtext", json!({ "at": [0, 10], "text": "C", "height": 1 })), + ("dimlinear", json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })), + ] { + s.execute(cmd, &p).unwrap(); + } + let d = s.doc().unwrap(); + let mut labels = BTreeSet::new(); + for e in d.model.iter() { + for g in describe(d, &[e.handle], None).groups { + labels.insert(g.name.to_string()); + for r in g.rows { + labels.insert(r.label.to_string()); + if r.kind == Kind::Choice { + labels.extend(r.options.into_iter().map(|o| o.label)); + } + } + } + } + labels.extend(["Yes", "No"].map(String::from)); + // Numbers (precisions, lineweights in mm) aren't words to translate. + labels + .into_iter() + .filter(|l| l.chars().any(char::is_alphabetic) && !l.ends_with(" mm")) + .filter(|l| !catalog.contains_key(&("", l.as_str()))) + .collect() +} + fn missing_commands_menus_tools_and_snap_labels(language: &str) -> Vec { let catalog = catalog(language).unwrap(); let mut sources = BTreeSet::new(); diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 91be500de..708f7abed 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1391,3 +1391,146 @@ Text to find Text to find Whole words Whole words Nothing found Nothing found +# Properties palette: text, mtext and dimension rows (properties.describe) + Overrides the dimension style. Right-click to use the style's value. Перевизначає розмірний стиль. Клацніть правою кнопкою, щоб використати значення стилю. + Use the style's value Використати значення стилю + Set by text style "{style}", which has a fixed height. Give the style a height of 0 to use the dimension text height. Задано текстовим стилем «{style}» із фіксованою висотою. Задайте стилю висоту 0, щоб використовувати висоту тексту розміру. + Some of these dimensions take their text height from a fixed-height text style. Деякі з цих розмірів беруть висоту тексту з текстового стилю з фіксованою висотою. + {property}: that value can't be used here. {property}: це значення тут не можна використати. + Misc Інше + Lines & Arrows Лінії та стрілки + Fit Вписування + Primary Units Основні одиниці + Alternate Units Альтернативні одиниці + Tolerances Допуски + Style Стиль + Annotative Анотативний + Justification Вирівнювання + Obliquing Кут нахилу + Text alignment X Точка вирівнювання X + Text alignment Y Точка вирівнювання Y + Columns Стовпці + Line space factor Коефіцієнт міжрядкового інтервалу + Line space distance Міжрядковий інтервал + Line space style Тип міжрядкового інтервалу + At least Не менше + Exactly Точно + Middle Посередині + Top center Угорі по центру + Middle left Посередині ліворуч + Middle center Посередині по центру + Middle right Посередині праворуч + Bottom center Унизу по центру + Top Угорі + Bottom Унизу + Arrow 1 Стрілка 1 + Arrow 2 Стрілка 2 + Arrow size Розмір стрілки + Tick size Розмір засічки + Dim line color Колір розмірної лінії + Dim line linetype Тип розмірної лінії + Dim line lineweight Товщина розмірної лінії + Dim line ext Подовження розмірної лінії + Hide dim line 1 Приховати розмірну лінію 1 + Hide dim line 2 Приховати розмірну лінію 2 + Ext line color Колір виносної лінії + Ext line 1 linetype Тип виносної лінії 1 + Ext line 2 linetype Тип виносної лінії 2 + Ext line lineweight Товщина виносної лінії + Ext line ext Подовження виносної лінії + Ext line offset Відступ виносної лінії + Ext line fixed Фіксована виносна лінія + Ext line length Довжина виносної лінії + Hide ext line 1 Приховати виносну лінію 1 + Hide ext line 2 Приховати виносну лінію 2 + Center mark size Розмір маркера центру + Jog angle Кут зламу + Arc length symbol Символ довжини дуги + Before text Перед текстом + Above text Над текстом + Text offset Відступ тексту + Text outside align Вирівнювання тексту зовні + Text pos hor Положення тексту по горизонталі + Text pos vert Положення тексту по вертикалі + Text inside align Вирівнювання тексту всередині + Text position X Положення тексту X + Text position Y Положення тексту Y + Text rotation Поворот тексту + Measurement Вимір + At Ext Line 1 Біля виносної лінії 1 + At Ext Line 2 Біля виносної лінії 2 + Over Ext Line 1 Над виносною лінією 1 + Over Ext Line 2 Над виносною лінією 2 + Above Над лінією + Below Під лінією + Outside Зовні + JIS JIS + Dim line forced Примусова розмірна лінія + Suppress arrows Приховувати стрілки, що не вміщуються + Dim scale overall Загальний масштаб розміру + Text inside Текст усередині + Text movement Переміщення тексту + Text and arrows Текст і стрілки + Arrows Стрілки + Best fit Найкраще вписування + Keep dim line with text Розмірна лінія рухається з текстом + Move text, add leader Перемістити текст і додати виноску + Move text, no leader Перемістити текст без виноски + Decimal separator Десятковий роздільник + Period Крапка + Comma Кома + Space Пробіл + Dim prefix Префікс розміру + Dim roundoff Округлення розміру + Dim scale linear Лінійний масштаб розміру + Dim suffix Суфікс розміру + Dim units Одиниці розміру + Scientific Науковий + Decimal Десятковий + Engineering Інженерний + Architectural Архітектурний + Fractional Дробовий + Windows desktop Як у Windows + Architectural stacked Архітектурний (дріб стовпчиком) + Fractional stacked Дробовий (дріб стовпчиком) + Precision Точність + Fraction format Формат дробу + Horizontal stacking Горизонтальний дріб + Diagonal stacking Діагональний дріб + Not stacked Дріб у рядок + Angle format Формат кута + Decimal degrees Десяткові градуси + Degrees Minutes Seconds Градуси, мінути, секунди + Gradians Гради + Radians Радіани + Angle precision Точність кута + Alt enabled Альтернативні одиниці ввімкнено + Alt format Формат альтернативних одиниць + Alt precision Точність альтернативних одиниць + Alt scale factor Коефіцієнт альтернативних одиниць + Alt round Округлення альтернативних одиниць + Alt prefix Префікс альтернативних одиниць + Alt suffix Суфікс альтернативних одиниць + Limits Граничні розміри + Upper tolerance Верхнє відхилення + Lower tolerance Нижнє відхилення + Tolerance precision Точність допуску + Tolerance height Висота допуску + Tolerance pos vert Вертикальне положення допуску + Closed filled Замкнена зафарбована + Closed blank Замкнена порожня + Dot Точка + Architectural tick Архітектурна засічка + Open arrow Відкрита стрілка + Origin indicator Позначка початку + Origin indicator 2 Позначка початку 2 + Right angle Прямий кут + Open 30 Відкрита 30 + Dot small Мала точка + Dot blank Порожня точка + Small Мала + Box blank Порожній квадрат + Box filled Зафарбований квадрат + Datum triangle Базовий трикутник + Datum triangle filled Зафарбований базовий трикутник + Integral Інтеграл diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index 7e01a15d4..4130a1d77 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -9,6 +9,8 @@ use crate::CadApp; use crate::icons::{self, Icon}; use crate::theme::Tokens; +/// Rows the engine describes (text, mtext, dimensions). +mod described; #[cfg(test)] mod layer_menu_tests; /// The hatch pattern picker. @@ -993,7 +995,11 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { }); }); }); - if sel.len() == 1 { + // Text, mtext and dimensions: the rows the engine describes, for one or many of them. + let desc = described::described(ui, app, &sel); + let mut edit: Option = None; + let drawn = desc.as_ref().is_some_and(|desc| described::groups(ui, d, desc, &ids, &mut edit, &mut bad)); + if !drawn && sel.len() == 1 { group(ui, "Geometry"); let real = |v: f64| format!("{v:.4}"); // Rotations show as the drawing measures directions (ANGBASE, ANGDIR). @@ -1057,25 +1063,6 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { num(ui, "Start angle", "startAngle", real(a.start.to_degrees()), &mut set, &mut bad, &ids); num(ui, "End angle", "endAngle", real(a.end.to_degrees()), &mut set, &mut bad, &ids); } - EntityKind::Text(tx) => { - prop_row(ui, "Contents", |ui| { - if let Some(s) = edit_field(ui, ui.scope_id().with(("txt", &ids)), tx.value.clone()) { - set = Some(json!({ "handles": ids, "text": s })); - } - }); - num(ui, "Height", "height", len(tx.height), &mut set, &mut bad, &ids); - num(ui, "Rotation", "rotation", real(angles.shown(tx.rotation).to_degrees()), &mut set, &mut bad, &ids); - num(ui, "Width factor", "widthFactor", real(tx.width_factor), &mut set, &mut bad, &ids); - } - EntityKind::MText(tx) => { - prop_row(ui, "Contents", |ui| { - if let Some(s) = edit_field(ui, ui.scope_id().with(("mtxt", &ids)), tx.contents.clone()) { - set = Some(json!({ "handles": ids, "text": s })); - } - }); - num(ui, "Text height", "height", len(tx.height), &mut set, &mut bad, &ids); - num(ui, "Defined width", "width", len(tx.width), &mut set, &mut bad, &ids); - } EntityKind::LwPolyline(pl) => { num(ui, "Global width", "width", len(pl.const_width), &mut set, &mut bad, &ids); let g = cadcraft_geom::Polyline { vertices: pl.vertices.clone(), closed: pl.closed }; @@ -1103,30 +1090,6 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { num(ui, "Scale", "scale", real(hh.scale), &mut set, &mut bad, &ids); num(ui, "Angle", "angle", real(hh.angle.to_degrees()), &mut set, &mut bad, &ids); } - EntityKind::Dimension(dm) => { - prop_row(ui, "Text override", |ui| { - if let Some(s) = edit_field(ui, ui.scope_id().with(("dimtxt", &ids)), dm.text.clone()) { - set = Some(json!({ "handles": ids, "textOverride": s })); - } - }); - prop_row(ui, "Dim style", |ui| { - if let Some(n) = pick_menu(ui, &dm.style, d.dim_styles.iter().map(|st| st.name.clone())) { - set = Some(json!({ "handles": ids, "dimStyle": n })); - } - }); - // The style's values with this dimension's own overrides; editing one overrides - // it for the selected dimensions, as AutoCAD's Properties palette does. - let st = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides); - num(ui, "Text height", "textHeight", len(st.text_height), &mut set, &mut bad, &ids); - num(ui, "Arrow size", "arrowSize", len(st.arrow_size), &mut set, &mut bad, &ids); - num(ui, "Dim scale overall", "dimScale", real(st.scale), &mut set, &mut bad, &ids); - prop_row(ui, "Precision", |ui| { - let cur = st.decimals.to_string(); - if let Some(n) = pick_menu(ui, &cur, (0..=8).map(|n: u8| n.to_string())).and_then(|n| n.parse::().ok()) { - set = Some(json!({ "handles": ids, "precision": n })); - } - }); - } EntityKind::Insert(i) => { // A dynamic block reference shows its dynamic block's name, not its anonymous // block's (`*U12`), and its custom properties below. @@ -1170,6 +1133,13 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } let _ = app.run("properties.set", p); } + // A described row the engine couldn't take (a value out of range…) says so. + if let Some(e) = edit + && let Ok(r) = app.run("properties.set", e.params) + && r["ignored"].as_array().is_some_and(|a| !a.is_empty()) + { + app.session.echo(crate::tf!("{property}: that value can't be used here.", property = crate::i18n::t(e.label))); + } report_bad(app, bad); if let Some(p) = custom_set { let _ = app.run("blocks.reference.set", p); diff --git a/crates/ui-egui/src/palettes/described.rs b/crates/ui-egui/src/palettes/described.rs new file mode 100644 index 000000000..c87f19826 --- /dev/null +++ b/crates/ui-egui/src/palettes/described.rs @@ -0,0 +1,215 @@ +//! The Properties palette rows the engine describes (`properties.describe`): text, mtext and +//! dimensions, for one object or many of the same type, with *VARIES*, values in the drawing's +//! units, and dimension variables the dimension overrides. + +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +use cadcraft_engine::doc::{Drawing, Handle}; +use cadcraft_engine::properties::{Description, Kind, Row, VARIES}; +use cadcraft_engine::units::AngleSettings; +use egui::{Sense, pos2, vec2}; +use serde_json::{Value, json}; + +use super::{edit_field, number, value_box}; +use crate::CadApp; +use crate::theme::Tokens; + +/// What the engine says the palette shows for `sel`, worked out again only when the drawing, +/// its revision or the selection changes (dimension rows draw each dimension to measure it). +pub(super) fn described(ui: &egui::Ui, app: &CadApp, sel: &[Handle]) -> Option> { + let st = app.session.state().ok()?; + let mut hasher = std::hash::DefaultHasher::new(); + (st.uid, st.revision, sel).hash(&mut hasher); + let key = hasher.finish(); + let id = egui::Id::unique("properties-describe"); + if let Some((k, d)) = ui.data(|m| m.get_temp::<(u64, Arc)>(id)) + && k == key + { + return Some(d); + } + let d = Arc::new(cadcraft_engine::properties::describe(&st.doc, sel, None)); + ui.data_mut(|m| m.insert_temp(id, (key, d.clone()))); + Some(d) +} + +/// A group header, as the palette draws General and Geometry. +fn group(ui: &mut egui::Ui, title: &str) { + let t = Tokens::get(); + let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::hover()); + ui.painter().rect_filled(r.shrink2(vec2(6.0, 1.0)), 2.0, t.chrome_dark); + ui.painter().text(pos2(r.left() + 12.0, r.center().y), egui::Align2::LEFT_CENTER, crate::i18n::t(title), crate::theme::small(), t.text_dim); +} + +/// An edit the palette makes: the `properties.set` call and the row it came from. +pub(super) struct Edit { + pub params: Value, + pub label: &'static str, +} + +/// The described groups after General (the palette draws General itself). Returns false when +/// the description has none, so the palette draws its own rows for the object. +pub(super) fn groups(ui: &mut egui::Ui, d: &Drawing, desc: &Description, ids: &[String], edit: &mut Option, bad: &mut Option) -> bool { + let typed: Vec<_> = desc.groups.iter().filter(|g| g.name != "General").collect(); + if typed.is_empty() { + return false; + } + let angles = AngleSettings::from_header(&d.header); + // A fixed-height text style names itself in the dimension's Text style row. + let text_style = typed.iter().flat_map(|g| &g.rows).find(|r| r.key == "textStyle" && !r.varies).map(|r| r.display.clone()); + for g in typed { + group(ui, g.name); + for row in &g.rows { + // The row's label names its value field and menu for screen readers. + ui.name_inputs(crate::i18n::t(row.label).to_string(), |ui| described_row(ui, d, row, ids, &angles, text_style.as_deref(), edit, bad)); + } + } + true +} + +/// The value as the row shows it: *VARIES* and choice labels in the interface language, the +/// drawing's own names and the objects' text as they are. +fn shown(row: &Row) -> String { + if row.varies { + return crate::i18n::t(VARIES).to_string(); + } + match row.kind { + Kind::Bool | Kind::Choice | Kind::Color => crate::i18n::t(&row.display).to_string(), + Kind::Linetype if row.display == "ByBlock" => crate::i18n::t("ByBlock").to_string(), + _ => row.display.clone(), + } +} + +/// Why a row can't be edited (or what decides its value), in the interface language. +fn note(row: &Row, text_style: Option<&str>) -> Option { + row.note.as_ref()?; + Some(match (row.key, row.editable, text_style) { + ("textHeight", false, Some(style)) => crate::tf!( + "Set by text style \"{style}\", which has a fixed height. Give the style a height of 0 to use the dimension text height.", + style = style + ) + .to_string(), + ("textHeight", _, _) => crate::tl!("Some of these dimensions take their text height from a fixed-height text style.").to_string(), + _ => crate::i18n::t(row.note.as_deref().unwrap_or_default()).to_string(), + }) +} + +fn described_row( + ui: &mut egui::Ui, + d: &Drawing, + row: &Row, + ids: &[String], + angles: &AngleSettings, + text_style: Option<&str>, + edit: &mut Option, + bad: &mut Option, +) { + let t = Tokens::get(); + let key = row.key; + let mut picked: Option = None; + ui.horizontal(|ui| { + // The label: in the accent color where a dimension overrides its style, with a menu + // that goes back to the style's value. + let color = if row.overridden { t.accent } else { t.text_dim }; + let mut job = egui::text::LayoutJob::simple(crate::i18n::t(row.label).to_string(), crate::theme::body(), color, 106.0); + job.halign = egui::Align::RIGHT; + let galley = ui.painter().layout_job(job); + let sense = if row.overridden { Sense::click() } else { Sense::hover() }; + let (lr, resp) = ui.allocate_exact_size(vec2(118.0, galley.size().y.max(22.0)), sense); + ui.painter().galley(pos2(lr.right() - 6.0, lr.center().y - galley.size().y / 2.0), galley, color); + if row.overridden { + resp.on_hover_text(crate::tl!("Overrides the dimension style. Right-click to use the style's value.")).context_menu(|ui| { + if ui.button(crate::tl!("Use the style's value")).clicked() { + *edit = Some(Edit { params: json!({ "handles": ids, "clear": [key] }), label: row.label }); + ui.close(); + } + }); + } + let shown = shown(row); + if !row.editable { + let tip = note(row, text_style).unwrap_or_else(|| crate::tl!("Read-only").to_string()); + value_box(ui, &shown, false, false).on_hover_text(tip); + return; + } + let id = ui.scope_id().with(("described", key, ids)); + match row.kind { + Kind::Text | Kind::Contents => picked = edit_field(ui, id, shown).map(Value::String), + Kind::Number | Kind::Distance => picked = number(edit_field(ui, id, shown), bad).map(|v| json!(v)), + Kind::Angle | Kind::Direction => { + if let Some(typed) = edit_field(ui, id, shown) { + match angles.amount(&typed) { + // A direction is typed as shown (from ANGBASE, in the ANGDIR sense); + // properties.set takes it from +X counterclockwise. + Some(a) if row.kind == Kind::Direction => picked = Some(json!(angles.unshown(a).to_degrees())), + Some(a) => picked = Some(json!(a.to_degrees())), + None => *bad = Some(typed), + } + } + } + Kind::Bool => { + ui.menu_button(shown, |ui| { + for (v, label) in [(true, "Yes"), (false, "No")] { + if ui.button(crate::i18n::t(label)).clicked() { + picked = Some(json!(v)); + ui.close(); + } + } + }); + } + Kind::Choice | Kind::TextStyle | Kind::DimStyle => { + // Choice labels are ours to translate; style names are the drawing's. + let translate = row.kind == Kind::Choice; + ui.menu_button(shown, |ui| { + for o in &row.options { + let label = if translate { crate::i18n::t(&o.label).to_string() } else { o.label.clone() }; + if ui.button(label).clicked() { + picked = Some(o.value.clone()); + ui.close(); + } + } + }); + } + Kind::Color => { + ui.menu_button(format!("■ {shown}"), |ui| { + for (n, c) in [ + ("ByBlock", 0), + ("ByLayer", 256), + ("Red", 1), + ("Yellow", 2), + ("Green", 3), + ("Cyan", 4), + ("Blue", 5), + ("Magenta", 6), + ("White", 7), + ] { + if ui.button(crate::i18n::t(n)).clicked() { + picked = Some(json!(c)); + ui.close(); + } + } + }); + } + Kind::Linetype => { + let names = std::iter::once("ByBlock".to_string()).chain( + d.linetypes.iter().map(|l| l.name.clone()).filter(|n| !n.eq_ignore_ascii_case("ByLayer") && !n.eq_ignore_ascii_case("ByBlock")), + ); + ui.menu_button(shown, |ui| { + for n in names { + let label = if n == "ByBlock" { crate::i18n::t("ByBlock").to_string() } else { n.clone() }; + if ui.button(label).clicked() { + picked = Some(json!(n)); + ui.close(); + } + } + }); + } + // General's own kinds (layer, lineweight, transparency) aren't in the typed groups. + _ => { + value_box(ui, &shown, false, false); + } + } + }); + if let Some(v) = picked.filter(|v| row.varies || *v != row.value) { + *edit = Some(Edit { params: json!({ "handles": ids, key: v }), label: row.label }); + } +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 6cc883a66..5522bac97 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -25,6 +25,7 @@ mod native_windows; mod options_dialog; mod parameters_rename; mod pickdrag; +mod properties_described; mod properties_units; mod rapid_clicks; mod selection_cycling; diff --git a/crates/ui-egui/tests/it/properties_described.rs b/crates/ui-egui/tests/it/properties_described.rs new file mode 100644 index 000000000..81ebc30fb --- /dev/null +++ b/crates/ui-egui/tests/it/properties_described.rs @@ -0,0 +1,172 @@ +//! The Properties palette's text, mtext and dimension rows come from `properties.describe`: a +//! dimension's text height is an override of that dimension, several objects of one type edit +//! together, styles are picked from the drawing's, and a fixed-height text style shows the +//! height it fixes instead of a field that would change nothing. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{Dimension, EntityKind, MText}; +use cadcraft_ui_egui::{CadApp, Services}; +use egui::{Key, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{Queryable, by}; +use serde_json::json; + +/// The palettes with `setup` run on a new drawing, then everything in it selected. +fn palettes(setup: impl FnOnce(&mut CadApp)) -> Harness<'static, CadApp> { + harness(setup, false) +} + +/// `palettes`, drawn with the GPU renderer and the dark theme when `render`, for pictures. +fn harness(setup: impl FnOnce(&mut CadApp), render: bool) -> Harness<'static, CadApp> { + let mut app = CadApp::new(Session::default(), Services::default()); + setup(&mut app); + let all: Vec = app.session.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + app.run("select", json!({ "handles": all })).unwrap(); + let builder = Harness::builder().with_size(vec2(400.0, 3000.0)); + let builder = if render { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( + move |ui, app: &mut CadApp| { + if render { + cadcraft_ui_egui::theme::apply(ui.ctx(), egui::Theme::Dark, false); + } + app.logic(&ui.ctx().clone()); + cadcraft_ui_egui::palettes::right_palettes(app, ui); + }, + app, + ); + h.run_steps(4); + h +} + +fn field<'h>(h: &'h Harness<'static, CadApp>, shown: &'h str) -> egui_kittest::Node<'h> { + h.get(by().role(egui::accesskit::Role::TextInput).value(shown)) +} + +fn type_into(h: &mut Harness<'static, CadApp>, shown: &str, text: &str) { + field(h, shown).focus(); + h.run_steps(2); + h.key_press_modifiers(egui::Modifiers::COMMAND, Key::A); + h.run_steps(1); + field(h, shown).type_text(text); + h.run_steps(2); + h.key_press(Key::Enter); + h.run_steps(3); +} + +fn dims(app: &CadApp) -> Vec { + app.session.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Dimension(d) = &e.kind { Some(d.clone()) } else { None }).collect() +} + +fn mtext(app: &CadApp) -> MText { + app.session.doc().unwrap().model.iter().find_map(|e| if let EntityKind::MText(t) = &e.kind { Some(t.clone()) } else { None }).unwrap() +} + +fn heights(app: &CadApp) -> Vec { + app.session.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.height) } else { None }).collect() +} + +#[test] +fn a_dimension_text_height_is_an_override_of_that_dimension() { + let mut h = palettes(|app| { + // A text height no other row has, so its field is easy to find. + app.run("dimstyle", json!({ "name": "Standard", "DIMTXT": 0.123 })).unwrap(); + app.run("dimlinear", json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + }); + type_into(&mut h, "0.1230", "0.25"); + let d = &dims(h.state())[0]; + assert_eq!(d.overrides.get("textHeight"), Some(&json!(0.25))); + field(&h, "0.2500"); + // The style keeps its own height. + let st = h.state_mut().run("dimstyle.list", json!({ "name": "Standard" })).unwrap(); + assert_eq!(st["variables"]["DIMTXT"], 0.123); +} + +#[test] +fn several_texts_edit_together() { + let mut h = palettes(|app| { + app.run("text", json!({ "at": [0, 0], "text": "Note", "height": 1 })).unwrap(); + app.run("text", json!({ "at": [0, 0], "text": "Note", "height": 2 })).unwrap(); + }); + type_into(&mut h, "*VARIES*", "3"); + assert_eq!(heights(h.state()), [3.0, 3.0]); +} + +#[test] +fn an_mtext_style_is_picked_from_the_drawing_styles() { + let mut h = palettes(|app| { + app.run("style", json!({ "name": "Notes", "current": false })).unwrap(); + app.run("mtext", json!({ "at": [0, 0], "text": "One", "height": 2.5 })).unwrap(); + }); + h.get_by_label("Standard").click(); + h.run_steps(3); + h.get_by_label("Notes").click(); + h.run_steps(3); + assert_eq!(mtext(h.state()).style, "Notes"); + // Justify is a choice too. + h.get_by_label("Top left").click(); + h.run_steps(3); + h.get_by_label("Middle center").click(); + h.run_steps(3); + assert_eq!(mtext(h.state()).attach, 5); +} + +#[test] +fn a_fixed_height_text_style_shows_the_height_it_fixes() { + let h = palettes(|app| { + app.run("style", json!({ "name": "Fixed", "height": 0.5, "current": false })).unwrap(); + app.run("dimstyle", json!({ "name": "FixedDims", "textStyle": "Fixed", "DIMTXT": 0.123 })).unwrap(); + app.run("dimlinear", json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + }); + // No field to type a height into: neither the style's fixed height nor DIMTXT. + assert!(h.query(by().role(egui::accesskit::Role::TextInput).value("0.5000")).is_none()); + assert!(h.query(by().role(egui::accesskit::Role::TextInput).value("0.1230")).is_none()); +} + +#[test] +fn a_value_the_engine_refuses_is_reported() { + let mut h = palettes(|app| { + app.run("mtext", json!({ "at": [0, 0], "text": "One", "height": 2.5, "lineSpacing": 1.25 })).unwrap(); + }); + let before = h.state().session.log.len(); + // MTEXT line spacing factors run from 0.25 to 4. + type_into(&mut h, "1.2500", "9"); + assert_eq!(mtext(h.state()).line_spacing, 1.25); + let log: Vec<&String> = h.state().session.log[before..].iter().collect(); + assert!(log.iter().any(|l| l.contains("Line space factor")), "{log:?}"); +} + +#[test] +fn other_objects_keep_their_own_rows() { + let h = palettes(|app| { + app.run("line", json!({ "points": [[0, 0], [10, 5]] })).unwrap(); + }); + // End X of the line (its length is 11.1803). + field(&h, "10.0000"); +} + +/// With `CADCRAFT_PROPERTIES_SHOTS=`, pictures of the palette for a dimension with a +/// text height override, an MTEXT and two TEXTs of different heights, to look at the rows. +#[test] +fn pictures_of_the_rows() { + let Some(directory) = std::env::var_os("CADCRAFT_PROPERTIES_SHOTS").map(std::path::PathBuf::from) else { return }; + std::fs::create_dir_all(&directory).unwrap(); + let shots: [(&str, fn(&mut CadApp)); 3] = [ + ("properties-dimension.png", |app| { + app.run("dimlinear", json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + let h = app.session.doc().unwrap().model.last().unwrap().handle.hex(); + app.run("properties.set", json!({ "handles": [h], "textHeight": 0.25 })).unwrap(); + }), + ("properties-mtext.png", |app| { + app.run("mtext", json!({ "at": [0, 0], "text": "One\\PTwo", "height": 2.5, "width": 40 })).unwrap(); + }), + ("properties-texts.png", |app| { + app.run("text", json!({ "at": [0, 0], "text": "Note", "height": 1 })).unwrap(); + app.run("text", json!({ "at": [0, 0], "text": "Note", "height": 2, "justify": "MC" })).unwrap(); + }), + ]; + for (name, setup) in shots { + let mut h = harness(setup, true); + h.run_steps(2); + h.render().unwrap().save(directory.join(name)).unwrap(); + } +} From ea0d0e9595f9cdece2e1ee92400739560f6d7b2a Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Fri, 23 Oct 2026 20:45:28 -0400 Subject: [PATCH 07/41] Review fixes: picking the color a row already has is no edit; directions typed as measured From CodeRabbit's reviews of #994: - The palette's color menu sent the color number while the row's value is the color's name, so picking the color a row already showed still ran properties.set (and made an undo step). The menu now compares by name and sends nothing for the color already set. - A rotation (a direction row) typed in the palette is read as the drawing measures directions (AngleSettings::direction): a surveyor's bearing such as N45dE is absolute, and `< --- crates/ui-egui/src/palettes/described.rs | 18 +++++++++---- .../ui-egui/tests/it/properties_described.rs | 25 +++++++++++++++++++ 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/palettes/described.rs b/crates/ui-egui/src/palettes/described.rs index c87f19826..e0e7ed8c2 100644 --- a/crates/ui-egui/src/palettes/described.rs +++ b/crates/ui-egui/src/palettes/described.rs @@ -137,10 +137,15 @@ fn described_row( Kind::Number | Kind::Distance => picked = number(edit_field(ui, id, shown), bad).map(|v| json!(v)), Kind::Angle | Kind::Direction => { if let Some(typed) = edit_field(ui, id, shown) { - match angles.amount(&typed) { - // A direction is typed as shown (from ANGBASE, in the ANGDIR sense); - // properties.set takes it from +X counterclockwise. - Some(a) if row.kind == Kind::Direction => picked = Some(json!(angles.unshown(a).to_degrees())), + // A direction is typed as the drawing measures directions (from ANGBASE in the + // ANGDIR sense; bearings and `<<` overrides absolute); properties.set takes it + // from +X counterclockwise. + let parsed = if row.kind == Kind::Direction { + angles.direction(&typed).map(|a| a.rem_euclid(std::f64::consts::TAU)) + } else { + angles.amount(&typed) + }; + match parsed { Some(a) => picked = Some(json!(a.to_degrees())), None => *bad = Some(typed), } @@ -183,7 +188,10 @@ fn described_row( ("White", 7), ] { if ui.button(crate::i18n::t(n)).clicked() { - picked = Some(json!(c)); + // The row shows a color by name: picking the one it has is no edit. + if row.varies || row.value != json!(n) { + picked = Some(json!(c)); + } ui.close(); } } diff --git a/crates/ui-egui/tests/it/properties_described.rs b/crates/ui-egui/tests/it/properties_described.rs index 81ebc30fb..818563a8a 100644 --- a/crates/ui-egui/tests/it/properties_described.rs +++ b/crates/ui-egui/tests/it/properties_described.rs @@ -91,6 +91,31 @@ fn several_texts_edit_together() { assert_eq!(heights(h.state()), [3.0, 3.0]); } +#[test] +fn a_rotation_is_typed_as_the_drawing_measures_directions() { + let rotation = |app: &CadApp| { + app.session + .doc() + .unwrap() + .model + .iter() + .find_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.rotation.to_degrees()) } else { None }) + .unwrap() + }; + let mut h = palettes(|app| { + // Directions measured from north: a text along +X shows 270. + app.run("setvar", json!({ "name": "ANGBASE", "value": 90 })).unwrap(); + app.run("text", json!({ "at": [0, 0], "text": "Note", "height": 1 })).unwrap(); + }); + // A bearing is an angle like a number, measured from ANGBASE as AutoCAD does (#2590): north + // 45° east is 45° on from north, 135° from +X. + type_into(&mut h, "270", "N45dE"); + assert!((rotation(h.state()) - 135.0).abs() < 1e-9, "{}", rotation(h.state())); + // `<<` measures from +X counterclockwise, whatever ANGBASE says. + type_into(&mut h, "45", "<<10"); + assert!((rotation(h.state()) - 10.0).abs() < 1e-9, "{}", rotation(h.state())); +} + #[test] fn an_mtext_style_is_picked_from_the_drawing_styles() { let mut h = palettes(|app| { From 1c02f239c345a0949b56daf57d0ff947b4b3029c Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Wed, 28 Oct 2026 16:14:28 -0400 Subject: [PATCH 08/41] Properties palette: the described rows' shared inputs in one struct, within #2239's limit #2239 denies functions with more than seven arguments. `described_row` took eight; the drawing, the handles, the angle settings and the shared text style now come together as `Rows`, which the row destructures under the same names. Nothing changes in behavior. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/palettes/described.rs | 25 +++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/palettes/described.rs b/crates/ui-egui/src/palettes/described.rs index e0e7ed8c2..590e5f85e 100644 --- a/crates/ui-egui/src/palettes/described.rs +++ b/crates/ui-egui/src/palettes/described.rs @@ -57,11 +57,12 @@ pub(super) fn groups(ui: &mut egui::Ui, d: &Drawing, desc: &Description, ids: &[ let angles = AngleSettings::from_header(&d.header); // A fixed-height text style names itself in the dimension's Text style row. let text_style = typed.iter().flat_map(|g| &g.rows).find(|r| r.key == "textStyle" && !r.varies).map(|r| r.display.clone()); + let rows = Rows { d, ids, angles: &angles, text_style: text_style.as_deref() }; for g in typed { group(ui, g.name); for row in &g.rows { // The row's label names its value field and menu for screen readers. - ui.name_inputs(crate::i18n::t(row.label).to_string(), |ui| described_row(ui, d, row, ids, &angles, text_style.as_deref(), edit, bad)); + ui.name_inputs(crate::i18n::t(row.label).to_string(), |ui| described_row(ui, &rows, row, edit, bad)); } } true @@ -94,16 +95,18 @@ fn note(row: &Row, text_style: Option<&str>) -> Option { }) } -fn described_row( - ui: &mut egui::Ui, - d: &Drawing, - row: &Row, - ids: &[String], - angles: &AngleSettings, - text_style: Option<&str>, - edit: &mut Option, - bad: &mut Option, -) { +/// What every described row is drawn with: the drawing, the selected objects' handles, how the +/// drawing measures angles, and the dimension text style when the objects share one. +#[derive(Clone, Copy)] +struct Rows<'a> { + d: &'a Drawing, + ids: &'a [String], + angles: &'a AngleSettings, + text_style: Option<&'a str>, +} + +fn described_row(ui: &mut egui::Ui, rows: &Rows<'_>, row: &Row, edit: &mut Option, bad: &mut Option) { + let Rows { d, ids, angles, text_style } = *rows; let t = Tokens::get(); let key = row.key; let mut picked: Option = None; From 5f4a17cb7c71241c752791d91b922ab880f38602 Mon Sep 17 00:00:00 2001 From: eldrir Date: Tue, 13 Oct 2026 12:25:07 -0400 Subject: [PATCH 09/41] Dimension shortcut menu: Remove Style Overrides, Dimension Style, Precision, Align Text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With dimensions selected, the canvas shortcut menu adds AutoCAD's dimension items: Align Text ▸ (DIMTEDIT Home/Angle/Left/Center/Right), Dimension Style ▸ (the drawing's styles, which the selected dimensions take, then Save as New Style), Precision ▸ (DIMDEC, or DIMADEC for angular dimensions, as overrides) and Remove Style Overrides (available while one of them overrides its style). Two commands behind them: dimoverride.clear clears the selected dimensions' overrides, and dimstyle.saveas makes a new dimension style of a dimension's settings, its overrides included, gives it to the dimension and clears its overrides (the current style is unchanged). From the menu it uses the selected dimension, or asks for one, then asks for the name. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/dimstyles.rs | 111 ++++++++++++++++++++++ crates/engine/tests/it/dim_style_menu.rs | 88 +++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/context_menu.rs | 75 ++++++++++++++- crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/zh.tsv | 3 + crates/ui-egui/tests/it/dimension_menu.rs | 83 ++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + 9 files changed, 365 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/dimstyles.rs create mode 100644 crates/engine/tests/it/dim_style_menu.rs create mode 100644 crates/ui-egui/tests/it/dimension_menu.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index f16a16fe7..343fa6a1e 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -8,6 +8,7 @@ mod audit; pub(crate) mod blocks; pub mod clipboard; pub mod constraints; +mod dimstyles; mod draw; mod draw2; mod draworder; @@ -186,6 +187,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(draw::specs()); v.extend(draw2::specs()); v.extend(annotate::specs()); + v.extend(dimstyles::specs()); v.extend(mleader_edit::specs()); v.extend(annoscale::specs()); v.extend(hatch::specs()); diff --git a/crates/engine/src/cmd/dimstyles.rs b/crates/engine/src/cmd/dimstyles.rs new file mode 100644 index 000000000..ed5f614a2 --- /dev/null +++ b/crates/engine/src/cmd/dimstyles.rs @@ -0,0 +1,111 @@ +//! Dimension style commands of the dimension shortcut menu: Remove Style Overrides (DIMOVERRIDE +//! Clear for the selected dimensions) and Save as New Style (a style made of a dimension's +//! settings, its overrides included, which the dimension then uses). + +use cadcraft_doc::{DimStyle, EntityKind, Handle}; +use serde_json::{Value, json}; + +use super::machines::SelectRun; +use super::*; +use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; + +fn other(m: impl Into) -> EngineError { + EngineError::Other(m.into()) +} + +pub fn specs() -> Vec { + vec![ + CommandSpec::new("dimoverride.clear", "Remove Style Overrides", run_clear) + .params("{handles?} (dimensions; they draw with their style's settings again) → {changed}") + .interactive(|_| Ok(Box::new(SelectRun::new("dimoverride.clear", "DIMOVERRIDE")))), + CommandSpec::new("dimstyle.saveas", "Save as New Style...", run_save_as) + .params( + "{handle? (default: the first selected dimension), name} → {style, handle} (a new dimension style with the dimension's \ + settings, overrides included; the dimension takes it and its overrides are cleared; the current style is unchanged)", + ) + .interactive(|_| Ok(Box::new(SaveAsM::default()))), + ] +} + +fn run_clear(s: &mut Session, p: &Value) -> Result { + let hs: Vec = targets(s, p)?.iter().map(|h| h.hex()).collect(); + super::props::dim_override(s, &json!({ "handles": hs, "clear": true })) +} + +fn is_dim(s: &Session, h: Handle) -> bool { + s.doc().ok().and_then(|d| d.entity(h)).is_some_and(|e| matches!(e.kind, EntityKind::Dimension(_))) +} + +/// A usable new dimension style name. +fn new_name(s: &Session, name: &str) -> Result { + let name = name.trim(); + if name.is_empty() || name.len() > 255 || name.contains(['<', '>', '/', '\\', '"', ':', ';', '?', '*', '|', ',', '=', '`']) { + return Err(bad("dimstyle.saveas", "bad style name")); + } + if s.doc()?.dim_style(name).is_some() { + return Err(bad("dimstyle.saveas", format!("a dimension style `{name}` already exists"))); + } + Ok(name.to_string()) +} + +/// Make style `name` from dimension `h`'s settings and give it to the dimension. +fn save_as(s: &mut Session, h: Handle, name: &str) -> Result { + let name = new_name(s, name)?; + let d = s.doc_mut()?; + let Some(EntityKind::Dimension(dm)) = d.entity(h).map(|e| e.kind.clone()) else { return Err(bad("dimstyle.saveas", "not a dimension")) }; + let st = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides); + d.dim_styles.push(DimStyle { name: name.clone(), ..st }); + d.modify_entity(h, |e| { + if let EntityKind::Dimension(dm) = &mut e.kind { + dm.style.clone_from(&name); + dm.overrides.clear(); + dm.block = None; + } + })?; + Ok(json!({ "style": name, "handle": h.hex() })) +} + +fn run_save_as(s: &mut Session, p: &Value) -> Result { + let name = str_param(p, "name").ok_or_else(|| bad("dimstyle.saveas", "`name` is required"))?.to_string(); + let hs = targets(s, p)?; + let h = hs.into_iter().find(|h| is_dim(s, *h)).ok_or_else(|| bad("dimstyle.saveas", "select a dimension"))?; + save_as(s, h, &name) +} + +/// Save as New Style: the selected dimension (or one picked), then the new style's name. +#[derive(Default)] +struct SaveAsM { + dim: Option, +} + +impl Interactive for SaveAsM { + fn name(&self) -> &'static str { + "DIMSTYLE" + } + fn begin(&mut self, s: &mut Session) -> Result { + self.dim = s.selection().into_iter().find(|h| is_dim(s, *h)); + Ok(Step::Continue) + } + fn prompt(&self, _s: &Session) -> Prompt { + match self.dim { + None => Prompt::new("Select a dimension", Accept::POINT), + Some(_) => Prompt::new("Enter name of new dimension style", Accept::TEXT), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + match (self.dim, i) { + (None, Input::Point(p)) => { + let h = curves::pick_at(s, p).filter(|h| is_dim(s, *h)).ok_or_else(|| other("Select a dimension."))?; + self.dim = Some(h); + Ok(Step::Continue) + } + (Some(h), Input::Text(t) | Input::Keyword(t)) => { + let r = save_as(s, h, &t)?; + s.echo(format!("Dimension style {} created from the dimension.", r["style"].as_str().unwrap_or_default())); + Ok(Step::Done) + } + (_, Input::Enter) => Ok(Step::Done), + _ => Ok(Step::Continue), + } + } +} diff --git a/crates/engine/tests/it/dim_style_menu.rs b/crates/engine/tests/it/dim_style_menu.rs new file mode 100644 index 000000000..809ebf898 --- /dev/null +++ b/crates/engine/tests/it/dim_style_menu.rs @@ -0,0 +1,88 @@ +//! The dimension shortcut menu's style commands: Remove Style Overrides clears the selected +//! dimensions' overrides, and Save as New Style makes a style of a dimension's settings (its +//! overrides included) and gives it to the dimension. + +use cadcraft_engine::doc::{Dimension, EntityKind, Handle}; +use cadcraft_engine::{Input, Session}; +use serde_json::json; + +fn dimension(s: &mut Session, y: f64) -> Handle { + s.execute("dimlinear", &json!({ "p1": [0, y], "p2": [10, y], "at": [5, y + 3.0] })).unwrap(); + s.doc().unwrap().model.last().unwrap().handle +} + +fn dim(s: &Session, h: Handle) -> Dimension { + match &s.doc().unwrap().entity(h).unwrap().kind { + EntityKind::Dimension(d) => d.clone(), + k => panic!("not a dimension: {k:?}"), + } +} + +#[test] +fn remove_style_overrides_clears_the_selected_dimensions() { + let mut s = Session::new(); + let (a, b) = (dimension(&mut s, 0.0), dimension(&mut s, 10.0)); + s.execute("properties.set", &json!({ "handles": [a.hex(), b.hex()], "textHeight": 0.3 })).unwrap(); + s.execute("dimoverride.clear", &json!({ "handles": [a.hex()] })).unwrap(); + assert!(dim(&s, a).overrides.is_empty() && !dim(&s, b).overrides.is_empty()); + // From the menu: the selected dimensions, in one undo step. + s.set_selection(vec![b]); + s.start("dimoverride.clear").unwrap(); + assert!(s.running.is_none() && dim(&s, b).overrides.is_empty()); + s.undo().unwrap(); + assert_eq!(dim(&s, b).overrides.get("textHeight"), Some(&json!(0.3))); +} + +#[test] +fn save_as_new_style_takes_the_dimensions_settings() { + let mut s = Session::new(); + let h = dimension(&mut s, 0.0); + s.execute("properties.set", &json!({ "handles": [h.hex()], "textHeight": 0.3, "DIMDEC": 2 })).unwrap(); + let r = s.execute("dimstyle.saveas", &json!({ "handle": h.hex(), "name": "Detail" })).unwrap(); + assert_eq!(r["style"], "Detail"); + let d = dim(&s, h); + assert!(d.style == "Detail" && d.overrides.is_empty(), "{d:?}"); + let st = s.execute("dimstyle.list", &json!({ "name": "Detail" })).unwrap(); + assert_eq!((st["variables"]["DIMTXT"].as_f64(), st["variables"]["DIMDEC"].as_u64()), (Some(0.3), Some(2))); + // The dimension looks the same, and the current style is still Standard. + let g = cadcraft_engine::render::dimension_in(s.doc().unwrap(), &d); + assert!((g.text_height - 0.3).abs() < 1e-12 && g.value == "10.00", "{} {}", g.text_height, g.value); + assert_eq!(s.doc().unwrap().header.str("DIMSTYLE", "Standard"), "Standard"); + // A new name that a style can have. + for name in ["detail", " ", "a) -> Option { let spec = find_command(id)?; @@ -153,9 +158,70 @@ fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> { } } -/// [`object_commands`] that are registered, as menu items. +/// [`object_commands`] that are registered, as menu items, then the dimension shortcut menu's +/// items when the selection is dimensions. pub fn object_entries(app: &CadApp) -> Vec { - object_commands(app).into_iter().filter_map(|(id, label)| item(app, id, label)).collect() + let mut out: Vec = object_commands(app).into_iter().filter_map(|(id, label)| item(app, id, label)).collect(); + out.extend(dimension_entries(app)); + out +} + +/// For selected dimensions (and only dimensions): Align Text ▸, Dimension Style ▸ (the +/// drawing's styles, then Save as New Style), Precision ▸ and Remove Style Overrides. +fn dimension_entries(app: &CadApp) -> Vec { + let Ok(d) = app.session.doc() else { return Vec::new() }; + let sel = app.session.selection(); + let dims: Vec<&cadcraft_doc::Dimension> = + sel.iter().filter_map(|h| d.entity(*h)).filter_map(|e| if let EntityKind::Dimension(dm) = &e.kind { Some(dm) } else { None }).collect(); + if dims.is_empty() || dims.len() != sel.len() { + return Vec::new(); + } + let mut out: Vec = + sub("Align Text", items(app, &["dimtedit.home", "dimtedit.angle", "dimtedit.left", "dimtedit.center", "dimtedit.right"])) + .into_iter() + .collect(); + // Style names are the drawing's own. + let mut styles: Vec = d + .dim_styles + .iter() + .map(|st| Entry::Item { label: st.name.clone(), id: format!("{DIM_STYLE}{}", st.name), shortcut: None, enabled: true }) + .collect(); + styles.extend(item(app, "dimstyle.saveas", None)); + out.extend(sub("Dimension Style", styles)); + let precision = (0..=8usize) + .map(|n| Entry::Item { + label: if n == 0 { "0".into() } else { format!("0.{}", "0".repeat(n)) }, + id: format!("{DIM_PRECISION}{n}"), + shortcut: None, + enabled: true, + }) + .collect(); + out.extend(sub("Precision", precision)); + // Available while some selected dimension overrides its style. + if let Some(Entry::Item { label, id, shortcut, .. }) = item(app, "dimoverride.clear", None) { + out.push(Entry::Item { label, id, shortcut, enabled: dims.iter().any(|dm| !dm.overrides.is_empty()) }); + } + out +} + +/// Precision ▸: the selected dimensions show `places` decimal places (DIMDEC, or DIMADEC for +/// angular dimensions), as overrides. +fn set_precision(app: &mut CadApp, places: u8) { + let (mut linear, mut angular) = (Vec::new(), Vec::new()); + if let Ok(d) = app.session.doc() { + for h in app.session.selection() { + if let Some(EntityKind::Dimension(dm)) = d.entity(h).map(|e| &e.kind) { + let list = + if matches!(dm.kind, cadcraft_doc::DimKind::Angular | cadcraft_doc::DimKind::Angular3P) { &mut angular } else { &mut linear }; + list.push(h.hex()); + } + } + } + for (hs, key) in [(linear, "decimals"), (angular, "angularDecimals")] { + if !hs.is_empty() { + let _ = app.run("properties.set", json!({ "handles": hs, key: places })); + } + } } /// The command menu while a command runs (`None` when none does): Enter and Cancel, Recent Input, @@ -213,6 +279,11 @@ pub fn choose(app: &mut CadApp, id: &str) { } } else if let Some(s) = id.strip_prefix(SNAP) { choose_snap(app, s); + } else if let Some(name) = id.strip_prefix(DIM_STYLE) { + let hs: Vec = app.session.selection().iter().map(|h| h.hex()).collect(); + let _ = app.run("properties.set", json!({ "handles": hs, "dimStyle": name })); + } else if let Some(n) = id.strip_prefix(DIM_PRECISION).and_then(|n| n.parse::().ok()) { + set_precision(app, n.min(8)); } else { activate(app, id); } diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 708f7abed..2efc774f8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1534,3 +1534,6 @@ Datum triangle Базовий трикутник Datum triangle filled Зафарбований базовий трикутник Integral Інтеграл + Remove Style Overrides Видалити перевизначення стилю + Save as New Style... Зберегти як новий стиль... + Dimension Style Розмірний стиль diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index e65053cdd..246412d4c 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -177,6 +177,7 @@ Dim style 标注样式 Dimension 标注 Dimension Space 标注间距 + Dimension Style 标注样式 Dimension Style Override 标注样式替代 Dimension Style... 标注样式... Dimension Text Edit 编辑标注文字 @@ -616,6 +617,7 @@ Region/Mass Properties 面域/质量特性 Relative 相对 Remove Leader 删除引线 + Remove Style Overrides 删除样式替代 Remove the viewport override 移除视口替代 Rename Dimension Style 重命名标注样式 Rename Layer 重命名图层 @@ -641,6 +643,7 @@ Save (⌘S) 保存 (⌘S) Save As 另存为 Save As... 另存为... + Save as New Style... 另存为新样式... Save Layer State 保存图层状态 Save State 保存状态 Scale 缩放 diff --git a/crates/ui-egui/tests/it/dimension_menu.rs b/crates/ui-egui/tests/it/dimension_menu.rs new file mode 100644 index 000000000..be1d0cb8c --- /dev/null +++ b/crates/ui-egui/tests/it/dimension_menu.rs @@ -0,0 +1,83 @@ +//! The dimension shortcut menu: Align Text, Dimension Style (the drawing's styles, then Save as +//! New Style), Precision and Remove Style Overrides. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{Dimension, EntityKind}; +use cadcraft_ui_egui::menus::Entry; +use cadcraft_ui_egui::{CadApp, Services, context_menu}; +use serde_json::json; + +/// (label path, id, enabled) of the items, submenu items as "Sub/Item". +fn flatten(es: &[Entry]) -> Vec<(String, String, bool)> { + fn walk(prefix: &str, es: &[Entry], out: &mut Vec<(String, String, bool)>) { + for e in es { + match e { + Entry::Item { label, id, enabled, .. } => out.push((format!("{prefix}{label}"), id.clone(), *enabled)), + Entry::Sub { label, children } => walk(&format!("{prefix}{label}/"), children, out), + } + } + } + let mut out = Vec::new(); + walk("", es, &mut out); + out +} + +fn dims(app: &CadApp) -> Vec { + app.session.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Dimension(d) = &e.kind { Some(d.clone()) } else { None }).collect() +} + +/// A drawing with styles Standard and Big and a dimension and an angular dimension, all selected. +fn app() -> CadApp { + let mut app = CadApp::new(Session::new(), Services::default()); + app.run("dimstyle", json!({ "name": "Big", "current": false })).unwrap(); + app.run("dimlinear", json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + app.run("dimangular", json!({ "vertex": [0, 10], "p1": [10, 10], "p2": [0, 20], "at": [3, 13] })).unwrap(); + let all = app.session.doc().unwrap().model.handles(); + app.session.set_selection(all); + app +} + +#[test] +fn selected_dimensions_offer_their_style_precision_and_overrides() { + let mut app = app(); + assert_eq!(dims(&app).len(), 2, "the angular dimension was made"); + let items = flatten(&context_menu::object_entries(&app)); + let has = |label: &str| items.iter().find(|(l, _, _)| l == label).unwrap_or_else(|| panic!("{label} missing from {items:?}")); + for label in ["Align Text/Home", "Dimension Style/Standard", "Dimension Style/Big", "Dimension Style/Save as New Style...", "Precision/0.00"] { + has(label); + } + // Nothing to remove until a dimension overrides its style. + assert!(!has("Remove Style Overrides").2); + // Precision ▸ 0.00: DIMDEC for the linear dimension, DIMADEC for the angular one. + context_menu::choose(&mut app, &format!("{}2", context_menu::DIM_PRECISION)); + let d = dims(&app); + assert_eq!(d[0].overrides.get("decimals"), Some(&json!(2))); + assert_eq!(d[1].overrides.get("angularDecimals"), Some(&json!(2))); + let items = flatten(&context_menu::object_entries(&app)); + assert!(items.iter().any(|(l, _, enabled)| l == "Remove Style Overrides" && *enabled)); + // Dimension Style ▸ Big. + context_menu::choose(&mut app, &format!("{}Big", context_menu::DIM_STYLE)); + assert!(dims(&app).iter().all(|d| d.style == "Big")); + // Remove Style Overrides acts on the selection. + context_menu::choose(&mut app, "dimoverride.clear"); + assert!(app.session.running.is_none()); + assert!(dims(&app).iter().all(|d| d.overrides.is_empty())); +} + +#[test] +fn the_dimension_menu_is_translated() { + let app = app(); + let mut missing = Vec::new(); + for (label, id, _) in flatten(&context_menu::object_entries(&app)) { + let segments: Vec<&str> = label.split('/').collect(); + // Style names are the drawing's own, precisions are numbers. + let data = id.starts_with(context_menu::DIM_STYLE) || id.starts_with(context_menu::DIM_PRECISION); + let n = segments.len() - usize::from(data); + for s in &segments[..n] { + if cadcraft_ui_egui::i18n::tr("uk", s) == *s { + missing.push(s.to_string()); + } + } + } + assert!(missing.is_empty(), "untranslated: {missing:?}"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 5522bac97..1b67627ef 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -8,6 +8,7 @@ mod control_cmdline; mod control_cmdline_key; mod control_methods; mod dialog_dispatch; +mod dimension_menu; mod docking_workflows; mod drafting_polar_increment; mod drafting_spacing; From 8fb5e95f154536ea52887c11c771a8471238e889 Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Wed, 28 Oct 2026 16:17:31 -0400 Subject: [PATCH 10/41] Dimension style shortcut commands: imports by name, as #2239 requires Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/dimstyles.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/dimstyles.rs b/crates/engine/src/cmd/dimstyles.rs index ed5f614a2..57a0280a6 100644 --- a/crates/engine/src/cmd/dimstyles.rs +++ b/crates/engine/src/cmd/dimstyles.rs @@ -6,7 +6,7 @@ use cadcraft_doc::{DimStyle, EntityKind, Handle}; use serde_json::{Value, json}; use super::machines::SelectRun; -use super::*; +use super::{CommandSpec, bad, curves, str_param, targets}; use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; fn other(m: impl Into) -> EngineError { From cec2e0c04a43d84b87e9631e848d5e4426103c93 Mon Sep 17 00:00:00 2001 From: eldrir Date: Tue, 13 Oct 2026 14:06:08 -0400 Subject: [PATCH 11/41] Dimension Style Manager (DIMSTYLE) and -DIMSTYLE DIMSTYLE (D, DST, DDIM, Format and Dimension menus) opens AutoCAD's Dimension Style Manager: the drawing's styles (all, or those in use) with the current style's