Dimension Style Manager, -DIMSTYLE and dimension properties (#1460)

Adds the Dimension Style Manager: DIMSTYLE, D, DST, DDIM and both menu items open it, with the style list, a preview, Set Current, New, Modify, Override, Compare, Delete, Rename and the seven tabs. Also adds -DIMSTYLE and dimstyle.overrides; properties.describe and properties.set rows for text, mtext and dimensions in the Properties palette; and the dimension shortcut menu. Ported from #1042 (with #954, #994 and #1008), on top of this PR's dialog and its validation.

An open manager page is cancelled when another drawing becomes active (from #2322).

Fixes #1459, #1417, #1389.

Co-authored-by: eldrir <[email protected]>
Co-authored-by: Slopapalooza <[email protected]>
Co-authored-by: Luminati <[email protected]>
Signed-off-by: FredApps <[email protected]>
This commit is contained in:
Kushagra Kumar
2026-11-18 21:46:38 +07:00
committed by GitHub
co-authored by eldrir Slopapalooza Luminati
parent b23d172885
commit a770fa5a5e
42 changed files with 5509 additions and 494 deletions
+1
View File
@@ -476,6 +476,7 @@ impl DimStyle {
match field {
"textHeight" | "tolScale" => x.is_some_and(|x| x <= 0.0),
"scale" | "arrowSize" | "tickSize" | "fixedExtLength" => x.is_some_and(|x| x < 0.0),
"decimals" | "altDecimals" | "tolDecimals" => x.is_some_and(|x| !(0.0..=8.0).contains(&x)),
"fit" | "angularZeroSuppression" => x.is_some_and(|x| x > 3.0),
"textMove" | "tolJust" | "arcSymbol" | "textFill" => x.is_some_and(|x| x > 2.0),
"dimLineweight" | "extLineweight" => x.is_some_and(|x| !(-3.0..=211.0).contains(&x)),
+5
View File
@@ -8,6 +8,8 @@ mod audit;
pub(crate) mod blocks;
pub mod clipboard;
pub mod constraints;
mod dimstyle_cli;
mod dimstyles;
mod draw;
mod draw2;
mod draworder;
@@ -35,6 +37,7 @@ mod pline_opts;
pub mod plotters;
mod props;
pub use blocks::library::{clear_library_cache, list_library, read_library_file};
pub use dimstyle_cli::usable_dim_style_name;
pub use draw2::breakline::BreaklineOptions;
pub use props::MatchProps;
pub(crate) use props::UNIT_RANGES;
@@ -187,6 +190,8 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(draw::specs());
v.extend(draw2::specs());
v.extend(annotate::specs());
v.extend(dimstyles::specs());
v.extend(dimstyle_cli::specs());
v.extend(mleader_edit::specs());
v.extend(annoscale::specs());
v.extend(hatch::specs());
+509
View File
@@ -0,0 +1,509 @@
//! -DIMSTYLE, dimension styles at the command line (scripts, the keyboard): save the current
//! settings as a style (annotative or not), make a style current, list the current settings or
//! a style's or a dimension's, compare a style with the current one, give the current settings
//! to dimensions, list the styles. Also `dimstyle.overrides`, which sets the current style's
//! overrides (what the Dimension Style Manager's Override edits), in one undo step.
use cadcraft_doc::{DimStyle, Drawing, EntityKind, Handle};
use serde_json::{Value, json};
use super::machines::{SelOutcome, SelectPhase};
use super::{CommandSpec, bad, bool_or, curves, str_param, targets};
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
const CMD: &str = "-dimstyle";
fn other(m: impl Into<String>) -> EngineError {
EngineError::Other(m.into())
}
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("-dimstyle", "Dimension Style", run)
.params(
"{option: save | annotative | restore | status | variables | apply | list, name?, handle?, handles?, replace?: bool, pattern?} \
→ save (annotative: an annotative style): the current settings (style and its overrides) as style `name`, made current \
(`replace` redefines one); restore: style `name` (or dimension `handle`'s style) made current; status: {variables} of the \
current settings; variables: {variables} of style `name` or dimension `handle`; apply: the current settings given to \
`handles` (default: the selection); list: {styles} matching `pattern` (*, ? and #)",
)
.interactive(|_| Ok(Box::new(DashDimStyle::default()))),
CommandSpec::new("dimstyle.overrides", "Dimension Style Overrides", run_overrides).params(
"{<style fields or DIM* variables: values>, clear?: bool} → {overrides} (the current style's overrides, which new \
dimensions take; `clear` drops them all first)",
),
]
}
/// What new dimensions are drawn with: the current style with its overrides.
fn current_settings(d: &Drawing) -> DimStyle {
let name = d.header.str("DIMSTYLE", "Standard");
let mut st = d.dim_style(&name).cloned().unwrap_or_default().with_overrides(&d.dim_overrides());
st.name = name;
st
}
/// A style's variables (DIM* name → value) as `dimstyle.list` reports them.
fn variables(st: &DimStyle) -> serde_json::Map<String, Value> {
let v = serde_json::to_value(st).unwrap_or(Value::Null);
cadcraft_doc::DIMVARS.iter().filter_map(|(var, field)| v.get(*field).map(|x| ((*var).to_string(), x.clone()))).collect()
}
/// A variable's value as the command line shows it.
fn shown(v: &Value) -> String {
if v.is_object()
&& let Ok(c) = serde_json::from_value::<cadcraft_color::Color>(v.clone())
{
return c.name();
}
match v {
Value::String(s) if s.is_empty() => "\"\"".into(),
Value::String(s) => s.clone(),
Value::Bool(b) => (if *b { "On" } else { "Off" }).into(),
other => other.to_string(),
}
}
/// One line per variable: name, value and what it is.
fn listing(vars: &serde_json::Map<String, Value>) -> Vec<String> {
cadcraft_doc::DIMVARS
.iter()
.filter_map(|(var, field)| {
let v = vars.get(*var)?;
let label = crate::properties::dim_prop(field).map_or(*field, |p| p.label);
Some(format!("{var:<10} {:<20} {label}", shown(v)))
})
.collect()
}
/// The variables of `b` that differ from `a`'s: (name, a's value, b's value).
fn differences(a: &DimStyle, b: &DimStyle) -> Vec<(String, Value, Value)> {
let (va, vb) = (variables(a), variables(b));
cadcraft_doc::DIMVARS
.iter()
.filter_map(|(var, _)| {
let (x, y) = (va.get(*var)?, vb.get(*var)?);
(x != y).then(|| ((*var).to_string(), x.clone(), y.clone()))
})
.collect()
}
/// `name` against a pattern with `*` (any run), `?` (any character) and `#` (a digit), ignoring
/// case: QSELECT's matcher, which takes time in proportion to the lengths (a pattern that backs
/// up at every `*` can't hang the command).
fn matches(pattern: &str, name: &str) -> bool {
let p = pattern.trim();
p.is_empty() || super::qselect::wildcard(p, name)
}
fn styles_matching(d: &Drawing, pattern: &str) -> Vec<String> {
d.dim_styles.iter().filter(|s| matches(pattern, &s.name)).map(|s| s.name.clone()).collect()
}
/// A usable dimension style name, trimmed: for -DIMSTYLE and `dimstyle.saveas` alike. No `~`,
/// which Restore reads as "compare with".
pub(super) fn check_name(name: &str) -> Result<String> {
let name = name.trim();
if !usable_dim_style_name(name) {
return Err(bad(CMD, "bad style name"));
}
Ok(name.to_string())
}
/// Whether `name` (trimmed) is one a new dimension style can have: what -DIMSTYLE,
/// `dimstyle.saveas`, `dimstyle` and `dimstyle.rename` take, for dialogs to check before OK.
pub fn usable_dim_style_name(name: &str) -> bool {
let name = name.trim();
!(name.is_empty() || name.len() > 255 || name.contains(['<', '>', '/', '\\', '"', ':', ';', '?', '*', '|', ',', '=', '`', '~']))
}
/// Save the current settings as style `name` and make it current.
fn save(s: &mut Session, name: &str, annotative: Option<bool>, replace: bool) -> Result<Value> {
let name = check_name(name)?;
// Refused before the drawing is touched: a failed call leaves no (empty) undo step.
if !replace && s.doc()?.dim_style(&name).is_some() {
return Err(bad(CMD, format!("a dimension style `{name}` already exists")));
}
let d = s.doc_mut()?;
let mut st = current_settings(d);
if let Some(a) = annotative {
st.annotative = a;
}
let name = match d.dim_styles.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
Some(existing) if replace => {
let kept = existing.name.clone();
*existing = DimStyle { name: kept.clone(), ..st };
kept
}
Some(_) => return Err(bad(CMD, format!("a dimension style `{name}` already exists"))),
None => {
d.dim_styles.push(DimStyle { name: name.clone(), ..st });
name
}
};
d.header.set_str("DIMSTYLE", &name);
d.sync_dim_vars();
// A redefined style redraws the dimensions that use it.
super::props::regen_dims(d, |dm| dm.style.eq_ignore_ascii_case(&name))?;
Ok(json!({ "style": name }))
}
/// Make style `name` current (its overrides go).
fn restore(s: &mut Session, name: &str) -> Result<Value> {
let n = s.doc()?.dim_style(name).map(|t| t.name.clone()).ok_or_else(|| bad(CMD, format!("no dimension style `{name}`")))?;
let d = s.doc_mut()?;
d.header.set_str("DIMSTYLE", &n);
d.sync_dim_vars();
Ok(json!({ "current": n }))
}
/// Give dimensions the current settings: the current style and its overrides.
fn apply(s: &mut Session, hs: &[Handle]) -> Result<Value> {
// The dimensions among them, found before the drawing is touched: none leaves no undo step.
let d = s.doc()?;
let dims: Vec<Handle> = hs.iter().copied().filter(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Dimension(_)))).collect();
if dims.is_empty() {
return Ok(json!({ "changed": 0 }));
}
let d = s.doc_mut()?;
let style = d.header.str("DIMSTYLE", "Standard");
let overrides = d.dim_overrides();
let mut n = 0;
for h in dims {
d.modify_entity(h, |e| {
if let EntityKind::Dimension(dm) = &mut e.kind {
dm.style.clone_from(&style);
dm.overrides.clone_from(&overrides);
dm.block = None;
n += 1;
}
})?;
}
Ok(json!({ "changed": n }))
}
/// The style and effective settings of dimension `h`.
fn dimension_settings(s: &Session, h: Handle) -> Result<DimStyle> {
let d = s.doc()?;
match d.entity(h).map(|e| &e.kind) {
Some(EntityKind::Dimension(dm)) => Ok(d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides)),
_ => Err(bad(CMD, "not a dimension")),
}
}
fn handle_param(p: &Value) -> Option<Handle> {
p.get("handle").and_then(|v| v.as_str().and_then(Handle::parse_hex).or_else(|| v.as_u64().map(Handle)))
}
fn run(s: &mut Session, p: &Value) -> Result<Value> {
let option = str_param(p, "option").unwrap_or("restore").trim().to_ascii_lowercase();
match option.as_str() {
"save" | "annotative" => {
let name = str_param(p, "name").ok_or_else(|| bad(CMD, "`name` is required"))?.to_string();
let anno = if option == "annotative" { Some(true) } else { p.get("annotative").and_then(Value::as_bool) };
save(s, &name, anno, bool_or(p, "replace", false))
}
"restore" => match handle_param(p) {
Some(h) => {
let name = dimension_settings(s, h)?.name;
restore(s, &name)
}
None => restore(s, str_param(p, "name").ok_or_else(|| bad(CMD, "`name` or `handle` is required"))?),
},
"status" => Ok(json!({ "variables": variables(&current_settings(s.doc()?)) })),
"variables" => {
let st = match handle_param(p) {
Some(h) => dimension_settings(s, h)?,
None => {
let name = str_param(p, "name").ok_or_else(|| bad(CMD, "`name` or `handle` is required"))?;
s.doc()?.dim_style(name).cloned().ok_or_else(|| bad(CMD, format!("no dimension style `{name}`")))?
}
};
Ok(json!({ "style": st.name, "variables": variables(&st) }))
}
"apply" => {
let hs = targets(s, p)?;
apply(s, &hs)
}
"list" | "?" => Ok(json!({ "styles": styles_matching(s.doc()?, str_param(p, "pattern").unwrap_or("*")) })),
_ => Err(bad(CMD, "`option` is save, annotative, restore, status, variables, apply or list")),
}
}
/// `dimstyle.overrides`: set the current style's overrides (the header DIM* variables).
fn run_overrides(s: &mut Session, p: &Value) -> Result<Value> {
let clear = bool_or(p, "clear", false);
let mut given = serde_json::Map::new();
for (k, v) in p.as_object().into_iter().flatten() {
if k == "clear" {
continue;
}
let field = DimStyle::field_name(k)
.filter(|f| !matches!(*f, "name" | "annotative"))
.ok_or_else(|| bad("dimstyle.overrides", format!("`{k}` is not a dimension variable")))?;
given.insert(field.to_string(), v.clone());
}
// Checked first (against the style alone when its overrides go), so nothing changes when
// one value is unusable: a command's error doesn't undo what it did.
let d = s.doc()?;
let mut base = current_settings(d);
if clear {
base = d.dim_style(&base.name).cloned().unwrap_or_default();
}
let rejected = base.apply_fields(&given);
if !rejected.is_empty() {
return Err(bad("dimstyle.overrides", format!("unusable values for {}", rejected.join(", "))));
}
// The values as the style took them (a lineweight named ByLayer is -1, ...): what the
// header variables hold, so writing them can't fail halfway.
let taken = serde_json::to_value(&base).unwrap_or(Value::Null);
if clear {
s.doc_mut()?.sync_dim_vars();
}
for (field, v) in &given {
let Some((var, _)) = cadcraft_doc::DIMVARS.iter().find(|(_, f)| f == field) else { continue };
let v = taken.get(field.as_str()).unwrap_or(v);
// Colors are stored as color numbers in the header.
let v = match serde_json::from_value::<cadcraft_color::Color>(v.clone()).ok().or_else(|| v.as_str().and_then(cadcraft_color::Color::parse)) {
Some(c) if field.ends_with("Color") => json!(c.to_aci()),
_ => v.clone(),
};
crate::sysvars::set(s, var, &v)?;
}
Ok(json!({ "overrides": s.doc()?.dim_overrides() }))
}
/// What -DIMSTYLE asks next.
#[derive(Clone, Default)]
enum Ask {
#[default]
Option,
Annotative,
SaveName {
annotative: Option<bool>,
},
Redefine {
name: String,
annotative: Option<bool>,
},
RestoreName,
RestorePick,
VariablesName,
VariablesPick,
Apply,
ListPattern,
}
#[derive(Default)]
struct DashDimStyle {
ask: Ask,
sel: SelectPhase,
}
impl DashDimStyle {
fn list(&self, s: &mut Session, pattern: &str) -> Result<()> {
let names = styles_matching(s.doc()?, pattern);
s.echo(format!("Named dimension styles: {}", if names.is_empty() { "none".into() } else { names.join(", ") }));
Ok(())
}
fn show_variables(&self, s: &mut Session, st: &DimStyle) {
s.echo(format!("Dimension style: {}", st.name));
for line in listing(&variables(st)) {
s.echo(line);
}
}
fn answer(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let ask = std::mem::take(&mut self.ask);
let text = match &i {
Input::Text(t) | Input::Keyword(t) => Some(t.trim().to_string()),
_ => None,
};
match ask {
Ask::Option => {
let k = text.unwrap_or_else(|| "Restore".into());
self.ask = match k.to_ascii_lowercase().as_str() {
"annotative" | "an" => Ask::Annotative,
"save" | "s" => Ask::SaveName { annotative: None },
"restore" | "r" | "" => Ask::RestoreName,
"status" | "st" => {
let st = current_settings(s.doc()?);
self.show_variables(s, &st);
return Ok(Step::Done);
}
"variables" | "v" => Ask::VariablesName,
"apply" | "a" => Ask::Apply,
"?" => Ask::ListPattern,
_ => return Err(other("Enter one of the options.")),
};
Ok(Step::Continue)
}
Ask::Annotative => {
let yes = !matches!(text.as_deref().map(str::to_ascii_lowercase).as_deref(), Some("no" | "n"));
self.ask = Ask::SaveName { annotative: Some(yes) };
Ok(Step::Continue)
}
Ask::SaveName { annotative } => match text.as_deref() {
None | Some("") => Ok(Step::Done),
Some("?") => {
self.list(s, "*")?;
self.ask = Ask::SaveName { annotative };
Ok(Step::Continue)
}
Some(name) => {
let name = match check_name(name) {
Ok(n) => n,
Err(e) => {
self.ask = Ask::SaveName { annotative };
return Err(e);
}
};
if s.doc()?.dim_style(&name).is_some() {
self.ask = Ask::Redefine { name, annotative };
return Ok(Step::Continue);
}
save(s, &name, annotative, false)?;
Ok(Step::Done)
}
},
Ask::Redefine { name, annotative } => {
if matches!(text.as_deref().map(str::to_ascii_lowercase).as_deref(), Some("yes" | "y")) {
save(s, &name, annotative, true)?;
Ok(Step::Done)
} else {
self.ask = Ask::SaveName { annotative };
Ok(Step::Continue)
}
}
Ask::RestoreName => match text.as_deref() {
None | Some("") => {
self.ask = Ask::RestorePick;
Ok(Step::Continue)
}
Some("?") => {
self.list(s, "*")?;
self.ask = Ask::RestoreName;
Ok(Step::Continue)
}
// ~name: how style `name` differs from the current settings.
Some(t) if t.starts_with('~') => {
let d = s.doc()?;
let other_style = d.dim_style(t.trim_start_matches('~').trim()).cloned().ok_or_else(|| other("No such dimension style."))?;
let current = current_settings(d);
let diff = differences(&current, &other_style);
s.echo(format!("Differences between {} and current settings:", other_style.name));
if diff.is_empty() {
s.echo("None".to_string());
}
for (var, cur, theirs) in diff {
s.echo(format!("{var:<10} {:<20} {}", shown(&theirs), shown(&cur)));
}
self.ask = Ask::RestoreName;
Ok(Step::Continue)
}
Some(name) => {
if let Err(e) = restore(s, name) {
self.ask = Ask::RestoreName;
return Err(e);
}
Ok(Step::Done)
}
},
Ask::RestorePick | Ask::VariablesPick => {
let restoring = matches!(ask, Ask::RestorePick);
let Input::Point(p) = i else {
if matches!(i, Input::Enter) {
return Ok(Step::Done);
}
// Anything else asks for the dimension again.
self.ask = ask;
return Ok(Step::Continue);
};
let picked = curves::pick_at(s, p).and_then(|h| dimension_settings(s, h).ok());
let Some(st) = picked else {
self.ask = if restoring { Ask::RestorePick } else { Ask::VariablesPick };
return Err(other("Select a dimension."));
};
if restoring {
restore(s, &st.name)?;
} else {
self.show_variables(s, &st);
}
Ok(Step::Done)
}
Ask::VariablesName => match text.as_deref() {
None | Some("") => {
self.ask = Ask::VariablesPick;
Ok(Step::Continue)
}
Some("?") => {
self.list(s, "*")?;
self.ask = Ask::VariablesName;
Ok(Step::Continue)
}
Some(name) => {
let Some(st) = s.doc()?.dim_style(name).cloned() else {
self.ask = Ask::VariablesName;
return Err(other("No such dimension style."));
};
self.show_variables(s, &st);
Ok(Step::Done)
}
},
Ask::Apply => match self.sel.feed(s, &i)? {
SelOutcome::More => {
self.ask = Ask::Apply;
Ok(Step::Continue)
}
SelOutcome::Empty => Ok(Step::Done),
SelOutcome::Done(hs) => {
let r = apply(s, &hs)?;
s.echo(format!("{} dimension(s) take the current settings.", r["changed"]));
s.set_selection(Vec::new());
Ok(Step::Done)
}
},
Ask::ListPattern => {
self.list(s, text.as_deref().filter(|t| !t.is_empty()).unwrap_or("*"))?;
Ok(Step::Done)
}
}
}
}
impl Interactive for DashDimStyle {
fn name(&self) -> &'static str {
"-DIMSTYLE"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
let d = s.doc()?;
let current = d.header.str("DIMSTYLE", "Standard");
let annotative = d.dim_style(&current).is_some_and(|st| st.annotative);
let overridden = if d.dim_overrides().is_empty() { "" } else { " (with overrides)" };
s.echo(format!("Current dimension style: {current}{overridden} Annotative: {}", if annotative { "Yes" } else { "No" }));
Ok(Step::Continue)
}
fn prompt(&self, _s: &Session) -> Prompt {
match &self.ask {
Ask::Option => Prompt::new("Enter a dimension style option", curves::KW)
.kw(&["ANnotative", "Save", "Restore", "STatus", "Variables", "Apply", "?"])
.default("Restore"),
Ask::Annotative => Prompt::new("Create annotative dimension style", curves::KW).kw(&["Yes", "No"]).default("Yes"),
Ask::SaveName { .. } => Prompt::new("Enter name for new dimension style or [?]", Accept::TEXT).kw(&["?"]),
Ask::Redefine { .. } => Prompt::new("That name is already in use, redefine it?", curves::KW).kw(&["Yes", "No"]).default("No"),
Ask::RestoreName => Prompt::new("Enter a dimension style name, [?] or <select dimension>", Accept::TEXT).kw(&["?"]),
Ask::RestorePick | Ask::VariablesPick => Prompt::new("Select dimension", Accept::POINT),
Ask::VariablesName => Prompt::new("Enter a dimension style name, [?] or <select dimensions>", Accept::TEXT).kw(&["?"]),
Ask::Apply => self.sel.prompt(),
Ask::ListPattern => Prompt::new("Enter dimension style(s) to list", Accept::TEXT).default("*"),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
// A refused answer asks the same question again.
let asked = self.ask.clone();
let r = self.answer(s, i);
if r.is_err() {
self.ask = asked;
}
r
}
}
+108
View File
@@ -0,0 +1,108 @@
//! 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::{CommandSpec, bad, curves, str_param, targets};
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
fn other(m: impl Into<String>) -> EngineError {
EngineError::Other(m.into())
}
pub fn specs() -> Vec<CommandSpec> {
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<Value> {
let hs: Vec<String> = 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 (as -DIMSTYLE takes one).
fn new_name(s: &Session, name: &str) -> Result<String> {
let name = super::dimstyle_cli::check_name(name).map_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)
}
/// 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<Value> {
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<Value> {
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<Handle>,
}
impl Interactive for SaveAsM {
fn name(&self) -> &'static str {
"DIMSTYLE"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
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<Step> {
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),
}
}
}
+2 -1
View File
@@ -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::{lines_for, run_patterns};
use cadcraft_color::Color;
use cadcraft_doc::{Drawing, Entity, EntityKind, Gradient, Handle, Hatch, HatchLoop, Space, entity_bounds};
+40 -18
View File
@@ -143,21 +143,8 @@ fn separate(s: &mut Session, handle: Handle) -> Result<Vec<Handle>> {
/// 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<Value> {
// 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));
+94 -372
View File
@@ -6,22 +6,31 @@ 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, Handle, Lineweight, Transparency};
use cadcraft_geom::Vec3;
use cadcraft_doc::{EntityKind, Lineweight, Transparency};
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};
pub fn specs() -> Vec<CommandSpec> {
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?, <geometry fields: radius, center, start, end, text, height, rotation…>; dimensions: textOverride, dimStyle, textHeight, arrowSize, dimScale, precision (per-dimension overrides)} → {changed, locked, message?}: objects on locked layers (and, during REFEDIT, outside the working set) are left out, and `message` says how many"),
CommandSpec::new("properties.set", "Set Properties", run_set).params(
"{handles?, layer?, color?, linetype?, lineweight?, ltscale?, thickness?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, annotative?, \
<geometry fields: radius, center, start, end, text, height, rotation…>, 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?, \
<dimension style variables (field or DIM* name, e.g. textHeight / DIMTXT) set as overrides of each dimension>, clearOverrides?, clear?: [variable]} \
→ {changed, locked, message?, ignored: keys no selected object took} (the keys are those of `properties.describe` rows): objects on locked layers \
(and, during REFEDIT, outside the working set) are left out, and `message` says how many",
),
CommandSpec::new("chprop", "Change Properties", run_set)
.params("as properties.set, leaving out objects on locked layers (and, during REFEDIT, outside the working set) → {changed, locked, message?} (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<CommandSpec> {
.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<Color> {
/// 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<Value> {
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,369 +208,6 @@ fn parse_transparency(v: &Value) -> Option<Transparency> {
(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;
}
}
/// The objects `properties.set` leaves alone, as CHPROP, MATCHPROP and MOVE do: those on locked
/// layers and, while a reference is edited in place, those outside the working set.
#[derive(Default)]
struct LeftOut {
locked: usize,
outside: usize,
}
impl LeftOut {
/// `hs` without the objects that can't be edited, each object once, and how many those were. A
/// handle that names no object is an error, before anything changes.
fn split(s: &Session, hs: Vec<Handle>) -> Result<(Vec<Handle>, LeftOut)> {
let d = s.doc()?;
// The working set, once: `RefEdit::is_working` searches a list.
let working: Option<std::collections::HashSet<Handle>> = d.refedit.as_ref().map(|r| r.items.iter().map(|i| i.copy).collect());
let mut seen = std::collections::HashSet::new();
let mut out = LeftOut::default();
let mut free = Vec::new();
for h in hs {
let Some(e) = d.entity(h) else {
return Err(cadcraft_doc::DocError::NoEntity(h).into());
};
if !seen.insert(h) {
continue;
}
if working.as_ref().is_some_and(|w| !w.contains(&h)) {
out.outside += 1;
} else if d.layer(&e.common.layer).is_some_and(|l| l.locked) {
out.locked += 1;
} else {
free.push(h);
}
}
Ok((free, out))
}
/// `{changed, locked}`, and a message saying how many were left out when any were.
fn result(&self, changed: usize) -> Value {
let mut notes = Vec::new();
match self.locked {
0 => {}
1 => notes.push("1 object was on a locked layer.".to_string()),
n => notes.push(format!("{n} objects were on a locked layer.")),
}
match self.outside {
0 => {}
1 => notes.push("1 object was not in the working set.".to_string()),
n => notes.push(format!("{n} objects were not in the working set.")),
}
if changed == 0 && !notes.is_empty() {
notes.push("Nothing was changed.".to_string());
}
let mut r = json!({ "changed": changed, "locked": self.locked + self.outside });
if !notes.is_empty()
&& let Some(o) = r.as_object_mut()
{
o.insert("message".into(), json!(notes.join(" ")));
}
r
}
}
fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
if hs.is_empty() {
return Err(bad("properties.set", "nothing selected"));
}
let (hs, left_out) = LeftOut::split(s, hs)?;
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()?;
// 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()?;
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)?;
if hs.is_empty() {
// Every object was left out: the drawing stays as it was, with no undo step.
return Ok(left_out.result(0));
}
let d = s.doc_mut()?;
if let Some(l) = str_param(p, "layer") {
d.ensure_layer(l);
}
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(left_out.result(hs.len()))
}
fn apply_kind_properties(
entity: &mut cadcraft_doc::Entity,
params: &Value,
dim_style: Option<&String>,
dim_overrides: &serde_json::Map<String, Value>,
) {
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();
}
}
// A multileader's text: its contents (#1081) and height.
EntityKind::MLeader(m) => {
if let Some(t) = &mut m.text {
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;
}
}
}
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<String, Value>,
) {
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<Color>,
linetype: Option<&'a str>,
lineweight: Option<Lineweight>,
transparency: Option<Transparency>,
thickness: Option<f64>,
}
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<Value> {
let c = p.get("color").and_then(parse_color).ok_or_else(|| bad("color", "`color` is required"))?;
set_current_color(s.doc_mut()?, c);
@@ -791,6 +447,8 @@ fn run_style(s: &mut Session, p: &Value) -> Result<Value> {
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 => {
@@ -826,6 +484,13 @@ fn run_style(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
// 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<String, String> =
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);
}
@@ -860,6 +525,7 @@ pub(super) fn text_styles_in_use(d: &cadcraft_doc::Drawing) -> Vec<String> {
EntityKind::MText(t) => out.push(t.style.clone()),
EntityKind::AttDef(a) => out.extend(attrib_text_styles(a)),
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()
@@ -907,6 +573,7 @@ fn run_style_rename(s: &mut Session, p: &Value) -> Result<Value> {
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 {
@@ -915,6 +582,8 @@ fn run_style_rename(s: &mut Session, p: &Value) -> Result<Value> {
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<cadcraft_doc::Handle> = d.model.iter().filter(|e| uses(&e.kind)).map(|e| e.handle).collect();
@@ -964,7 +633,14 @@ fn run_dimstyle(s: &mut Session, p: &Value) -> Result<Value> {
if name.is_empty() || name.len() > 255 {
return Err(bad("dimstyle", "bad style name"));
}
// A new style's name is one -DIMSTYLE takes (no `~`, which its Restore reads as compare, or
// wildcards); a style read from a file keeps the name it has.
if s.doc()?.dim_style(&name).is_none() {
super::dimstyle_cli::check_name(&name).map_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,
@@ -979,6 +655,12 @@ fn run_dimstyle(s: &mut Session, p: &Value) -> Result<Value> {
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 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);
}
@@ -990,7 +672,8 @@ fn run_dimstyle(s: &mut Session, p: &Value) -> Result<Value> {
if !rejected.is_empty()
&& let Some(o) = out.as_object_mut()
{
o.insert("ignored".into(), json!(rejected));
o.insert("ignored".into(), json!(rejected.clone()));
o.insert("message".into(), json!(format!("Ignored invalid value for: {}", rejected.join(", "))));
}
Ok(out)
}
@@ -1021,6 +704,44 @@ fn run_dimstyle_current(s: &mut Session, p: &Value) -> Result<Value> {
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.
pub(super) 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<cadcraft_doc::Handle> = 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<cadcraft_doc::Handle> = 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, String>) -> 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()))) {
@@ -1063,6 +784,7 @@ fn block_dims_using(d: &cadcraft_doc::Drawing, name: &str) -> Vec<(String, cadcr
fn run_dimstyle_rename(s: &mut Session, p: &Value) -> Result<Value> {
let from = str_param(p, "from").ok_or_else(|| bad("dimstyle.rename", "`from` is required"))?.to_string();
let to = str_param(p, "to").map(str::trim).filter(|t| !t.is_empty()).ok_or_else(|| bad("dimstyle.rename", "`to` is required"))?.to_string();
let to = super::dimstyle_cli::check_name(&to).map_err(|_| bad("dimstyle.rename", "bad style name"))?;
let d = s.doc_mut()?;
if from.eq_ignore_ascii_case("Standard") {
return Err(bad("dimstyle.rename", "the Standard style cannot be renamed"));
+781
View File
@@ -0,0 +1,781 @@
//! `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_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::{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) {
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",
// 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
/// 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<String>,
}
impl DimVars {
fn new(d: &Drawing, p: &Value) -> Result<Self> {
// 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")))?)
}
}
// 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);
}
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<Handle, Vec2>,
/// Dimensions: where their text is drawn now.
text_pos: HashMap<Handle, Vec2>,
/// 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<HashMap<String, (String, String)>>,
}
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 => {
// 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 {
out.posts = Some(d.dim_styles.iter().map(|st| (st.name.to_ascii_lowercase(), (st.post.clone(), st.alt_post.clone()))).collect());
}
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<Vec2>) {
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);
}
/// 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<Color>,
transparency: Option<Transparency>,
thickness: Option<f64>,
lineweight: Option<Lineweight>,
linetype: Option<String>,
dim_style: Option<String>,
text_style: Option<String>,
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<f64> {
self.p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite())
}
}
/// The objects `properties.set` leaves alone, as CHPROP, MATCHPROP and MOVE do: those on locked
/// layers and, while a reference is edited in place, those outside the working set.
#[derive(Default)]
struct LeftOut {
locked: usize,
outside: usize,
}
impl LeftOut {
/// `hs` without the objects that can't be edited, each object once, and how many those were. A
/// handle that names no object is an error, before anything changes.
fn split(s: &Session, hs: Vec<Handle>) -> Result<(Vec<Handle>, LeftOut)> {
let d = s.doc()?;
// The working set, once: `RefEdit::is_working` searches a list.
let working: Option<std::collections::HashSet<Handle>> = d.refedit.as_ref().map(|r| r.items.iter().map(|i| i.copy).collect());
let mut seen = std::collections::HashSet::new();
let mut out = LeftOut::default();
let mut free = Vec::new();
for h in hs {
let Some(e) = d.entity(h) else {
return Err(cadcraft_doc::DocError::NoEntity(h).into());
};
if !seen.insert(h) {
continue;
}
if working.as_ref().is_some_and(|w| !w.contains(&h)) {
out.outside += 1;
} else if d.layer(&e.common.layer).is_some_and(|l| l.locked) {
out.locked += 1;
} else {
free.push(h);
}
}
Ok((free, out))
}
/// `{changed, locked, ignored}`, and a message saying how many were left out when any were.
fn result(&self, changed: usize, ignored: &[&str]) -> Value {
let mut notes = Vec::new();
match self.locked {
0 => {}
1 => notes.push("1 object was on a locked layer.".to_string()),
n => notes.push(format!("{n} objects were on a locked layer.")),
}
match self.outside {
0 => {}
1 => notes.push("1 object was not in the working set.".to_string()),
n => notes.push(format!("{n} objects were not in the working set.")),
}
if changed == 0 && !notes.is_empty() {
notes.push("Nothing was changed.".to_string());
}
let mut r = json!({ "changed": changed, "locked": self.locked + self.outside, "ignored": ignored });
if !notes.is_empty()
&& let Some(o) = r.as_object_mut()
{
o.insert("message".into(), json!(notes.join(" ")));
}
r
}
}
pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
if hs.is_empty() {
return Err(bad("properties.set", "nothing selected"));
}
let (hs, left_out) = LeftOut::split(s, hs)?;
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 lineweight =
p.get("lineweight").map(|v| crate::cmd::layer::parse_lw(v).ok_or_else(|| bad("properties.set", "bad lineweight"))).transpose()?;
// Every check reads the drawing first: a refused call leaves no empty undo step.
let d = s.doc()?;
// 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()?;
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)?;
// 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())));
}
if hs.is_empty() {
// Every object was left out: the drawing stays as it was, with no undo step.
return Ok(left_out.result(0, &[]));
}
let prep = Prepared::new(d, p, &hs);
let anno_scale = d.current_anno_scale();
let c = Call { p, color, transparency, thickness, lineweight, linetype, dim_style, text_style, dim_vars, prep, anno_scale };
// A failed call changes nothing (a command's error doesn't undo what it did), so the drawing
// is taken for writing, and the layer made, only after every check.
let d = s.doc_mut()?;
if let Some(l) = str_param(p, "layer") {
d.ensure_layer(l);
}
let mut used = Used::new();
for h in &hs {
let h = *h;
d.modify_entity(h, |e| {
common(e, &c, &mut used);
match &mut e.kind {
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) => {
text(t, &c, h, &mut used);
text_position(t, &c, &mut used);
}
EntityKind::MText(t) => mtext(t, &c, &mut used),
EntityKind::MLeader(m) => mleader(m, &c, &mut used),
EntityKind::LwPolyline(pl) => {
if let Some(x) = c.num("width").filter(|x| *x >= 0.0) {
pl.const_width = x;
used.insert("width");
}
if let Some(closed) = p.get("closed").and_then(Value::as_bool) {
pl.closed = closed;
used.insert("closed");
}
}
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),
_ => {}
}
})?;
}
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(left_out.result(hs.len(), &ignored))
}
/// A multileader's text: its contents (#1081) and height.
fn mleader<'c>(m: &mut cadcraft_doc::MLeader, c: &'c Call<'_>, used: &mut Used<'c>) {
let Some(t) = &mut m.text else { return };
if let Some(v) = str_param(c.p, "text") {
t.contents = v.replace('\n', "\\P");
used.insert("text");
}
if let Some(x) = c.num("height").filter(|x| *x > 0.0) {
t.height = x;
used.insert("height");
}
}
/// 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::<String>().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");
}
}
+1
View File
@@ -27,6 +27,7 @@ pub mod lisp;
pub mod mtext_edit;
pub mod pointmod;
pub mod prompt;
pub mod properties;
mod recent;
pub mod render_look;
pub mod sample;
+806
View File
@@ -0,0 +1,806 @@
//! 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<TypeCount>,
/// 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<Group>,
}
#[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<Row>,
}
/// 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<String>,
/// 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<Choice>,
/// 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
}
fn overridden_if(mut self, overridden: bool) -> Self {
self.overridden = overridden;
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Choice {
pub value: Value,
pub label: String,
}
impl Choice {
fn new(value: Value, label: impl Into<String>) -> 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,
/// 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,
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<TypeCount> = 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,
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),
angles: units::AngleSettings::from_header(h),
}
}
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::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),
}
}
/// A row valued by `values` (one per described object).
fn row(&self, key: &'static str, label: &'static str, kind: Kind, values: impl IntoIterator<Item = Value>) -> 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<Choice>, values: impl IntoIterator<Item = Value>) -> Row {
let mut it = values.into_iter();
let first = it.next().unwrap_or(Value::Null);
let varies = it.any(|v| !same(&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<Choice> {
self.d.text_styles.iter().map(|t| Choice::new(json!(t.name), t.name.clone())).collect()
}
fn dim_styles(&self) -> Vec<Choice> {
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", "Align"),
("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<Choice> {
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<Group> {
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", "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::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()))),
];
// Aligned and fit text sit between two points: the second is the text alignment point.
let second: Option<Vec<cadcraft_geom::Vec3>> =
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<Group> {
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", "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::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(
"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 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")];
/// 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", "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),
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 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)),
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", 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", "Upper tolerance", DimPropKind::Number),
prop("tolMinus", "Tolerances", "Lower tolerance", DimPropKind::Number),
prop("tolDecimals", "Tolerances", "Tolerance precision", DimPropKind::Precision),
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),
];
/// 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 arrow"),
("_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 {
/// The values a choice kind can take, with their labels (none for the other kinds; text
/// styles are the drawing's).
pub fn options(self) -> Vec<Choice> {
match self {
DimPropKind::Choice(list) => list.iter().map(|(v, l)| Choice::new(json!(v), *l)).collect(),
DimPropKind::Precision => {
(0..=8u8).map(|n| Choice::new(json!(n), if n == 0 { "0".into() } else { format!("0.{}", "0".repeat(usize::from(n))) })).collect()
}
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())));
o
}
DimPropKind::Arrow => ARROWHEADS.iter().map(|(v, l)| Choice::new(json!(v), *l)).collect(),
DimPropKind::Separator => [(".", "Period"), (",", "Comma"), (" ", "Space")].iter().map(|(v, l)| Choice::new(json!(v), *l)).collect(),
_ => Vec::new(),
}
}
fn row_kind(self, c: &Ctx) -> (Kind, Vec<Choice>) {
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::Color => (Kind::Color, Vec::new()),
DimPropKind::TextStyle => (Kind::TextStyle, c.text_styles()),
DimPropKind::Linetype => (Kind::Linetype, Vec::new()),
DimPropKind::Choice(_) | DimPropKind::Precision | DimPropKind::Lineweight | DimPropKind::Arrow | DimPropKind::Separator => {
(Kind::Choice, self.options())
}
}
}
}
/// `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::<String>().to_ascii_lowercase()
}
/// A dimension style field's value as the row shows and `properties.set` takes it: a color's
/// name, ByBlock for an empty linetype, and the arrowhead an empty per-end arrowhead draws.
pub 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::<cadcraft_color::Color>(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 (an empty leader arrowhead is closed filled).
let name = v.as_str().filter(|s| !s.is_empty() || !matches!(p.field, "arrowBlock1" | "arrowBlock2")).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 {
// 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),
}
}
fn dimension_groups(c: &Ctx, ents: &[&Entity], dims: &[&Dimension]) -> Vec<Group> {
let styles: Vec<DimStyle> = dims.iter().map(|dm| c.d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides)).collect();
let values: Vec<Value> = 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<Vec<cadcraft_render::DimGeometry>> =
(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<Row> = 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<Value>, Vec<Value>) = 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();
let shown = measured.first().map(|(_, s)| s.clone()).unwrap_or_default();
// Equal measurements written differently (units, precision) vary too.
if measured.iter().any(|(_, s)| *s != shown) {
(m.value, m.varies, m.display) = (Value::Null, true, VARIES.to_string());
} else if !m.varies {
m.display = shown;
}
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<Value>, Vec<Value>) = 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());
// 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).overridden_if(posted));
}
"Alternate Units" => {
let (pre, suf): (Vec<Value>, Vec<Value>) =
styles.iter().map(|st| split_post(&st.alt_post)).map(|(p, s)| (json!(p), json!(s))).unzip();
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));
}
_ => {}
}
groups.push(Group { name, rows });
}
groups
}
/// Equal values, numbers to 12 significant digits, as the palette compares them: float noise
/// (7 and 7.0000000000001, or 1.2e-16 next to zero) is no difference, while values the display
/// rounds alike (7 and 7.000001) still differ.
fn same(a: &Value, b: &Value) -> bool {
fn tag(v: f64) -> String {
let v = if v.abs() < 1e-12 { 0.0 } else { v };
format!("{:.11e}", v + 0.0)
}
match (a, b) {
(Value::Number(x), Value::Number(y)) => match (x.as_f64(), y.as_f64()) {
(Some(x), Some(y)) => tag(x) == tag(y),
_ => x == y,
},
_ => a == b,
}
}
/// 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<Option<(&str, f64)>> = 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 {
// Each dimension's text is its style's fixed height or its own DIMTXT.
let heights: Vec<f64> = 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());
}
}
+88
View File
@@ -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 (no `~`, which -DIMSTYLE Restore reads as compare).
for name in ["detail", " ", "a<b", "~Plan"] {
assert!(s.execute("dimstyle.saveas", &json!({ "handle": h.hex(), "name": name })).is_err(), "{name}");
}
// Only dimensions.
s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap();
let c = s.doc().unwrap().model.last().unwrap().handle;
assert!(s.execute("dimstyle.saveas", &json!({ "handle": c.hex(), "name": "Other" })).is_err());
}
#[test]
fn save_as_new_style_from_the_menu_asks_for_a_name() {
let mut s = Session::new();
let h = dimension(&mut s, 0.0);
s.execute("properties.set", &json!({ "handles": [h.hex()], "textHeight": 0.3 })).unwrap();
s.set_selection(vec![h]);
s.start("dimstyle.saveas").unwrap();
assert!(s.prompt_text().contains("name of new dimension style"), "{}", s.prompt_text());
// A name already taken is refused, said why, and asked again.
let _ = s.input(Input::Text("Standard".into()));
assert!(s.running.is_some(), "a taken name asks again");
assert!(s.log.iter().any(|l| l.contains("already exists")), "{:?}", s.log);
s.input(Input::Text("Detail".into())).unwrap();
assert!(s.running.is_none());
assert_eq!(dim(&s, h).style, "Detail");
}
#[test]
fn save_as_new_style_picks_a_dimension_when_none_is_selected() {
let mut s = Session::new();
let h = dimension(&mut s, 0.0);
s.start("dimstyle.saveas").unwrap();
assert!(s.prompt_text().contains("Select a dimension"), "{}", s.prompt_text());
// The dimension line of the dimension.
s.input(Input::Point(cadcraft_engine::geom::Vec2::new(5.0, 3.0))).unwrap();
s.input(Input::Text("Picked".into())).unwrap();
assert_eq!(dim(&s, h).style, "Picked");
}
+228
View File
@@ -0,0 +1,228 @@
//! -DIMSTYLE at the command line and as JSON (save, annotative, restore, status, variables,
//! apply, list), and `dimstyle.overrides`, which sets the current style's overrides.
use cadcraft_engine::doc::{Dimension, EntityKind, Handle};
use cadcraft_engine::{Input, Session};
use serde_json::json;
fn dimension(s: &mut Session) -> Handle {
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).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:?}"),
}
}
fn current(s: &Session) -> String {
s.doc().unwrap().header.str("DIMSTYLE", "")
}
#[test]
fn save_restore_status_and_variables_as_json() {
let mut s = Session::new();
// A current-style override (SETVAR) goes into the saved style.
s.execute("setvar", &json!({ "name": "DIMTXT", "value": 0.25 })).unwrap();
let r = s.execute("-dimstyle", &json!({ "option": "save", "name": "Plan" })).unwrap();
assert_eq!(r["style"], "Plan");
assert_eq!(current(&s), "Plan");
let d = s.doc().unwrap();
assert!(d.dim_overrides().is_empty(), "saved into the style");
assert_eq!(d.dim_style("Plan").unwrap().text_height, 0.25);
// A name in use is redefined only when asked to.
assert!(s.execute("-dimstyle", &json!({ "option": "save", "name": "plan" })).is_err());
s.execute("-dimstyle", &json!({ "option": "save", "name": "plan", "replace": true })).unwrap();
assert_eq!(s.doc().unwrap().dim_styles.iter().filter(|st| st.name.eq_ignore_ascii_case("plan")).count(), 1);
s.execute("-dimstyle", &json!({ "option": "restore", "name": "standard" })).unwrap();
assert_eq!(current(&s), "Standard");
let status = s.execute("-dimstyle", &json!({ "option": "status" })).unwrap();
assert_eq!(status["variables"]["DIMTXT"], 0.18);
let vars = s.execute("-dimstyle", &json!({ "option": "variables", "name": "Plan" })).unwrap();
assert_eq!(vars["variables"]["DIMTXT"], 0.25);
s.execute("-dimstyle", &json!({ "option": "annotative", "name": "Anno" })).unwrap();
assert!(s.doc().unwrap().dim_style("Anno").unwrap().annotative);
let list = s.execute("-dimstyle", &json!({ "option": "list", "pattern": "p*" })).unwrap();
assert_eq!(list["styles"], json!(["Plan"]));
// A dimension's style becomes current; its variables include its overrides.
let h = dimension(&mut s);
s.execute("properties.set", &json!({ "handles": [h.hex()], "textHeight": 0.4 })).unwrap();
let vars = s.execute("-dimstyle", &json!({ "option": "variables", "handle": h.hex() })).unwrap();
assert_eq!(vars["variables"]["DIMTXT"], 0.4);
s.execute("-dimstyle", &json!({ "option": "restore", "handle": h.hex() })).unwrap();
assert_eq!(current(&s), "Anno");
}
#[test]
fn apply_gives_dimensions_the_current_settings() {
let mut s = Session::new();
let h = dimension(&mut s);
s.execute("dimstyle", &json!({ "name": "Plan", "DIMTXT": 0.3 })).unwrap();
s.execute("setvar", &json!({ "name": "DIMDEC", "value": 1 })).unwrap();
let r = s.execute("-dimstyle", &json!({ "option": "apply", "handles": [h.hex()] })).unwrap();
assert_eq!(r["changed"], 1);
let d = dim(&s, h);
assert_eq!(d.style, "Plan");
assert_eq!(d.overrides.get("decimals"), Some(&json!(1)));
let g = cadcraft_engine::render::dimension_in(s.doc().unwrap(), &d);
assert_eq!(g.value, "10.0");
}
#[test]
fn the_command_line_asks_like_autocad() {
let mut s = Session::new();
s.cmdline("-DIMSTYLE").unwrap();
assert!(s.prompt_text().contains("ANnotative"), "{}", s.prompt_text());
s.cmdline("S").unwrap();
s.cmdline("Plan").unwrap();
assert!(s.running.is_none());
assert_eq!(current(&s), "Plan");
s.cmdline("-DIMSTYLE").unwrap();
s.cmdline("R").unwrap();
s.cmdline("Standard").unwrap();
assert_eq!(current(&s), "Standard");
let before = s.log.len();
s.cmdline("-DIMSTYLE").unwrap();
s.cmdline("ST").unwrap();
assert!(s.log[before..].iter().any(|l| l.starts_with("DIMTXT") && l.contains("Text height")), "{:?}", &s.log[before..]);
// A name in use asks to redefine it.
s.cmdline("-DIMSTYLE").unwrap();
s.cmdline("S").unwrap();
s.cmdline("Plan").unwrap();
assert!(s.prompt_text().contains("redefine"), "{}", s.prompt_text());
s.cmdline("Y").unwrap();
assert!(s.running.is_none());
// Apply: the objects to give the current settings.
s.cmdline("-DIMSTYLE").unwrap();
s.cmdline("R").unwrap();
s.cmdline("Standard").unwrap();
let h = dimension(&mut s);
s.execute("dimstyle.current", &json!({ "name": "Plan" })).unwrap();
s.cmdline("-DIMSTYLE").unwrap();
s.cmdline("A").unwrap();
s.input(Input::Pick(vec![h])).unwrap();
s.input(Input::Enter).unwrap();
assert!(s.running.is_none());
assert_eq!(dim(&s, h).style, "Plan");
// ~name compares a style with the current settings.
s.cmdline("-DIMSTYLE").unwrap();
s.cmdline("R").unwrap();
let before = s.log.len();
s.cmdline("~Standard").unwrap();
assert!(s.log[before..].iter().any(|l| l.contains("Differences")), "{:?}", &s.log[before..]);
s.cancel();
}
#[test]
fn style_overrides_are_set_in_one_step() {
let mut s = Session::new();
s.execute("dimstyle.overrides", &json!({ "textHeight": 0.3, "DIMCLRT": 1 })).unwrap();
let o = s.doc().unwrap().dim_overrides();
assert_eq!(o.get("textHeight"), Some(&json!(0.3)));
assert!(o.contains_key("textColor"), "{o:?}");
s.undo().unwrap();
assert!(s.doc().unwrap().dim_overrides().is_empty(), "one undo step");
// Unusable values change nothing; names that aren't variables are refused.
assert!(s.execute("dimstyle.overrides", &json!({ "textHeight": -1, "DIMDEC": 2 })).is_err());
assert!(s.execute("dimstyle.overrides", &json!({ "nope": 1 })).is_err());
assert!(s.doc().unwrap().dim_overrides().is_empty());
s.execute("dimstyle.overrides", &json!({ "DIMDEC": 2 })).unwrap();
// Clear drops them only when every value is usable.
assert!(s.execute("dimstyle.overrides", &json!({ "clear": true, "textHeight": -1 })).is_err());
assert!(s.execute("dimstyle.overrides", &json!({ "clear": true, "nope": 1 })).is_err());
assert_eq!(s.doc().unwrap().dim_overrides().get("decimals"), Some(&json!(2)));
s.execute("dimstyle.overrides", &json!({ "clear": true, "textGap": 0.05 })).unwrap();
let o = s.doc().unwrap().dim_overrides();
assert_eq!((o.len(), o.get("textGap")), (1, Some(&json!(0.05))));
s.execute("dimstyle.overrides", &json!({ "clear": true })).unwrap();
assert!(s.doc().unwrap().dim_overrides().is_empty());
// A lineweight by name goes in as the number the header variable holds.
s.execute("dimstyle.overrides", &json!({ "clear": true, "DIMLWD": "bylayer" })).unwrap();
assert_eq!(s.doc().unwrap().header.i64("DIMLWD", 0), -1);
}
#[test]
fn refused_calls_leave_no_undo_step() {
let mut s = Session::new();
s.execute("-dimstyle", &json!({ "option": "save", "name": "Plan" })).unwrap();
assert!(s.execute("-dimstyle", &json!({ "option": "save", "name": "plan" })).is_err());
assert!(s.execute("-dimstyle", &json!({ "option": "restore", "name": "Nope" })).is_err());
// Apply to objects none of which is a dimension changes nothing, and makes no step either.
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
let line = s.doc().unwrap().model.last().unwrap().handle.hex();
assert_eq!(s.execute("-dimstyle", &json!({ "option": "apply", "handles": [line] })).unwrap()["changed"], 0);
// The undo steps are the line and the save: none for the refused calls or that Apply.
s.undo().unwrap();
assert!(s.doc().unwrap().dim_style("Plan").is_some(), "the first undo is the line's");
s.undo().unwrap();
assert!(s.doc().unwrap().dim_style("Plan").is_none());
}
#[test]
fn new_and_renamed_styles_take_the_names_dimstyle_takes() {
let mut s = Session::new();
for name in ["~Plan", "a*b", "x?"] {
assert!(s.execute("dimstyle", &json!({ "name": name })).is_err(), "{name}");
}
s.execute("dimstyle", &json!({ "name": "Plan", "current": false })).unwrap();
assert!(s.execute("dimstyle.rename", &json!({ "from": "Plan", "to": "~Plan" })).is_err());
s.execute("dimstyle.rename", &json!({ "from": "Plan", "to": "Site" })).unwrap();
assert!(s.doc().unwrap().dim_style("Site").is_some());
}
#[test]
fn a_refused_answer_asks_the_same_question() {
let mut s = Session::new();
s.cmdline("-DIMSTYLE").unwrap();
s.cmdline("R").unwrap();
// A style to compare with that doesn't exist.
let _ = s.cmdline("~Nope");
assert!(s.prompt_text().contains("Enter a dimension style name"), "{}", s.prompt_text());
// Words at "Select dimension".
s.cmdline("").unwrap();
let _ = s.cmdline("Standard");
assert!(s.prompt_text().contains("Select dimension"), "{}", s.prompt_text());
s.cancel();
}
#[test]
fn listing_with_many_stars_takes_no_time() {
let mut s = Session::new();
s.execute("dimstyle", &json!({ "name": "a".repeat(200), "current": false })).unwrap();
let start = std::time::Instant::now();
for pattern in ["*".repeat(255) + "x", "*a".repeat(120) + "b"] {
let r = s.execute("-dimstyle", &json!({ "option": "list", "pattern": pattern })).unwrap();
assert_eq!(r["styles"], json!([]));
}
assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed());
let r = s.execute("-dimstyle", &json!({ "option": "list", "pattern": "a*a?" })).unwrap();
assert_eq!(r["styles"], json!(["a".repeat(200)]));
}
#[test]
fn hostile_requests_never_panic() {
let mut s = Session::new();
let h = dimension(&mut s);
for p in [
json!({ "option": "save", "name": "" }),
json!({ "option": "save", "name": "a*b" }),
json!({ "option": "restore", "handle": "zz" }),
json!({ "option": "variables", "handle": 1e300 }),
json!({ "option": "apply", "handles": [h.hex(), "1", 5] }),
json!({ "option": "list", "pattern": "*".repeat(100_000) }),
json!({ "option": 5 }),
] {
let r = s.execute("-dimstyle", &p);
assert!(!matches!(r, Err(cadcraft_engine::EngineError::Internal(..))), "{p}: {r:?}");
}
for p in [json!({ "DIMTXT": "x" }), json!({ "DIMBLK": [1] }), json!({ "DIMCLRT": { "a": 1 } }), json!({ "clear": "yes" })] {
let r = s.execute("dimstyle.overrides", &p);
assert!(!matches!(r, Err(cadcraft_engine::EngineError::Internal(..))), "{p}: {r:?}");
}
for line in ["-DIMSTYLE", "?", "", "-DIMSTYLE", "V", "", "-DIMSTYLE", "AN", "N", "?", "Bad/Name", "Good"] {
let _ = s.cmdline(line);
}
s.cancel();
}
+4
View File
@@ -39,8 +39,10 @@ mod dim_explode_text;
mod dim_properties;
mod dim_radial_inside;
mod dim_radial_outside;
mod dim_style_menu;
mod dim_text_frame;
mod dim_vars;
mod dimstyle_cli;
mod dimtedit_prompts;
mod drafting_spacing;
mod draw_prompts;
@@ -119,7 +121,9 @@ mod polyface_explode;
mod post_command_passes;
mod prompt_keywords;
mod prompt_or_once;
mod properties_describe;
mod properties_set_locked;
mod properties_set_text_dims;
mod props_bad_lineweight;
mod props_insert_scale_attribs;
mod purge_mlinestyles;
@@ -0,0 +1,228 @@
//! `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<String> {
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}");
// 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]
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);
}
#[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);
}
#[test]
fn empty_arrowheads_read_as_the_ones_drawn() {
use cadcraft_engine::doc::DimStyle;
use cadcraft_engine::properties::{DIM_PROPS, dim_value};
let st = serde_json::to_value(DimStyle { arrow_block: "_DOT".into(), ..DimStyle::default() }).unwrap();
let p = |field: &str| DIM_PROPS.iter().find(|p| p.field == field).unwrap();
// An empty per-end arrowhead draws DIMBLK's; an empty leader arrowhead is closed filled.
assert_eq!(dim_value(p("arrowBlock1"), &st), json!("_DOT"));
assert_eq!(dim_value(p("arrowBlock"), &st), json!("_DOT"));
assert_eq!(dim_value(p("leaderArrowBlock"), &st), json!(""));
}
/// Float noise is no difference between two objects' values (7 and 7.0000000000001), but values
/// the display rounds alike still vary (7 and 7.000001 both show as 7.0000).
#[test]
fn float_noise_does_not_vary_but_a_real_difference_does() {
let mut s = Session::new();
let a = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "A", "height": 7.0 })).unwrap());
let b = handle(&s.execute("text", &json!({ "at": [0, 5], "text": "B", "height": 7.0 + 1e-13 })).unwrap());
let both = describe(&mut s, json!({ "handles": [a.clone(), b.clone()] }));
let h = row(&both, "Text", "height");
assert_eq!((h["varies"].as_bool(), h["display"].as_str()), (Some(false), Some("7.0000")));
s.execute("properties.set", &json!({ "handles": [b.clone()], "height": 7.000001 })).unwrap();
let both = describe(&mut s, json!({ "handles": [a, b] }));
assert_eq!(row(&both, "Text", "height")["varies"], true);
}
@@ -0,0 +1,366 @@
//! `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::<Vec<_>>(), ["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());
// 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]
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!("~<>")));
// 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]
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")));
// 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]
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());
}
+17
View File
@@ -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");
+17 -3
View File
@@ -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)
+15
View File
@@ -354,6 +354,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);
+77 -6
View File
@@ -22,6 +22,7 @@
use cadcraft_doc::EntityKind;
use cadcraft_engine::snap::mode;
use cadcraft_engine::{Input, find_command};
use serde_json::json;
use crate::CadApp;
use crate::menus::{Entry, activate, entry_ui};
@@ -58,6 +59,10 @@ pub const TYPE: &str = "type:";
pub const KEYWORD: &str = "keyword:";
/// An object snap menu item ([`choose_snap`]).
pub const SNAP: &str = "snap:";
/// Dimension Style ▸ item: the selected dimensions take the style that follows.
pub const DIM_STYLE: &str = "dimstyle:";
/// Precision ▸ item: the selected dimensions show this many decimal places (an override).
pub const DIM_PRECISION: &str = "dimprecision:";
fn item(app: &CadApp, id: &str, label: Option<&str>) -> Option<Entry> {
let spec = find_command(id)?;
@@ -158,15 +163,18 @@ fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> {
}
}
/// [`object_commands`] that are registered, as menu items. The Edit Text entry of a single
/// selected text, mtext or attribute definition opens the Edit Text window instead of the
/// TEXTEDIT command line; the double-click keeps its in-place editing (#842), and several
/// selected texts still take the command line.
/// [`object_commands`] that are registered, as menu items, then the dimension shortcut menu's
/// items when the selection is dimensions. The Edit Text entry of a single selected text, mtext or
/// attribute definition opens the Edit Text window instead of the TEXTEDIT command line; the
/// double-click keeps its in-place editing (#842), and several selected texts still take the
/// command line.
pub fn object_entries(app: &CadApp) -> Vec<Entry> {
object_commands(app)
let mut out: Vec<Entry> = object_commands(app)
.into_iter()
.filter_map(|(id, label)| if id == "textedit" { edit_text_window_entry(app).or_else(|| item(app, id, label)) } else { item(app, id, label) })
.collect()
.collect();
out.extend(dimension_entries(app));
out
}
/// The Edit Text entry as the `textedit:<handle>` dialog id, for a single selected text, mtext
@@ -183,6 +191,64 @@ fn edit_text_window_entry(app: &CadApp) -> Option<Entry> {
Some(Entry::Item { label: "Edit Text".into(), id: format!("textedit:{}", h.hex()), shortcut: None, enabled: true })
}
/// 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<Entry> {
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<Entry> =
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<Entry> = 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,
/// the prompt's options, Snap Overrides at point prompts, Pan and Zoom.
pub fn command_entries(app: &CadApp) -> Option<Vec<Vec<Entry>>> {
@@ -239,6 +305,11 @@ pub fn choose(app: &mut CadApp, id: &str) {
} else if id.starts_with("textedit:") {
// The Edit Text window of the single selected text object; the id carries the handle.
app.ui.dialog = Some(id.to_string());
} else if let Some(name) = id.strip_prefix(DIM_STYLE) {
let hs: Vec<String> = 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::<u8>().ok()) {
set_precision(app, n.min(8));
} else {
activate(app, id);
}
+1
View File
@@ -906,6 +906,7 @@
Set Current Viewport تعيين إطار العرض الحالي
Set Layer Properties تعيين خصائص الطبقة
Set Properties تعيين الخصائص
Describe Properties وصف الخصائص
Set Table Cell تعيين خلية الجدول
Set Table Cell Style تعيين نمط خلية الجدول
Set Variable تعيين متغير
1 # CADCraft Arabic interface catalog — original translations.
906
907
908
909
910
911
912
+1
View File
@@ -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
1 # CADCraft Czech interface catalog — original translations by @Losminek (AI-assisted).
840
841
842
843
844
845
846
+1
View File
@@ -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
1 # CADCraft German interface catalog — original translations by the CADCraft contributors.
729
730
731
732
733
734
735
+1
View File
@@ -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
1 # CADCraft Spanish interface catalog — original translations.
933
934
935
936
937
938
939
+1
View File
@@ -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
1 # CADCraft French interface catalog — original translations by @pechnikov2026-star.
723
724
725
726
727
728
729
+1
View File
@@ -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
1 # CADCraft Italian interface catalog — original translations by Emanuele Bottelli (AI-assisted, Claude).
847
848
849
850
851
852
853
+1
View File
@@ -837,6 +837,7 @@
Set Current Viewport 현재 뷰포트 설정
Set Layer Properties 도면층 특성 설정
Set Properties 특성 설정
Describe Properties 특성 설명
Set Table Cell 표 셀 설정
Set Table Cell Style 표 셀 스타일 설정
Set Variable 변수 설정
1 # CADCraft Korean interface catalog — original Korean translations.
837
838
839
840
841
842
843
+1
View File
@@ -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
1 # CADCraft Brazilian Portuguese (pt-BR) interface catalog.
928
929
930
931
932
933
934
+1
View File
@@ -723,6 +723,7 @@
Set Current Text Style Сделать текстовый стиль текущим
Set Layer Properties Задать свойства слоя
Set Properties Задать свойства
Describe Properties Описать свойства
Set Table Cell Задать ячейку таблицы
Set Variable Задать переменную
Set View Задать вид
1 # CADCraft Russian interface catalog — original translations by @pechnikov2026-star.
723
724
725
726
727
728
729
+1
View File
@@ -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
1 # CADCraft Swedish interface catalog — original translations by the CADCraft contributors.
926
927
928
929
930
931
932
+44
View File
@@ -59,6 +59,7 @@ fn translation_gaps() {
for language in translated() {
let mut missing: BTreeSet<String> = 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,48 @@ 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<String> {
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));
// The Dimension Style dialog edits every dimension variable, the style's own ones too.
for p in cadcraft_engine::properties::DIM_PROPS {
labels.insert(p.label.to_string());
labels.extend(p.kind.options().into_iter().map(|o| o.label));
}
// 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<String> {
let catalog = catalog(language).unwrap();
let mut sources = BTreeSet::new();
@@ -111,6 +154,7 @@ fn missing_marked_ui_literals(language: &str) -> BTreeSet<String> {
"layers",
"bedit",
"palettes",
"managers/dimstyle",
"parametric",
"quick",
"vpscale",
+190
View File
@@ -862,6 +862,7 @@
Set Current Viewport Зробити видовий екран поточним
Set Layer Properties Задати властивості шару
Set Properties Задати властивості
Describe Properties Описати властивості
Set Table Cell Задати комірку таблиці
Set Table Cell Style Задати стиль комірки таблиці
Set Variable Задати змінну
@@ -1452,3 +1453,192 @@
# ArtCraft feature naming
Additional Tools Додаткові інструменти
# 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 Інтеграл
Remove Style Overrides Видалити перевизначення стилю
Save as New Style... Зберегти як новий стиль...
Dimension Style Розмірний стиль
# Dimension Style Manager (DIMSTYLE) and -DIMSTYLE
Dimension Style Manager Диспетчер розмірних стилів
Current dimension style: {style} Поточний розмірний стиль: {style}
Styles Стилі
All styles Усі стилі
Styles in use Стилі, що використовуються
<style overrides> <перевизначення стилю>
Save to current style Зберегти в поточному стилі
Rename Перейменувати
Preview of: {style} Попередній перегляд: {style}
Preview of: {style} (overrides) Попередній перегляд: {style} (перевизначення)
New... Новий...
Modify... Змінити...
Override... Перевизначити...
Compare... Порівняти...
Create New Dimension Style Створення нового розмірного стилю
New style name Назва нового стилю
Start with На основі
A dimension style with this name already exists. Розмірний стиль із такою назвою вже існує.
Modify Dimension Style: {style} Змінення розмірного стилю: {style}
Override Current Style: {style} Перевизначення поточного стилю: {style}
New Dimension Style: {style} Новий розмірний стиль: {style}
Lines Лінії
Symbols and Arrows Символи та стрілки
Leading Початкові
Trailing Кінцеві
Compare Dimension Styles Порівняння розмірних стилів
Compare Порівняти
With з
All properties of {style} Усі властивості стилю {style}
{count} differences Відмінностей: {count}
Variable Змінна
Dimension Style Overrides Перевизначення розмірного стилю
Arrowheads Наконечники стрілок
Leader arrow Стрілка виноски
Baseline spacing Крок базових розмірів
Text vertical position Вертикальне положення тексту
Prefix and suffix Префікс і суфікс
Zero suppression Приховування нулів
Angular zero suppression Приховування нулів у кутах
Alt prefix and suffix Префікс і суфікс альтернативних одиниць
Alt zero suppression Приховування нулів альтернативних одиниць
Tolerance zero suppression Приховування нулів допусків
Can't render this file because it contains an unexpected character in line 1386 and column 24.
+5
View File
@@ -177,7 +177,9 @@
Dim style 标注样式
Dimension 标注
Dimension Space 标注间距
Dimension Style 标注样式
Dimension Style Override 标注样式替代
Dimension Style Overrides 标注样式替代
Dimension Style... 标注样式...
Dimension Text Edit 编辑标注文字
Dimension style 标注样式
@@ -617,6 +619,7 @@
Region/Mass Properties 面域/质量特性
Relative 相对
Remove Leader 删除引线
Remove Style Overrides 删除样式替代
Remove the viewport override 移除视口替代
Rename Dimension Style 重命名标注样式
Rename Layer 重命名图层
@@ -642,6 +645,7 @@
Save (⌘S) 保存 (⌘S)
Save As 另存为
Save As... 另存为...
Save as New Style... 另存为新样式...
Save Layer State 保存图层状态
Save State 保存状态
Scale 缩放
@@ -727,6 +731,7 @@
Set Current Text Style 设置当前文字样式
Set Layer Properties 设置图层特性
Set Properties 设置特性
Describe Properties 描述特性
Set Table Cell 设置表格单元格
Set Variable 设置变量
Set View 设置视图
1 # CADCraft Simplified Chinese interface catalog — original translations.
177
178
179
180
181
182
183
184
185
619
620
621
622
623
624
625
645
646
647
648
649
650
651
731
732
733
734
735
736
737
+121 -40
View File
@@ -1,5 +1,5 @@
//! Style and settings dialogs opened from the menus: Linetype Manager, Point Style, Text Style,
//! Table Style, Multileader Style, Page Setup Manager, Plot, Constraint Settings and Named
//! Dimension Style, Table Style, Multileader Style, Page Setup Manager, Plot, Constraint Settings and Named
//! Viewports.
//!
//! Typed or chosen from a menu (no parameters) these commands open their dialog; JSON calls run
@@ -17,6 +17,8 @@ use crate::{CadApp, Pick};
/// The Block Attribute Manager (BATTMAN).
mod battman;
/// The Dimension Style Manager (DIMSTYLE).
mod dimstyle;
/// Named Viewports (View > Viewports > Named Viewports...).
mod named_vports;
@@ -31,6 +33,7 @@ pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option<Result<Value,
"linetype" | "lt" | "ltype" => "linetype",
"ddptype" | "ptype" => "ptype",
"style" | "st" => "textstyle",
"dimstyle" | "dimstyle.dimension" | "d" | "dst" | "ddim" => "dimstyle",
"tablestyle" | "ts" => "tablestyle",
"mleaderstyle" | "mls" => "mleaderstyle",
"pagesetup" => "pagesetup",
@@ -53,6 +56,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, name: &str, open: &mut bool
"linetype" => linetype(app, ctx, open),
"ptype" => point_style(app, ctx, open),
"textstyle" => text_style(app, ctx, open),
"dimstyle" => dimstyle::dialog(app, ctx, open),
"tablestyle" => table_style(app, ctx, open),
"mleaderstyle" => mleader_style(app, ctx, open),
"pagesetup" => page_setup(app, ctx, open),
@@ -66,7 +70,14 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, name: &str, open: &mut bool
};
if let Some((cmd, p)) = action {
// Errors are echoed on the command line by `run`.
let _ = app.run(cmd, p);
let r = app.run(cmd, p);
if let Ok(v) = r
&& let Some(ignored) = v.get("ignored").and_then(Value::as_array)
&& !ignored.is_empty()
{
let names: Vec<_> = ignored.iter().filter_map(Value::as_str).collect();
set_temp(ctx, &format!("{cmd}_err"), Some(format!("Ignored invalid value for: {}", names.join(", "))));
}
}
}
@@ -78,11 +89,15 @@ fn fmt_num(v: f64) -> String {
if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s }
}
fn parse_num_field(ui: &mut egui::Ui, id: impl egui::AsIdSalt, v: f64, label: Option<egui::Id>) -> Option<Result<f64, ()>> {
expr_field(ui, ui.make_persistent_id(id), &fmt_num(v), label).map(|t| t.parse::<f64>().ok().filter(|v| v.is_finite()).ok_or(()))
}
/// A number field that commits on Enter or focus loss.
///
/// `label` is the visible label's widget id (see [`expr_field`]).
fn num_field(ui: &mut egui::Ui, id: impl egui::AsIdSalt, v: f64, label: Option<egui::Id>) -> Option<f64> {
expr_field(ui, ui.make_persistent_id(id), &fmt_num(v), label).and_then(|t| t.parse::<f64>().ok()).filter(|v| v.is_finite())
parse_num_field(ui, id, v, label).and_then(Result::ok)
}
fn temp<T: Clone + Send + Sync + 'static>(ctx: &egui::Context, id: &str) -> Option<T> {
@@ -305,9 +320,28 @@ fn point_style(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action
// ---------- Text Style, Table Style and Multileader Style ----------
/// Numerical validation rule for style properties.
#[derive(Clone, Copy)]
enum NumRule {
/// Values must be 0 or greater (default for dimensions and sizes).
NonNegative,
/// Values must be strictly greater than 0 (e.g. text height).
Positive,
}
impl NumRule {
fn validate(self, v: f64) -> Result<f64, &'static str> {
match self {
NumRule::NonNegative if v < 0.0 => Err("must be 0 or greater"),
NumRule::Positive if v <= 0.0 => Err("must be greater than 0"),
_ => Ok(v),
}
}
}
/// One editable style property.
enum Field {
Num(&'static str, &'static str, f64),
Num(&'static str, &'static str, f64, NumRule),
Bool(&'static str, &'static str, bool),
Choice(&'static str, &'static str, String, std::sync::Arc<[String]>),
}
@@ -328,8 +362,8 @@ fn text_style(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action
.map(|s| Style {
name: s.name.clone(),
fields: vec![
Field::Num("height", "Height (0 = ask)", s.height),
Field::Num("widthFactor", "Width factor", s.width_factor),
Field::Num("height", "Height (0 = ask)", s.height, NumRule::NonNegative),
Field::Num("widthFactor", "Width factor", s.width_factor, NumRule::Positive),
Field::Bool("backwards", "Backwards", s.backwards),
Field::Bool("upsideDown", "Upside down", s.upside_down),
],
@@ -354,8 +388,8 @@ fn table_style(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action
.map(|s| Style {
name: s.name.clone(),
fields: vec![
Field::Num("textHeight", "Text height", s.text_height),
Field::Num("margin", "Cell margin", s.margin),
Field::Num("textHeight", "Text height", s.text_height, NumRule::Positive),
Field::Num("margin", "Cell margin", s.margin, NumRule::NonNegative),
Field::Bool("title", "Title row", s.title),
Field::Bool("header", "Header row", s.header),
],
@@ -382,10 +416,10 @@ fn mleader_style(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Acti
.map(|s| Style {
name: s.name.clone(),
fields: vec![
Field::Num("arrowSize", "Arrowhead size", s.arrow_size),
Field::Num("textHeight", "Text height", s.text_height),
Field::Num("landingGap", "Landing gap", s.landing_gap),
Field::Num("dogleg", "Landing length", s.dogleg),
Field::Num("arrowSize", "Arrowhead size", s.arrow_size, NumRule::NonNegative),
Field::Num("textHeight", "Text height", s.text_height, NumRule::Positive),
Field::Num("landingGap", "Landing gap", s.landing_gap, NumRule::NonNegative),
Field::Num("dogleg", "Landing length", s.dogleg, NumRule::NonNegative),
Field::Choice("textStyle", "Text style", s.text_style.clone(), std::sync::Arc::clone(&text_styles)),
],
})
@@ -404,16 +438,18 @@ fn style_manager(ctx: &egui::Context, open: &mut bool, title: &str, cmd: &'stati
let t = Tokens::get();
let sel_key = format!("{cmd}_sel");
let new_key = format!("{cmd}_new");
let err_key = format!("{cmd}_err");
let mut sel = temp::<String>(ctx, &sel_key).filter(|s| styles.iter().any(|x| x.name == *s)).unwrap_or_else(|| current.to_string());
let mut new_name = temp::<String>(ctx, &new_key).unwrap_or_default();
let mut err_msg = temp::<Option<String>>(ctx, &err_key).flatten().or_else(|| temp::<String>(ctx, &err_key));
let mut action = None;
egui::Window::new(title).open(open).default_size(vec2(520.0, 280.0)).resizable(true).show(ctx, |ui| {
egui::Window::new(title).open(open).default_size(vec2(540.0, 320.0)).resizable(true).show(ctx, |ui| {
ui.label(RichText::new(format!("Current style: {current}")).color(t.text_dim));
ui.separator();
ui.columns(2, |cols| {
let [left, right] = cols else { return };
left.label(RichText::new("Styles").strong());
egui::ScrollArea::vertical().id_salt((cmd, "list")).max_height(160.0).auto_shrink([false, true]).show(left, |ui| {
egui::ScrollArea::vertical().id_salt((cmd, "list")).max_height(200.0).auto_shrink([false, true]).show(left, |ui| {
for s in styles {
let mut label = RichText::new(&s.name);
if s.name.eq_ignore_ascii_case(current) {
@@ -421,11 +457,13 @@ fn style_manager(ctx: &egui::Context, open: &mut bool, title: &str, cmd: &'stati
}
if ui.selectable_label(s.name == sel, label).clicked() {
sel = s.name.clone();
err_msg = None;
}
}
});
if left.add_enabled(!sel.eq_ignore_ascii_case(current), egui::Button::new("Set Current")).clicked() {
action = Some((cmd, json!({ "name": sel })));
err_msg = None;
}
left.horizontal(|ui| {
ui.add(egui::TextEdit::singleline(&mut new_name).hint_text("New style name").desired_width(120.0)).on_hover_text("New style name");
@@ -435,45 +473,77 @@ fn style_manager(ctx: &egui::Context, open: &mut bool, title: &str, cmd: &'stati
action = Some((cmd, json!({ "name": name, "current": false })));
sel = name;
new_name.clear();
err_msg = None;
}
});
right.label(RichText::new(format!("Properties of {sel}")).strong());
if let Some(err) = &err_msg {
right.colored_label(t.warn, err);
}
let Some(style) = styles.iter().find(|s| s.name == sel) else { return };
egui::Grid::new((cmd, "props")).num_columns(2).spacing(vec2(10.0, 6.0)).show(right, |ui| {
for f in &style.fields {
let change = match f {
Field::Num(key, label, v) => {
let field_label = ui.label(*label);
num_field(ui, (cmd, &style.name, *key), *v, Some(field_label.id)).filter(|v| *v >= 0.0).map(|v| (*key, json!(v)))
}
Field::Bool(key, label, v) => {
ui.label("");
let mut b = *v;
ui.checkbox(&mut b, *label).changed().then(|| (*key, json!(b)))
}
Field::Choice(key, label, v, choices) => {
ui.label(*label);
let mut picked = None;
craft_ui::ComboBox::from_id_salt((cmd, *key)).selected_text(v.as_str()).show_ui(ui, |ui| {
for c in choices.iter() {
if ui.selectable_label(c == v, c).clicked() && c != v {
picked = Some(c.clone());
egui::ScrollArea::vertical().id_salt((cmd, "props_scroll")).max_height(200.0).auto_shrink([false, true]).show(right, |right| {
egui::Grid::new((cmd, "props")).num_columns(2).spacing(vec2(10.0, 6.0)).show(right, |ui| {
for f in &style.fields {
let change = match f {
Field::Num(key, label, v, rule) => {
let field_label = ui.label(*label);
if let Some(parsed) = parse_num_field(ui, (cmd, &style.name, *key), *v, Some(field_label.id)) {
match parsed {
Ok(raw) => match rule.validate(raw) {
Ok(valid) => {
err_msg = None;
Some((*key, json!(valid)))
}
Err(why) => {
err_msg = Some(format!("{label}: {why}"));
None
}
},
Err(()) => {
err_msg = Some(format!("{label}: Enter a valid number"));
None
}
}
} else {
None
}
});
picked.map(|c| (*key, json!(c)))
}
Field::Bool(key, label, v) => {
ui.label("");
let mut b = *v;
ui.checkbox(&mut b, *label).changed().then(|| {
err_msg = None;
(*key, json!(b))
})
}
Field::Choice(key, label, v, choices) => {
ui.label(*label);
let mut picked = None;
craft_ui::ComboBox::from_id_salt((cmd, *key)).selected_text(v.as_str()).show_ui(ui, |ui| {
for c in choices.iter() {
if ui.selectable_label(c == v, c).clicked() && c != v {
picked = Some(c.clone());
}
}
});
picked.map(|c| {
err_msg = None;
(*key, json!(c))
})
}
};
if let Some((key, v)) = change {
action = Some((cmd, json!({ "name": style.name, key: v, "current": false })));
}
};
if let Some((key, v)) = change {
action = Some((cmd, json!({ "name": style.name, key: v, "current": false })));
ui.end_row();
}
ui.end_row();
}
});
});
});
});
set_temp(ctx, &sel_key, sel);
set_temp(ctx, &new_key, new_name);
set_temp(ctx, &err_key, err_msg);
action
}
@@ -1283,4 +1353,15 @@ mod plot_dialog_tests {
assert_eq!(app.ui.dialog.as_deref(), Some("plot"));
assert_eq!(temp::<PlotState>(&ctx, "plot_state").unwrap().window, [2.0, 3.0, 12.0, 9.0]);
}
#[test]
fn num_rule_validates_ranges_and_precision() {
assert_eq!(NumRule::NonNegative.validate(0.0), Ok(0.0));
assert_eq!(NumRule::NonNegative.validate(1.5), Ok(1.5));
assert!(NumRule::NonNegative.validate(-0.01).is_err());
assert_eq!(NumRule::Positive.validate(0.1), Ok(0.1));
assert!(NumRule::Positive.validate(0.0).is_err());
assert!(NumRule::Positive.validate(-1.0).is_err());
}
}
+813
View File
@@ -0,0 +1,813 @@
//! The Dimension Style Manager (DIMSTYLE): the drawing's dimension styles with a preview, Set
//! Current, New, Modify, Override, Compare, Rename and Delete. Modify, Override and New edit every
//! style variable in AutoCAD's tabs (Lines, Symbols and Arrows, Text, Fit, Primary Units,
//! Alternate Units, Tolerances), from the engine's table of dimension properties; the preview
//! draws sample dimensions with the settings being edited.
use std::hash::{Hash, Hasher};
use cadcraft_engine::doc::{DimStyle, Drawing, EntityKind};
use cadcraft_engine::properties::{DIM_PROPS, DimProp, DimPropKind, dim_value, join_post, split_post};
use egui::{RichText, vec2};
use serde_json::{Map, Value, json};
use crate::CadApp;
use crate::parametric::expr_field;
use crate::theme::Tokens;
/// The current style's overrides in the list.
const OVERRIDES: &str = "<style overrides>";
const STATE: &str = "dimstyle_manager";
/// The editing tabs, in AutoCAD's order.
const TABS: usize = 7;
fn tab_label(i: usize) -> &'static str {
match i {
0 => crate::tl!("Lines"),
1 => crate::tl!("Symbols and Arrows"),
2 => crate::tl!("Text"),
3 => crate::tl!("Fit"),
4 => crate::tl!("Primary Units"),
5 => crate::tl!("Alternate Units"),
_ => crate::tl!("Tolerances"),
}
}
#[derive(Clone, Default, PartialEq)]
enum Page {
#[default]
List,
New,
Edit,
Compare,
}
/// What the editing pages change: an existing style, the current style's overrides, or a style
/// being created.
#[derive(Clone, Default, PartialEq)]
enum Target {
#[default]
Modify,
Override,
Create,
}
#[derive(Clone, Default)]
struct State {
page: Page,
/// The style chosen in the list, or [`OVERRIDES`].
selected: String,
in_use_only: bool,
new_name: String,
start_with: String,
new_annotative: bool,
/// The style the editing pages show, its settings as edited, and what OK does with them.
editing: String,
target: Target,
values: Map<String, Value>,
original: Map<String, Value>,
tab: usize,
compare_with: String,
/// (style, new name) while renaming.
renaming: Option<(String, String)>,
/// OK was clicked on an editing page: the entry the list chooses once its commands succeed
/// (a refused value keeps the page open with every edit).
after_ok: Option<String>,
/// Why OK's command refused the edits, or left a value out, shown on the editing page.
error: Option<String>,
/// The drawing the pages were opened on ([`cadcraft_engine::DocState::uid`]).
doc: u64,
}
/// The tab a variable is edited on.
fn tab_of(p: &DimProp) -> usize {
match p.group {
"Lines & Arrows" => {
let symbol = matches!(
p.field,
"arrowBlock"
| "arrowBlock1"
| "arrowBlock2"
| "leaderArrowBlock"
| "arrowSize"
| "tickSize"
| "centerMark"
| "arcSymbol"
| "jogAngle"
);
usize::from(symbol)
}
"Text" => 2,
"Fit" => 3,
"Primary Units" => 4,
"Alternate Units" => 5,
_ => 6,
}
}
fn style_json(st: &DimStyle) -> Map<String, Value> {
match serde_json::to_value(st) {
Ok(Value::Object(m)) => m,
_ => Map::new(),
}
}
fn from_json(m: &Map<String, Value>) -> DimStyle {
serde_json::from_value(Value::Object(m.clone())).unwrap_or_default()
}
/// Names of the dimension styles some dimension (or leader) uses.
fn in_use(d: &Drawing) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(d.blocks.values().map(|b| &b.entities));
for st in stores {
for e in st.iter() {
let name = match &e.kind {
EntityKind::Dimension(dm) => &dm.style,
EntityKind::Leader(l) => &l.style,
EntityKind::Tolerance(t) => &t.style,
_ => continue,
};
if !out.iter().any(|n| n.eq_ignore_ascii_case(name)) {
out.push(name.clone());
}
}
}
out
}
pub(super) fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> super::Action {
let Ok(d) = app.session.doc() else {
super::no_drawing(ctx, crate::tl!("Dimension Style Manager"), open);
return None;
};
let mut st: State = super::temp(ctx, STATE).unwrap_or_default();
// A page left open while another drawing became active (its file tab) is cancelled, back to
// the list: its values are the first drawing's, and OK would write them into this one.
let uid = app.session.state().map_or(0, |s| s.uid);
if st.page != Page::List && st.doc != uid {
st = State::default();
}
st.doc = uid;
let current = d.header.str("DIMSTYLE", "Standard");
let overrides = d.dim_overrides();
let valid = |n: &str| n == OVERRIDES && !overrides.is_empty() || d.dim_style(n).is_some();
if !valid(&st.selected) {
st.selected = current.clone();
}
let mut actions: Vec<(&'static str, Value)> = Vec::new();
let title = match (&st.page, &st.target) {
(Page::List, _) => crate::tl!("Dimension Style Manager").to_string(),
(Page::New, _) => crate::tl!("Create New Dimension Style").to_string(),
(Page::Edit, Target::Modify) => crate::tf!("Modify Dimension Style: {style}", style = st.editing),
(Page::Edit, Target::Override) => crate::tf!("Override Current Style: {style}", style = st.editing),
(Page::Edit, Target::Create) => crate::tf!("New Dimension Style: {style}", style = st.editing),
(Page::Compare, _) => crate::tl!("Compare Dimension Styles").to_string(),
};
egui::Window::new(title).id(egui::Id::unique(STATE)).open(open).default_size(vec2(720.0, 480.0)).resizable(true).collapsible(false).show(
ctx,
|ui| match st.page {
Page::List => list_page(ui, d, &mut st, &current, &overrides, &mut actions),
Page::New => new_page(ui, d, &mut st),
Page::Edit => edit_page(ui, d, &mut st, &mut actions),
Page::Compare => compare_page(ui, d, &mut st, &current, &overrides),
},
);
// Errors are echoed on the command line by `run`; a failed step stops the rest. A value the
// command left out (`ignored`, such as a text height of 0) counts as refused too, so the page
// stays open with the edits and says which values were not taken.
let mut ok = true;
for (cmd, p) in actions {
match app.run(cmd, p) {
Ok(r) => {
if let Some(m) = left_out(&r) {
st.error = Some(m);
ok = false;
break;
}
}
Err(e) => {
st.error = Some(e);
ok = false;
break;
}
}
}
if let Some(selected) = st.after_ok.take()
&& ok
{
st.selected = selected;
st.page = Page::List;
st.error = None;
}
// Closed (the title bar's X), it opens on the list next time, not on a page left open.
super::set_temp(ctx, STATE, if *open { st } else { State::default() });
None
}
/// The message of a result that left some values out (`ignored`), as `dimstyle` reports them;
/// the variables' names when the command gave no message.
fn left_out(r: &Value) -> Option<String> {
let ignored = r.get("ignored").and_then(Value::as_array).filter(|a| !a.is_empty())?;
Some(
r.get("message")
.and_then(Value::as_str)
.map_or_else(|| ignored.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", "), str::to_string),
)
}
fn list_page(
ui: &mut egui::Ui,
d: &Drawing,
st: &mut State,
current: &str,
overrides: &Map<String, Value>,
actions: &mut Vec<(&'static str, Value)>,
) {
let t = Tokens::get();
ui.label(RichText::new(crate::tf!("Current dimension style: {style}", style = current)).color(t.text_dim));
ui.add_space(4.0);
let used = in_use(d);
ui.horizontal_top(|ui| {
// The styles, the current style's overrides under it.
ui.vertical(|ui| {
ui.set_width(190.0);
ui.label(RichText::new(crate::tl!("Styles")).strong());
egui::Frame::group(ui.style()).show(ui, |ui| {
egui::ScrollArea::vertical().id_salt("dimstyle_list").max_height(260.0).auto_shrink([false, true]).show(ui, |ui| {
for s in &d.dim_styles {
if st.in_use_only && !used.iter().any(|n| n.eq_ignore_ascii_case(&s.name)) && !s.name.eq_ignore_ascii_case(current) {
continue;
}
let mut label = RichText::new(&s.name);
if s.name.eq_ignore_ascii_case(current) {
label = label.strong();
}
let resp = ui.selectable_label(st.selected == s.name, label);
if resp.clicked() {
st.selected = s.name.clone();
}
resp.context_menu(|ui| {
if ui.add_enabled(!s.name.eq_ignore_ascii_case(current), egui::Button::new(crate::tl!("Set Current"))).clicked() {
actions.push(("dimstyle.current", json!({ "name": s.name })));
ui.close();
}
if ui.button(crate::tl!("Rename")).clicked() {
st.renaming = Some((s.name.clone(), s.name.clone()));
ui.close();
}
if ui.add_enabled(deletable(&s.name, current, &used), egui::Button::new(crate::tl!("Delete"))).clicked() {
actions.push(("dimstyle.delete", json!({ "name": s.name })));
ui.close();
}
});
if s.name.eq_ignore_ascii_case(current) && !overrides.is_empty() {
ui.horizontal(|ui| {
ui.add_space(14.0);
let resp = ui.selectable_label(st.selected == OVERRIDES, crate::tl!("<style overrides>"));
if resp.clicked() {
st.selected = OVERRIDES.into();
}
resp.context_menu(|ui| {
if ui.button(crate::tl!("Save to current style")).clicked() {
let mut p = overrides.clone();
p.insert("name".into(), json!(current));
actions.push(("dimstyle", Value::Object(p)));
ui.close();
}
if ui.button(crate::tl!("Delete")).clicked() {
actions.push(("dimstyle.current", json!({ "name": current })));
ui.close();
}
});
});
}
}
});
});
let filter = craft_ui::ComboBox::from_id_salt("dimstyle_list_filter")
.selected_text(if st.in_use_only { crate::tl!("Styles in use") } else { crate::tl!("All styles") })
.show_ui(ui, |ui| {
ui.selectable_value(&mut st.in_use_only, false, crate::tl!("All styles"));
ui.selectable_value(&mut st.in_use_only, true, crate::tl!("Styles in use"));
});
filter.response.accessible_name(crate::tl!("List"));
if let Some((from, to)) = &mut st.renaming {
let from = from.clone();
let mut done = false;
ui.horizontal(|ui| {
let r = ui.add(egui::TextEdit::singleline(to).desired_width(120.0)).accessible_name(crate::tl!("Name"));
let name = to.trim().to_string();
// Only a name the rename takes: a refused one would leave the list on another
// style (one already called that).
let usable = !bad_name(&name) && d.dim_style(&name).is_none_or(|s| s.name.eq_ignore_ascii_case(&from));
let enter = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
if ui.add_enabled(usable, egui::Button::new(crate::tl!("OK"))).clicked() || enter && usable {
if name != from {
actions.push(("dimstyle.rename", json!({ "from": from, "to": name })));
if st.selected == from {
st.selected = name;
}
}
done = true;
}
});
if done {
st.renaming = None;
}
}
});
// The preview and description of the chosen style.
ui.vertical(|ui| {
let shown = if st.selected == OVERRIDES {
d.dim_style(current).cloned().unwrap_or_default().with_overrides(overrides)
} else {
d.dim_style(&st.selected).cloned().unwrap_or_default()
};
let label = if st.selected == OVERRIDES {
crate::tf!("Preview of: {style} (overrides)", style = current)
} else {
crate::tf!("Preview of: {style}", style = st.selected)
};
ui.label(RichText::new(label).strong());
preview(ui, d, &shown, vec2(320.0, 240.0));
ui.label(RichText::new(crate::tl!("Description")).strong());
ui.label(description(d, &st.selected, current, overrides));
});
// The buttons.
ui.vertical(|ui| {
let w = vec2(110.0, 22.0);
let is_style = st.selected != OVERRIDES;
if ui
.add_enabled(is_style && !st.selected.eq_ignore_ascii_case(current), egui::Button::new(crate::tl!("Set Current")).min_size(w))
.clicked()
{
actions.push(("dimstyle.current", json!({ "name": st.selected })));
}
if ui.add(egui::Button::new(crate::tl!("New...")).min_size(w)).clicked() {
st.start_with = if is_style { st.selected.clone() } else { current.to_string() };
st.new_name = new_name(d, &st.start_with);
st.new_annotative = d.dim_style(&st.start_with).is_some_and(|s| s.annotative);
st.page = Page::New;
}
if ui.add_enabled(is_style, egui::Button::new(crate::tl!("Modify...")).min_size(w)).clicked()
&& let Some(s) = d.dim_style(&st.selected)
{
start_edit(st, s.name.clone(), Target::Modify, style_json(s));
}
if ui.add(egui::Button::new(crate::tl!("Override...")).min_size(w)).clicked()
&& let Some(s) = d.dim_style(current)
{
// The current settings: the style with the overrides it already has.
start_edit(st, s.name.clone(), Target::Override, style_json(&s.with_overrides(overrides)));
st.original = style_json(s);
}
if ui.add(egui::Button::new(crate::tl!("Compare...")).min_size(w)).clicked() {
st.compare_with = current.to_string();
st.page = Page::Compare;
}
if ui.add_enabled(is_style && deletable(&st.selected, current, &used), egui::Button::new(crate::tl!("Delete")).min_size(w)).clicked() {
actions.push(("dimstyle.delete", json!({ "name": st.selected })));
}
});
});
}
/// A name no new dimension style can have: the engine's rule (-DIMSTYLE's; `~` is its Restore's
/// "compare with").
fn bad_name(name: &str) -> bool {
!cadcraft_engine::cmd::usable_dim_style_name(name)
}
/// Whether style `name` can be deleted: not Standard, the current style or a style in use.
fn deletable(name: &str, current: &str, used: &[String]) -> bool {
!name.eq_ignore_ascii_case("Standard") && !name.eq_ignore_ascii_case(current) && !used.iter().any(|n| n.eq_ignore_ascii_case(name))
}
fn start_edit(st: &mut State, name: String, target: Target, values: Map<String, Value>) {
st.editing = name;
st.target = target;
st.original = values.clone();
st.values = values;
st.page = Page::Edit;
}
/// "Copy of <style>", numbered when that is taken.
fn new_name(d: &Drawing, base: &str) -> String {
let first = format!("Copy of {base}");
(1..1000).map(|i| if i == 1 { first.clone() } else { format!("{first} ({i})") }).find(|n| d.dim_style(n).is_none()).unwrap_or(first)
}
/// The chosen style's description: its name, or the current style and what its overrides change.
fn description(d: &Drawing, selected: &str, current: &str, overrides: &Map<String, Value>) -> String {
if selected != OVERRIDES {
let anno = if d.dim_style(selected).is_some_and(|s| s.annotative) { crate::tl!("Annotative").to_string() } else { String::new() };
return [selected.to_string(), anno].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(", ");
}
let base = d.dim_style(current).cloned().unwrap_or_default();
let mut parts = vec![current.to_string()];
let values = Value::Object(style_json(&base.with_overrides(overrides)));
for p in DIM_PROPS.iter().filter(|p| overrides.contains_key(p.field)) {
parts.push(format!("{} = {}", crate::i18n::t(p.label), shown(p, &values)));
}
parts.join(" + ")
}
/// `p` of a style's `values` as the dialog shows it: a choice's label (a precision as 0.00, an
/// arrowhead by name), a color's name, Yes or No.
fn shown(p: &DimProp, values: &Value) -> String {
let v = dim_value(p, values);
if let Some(o) = p.kind.options().into_iter().find(|o| o.value == v) {
return crate::i18n::t(&o.label).to_string();
}
match v {
Value::String(s) => crate::i18n::t(&s).to_string(),
Value::Bool(b) => crate::i18n::t(if b { "Yes" } else { "No" }).to_string(),
Value::Null => String::new(),
v => v.to_string(),
}
}
fn new_page(ui: &mut egui::Ui, d: &Drawing, st: &mut State) {
egui::Grid::new("dimstyle_new").num_columns(2).spacing(vec2(10.0, 8.0)).show(ui, |ui| {
let name_label = ui.label(crate::tl!("New style name"));
ui.add(egui::TextEdit::singleline(&mut st.new_name).desired_width(220.0)).labelled_by(name_label.id);
ui.end_row();
let start_label = ui.label(crate::tl!("Start with"));
let start = craft_ui::ComboBox::from_id_salt("dimstyle_start_with").selected_text(st.start_with.clone()).width(220.0).show_ui(ui, |ui| {
for s in &d.dim_styles {
ui.selectable_value(&mut st.start_with, s.name.clone(), &s.name);
}
});
start.response.labelled_by(start_label.id);
ui.end_row();
ui.label("");
ui.checkbox(&mut st.new_annotative, crate::tl!("Annotative"));
ui.end_row();
});
let name = st.new_name.trim().to_string();
let taken = d.dim_style(&name).is_some();
if taken {
ui.label(RichText::new(crate::tl!("A dimension style with this name already exists.")).color(Tokens::get().text_dim));
}
ui.add_space(8.0);
ui.horizontal(|ui| {
if ui.add_enabled(!bad_name(&name) && !taken, egui::Button::new(crate::tl!("Continue"))).clicked() {
let mut values = d.dim_style(&st.start_with).map(style_json).unwrap_or_default();
values.insert("name".into(), json!(name));
values.insert("annotative".into(), json!(st.new_annotative));
start_edit(st, name, Target::Create, values);
}
if ui.button(crate::tl!("Cancel")).clicked() {
st.page = Page::List;
st.error = None;
}
});
}
fn edit_page(ui: &mut egui::Ui, d: &Drawing, st: &mut State, actions: &mut Vec<(&'static str, Value)>) {
ui.horizontal(|ui| {
for i in 0..TABS {
ui.selectable_value(&mut st.tab, i, tab_label(i));
}
});
ui.separator();
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
ui.set_width(360.0);
egui::ScrollArea::vertical().id_salt(("dimstyle_tab", st.tab)).max_height(330.0).auto_shrink([false, true]).show(ui, |ui| {
egui::Grid::new(("dimstyle_fields", st.tab)).num_columns(2).spacing(vec2(10.0, 6.0)).show(ui, |ui| {
fields(ui, d, st);
});
});
});
ui.vertical(|ui| {
preview(ui, d, &from_json(&st.values), vec2(300.0, 225.0));
});
});
ui.separator();
if let Some(e) = &st.error {
ui.label(RichText::new(e.as_str()).color(Tokens::get().warn));
}
ui.horizontal(|ui| {
if ui.button(crate::tl!("OK")).clicked() {
let changed: Map<String, Value> = st
.values
.iter()
.filter(|(k, v)| k.as_str() != "name" && st.original.get(k.as_str()) != Some(*v))
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
match st.target {
Target::Modify if !changed.is_empty() => {
let mut p = changed;
p.insert("name".into(), json!(st.editing));
p.insert("current".into(), json!(false));
actions.push(("dimstyle", Value::Object(p)));
}
// What differs from the style is the whole override set: a value set back to the
// style's drops its override.
Target::Override if !changed.is_empty() || !d.dim_overrides().is_empty() => {
let mut p = changed;
p.insert("clear".into(), json!(true));
actions.push(("dimstyle.overrides", Value::Object(p)));
}
Target::Create => {
// Every variable, so the new style is what was shown whatever the current style is.
let mut p: Map<String, Value> =
st.values.iter().filter(|(k, _)| k.as_str() != "name").map(|(k, v)| (k.clone(), v.clone())).collect();
p.insert("name".into(), json!(st.editing));
p.insert("current".into(), json!(false));
actions.push(("dimstyle", Value::Object(p)));
}
_ => {}
}
st.after_ok = Some(if st.target == Target::Override { OVERRIDES.into() } else { st.editing.clone() });
}
if ui.button(crate::tl!("Cancel")).clicked() {
st.page = Page::List;
}
});
}
/// The fields of the chosen tab.
fn fields(ui: &mut egui::Ui, d: &Drawing, st: &mut State) {
let tab = st.tab;
// A fixed-height text style decides the text height (as in AutoCAD the field is off).
let fixed = st
.values
.get("textStyle")
.and_then(Value::as_str)
.and_then(|n| d.text_style(n))
.filter(|ts| ts.height > 0.0)
.map(|ts| (ts.name.clone(), ts.height));
let (lu, lp) = (d.header.i64("LUNITS", 2), d.header.i64("LUPREC", 4));
for p in DIM_PROPS.iter().filter(|p| tab_of(p) == tab) {
match p.field {
// Shown as a prefix and a suffix.
"post" | "altPost" => {
let template = st.values.get(p.field).and_then(Value::as_str).unwrap_or_default().to_string();
let (pre, suf) = split_post(&template);
let alt = p.field == "altPost";
let (lp_, ls_) = if alt { ("Alt prefix", "Alt suffix") } else { ("Dim prefix", "Dim suffix") };
let (mut pre2, mut suf2) = (pre.clone(), suf.clone());
let pre_label = ui.label(crate::i18n::t(lp_));
ui.add(egui::TextEdit::singleline(&mut pre2).desired_width(160.0)).labelled_by(pre_label.id);
ui.end_row();
let suf_label = ui.label(crate::i18n::t(ls_));
ui.add(egui::TextEdit::singleline(&mut suf2).desired_width(160.0)).labelled_by(suf_label.id);
ui.end_row();
if pre2 != pre || suf2 != suf {
st.values.insert(p.field.into(), json!(join_post(&pre2, &suf2)));
}
continue;
}
// Leading and trailing zeros (DIMZIN bits 4 and 8; DIMAZIN 1 and 2).
"zeroSuppression" | "altZeroSuppression" | "tolZeroSuppression" | "angularZeroSuppression" => {
let bits = st.values.get(p.field).and_then(Value::as_u64).unwrap_or(0);
let (lead, trail) = if p.field == "angularZeroSuppression" { (1, 2) } else { (4, 8) };
ui.label(crate::i18n::t(p.label));
let mut b = bits;
ui.horizontal(|ui| {
let mut l = b & lead != 0;
let mut t = b & trail != 0;
if ui.checkbox(&mut l, crate::tl!("Leading")).changed() {
b ^= lead;
}
if ui.checkbox(&mut t, crate::tl!("Trailing")).changed() {
b ^= trail;
}
});
if b != bits {
st.values.insert(p.field.into(), json!(b));
}
ui.end_row();
continue;
}
_ => {}
}
let label = ui.label(crate::i18n::t(p.label));
let id = ("dimstyle_field", &st.editing, p.field);
// A per-end arrowhead left empty shows the one DIMBLK draws.
let cur = if p.kind == DimPropKind::Arrow {
dim_value(p, &Value::Object(st.values.clone()))
} else {
st.values.get(p.field).cloned().unwrap_or(Value::Null)
};
// The row's label names its field, check box or drop-down.
let new = ui.label_inputs_by(label.id, |ui| match p.kind {
DimPropKind::Distance | DimPropKind::Number | DimPropKind::Angle => {
if p.field == "textHeight"
&& let Some((name, h)) = &fixed
{
ui.add_enabled(false, egui::Label::new(cadcraft_engine::units::format_distance(*h, lu, lp))).on_disabled_hover_text(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 = name
));
None
} else {
let v = cur.as_f64().unwrap_or(0.0);
let shown = if p.kind == DimPropKind::Distance { cadcraft_engine::units::format_distance(v, lu, lp) } else { format!("{v}") };
expr_field(ui, egui::Id::unique(id), &shown, Some(label.id))
.and_then(|t| cadcraft_engine::units::parse_distance(&t))
.filter(|f| f.is_finite())
.map(|f| json!(f))
}
}
DimPropKind::Bool => {
let mut b = cur.as_bool().unwrap_or(false);
ui.checkbox(&mut b, "").changed().then(|| json!(b))
}
DimPropKind::Color => {
let c = serde_json::from_value::<cadcraft_color::Color>(cur.clone()).unwrap_or(cadcraft_color::Color::ByBlock);
let mut out = None;
craft_ui::ComboBox::from_id_salt(id).selected_text(crate::i18n::t(&c.name())).width(160.0).show_ui(ui, |ui| {
for (n, aci) in [
("ByBlock", 0),
("ByLayer", 256),
("Red", 1),
("Yellow", 2),
("Green", 3),
("Cyan", 4),
("Blue", 5),
("Magenta", 6),
("White", 7),
] {
if ui
.selectable_label(c.to_aci() == aci && c.name() == cadcraft_color::Color::from_aci(aci).name(), crate::i18n::t(n))
.clicked()
{
out = serde_json::to_value(cadcraft_color::Color::from_aci(aci)).ok();
}
}
});
out
}
DimPropKind::TextStyle => combo(ui, egui::Id::unique(id), &cur, d.text_styles.iter().map(|s| (json!(s.name), s.name.clone())).collect()),
DimPropKind::Linetype => {
let mut names = vec![(json!(""), crate::i18n::t("ByBlock").to_string())];
names.extend(
d.linetypes
.iter()
.filter(|l| !l.name.eq_ignore_ascii_case("ByLayer") && !l.name.eq_ignore_ascii_case("ByBlock"))
.map(|l| (json!(l.name), l.name.clone())),
);
combo(ui, egui::Id::unique(id), &cur, names)
}
_ => {
let options = p.kind.options().into_iter().map(|o| (o.value, crate::i18n::t(&o.label).to_string())).collect();
combo(ui, egui::Id::unique(id), &cur, options)
}
});
if let Some(v) = new.filter(|v| *v != cur) {
st.values.insert(p.field.into(), v);
}
ui.end_row();
}
}
/// A drop-down of `options` (value, label) showing `cur`'s label; the value picked.
fn combo(ui: &mut egui::Ui, id: egui::Id, cur: &Value, options: Vec<(Value, String)>) -> Option<Value> {
let shown = options
.iter()
.find(|(v, _)| v == cur)
.map_or_else(|| cur.as_str().map(str::to_string).unwrap_or_else(|| cur.to_string()), |(_, l)| l.clone());
let mut out = None;
craft_ui::ComboBox::from_id_salt(id).selected_text(shown).width(160.0).show_ui(ui, |ui| {
for (v, label) in options {
if ui.selectable_label(v == *cur, label).clicked() {
out = Some(v);
}
}
});
out
}
fn compare_page(ui: &mut egui::Ui, d: &Drawing, st: &mut State, current: &str, overrides: &Map<String, Value>) {
let mut names: Vec<String> = d.dim_styles.iter().map(|s| s.name.clone()).collect();
// The current settings can be compared too: the current style with its overrides.
if !overrides.is_empty() {
names.push(OVERRIDES.to_string());
}
if !names.contains(&st.selected) {
st.selected = current.to_string();
}
ui.horizontal(|ui| {
let compare_label = ui.label(crate::tl!("Compare"));
let a = craft_ui::ComboBox::from_id_salt("dimstyle_compare_a").selected_text(st.selected.clone()).show_ui(ui, |ui| {
for n in &names {
ui.selectable_value(&mut st.selected, n.clone(), n);
}
});
a.response.labelled_by(compare_label.id);
let with_label = ui.label(crate::tl!("With"));
let b = craft_ui::ComboBox::from_id_salt("dimstyle_compare_b").selected_text(st.compare_with.clone()).show_ui(ui, |ui| {
for n in &names {
ui.selectable_value(&mut st.compare_with, n.clone(), n);
}
});
b.response.labelled_by(with_label.id);
});
let style = |n: &str| {
let st = if n == OVERRIDES {
d.dim_style(current).cloned().unwrap_or_default().with_overrides(overrides)
} else {
d.dim_style(n).cloned().unwrap_or_default()
};
Value::Object(style_json(&st))
};
let (a, b) = (style(&st.selected), style(&st.compare_with));
let same = st.selected == st.compare_with;
let rows: Vec<&DimProp> = DIM_PROPS.iter().filter(|p| same || dim_value(p, &a) != dim_value(p, &b)).collect();
ui.label(if same { crate::tf!("All properties of {style}", style = st.selected) } else { crate::tf!("{count} differences", count = rows.len()) });
egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| {
egui::Grid::new("dimstyle_compare").num_columns(4).striped(true).spacing(vec2(12.0, 4.0)).show(ui, |ui| {
ui.label(RichText::new(crate::tl!("Description")).strong());
ui.label(RichText::new(crate::tl!("Variable")).strong());
ui.label(RichText::new(&st.selected).strong());
if !same {
ui.label(RichText::new(&st.compare_with).strong());
}
ui.end_row();
for p in rows {
let var = cadcraft_engine::doc::DIMVARS.iter().find(|(_, f)| *f == p.field).map_or("", |(v, _)| *v);
ui.label(crate::i18n::t(p.label));
ui.label(var);
ui.label(shown(p, &a));
if !same {
ui.label(shown(p, &b));
}
ui.end_row();
}
});
});
if ui.button(crate::tl!("Close")).clicked() {
st.page = Page::List;
}
}
/// Sample dimensions drawn with `style`: a plate with a hole and a slanted edge, dimensioned
/// linear, aligned, angular and diameter, sized to the style's text.
fn preview(ui: &mut egui::Ui, d: &Drawing, style: &DimStyle, size: egui::Vec2) {
let (w, h) = (size.x.max(16.0) as u32, size.y.max(16.0) as u32);
let mut hasher = std::hash::DefaultHasher::new();
serde_json::to_string(style).unwrap_or_default().hash(&mut hasher);
serde_json::to_string(&d.text_styles).unwrap_or_default().hash(&mut hasher);
// The drawing area's color, as the theme and the user's model background give it.
let bg = Tokens::get().canvas;
(w, h, bg.to_array()).hash(&mut hasher);
let key = hasher.finish();
let id = egui::Id::unique(("dimstyle_preview", size.x as u32, size.y as u32));
let cached = ui.data(|m| m.get_temp::<(u64, egui::TextureHandle)>(id)).filter(|(k, _)| *k == key).map(|(_, t)| t);
let tex = match cached {
Some(t) => Some(t),
None => sample(d, style, w, h, bg).map(|img| {
let t = ui.ctx().load_texture("dimstyle_preview", img, egui::TextureOptions::LINEAR);
ui.data_mut(|m| m.insert_temp(id, (key, t.clone())));
t
}),
};
match tex {
Some(t) => {
ui.image((t.id(), size));
}
None => {
ui.allocate_space(size);
}
}
}
fn sample(d: &Drawing, style: &DimStyle, w: u32, h: u32, bg: egui::Color32) -> Option<egui::ColorImage> {
let mut s = cadcraft_engine::Session::new();
{
let doc = s.doc_mut().ok()?;
doc.text_styles.clone_from(&d.text_styles);
doc.linetypes.clone_from(&d.linetypes);
doc.dim_styles = vec![DimStyle { name: "Preview".into(), ..style.clone() }];
doc.header.set_str("DIMSTYLE", "Preview");
doc.sync_dim_vars();
}
// Sizes in text heights, so any style's text reads at preview size.
let text = d.text_style(&style.text_style).map(|t| t.height).filter(|h| *h > 0.0).unwrap_or(style.text_height * style.effective_scale(1.0));
let u = if text.is_finite() && text > 1e-9 { text } else { 0.18 };
let (l, ht) = (14.0 * u, 9.0 * u);
let run = |s: &mut cadcraft_engine::Session, cmd: &str, p: Value| s.execute(cmd, &p).ok();
run(&mut s, "pline", json!({ "vertices": [[0, 0], [l, 0], [l, ht * 0.6], [l * 0.7, ht], [0, ht]], "closed": true }))?;
let c = run(&mut s, "circle", json!({ "center": [l * 0.35, ht * 0.5], "radius": ht * 0.2 }))?;
let circle = c.get("handle").or_else(|| c.get("handles").and_then(|h| h.get(0))).cloned().unwrap_or(Value::Null);
run(&mut s, "dimlinear", json!({ "p1": [0, 0], "p2": [l, 0], "at": [l / 2.0, -3.0 * u] }));
run(&mut s, "dimlinear", json!({ "p1": [0, 0], "p2": [0, ht], "at": [-3.0 * u, ht / 2.0] }));
run(&mut s, "dimaligned", json!({ "p1": [l, ht * 0.6], "p2": [l * 0.7, ht], "at": [l + 1.5 * u, ht + 1.5 * u] }));
run(&mut s, "dimangular", json!({ "vertex": [l * 0.7, ht], "p1": [0, ht], "p2": [l, ht * 0.6], "at": [l * 0.55, ht * 0.8] }));
run(&mut s, "dimdiameter", json!({ "handle": circle, "at": [l * 0.55, ht * 0.22] }));
let doc = s.doc().ok()?;
let list = cadcraft_engine::render::build(doc, &cadcraft_engine::doc::Space::Model, &cadcraft_engine::render::Options::default());
let view = cadcraft_engine::render::raster::View::fit(&list.bounds, w, h, 0.06);
let background = cadcraft_color::Rgb(bg.r(), bg.g(), bg.b());
let png = cadcraft_engine::render::raster::render_png(
&list,
&view,
&cadcraft_engine::render::raster::RasterOptions { background, ..Default::default() },
)?;
let img = image::load_from_memory(&png).ok()?.to_rgba8();
Some(egui::ColorImage::from_rgba_unmultiplied([img.width() as usize, img.height() as usize], img.as_raw()))
}
+28 -54
View File
@@ -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.
@@ -1091,7 +1093,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<described::Edit> = 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");
match &e.kind {
EntityKind::Line(l) => {
@@ -1145,25 +1151,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);
}
// A multileader's text (#1081): it had no field, so it couldn't be changed.
EntityKind::MLeader(ml) => {
if let Some(tx) = &ml.text {
@@ -1202,30 +1189,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::<u8>().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.
@@ -1258,13 +1221,14 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) {
}
_ => {}
}
} else if let Some(dims) = sel
.iter()
.map(|h| match d.entity(*h).map(|e| &e.kind) {
Some(EntityKind::Dimension(dm)) => Some(dm),
_ => None,
})
.collect::<Option<Vec<_>>>()
} else if !drawn
&& let Some(dims) = sel
.iter()
.map(|h| match d.entity(*h).map(|e| &e.kind) {
Some(EntityKind::Dimension(dm)) => Some(dm),
_ => None,
})
.collect::<Option<Vec<_>>>()
{
// Several dimensions: every property of one dimension, `*VARIES*` where they differ; an
// edit applies to all of them.
@@ -1314,7 +1278,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) {
set = Some(json!({ "handles": ids, "precision": n }));
}
});
} else if sel.iter().filter_map(|h| d.entity(*h)).all(|x| std::mem::discriminant(&x.kind) == std::mem::discriminant(&e.kind)) {
} else if !drawn && sel.iter().filter_map(|h| d.entity(*h)).all(|x| std::mem::discriminant(&x.kind) == std::mem::discriminant(&e.kind)) {
// Several objects of one type: the properties of one object, `*VARIES*` where they differ.
// Edits apply to all of them; positions are shown but stay read-only, since typing one
// would move every object to the same place.
@@ -1493,6 +1457,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);
@@ -1607,11 +1578,14 @@ mod tests {
app.run("select", json!({ "handles": dims.clone() })).unwrap();
app.run("properties.set", json!({ "handles": [dims[0].clone()], "textHeight": 7.0 })).unwrap();
app.run("properties.set", json!({ "handles": [dims[1].clone()], "textHeight": 7.0 + 1e-13 })).unwrap();
// The row's value is painted after its label (the measurements and text positions of the
// two dimensions do differ).
let text_height = |texts: &[String]| texts.iter().position(|t| t == "Text height").and_then(|i| texts.get(i + 1)).cloned();
let texts = painted_texts(&mut app, properties_section);
assert!(!texts.iter().any(|t| t == VARIES), "noise below 12 digits is not a difference; painted: {texts:?}");
assert_ne!(text_height(&texts).as_deref(), Some(VARIES), "noise below 12 digits is not a difference; painted: {texts:?}");
app.run("properties.set", json!({ "handles": [dims[1].clone()], "textHeight": 7.000001 })).unwrap();
let texts = painted_texts(&mut app, properties_section);
assert!(texts.iter().any(|t| t == VARIES), "7 and 7.000001 differ although both show as 7.0000; painted: {texts:?}");
assert_eq!(text_height(&texts).as_deref(), Some(VARIES), "7 and 7.000001 differ although both show as 7.0000; painted: {texts:?}");
let mut app = CadApp::new(Session::default(), Services::default());
let circles = circles(&mut app, &[2, 2], json!({}));
+226
View File
@@ -0,0 +1,226 @@
//! 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<Arc<Description>> {
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<Description>)>(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<Edit>, bad: &mut Option<String>) -> 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());
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, &rows, row, 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<String> {
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(),
})
}
/// 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<Edit>, bad: &mut Option<String>) {
let Rows { d, ids, angles, text_style } = *rows;
let t = Tokens::get();
let key = row.key;
let mut picked: Option<Value> = 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) {
// 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),
}
}
}
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() {
// 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();
}
}
});
}
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 });
}
}
+83
View File
@@ -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<Dimension> {
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:?}");
}
+320
View File
@@ -0,0 +1,320 @@
//! The Dimension Style Manager (#850): DIMSTYLE typed or from the menus opens it (JSON calls
//! don't); Modify, New, Override, Set Current, Compare and Delete do what AutoCAD's do.
use cadcraft_engine::Session;
use cadcraft_ui_egui::{CadApp, Services, dialogs, menus};
use egui::{Key, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable, by};
use serde_json::json;
#[test]
fn dimstyle_typed_or_from_the_menus_opens_the_manager() {
let mut app = CadApp::new(Session::new(), Services::default());
for typed in ["DIMSTYLE", "dimstyle", "D", "DST", "DDIM"] {
app.ui.dialog = None;
assert!(app.cmdline(typed).is_none(), "bare {typed} is not an error");
assert_eq!(app.ui.dialog.as_deref(), Some("dimstyle"), "{typed}");
}
for item in ["dimstyle", "dimstyle.dimension"] {
app.ui.dialog = None;
menus::activate(&mut app, item);
assert_eq!(app.ui.dialog.as_deref(), Some("dimstyle"), "{item}");
}
// Programmatic calls never open it.
app.ui.dialog = None;
app.run("dimstyle", json!({ "name": "Plan", "current": false })).unwrap();
assert!(app.ui.dialog.is_none());
}
/// The manager open on a new drawing after `setup`.
fn manager(setup: impl FnOnce(&mut CadApp)) -> Harness<'static, CadApp> {
harness(setup, false)
}
/// `manager`, 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::new(), Services::default());
setup(&mut app);
app.ui.dialog = Some("dimstyle".into());
let builder = Harness::builder().with_size(vec2(1000.0, 640.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());
dialogs::show(app, ui.ctx());
},
app,
);
h.run_steps(4);
h
}
/// Clicks the button (or list entry or tab) `label`.
fn click(h: &mut Harness<'static, CadApp>, label: &str) {
h.get(by().label(label).role(egui::accesskit::Role::Button)).click();
h.run_steps(3);
}
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 enabled(h: &Harness<'static, CadApp>, label: &str) -> bool {
!h.get(by().label(label).role(egui::accesskit::Role::Button)).accesskit_node().is_disabled()
}
fn text_height(h: &Harness<'static, CadApp>, style: &str) -> f64 {
h.state().session.doc().unwrap().dim_style(style).unwrap().text_height
}
#[test]
fn modify_edits_the_style() {
let mut h = manager(|_| {});
click(&mut h, "Modify...");
click(&mut h, "Text");
type_into(&mut h, "0.1800", "0.25");
// Nothing changes until OK.
assert_eq!(text_height(&h, "Standard"), 0.18);
click(&mut h, "OK");
assert_eq!(text_height(&h, "Standard"), 0.25);
assert_eq!(h.state().ui.dialog.as_deref(), Some("dimstyle"), "back to the list");
}
#[test]
fn cancel_leaves_the_style_alone() {
let mut h = manager(|_| {});
click(&mut h, "Modify...");
click(&mut h, "Text");
type_into(&mut h, "0.1800", "0.5");
click(&mut h, "Cancel");
assert_eq!(text_height(&h, "Standard"), 0.18);
}
#[test]
fn new_starts_with_a_style_and_creates_it_on_ok() {
let mut h = manager(|app| {
app.run("dimstyle", json!({ "name": "Plan", "DIMTXT": 0.3, "current": false })).unwrap();
});
click(&mut h, "Plan");
click(&mut h, "New...");
click(&mut h, "Continue");
assert!(h.state().session.doc().unwrap().dim_style("Copy of Plan").is_none(), "made on OK");
click(&mut h, "OK");
assert_eq!(text_height(&h, "Copy of Plan"), 0.3);
// The current style is unchanged.
assert_eq!(h.state().session.doc().unwrap().header.str("DIMSTYLE", ""), "Standard");
}
#[test]
fn override_changes_the_current_settings_only() {
let mut h = manager(|_| {});
click(&mut h, "Override...");
click(&mut h, "Text");
type_into(&mut h, "0.1800", "0.3");
click(&mut h, "OK");
let d = h.state().session.doc().unwrap();
assert_eq!(d.dim_overrides().get("textHeight"), Some(&json!(0.3)));
assert_eq!(d.dim_style("Standard").unwrap().text_height, 0.18, "the style keeps its value");
// The list shows the overrides under the current style.
h.get_by_label("<style overrides>");
}
#[test]
fn override_drops_a_value_set_back_to_the_styles() {
let mut h = manager(|app| {
app.run("dimstyle.overrides", json!({ "textHeight": 0.3, "textGap": 0.05 })).unwrap();
});
click(&mut h, "Override...");
click(&mut h, "Text");
type_into(&mut h, "0.3000", "0.18");
click(&mut h, "OK");
let o = h.state().session.doc().unwrap().dim_overrides();
assert_eq!((o.get("textHeight"), o.get("textGap")), (None, Some(&json!(0.05))), "{o:?}");
}
#[test]
fn a_refused_value_keeps_the_editor_and_its_edits() {
let mut h = manager(|_| {});
click(&mut h, "Override...");
click(&mut h, "Text");
type_into(&mut h, "0.1800", "-1");
click(&mut h, "OK");
// dimstyle.overrides refuses a negative text height: the page stays, with what was typed.
assert!(h.state().session.doc().unwrap().dim_overrides().is_empty());
field(&h, "-1.0000");
}
#[test]
fn modify_keeps_the_editor_and_says_so_when_a_value_is_left_out() {
let mut h = manager(|_| {});
click(&mut h, "Modify...");
click(&mut h, "Text");
type_into(&mut h, "0.1800", "0");
click(&mut h, "OK");
// `dimstyle` leaves a text height of 0 out (it must be greater than 0): the style keeps its
// value, and the page stays with what was typed and the reason.
assert_eq!(text_height(&h, "Standard"), 0.18);
field(&h, "0.0000");
h.get(by().label_contains("Ignored invalid value for: textHeight"));
// Set right, OK takes it and goes back to the list.
type_into(&mut h, "0.0000", "0.25");
click(&mut h, "OK");
assert_eq!(text_height(&h, "Standard"), 0.25);
assert!(h.query_by_label_contains("Ignored invalid value").is_none());
}
/// The editing pages belong to the drawing they were opened on: another drawing becoming active
/// cancels them, so OK can't write the first drawing's style into the second.
#[test]
fn the_editor_is_cancelled_when_another_drawing_becomes_active() {
let mut h = manager(|app| {
app.run("dimstyle", json!({ "name": "Standard", "textHeight": 7.0 })).unwrap();
app.run("new", json!({})).unwrap();
app.run("dimstyle", json!({ "name": "Standard", "textHeight": 3.0 })).unwrap();
// The manager opens on the first of the two drawings.
app.session.active = app.session.docs.len() - 2;
});
click(&mut h, "Modify...");
click(&mut h, "Text");
field(&h, "7.0000");
let other = h.state().session.docs.len() - 1;
h.state_mut().session.active = other;
h.run_steps(4);
assert!(h.query_by_label_contains("Modify Dimension Style:").is_none(), "the editor is cancelled");
assert!(h.query_by_label("OK").is_none(), "no OK left to press");
assert_eq!(text_height(&h, "Standard"), 3.0, "the second drawing keeps its own style");
}
#[test]
fn a_new_style_takes_a_name_dimstyle_takes() {
let mut h = manager(|_| {});
click(&mut h, "New...");
// `~` is -DIMSTYLE Restore's "compare with".
type_into(&mut h, "Copy of Standard", "~Plan");
assert!(!enabled(&h, "Continue"));
}
#[test]
fn the_style_overrides_compare_with_their_style() {
let mut h = manager(|app| {
app.run("dimstyle.overrides", json!({ "textHeight": 0.3 })).unwrap();
});
click(&mut h, "<style overrides>");
click(&mut h, "Compare...");
// The current settings against the style they override: the one difference.
h.get_by_label("1 differences");
}
#[test]
fn set_current_compare_and_delete() {
let mut h = manager(|app| {
app.run("dimstyle", json!({ "name": "Temp", "DIMASZ": 0.5, "current": false })).unwrap();
});
click(&mut h, "Temp");
click(&mut h, "Set Current");
assert_eq!(h.state().session.doc().unwrap().header.str("DIMSTYLE", ""), "Temp");
// Neither the current style nor Standard can be deleted.
assert!(!enabled(&h, "Delete"));
click(&mut h, "Standard");
assert!(!enabled(&h, "Delete"));
click(&mut h, "Temp");
click(&mut h, "Compare...");
h.get_by_label("All properties of Temp");
click(&mut h, "Close");
// The current style can't be deleted; another unused one can.
h.state_mut().run("dimstyle.current", json!({ "name": "Standard" })).unwrap();
h.run_steps(3);
click(&mut h, "Temp");
click(&mut h, "Delete");
assert!(h.state().session.doc().unwrap().dim_style("Temp").is_none());
}
/// Opens the shortcut menu of list entry `label`.
fn right_click(h: &mut Harness<'static, CadApp>, label: &str) {
h.get(by().label(label).role(egui::accesskit::Role::Button)).click_secondary();
h.run_steps(3);
}
/// Clicks the enabled button `label` (the shortcut menu's, when the dialog's own is off).
fn click_enabled(h: &mut Harness<'static, CadApp>, label: &str) {
h.get_all(by().label(label).role(egui::accesskit::Role::Button)).find(|n| !n.accesskit_node().is_disabled()).unwrap().click();
h.run_steps(3);
}
#[test]
fn shortcut_menus_save_or_discard_overrides_and_rename() {
let mut h = manager(|app| {
app.run("dimstyle", json!({ "name": "Plan", "current": false })).unwrap();
app.run("setvar", json!({ "name": "DIMTXT", "value": 0.3 })).unwrap();
});
right_click(&mut h, "<style overrides>");
click(&mut h, "Save to current style");
let d = h.state().session.doc().unwrap();
assert!(d.dim_overrides().is_empty());
assert_eq!(d.dim_style("Standard").unwrap().text_height, 0.3);
// Deleting the overrides leaves the style as it was.
h.state_mut().run("setvar", json!({ "name": "DIMTXT", "value": 0.5 })).unwrap();
h.run_steps(3);
right_click(&mut h, "<style overrides>");
click_enabled(&mut h, "Delete");
let d = h.state().session.doc().unwrap();
assert!(d.dim_overrides().is_empty());
assert_eq!(d.dim_style("Standard").unwrap().text_height, 0.3);
right_click(&mut h, "Plan");
click(&mut h, "Rename");
type_into(&mut h, "Plan", "Site");
let d = h.state().session.doc().unwrap();
assert!(d.dim_style("Plan").is_none() && d.dim_style("Site").is_some());
// A name another style has isn't offered: Site keeps its name.
right_click(&mut h, "Site");
click(&mut h, "Rename");
type_into(&mut h, "Site", "Standard");
assert!(!enabled(&h, "OK"));
assert!(h.state().session.doc().unwrap().dim_style("Site").is_some());
}
/// With `CADCRAFT_DIMSTYLE_SHOTS=<directory>`, pictures of the manager's pages to look at.
#[test]
fn pictures_of_the_pages() {
let Some(directory) = std::env::var_os("CADCRAFT_DIMSTYLE_SHOTS").map(std::path::PathBuf::from) else { return };
std::fs::create_dir_all(&directory).unwrap();
let setup = |app: &mut CadApp| {
app.run("dimstyle", json!({ "name": "Plan", "DIMTXT": 0.25, "DIMBLK": "_ARCHTICK", "current": false })).unwrap();
app.run("setvar", json!({ "name": "DIMDEC", "value": 2 })).unwrap();
};
let shots: [(&str, &[&str]); 10] = [
("dimstyle-list.png", &[]),
("dimstyle-overrides.png", &["<style overrides>"]),
("dimstyle-new.png", &["New..."]),
("dimstyle-lines.png", &["Modify..."]),
("dimstyle-symbols.png", &["Modify...", "Symbols and Arrows"]),
("dimstyle-text.png", &["Modify...", "Text"]),
("dimstyle-fit.png", &["Modify...", "Fit"]),
("dimstyle-units.png", &["Modify...", "Primary Units"]),
("dimstyle-tolerances.png", &["Override...", "Tolerances"]),
("dimstyle-compare.png", &["Plan", "Compare..."]),
];
for (name, clicks) in shots {
let mut h = harness(setup, true);
for c in clicks {
click(&mut h, c);
}
h.run_steps(2);
h.render().unwrap().save(directory.join(name)).unwrap();
}
}
+3
View File
@@ -8,6 +8,8 @@ mod control_cmdline;
mod control_cmdline_key;
mod control_methods;
mod dialog_dispatch;
mod dimension_menu;
mod dimstyle_dialog;
mod docking_workflows;
mod drafting_polar_increment;
mod drafting_settings_scroll;
@@ -27,6 +29,7 @@ mod options_dialog;
mod options_right_click;
mod parameters_rename;
mod pickdrag;
mod properties_described;
mod properties_units;
mod rapid_clicks;
mod selection_cycling;
@@ -0,0 +1,197 @@
//! 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<String> = 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<Dimension> {
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<f64> {
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 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| {
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=<directory>`, 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();
}
}
+73
View File
@@ -13,6 +13,8 @@ fn menu_items_open_their_dialogs() {
("pagesetup", "pagesetup"),
("linetype", "linetype"),
("style", "textstyle"),
("dimstyle", "dimstyle"),
("dimstyle.dimension", "dimstyle"),
("tablestyle", "tablestyle"),
("mleaderstyle", "mleaderstyle"),
("ddptype", "ptype"),
@@ -37,6 +39,11 @@ fn menu_items_open_their_dialogs() {
assert!(app.cmdline(typed).is_none(), "bare {typed} is not an error");
assert_eq!(app.ui.dialog.as_deref(), Some("textstyle"), "{typed}");
}
for typed in ["dimstyle", "D", "DST", "DDIM"] {
app.ui.dialog = None;
assert!(app.cmdline(typed).is_none(), "bare {typed} is not an error");
assert_eq!(app.ui.dialog.as_deref(), Some("dimstyle"), "{typed}");
}
}
#[test]
@@ -46,10 +53,76 @@ fn json_calls_never_open_the_dialogs() {
app.run("linetype", json!({ "load": "DASHED", "current": "DASHED" })).unwrap();
app.run("tablestyle", json!({ "name": "Schedule", "current": false })).unwrap();
app.run("style", json!({ "name": "SCHEM", "font": "Arial" })).unwrap();
app.run("dimstyle", json!({ "name": "Architectural", "scale": 2.5 })).unwrap();
assert!(app.session.doc().unwrap().text_styles.iter().any(|s| s.name == "SCHEM"));
assert!(app.session.doc().unwrap().dim_styles.iter().any(|s| s.name == "Architectural" && s.scale == 2.5));
assert!(app.ui.dialog.is_none());
let d = app.session.doc().unwrap();
assert_eq!((d.header.i64("PDMODE", 0), d.header.f64("PDSIZE", 0.0)), (34, -5.0));
assert_eq!(d.header.str("CELTYPE", ""), "DASHED");
assert!(d.table_styles.iter().any(|s| s.name == "Schedule"));
}
#[test]
fn dimstyle_dialog_renders_and_preserves_state() {
let mut app = CadApp::new(Session::new(), Services::default());
let ctx = egui::Context::default();
app.cmdline("D");
assert_eq!(app.ui.dialog.as_deref(), Some("dimstyle"));
let mut out = ctx.run_ui(Default::default(), |ui| dialogs::show(&mut app, ui.ctx()));
out.textures_delta.clear();
assert_eq!(app.ui.dialog.as_deref(), Some("dimstyle"));
let d = app.session.doc().unwrap();
assert!(d.dim_styles.iter().any(|s| s.name.eq_ignore_ascii_case("Standard")));
}
#[test]
fn dimstyle_refuses_invalid_values_with_diagnostic() {
let mut app = CadApp::new(Session::new(), Services::default());
let r = app.run("dimstyle", json!({ "name": "Standard", "textHeight": 2.5, "decimals": 4, "current": false })).unwrap();
assert!(r.get("ignored").is_none());
let d = app.session.doc().unwrap();
let st = d.dim_style("Standard").unwrap();
assert_eq!(st.text_height, 2.5);
assert_eq!(st.decimals, 4);
// Text height 0, precision 200, and negative precision -1 must be refused.
let r = app.run("dimstyle", json!({ "name": "Standard", "textHeight": 0.0, "decimals": 200, "current": false })).unwrap();
let ignored = r["ignored"].as_array().expect("ignored list");
assert!(ignored.iter().any(|v| v == "textHeight"));
assert!(ignored.iter().any(|v| v == "decimals"));
assert!(r["message"].as_str().unwrap().contains("Ignored invalid value"));
let r = app.run("dimstyle", json!({ "name": "Standard", "decimals": -1, "current": false })).unwrap();
let ignored = r["ignored"].as_array().expect("ignored list");
assert!(ignored.iter().any(|v| v == "decimals"));
// Style retains valid values.
let d = app.session.doc().unwrap();
let st = d.dim_style("Standard").unwrap();
assert_eq!(st.text_height, 2.5);
assert_eq!(st.decimals, 4);
}
#[test]
fn dimstyle_dialog_action_updates_style_properties() {
let mut app = CadApp::new(Session::new(), Services::default());
let ctx = egui::Context::default();
menus::activate(&mut app, "dimstyle");
assert_eq!(app.ui.dialog.as_deref(), Some("dimstyle"));
// Execute field update through the action mechanism.
app.run("dimstyle", json!({ "name": "Standard", "arrowSize": 3.5, "extExtend": 1.75, "current": false })).unwrap();
let d = app.session.doc().unwrap();
let st = d.dim_style("Standard").unwrap();
assert_eq!(st.arrow_size, 3.5);
assert_eq!(st.ext_extend, 1.75);
// The Dimension Style Manager draws over the changed style without panicking.
let mut out = ctx.run_ui(Default::default(), |ui| dialogs::show(&mut app, ui.ctx()));
out.textures_delta.clear();
assert_eq!(app.ui.dialog.as_deref(), Some("dimstyle"));
}
+9
View File
@@ -67,5 +67,14 @@ 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, 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
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.