Merge pull request #1413 from ramox81/codex/linear-constraint-parity

Linear dimensional constraints: point flow, dynamic dimension, driving parameter, persistence

# Conflicts:
#	src/scene/parametric_constraints.rs
This commit is contained in:
Hakan Seven committed 2026-09-21 22:36:20 +03:00
commit 0ee8b15511
19 files changed
+2204 -61

No files matched your search

+25 -15
View File
@@ -67,26 +67,36 @@ impl AlignedDimensionCommand {
let first = self.plane.to_local(first);
let second = self.plane.to_local(second);
let point = self.plane.to_local(point);
let mut dim = DimensionAligned::new(v3(first), v3(second));
// The placement point is stored so commit matches the preview.
dim.definition_point = v3(point);
dim.base.definition_point = v3(point);
let (d1, d2) = dim_line_endpoints(first, second, point);
dim.base.text_middle_point = v3((d1 + d2) * 0.5);
dim.base.insertion_point = dim.base.text_middle_point;
dim.base.actual_measurement = dim.measurement();
crate::entities::dimension::set_dimension_text_override(
&mut dim.base,
self.text_override.clone(),
);
let mut entity = aligned_dimension_entity(first, second, point, self.text_override.clone());
// An explicit text angle overrides the default rotation.
if let Some(angle) = self.text_angle {
dim.base.text_rotation = angle;
if let (Some(angle), EntityType::Dimension(dimension)) = (self.text_angle, &mut entity) {
dimension.base_mut().text_rotation = angle;
}
self.plane.place_entity(EntityType::Dimension(Dimension::Aligned(dim)))
self.plane.place_entity(entity)
}
}
/// An aligned dimension between two points of the working plane, its
/// dimension line through `point` — what DIMALIGNED places and what an
/// aligned dimensional constraint draws.
pub(crate) fn aligned_dimension_entity(
first: DVec3,
second: DVec3,
point: DVec3,
text_override: Option<String>,
) -> EntityType {
let mut dim = DimensionAligned::new(v3(first), v3(second));
// The placement point is stored so commit matches the preview.
dim.definition_point = v3(point);
dim.base.definition_point = v3(point);
let (d1, d2) = dim_line_endpoints(first, second, point);
dim.base.text_middle_point = v3((d1 + d2) * 0.5);
dim.base.insertion_point = dim.base.text_middle_point;
dim.base.actual_measurement = dim.measurement();
crate::entities::dimension::set_dimension_text_override(&mut dim.base, text_override);
EntityType::Dimension(Dimension::Aligned(dim))
}
impl CadCommand for AlignedDimensionCommand {
fn set_working_plane(&mut self, plane: WorkingPlane) {
self.plane = plane;
+27 -15
View File
@@ -15,7 +15,7 @@ use glam::DVec3;
use crate::t;
/// Select the measured axis from where the dimension line clears the points.
fn measure_axis(first: DVec3, second: DVec3, def: DVec3) -> DVec3 {
pub(crate) fn measure_axis(first: DVec3, second: DVec3, def: DVec3) -> DVec3 {
let outside = |value: f64, a: f64, b: f64| {
let (low, high) = if a <= b { (a, b) } else { (b, a) };
(low - value).max(value - high).max(0.0)
@@ -113,26 +113,38 @@ impl LinearDimensionCommand {
let first = self.plane.to_local(first);
let second = self.plane.to_local(second);
let point = self.plane.to_local(point);
let mut dim = DimensionLinear::new(v3(first), v3(second));
let axis = self.axis_mode.axis(first, second, point);
dim.rotation = axis.y.atan2(axis.x);
dim.set_offset(dimension_line_offset(second, point, axis));
dim.base.definition_point = dim.definition_point;
dim.base.text_middle_point = v3(linear_text_pos(first, second, point, axis));
dim.base.insertion_point = dim.base.text_middle_point;
dim.base.actual_measurement = dim.measurement();
crate::entities::dimension::set_dimension_text_override(
&mut dim.base,
self.text_override.clone(),
);
let mut entity =
linear_dimension_entity(first, second, point, axis, self.text_override.clone());
// An explicit text angle overrides the UCS-derived rotation.
if let Some(angle) = self.text_angle {
dim.base.text_rotation = angle;
if let (Some(angle), EntityType::Dimension(dimension)) = (self.text_angle, &mut entity) {
dimension.base_mut().text_rotation = angle;
}
self.plane.place_entity(EntityType::Dimension(Dimension::Linear(dim)))
self.plane.place_entity(entity)
}
}
/// A linear dimension between two points of the working plane, its
/// dimension line through `point` along `axis` — what DIMLINEAR places and
/// what a dynamic dimensional constraint draws.
pub(crate) fn linear_dimension_entity(
first: DVec3,
second: DVec3,
point: DVec3,
axis: DVec3,
text_override: Option<String>,
) -> EntityType {
let mut dim = DimensionLinear::new(v3(first), v3(second));
dim.rotation = axis.y.atan2(axis.x);
dim.set_offset(dimension_line_offset(second, point, axis));
dim.base.definition_point = dim.definition_point;
dim.base.text_middle_point = v3(linear_text_pos(first, second, point, axis));
dim.base.insertion_point = dim.base.text_middle_point;
dim.base.actual_measurement = dim.measurement();
crate::entities::dimension::set_dimension_text_override(&mut dim.base, text_override);
EntityType::Dimension(Dimension::Linear(dim))
}
impl CadCommand for LinearDimensionCommand {
fn name(&self) -> &'static str {
"DIMLINEAR"
+656
View File
@@ -0,0 +1,656 @@
use acadrust::{EntityType, Handle};
use glam::DVec3;
use crate::command::{CadCommand, CmdOption, CmdResult, CoincidentPick};
use crate::scene::parametric_constraints::{
measured_expression, resolve_point, ConstraintKind, ParametricRef,
};
/// Which distance a dimensional constraint measures.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum DimConstraintAxis {
/// Horizontal or vertical, decided by where the dimension line goes.
Linear,
Horizontal,
Vertical,
Aligned,
}
#[derive(Clone, Copy)]
enum Step {
/// `Specify first constraint point or [Object] <Object>:`
First,
/// `Select object:`
Object,
/// `Specify second constraint point:`
Second {
first: ParametricRef,
first_point: DVec3,
},
/// `Specify dimension line location:`
Location {
first: ParametricRef,
second: ParametricRef,
first_point: DVec3,
second_point: DVec3,
},
/// `Enter value or name and value <d1=100>:`
Value {
first: ParametricRef,
second: ParametricRef,
first_point: DVec3,
second_point: DVec3,
location: DVec3,
axis: DVec3,
kind: ConstraintKind,
measured: f64,
},
}
/// The reference's Linear/Horizontal/Vertical/Aligned dimensional constraint:
/// two constraint points (or one object's ends), a dimension line location,
/// then the parameter name and expression the dynamic dimension carries.
pub struct DimConstraintCommand {
axis: DimConstraintAxis,
step: Step,
picked_entity: Option<EntityType>,
/// The next free `dN` the host reserved for this constraint.
default_name: String,
}
impl DimConstraintCommand {
pub const NO_OBJECT: &'static str = "No object found.";
pub const NO_POINT: &'static str = "No valid constraint point found.";
pub const SAME_POINT: &'static str =
"The object or point is already selected. Select a different object or constraint point.";
pub fn new(axis: DimConstraintAxis, default_name: String) -> Self {
Self {
axis,
step: Step::First,
picked_entity: None,
default_name,
}
}
fn command_name(&self) -> &'static str {
match self.axis {
DimConstraintAxis::Linear => "DCLINEAR",
DimConstraintAxis::Horizontal => "DCHORIZONTAL",
DimConstraintAxis::Vertical => "DCVERTICAL",
DimConstraintAxis::Aligned => "DCALIGNED",
}
}
fn noun(&self) -> &'static str {
match self.axis {
DimConstraintAxis::Linear => "Linear",
DimConstraintAxis::Horizontal => "Horizontal",
DimConstraintAxis::Vertical => "Vertical",
DimConstraintAxis::Aligned => "Aligned",
}
}
fn report(message: &str) -> CmdResult {
CmdResult::ReportError(message.to_string())
}
/// The two end points an object pick constrains: a line's or an arc's
/// ends, the picked polyline segment's vertices.
fn object_ends(
entity: &EntityType,
handle: Handle,
point: DVec3,
) -> Option<(ParametricRef, ParametricRef)> {
match entity {
EntityType::Line(_) | EntityType::Arc(_) => {
Some((ParametricRef::point(handle, 0), ParametricRef::point(handle, 1)))
}
EntityType::LwPolyline(_) | EntityType::Polyline2D(_) => {
let (source, _, _) =
crate::scene::centerline::picked_source(entity, handle, point)?;
let index = source.segment_index;
// A closed polyline's last segment ends at the first vertex.
let end = if resolve_point(entity, index + 1).is_some() {
index + 1
} else {
0
};
Some((ParametricRef::point(handle, index), ParametricRef::point(handle, end)))
}
_ => None,
}
}
fn world(entity: &EntityType, reference: ParametricRef) -> Option<DVec3> {
let point = resolve_point(entity, reference.marker?)?;
Some(DVec3::new(point.x, point.y, point.z))
}
/// The measured kind and axis: Linear reads the dimension line location
/// the way a linear dimension does, the others are fixed.
fn decide(&self, first: DVec3, second: DVec3, location: DVec3) -> (ConstraintKind, DVec3) {
match self.axis {
DimConstraintAxis::Linear => {
let axis =
crate::modules::annotate::linear_dim::measure_axis(first, second, location);
if axis.x.abs() > 0.5 {
(ConstraintKind::DistanceX, DVec3::X)
} else {
(ConstraintKind::DistanceY, DVec3::Y)
}
}
DimConstraintAxis::Horizontal => (ConstraintKind::DistanceX, DVec3::X),
DimConstraintAxis::Vertical => (ConstraintKind::DistanceY, DVec3::Y),
DimConstraintAxis::Aligned => (
ConstraintKind::Distance,
(second - first).normalize_or(DVec3::X),
),
}
}
fn measured(kind: ConstraintKind, first: DVec3, second: DVec3) -> f64 {
match kind {
ConstraintKind::DistanceX => (second.x - first.x).abs(),
ConstraintKind::DistanceY => (second.y - first.y).abs(),
_ => (second - first).length(),
}
}
fn build(&self, name: String, expression: String) -> Option<CmdResult> {
let Step::Value {
first,
second,
first_point,
second_point,
location,
axis,
kind,
..
} = self.step
else {
return None;
};
if expression.trim().is_empty() {
return None;
}
Some(CmdResult::AddDimensionalConstraint {
kind,
first,
second,
first_point,
second_point,
location,
axis,
name,
expression,
label: match self.axis {
DimConstraintAxis::Linear => "Linear constraint",
DimConstraintAxis::Horizontal => "Horizontal distance constraint",
DimConstraintAxis::Vertical => "Vertical distance constraint",
DimConstraintAxis::Aligned => "Aligned constraint",
},
})
}
}
impl CadCommand for DimConstraintCommand {
fn name(&self) -> &'static str {
self.command_name()
}
fn prompt(&self) -> String {
let name = self.command_name();
match self.step {
Step::First => {
format!("{name} Specify first constraint point or [Object] <Object>:")
}
Step::Object => format!("{name} Select object:"),
Step::Second { .. } => format!("{name} Specify second constraint point:"),
Step::Location { .. } => format!("{name} Specify dimension line location:"),
Step::Value { measured, .. } => format!(
"{name} Enter value or name and value <{}={}>:",
self.default_name,
measured_expression(measured)
),
}
}
fn options(&self) -> Vec<CmdOption> {
matches!(self.step, Step::First)
.then(|| vec![CmdOption::new("Object", "O")])
.unwrap_or_default()
}
fn wants_text_input(&self) -> bool {
true
}
fn point_step_accepts_keywords(&self) -> bool {
matches!(self.step, Step::First | Step::Value { .. })
}
fn on_text_input(&mut self, text: &str) -> Option<CmdResult> {
match self.step {
Step::First => {
let keyword = text.trim().trim_start_matches('_').to_ascii_uppercase();
if matches!(keyword.as_str(), "O" | "OBJECT") {
self.step = Step::Object;
return Some(CmdResult::NeedPoint);
}
None
}
Step::Value { .. } => {
let text = text.trim();
let (name, expression) = match text.split_once('=') {
Some((name, expression)) => (name.trim().to_string(), expression.trim().to_string()),
None => (self.default_name.clone(), text.to_string()),
};
self.build(name, expression)
}
_ => None,
}
}
fn needs_entity_pick(&self) -> bool {
matches!(self.step, Step::First | Step::Object | Step::Second { .. })
}
fn entity_pick_accepts_points(&self) -> bool {
true
}
fn typed_point_picks_entity(&self) -> bool {
true
}
fn entity_pick_highlights_hover(&self) -> bool {
true
}
fn inject_before_entity_pick(&self) -> bool {
true
}
fn inject_picked_entity(&mut self, entity: EntityType) {
self.picked_entity = Some(entity);
}
fn on_entity_pick(&mut self, handle: Handle, point: DVec3) -> CmdResult {
match self.step {
// The host resolves the constraint point and hands it back
// through `accept_constraint_point`.
Step::First | Step::Second { .. } => CmdResult::CheckConstraintPoint(CoincidentPick {
handle: (!handle.is_null()).then_some(handle),
point,
whole_curve: false,
}),
Step::Object => {
if handle.is_null() {
return Self::report(Self::NO_OBJECT);
}
let Some(entity) = self.picked_entity.take() else {
return CmdResult::NeedPoint;
};
let Some((first, second)) = Self::object_ends(&entity, handle, point) else {
return Self::report(&format!(
"Invalid selection for {}. Select a line, polyline segment or arc.",
self.noun()
));
};
let (Some(first_point), Some(second_point)) =
(Self::world(&entity, first), Self::world(&entity, second))
else {
return Self::report(Self::NO_POINT);
};
self.step = Step::Location {
first,
second,
first_point,
second_point,
};
CmdResult::NeedPoint
}
Step::Location { .. } | Step::Value { .. } => self.on_point(point),
}
}
fn accept_constraint_point(&mut self, reference: ParametricRef, point: DVec3) -> CmdResult {
match self.step {
Step::First => {
self.step = Step::Second {
first: reference,
first_point: point,
};
CmdResult::NeedPoint
}
Step::Second { first, first_point } => {
if first == reference {
return Self::report(Self::SAME_POINT);
}
self.step = Step::Location {
first,
second: reference,
first_point,
second_point: point,
};
CmdResult::NeedPoint
}
_ => CmdResult::NeedPoint,
}
}
fn on_point(&mut self, point: DVec3) -> CmdResult {
match self.step {
Step::First | Step::Second { .. } => CmdResult::CheckConstraintPoint(CoincidentPick {
handle: None,
point,
whole_curve: false,
}),
Step::Object => Self::report(Self::NO_OBJECT),
Step::Location {
first,
second,
first_point,
second_point,
} => {
let (kind, axis) = self.decide(first_point, second_point, point);
let measured = Self::measured(kind, first_point, second_point);
self.step = Step::Value {
first,
second,
first_point,
second_point,
location: point,
axis,
kind,
measured,
};
CmdResult::ReportMeasurement(format!("Dimension text = {measured:.4}"))
}
Step::Value { .. } => CmdResult::NeedPoint,
}
}
fn on_enter(&mut self) -> CmdResult {
match self.step {
Step::First => {
self.step = Step::Object;
CmdResult::NeedPoint
}
Step::Value { measured, .. } => self
.build(self.default_name.clone(), measured_expression(measured))
.unwrap_or(CmdResult::Cancel),
_ => CmdResult::Cancel,
}
}
fn on_escape(&mut self) -> CmdResult {
CmdResult::Cancel
}
}
/// `DIMCONSTRAINT`: the reference's option front end for the dimensional
/// constraint family; each choice runs the focused command.
pub struct DimConstraintMenuCommand {
/// The option Enter takes: the dimensional constraint used last.
default: &'static str,
}
impl DimConstraintMenuCommand {
pub fn new(default: &'static str) -> Self {
Self { default }
}
fn dispatch(keyword: &str) -> Option<&'static str> {
Some(match keyword {
"L" | "LINEAR" => "DCLINEAR",
"H" | "HORIZONTAL" => "DCHORIZONTAL",
"V" | "VERTICAL" => "DCVERTICAL",
"A" | "ALIGNED" => "DCALIGNED",
"AN" | "ANGULAR" => "DCANGULAR",
"R" | "RADIAL" | "RADIUS" => "DCRADIUS",
"D" | "DIAMETER" => "DCDIAMETER",
"F" | "FORM" => "DCFORM",
"C" | "CONVERT" => "DCCONVERT",
_ => return None,
})
}
fn command_for_label(label: &str) -> &'static str {
match label {
"Linear" => "DCLINEAR",
"Horizontal" => "DCHORIZONTAL",
"Vertical" => "DCVERTICAL",
"ANgular" => "DCANGULAR",
"Radius" => "DCRADIUS",
"Diameter" => "DCDIAMETER",
"Convert" => "DCCONVERT",
_ => "DCALIGNED",
}
}
}
impl CadCommand for DimConstraintMenuCommand {
fn name(&self) -> &'static str {
"DIMCONSTRAINT"
}
fn prompt(&self) -> String {
format!(
"DIMCONSTRAINT Enter a dimensional constraint option [Linear/Horizontal/Vertical/Aligned/ANgular/Radius/Diameter/Form/Convert] <{}>:",
self.default
)
}
fn options(&self) -> Vec<CmdOption> {
vec![
CmdOption::new("Linear", "L"),
CmdOption::new("Horizontal", "H"),
CmdOption::new("Vertical", "V"),
CmdOption::new("Aligned", "A"),
CmdOption::new("ANgular", "AN"),
CmdOption::new("Radius", "R"),
CmdOption::new("Diameter", "D"),
CmdOption::new("Form", "F"),
CmdOption::new("Convert", "C"),
]
}
fn wants_text_input(&self) -> bool {
true
}
fn on_text_input(&mut self, text: &str) -> Option<CmdResult> {
let keyword = text.trim().trim_start_matches('_').to_ascii_uppercase();
Self::dispatch(&keyword).map(|command| CmdResult::Dispatch(command.to_string()))
}
fn on_point(&mut self, _point: DVec3) -> CmdResult {
CmdResult::NeedPoint
}
fn on_enter(&mut self) -> CmdResult {
CmdResult::Dispatch(Self::command_for_label(self.default).to_string())
}
fn on_escape(&mut self) -> CmdResult {
CmdResult::Cancel
}
}
/// `DCFORM`: `Enter constraint form [Annotational/Dynamic] <current>:`;
/// the host records the answer and continues into DIMCONSTRAINT's option
/// prompt, as the reference does.
pub struct ConstraintFormCommand {
annotational: bool,
}
impl ConstraintFormCommand {
pub fn new(annotational: bool) -> Self {
Self { annotational }
}
fn current(&self) -> &'static str {
if self.annotational {
"Annotational"
} else {
"Dynamic"
}
}
}
impl CadCommand for ConstraintFormCommand {
fn name(&self) -> &'static str {
"DCFORM"
}
fn prompt(&self) -> String {
format!(
"DCFORM Enter constraint form [Annotational/Dynamic] <{}>:",
self.current()
)
}
fn options(&self) -> Vec<CmdOption> {
vec![
CmdOption::new("Annotational", "A"),
CmdOption::new("Dynamic", "D"),
]
}
fn wants_text_input(&self) -> bool {
true
}
fn point_step_accepts_keywords(&self) -> bool {
true
}
fn on_text_input(&mut self, text: &str) -> Option<CmdResult> {
let keyword = text.trim().trim_start_matches('_').to_ascii_uppercase();
let form = match keyword.as_str() {
"A" | "ANNOTATIONAL" => "Annotational",
"D" | "DYNAMIC" => "Dynamic",
_ => return None,
};
Some(CmdResult::Dispatch(format!("DCFORM_SET {form}")))
}
fn on_point(&mut self, _point: DVec3) -> CmdResult {
CmdResult::NeedPoint
}
fn on_enter(&mut self) -> CmdResult {
CmdResult::Dispatch(format!("DCFORM_SET {}", self.current()))
}
fn on_escape(&mut self) -> CmdResult {
CmdResult::Cancel
}
}
/// The value prompt a double-clicked dynamic dimension opens, standing in
/// for the reference's in-place editor; `name=expression` also renames.
pub struct DimensionValueCommand {
name: String,
current: String,
}
impl DimensionValueCommand {
pub fn new(name: String, current: String) -> Self {
Self { name, current }
}
}
impl CadCommand for DimensionValueCommand {
fn name(&self) -> &'static str {
"DCVALUE"
}
fn prompt(&self) -> String {
format!(
"DCVALUE Enter value or name and value <{}={}>:",
self.name, self.current
)
}
fn wants_text_input(&self) -> bool {
true
}
fn point_step_accepts_keywords(&self) -> bool {
true
}
fn on_text_input(&mut self, text: &str) -> Option<CmdResult> {
let text = text.trim();
(!text.is_empty()).then(|| CmdResult::Dispatch(format!("DCVALUE {} {text}", self.name)))
}
fn on_point(&mut self, _point: DVec3) -> CmdResult {
CmdResult::NeedPoint
}
fn on_enter(&mut self) -> CmdResult {
CmdResult::Cancel
}
fn on_escape(&mut self) -> CmdResult {
CmdResult::Cancel
}
}
#[cfg(test)]
mod tests {
use super::*;
use acadrust::entities::Line;
use acadrust::types::Vector3;
#[test]
fn object_pick_takes_the_line_ends_then_asks_for_the_location() {
let mut command = DimConstraintCommand::new(DimConstraintAxis::Linear, "d1".into());
assert!(matches!(command.on_enter(), CmdResult::NeedPoint));
command.inject_picked_entity(EntityType::Line(Line::from_points(
Vector3::ZERO,
Vector3::new(100.0, 50.0, 0.0),
)));
assert!(matches!(
command.on_entity_pick(Handle::new(7), DVec3::new(50.0, 25.0, 0.0)),
CmdResult::NeedPoint
));
// Below the pair: horizontal, so the measured value is the X span.
let CmdResult::ReportMeasurement(text) = command.on_point(DVec3::new(50.0, -30.0, 0.0))
else {
panic!("the location must report the dimension text");
};
assert_eq!(text, "Dimension text = 100.0000");
assert_eq!(
command.prompt(),
"DCLINEAR Enter value or name and value <d1=100>:"
);
let CmdResult::AddDimensionalConstraint {
kind, name, expression, ..
} = command.on_text_input("w=d1*2").expect("a value builds the constraint")
else {
panic!("the value must build the constraint");
};
assert_eq!(kind, ConstraintKind::DistanceX);
assert_eq!(name, "w");
assert_eq!(expression, "d1*2");
}
#[test]
fn a_location_beside_the_pair_measures_vertically() {
let mut command = DimConstraintCommand::new(DimConstraintAxis::Linear, "d1".into());
let first = ParametricRef::point(Handle::new(7), 0);
let second = ParametricRef::point(Handle::new(7), 1);
command.accept_constraint_point(first, DVec3::ZERO);
command.accept_constraint_point(second, DVec3::new(100.0, 50.0, 0.0));
let CmdResult::ReportMeasurement(text) = command.on_point(DVec3::new(140.0, 25.0, 0.0))
else {
panic!("the location must report the dimension text");
};
assert_eq!(text, "Dimension text = 50.0000");
}
}
+8 -1
View File
@@ -4,6 +4,8 @@
mod coincident;
mod concentric;
mod dim_constraint;
mod parameters_cli;
mod constraint_bar;
mod equal_distance;
#[path = "equal.rs"]
@@ -25,6 +27,11 @@ mod tools;
mod value;
pub use coincident::{coincident_tool, CoincidentConstraintCommand};
pub use concentric::ConcentricConstraintCommand;
pub use dim_constraint::{
ConstraintFormCommand, DimConstraintAxis, DimConstraintCommand, DimConstraintMenuCommand,
DimensionValueCommand,
};
pub use parameters_cli::ParametersCliCommand;
pub use constraint_bar::ConstraintBarOptionCommand;
pub use equal_command::EqualConstraintCommand;
pub use equal_distance::{equal_distance_tool, EqualDistanceConstraintCommand};
@@ -156,7 +163,7 @@ inventory::submit!(crate::command::CommandRegistration {
names: &[
"AUTOCONSTRAIN", "CONSTRAINTSETTINGS", "GCSMOOTH", "GCSHOW", "GCHIDE", "GCRESET",
"GCSHOWALL", "GCHIDEALL", "DCSHOW", "DCHIDE", "DCSHOWALL", "DCHIDEALL",
"DCCONVERT", "DELCONSTRAINT",
"DCCONVERT", "DELCONSTRAINT", "DIMCONSTRAINT", "DCFORM", "-PARAMETERS",
]
});
+146
View File
@@ -0,0 +1,146 @@
use glam::DVec3;
use crate::command::{CadCommand, CmdOption, CmdResult};
/// `-PARAMETERS`: the reference's command-line parameter manager. One run
/// performs one operation; the host answers the `LIST`, `NEW`, `EDIT`,
/// `SET`, `RENAME` and `DELETE` dispatches.
pub struct ParametersCliCommand {
step: Step,
}
#[derive(Clone)]
enum Step {
/// `Enter a parameter option [New/Edit/Rename/Delete/?]:`
Option,
/// `Enter name for new user parameter:`
NewName,
/// `Enter expression:`
NewExpression { name: String },
/// `Enter parameter name:`
EditName,
/// `Enter expression:` after the host printed the old expression.
EditExpression { name: String },
/// `Enter old parameter name:`
RenameOld,
/// `Enter new parameter name:`
RenameNew { old: String },
/// `Enter parameter name to delete:`
DeleteName,
}
impl ParametersCliCommand {
pub fn new() -> Self {
Self { step: Step::Option }
}
/// The expression prompt the host opens after printing the old expression.
pub fn edit_expression(name: String) -> Self {
Self {
step: Step::EditExpression { name },
}
}
}
impl Default for ParametersCliCommand {
fn default() -> Self {
Self::new()
}
}
impl CadCommand for ParametersCliCommand {
fn name(&self) -> &'static str {
"-PARAMETERS"
}
fn prompt(&self) -> String {
let text = match &self.step {
Step::Option => "Enter a parameter option [New/Edit/Rename/Delete/?]:",
Step::NewName => "Enter name for new user parameter:",
Step::NewExpression { .. } | Step::EditExpression { .. } => "Enter expression:",
Step::EditName => "Enter parameter name:",
Step::RenameOld => "Enter old parameter name:",
Step::RenameNew { .. } => "Enter new parameter name:",
Step::DeleteName => "Enter parameter name to delete:",
};
format!("-PARAMETERS {text}")
}
fn options(&self) -> Vec<CmdOption> {
match self.step {
Step::Option => vec![
CmdOption::new("New", "N"),
CmdOption::new("Edit", "E"),
CmdOption::new("Rename", "R"),
CmdOption::new("Delete", "D"),
CmdOption::new("?", "?"),
],
_ => Vec::new(),
}
}
fn wants_text_input(&self) -> bool {
true
}
fn point_step_accepts_keywords(&self) -> bool {
true
}
fn on_text_input(&mut self, text: &str) -> Option<CmdResult> {
let text = text.trim();
if text.is_empty() {
return None;
}
match self.step.clone() {
Step::Option => {
let keyword = text.trim_start_matches('_').to_ascii_uppercase();
let next = match keyword.as_str() {
"N" | "NEW" => Step::NewName,
"E" | "EDIT" => Step::EditName,
"R" | "RENAME" => Step::RenameOld,
"D" | "DELETE" => Step::DeleteName,
"?" => return Some(CmdResult::Dispatch("-PARAMETERS LIST".to_string())),
_ => return None,
};
self.step = next;
Some(CmdResult::NeedPoint)
}
Step::NewName => {
self.step = Step::NewExpression {
name: text.to_string(),
};
Some(CmdResult::NeedPoint)
}
Step::NewExpression { name } => {
Some(CmdResult::Dispatch(format!("-PARAMETERS NEW {name} {text}")))
}
Step::EditName => Some(CmdResult::Dispatch(format!("-PARAMETERS EDIT {text}"))),
Step::EditExpression { name } => {
Some(CmdResult::Dispatch(format!("-PARAMETERS SET {name} {text}")))
}
Step::RenameOld => {
self.step = Step::RenameNew {
old: text.to_string(),
};
Some(CmdResult::NeedPoint)
}
Step::RenameNew { old } => {
Some(CmdResult::Dispatch(format!("-PARAMETERS RENAME {old} {text}")))
}
Step::DeleteName => Some(CmdResult::Dispatch(format!("-PARAMETERS DELETE {text}"))),
}
}
fn on_point(&mut self, _point: DVec3) -> CmdResult {
CmdResult::NeedPoint
}
fn on_enter(&mut self) -> CmdResult {
CmdResult::Cancel
}
fn on_escape(&mut self) -> CmdResult {
CmdResult::Cancel
}
}