From 3eb74dbc0a61c3f5469c7b28be6e99d09dd39320 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 21 Oct 2026 11:27:12 -0600 Subject: [PATCH 01/47] Dynamic blocks: author linear and point parameters with stretch and move actions (BPARAMETER, BACTION) In the Block Editor, BPARAMETER adds a linear or point parameter and BACTION a stretch or move action that follows it, with AutoCAD's command-line prompts and a JSON form. They are written into the block's evaluation graph as AutoCAD writes its own (nodes, grips, grip location components, edges, purge preventer, element tags), so the block is a dynamic block in CADCraft and in AutoCAD, from DXF and DWG. The Block Editor draws the parameters and actions. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock.rs | 7 +- crates/doc/src/dynblock/marks.rs | 58 +++ crates/doc/src/dynblock/write.rs | 618 ++++++++++++++++++++++ crates/engine/src/blockedit.rs | 25 + crates/engine/src/cmd/blocks.rs | 2 + crates/engine/src/cmd/blocks/bauthor.rs | 664 ++++++++++++++++++++++++ crates/engine/src/cmd/blocks/bedit.rs | 2 +- crates/engine/tests/block_authoring.rs | 169 ++++++ crates/io/tests/dynblock_author.rs | 317 +++++++++++ crates/ui-egui/src/canvas/blockedit.rs | 89 +++- 10 files changed, 1946 insertions(+), 5 deletions(-) create mode 100644 crates/doc/src/dynblock/marks.rs create mode 100644 crates/doc/src/dynblock/write.rs create mode 100644 crates/engine/src/cmd/blocks/bauthor.rs create mode 100644 crates/engine/tests/block_authoring.rs create mode 100644 crates/io/tests/dynblock_author.rs diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index ef0a88be21..48064917b0 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -1,4 +1,5 @@ -//! Dynamic blocks made in another program, read from the data CADCraft keeps for them. +//! Dynamic blocks made in another program, read from the data CADCraft keeps for them, and +//! authored in CADCraft (`write`: the same objects, written). //! //! A dynamic block's behaviour lives in objects CADCraft does not write itself and keeps as //! [`Foreign`](crate::foreign::Foreign) data: the block's BLOCK_RECORD has an extension dictionary @@ -21,10 +22,14 @@ use crate::{Drawing, Handle, RawTag}; mod apply; mod grips; +mod marks; mod reference; +mod write; pub use apply::{drag_grip, set_property}; pub use grips::{DynGrip, GripPart, GripShape, grips}; +pub use marks::{Mark, marks}; pub use reference::{CustomProperty, Reference, Value, custom_properties, reference}; +pub use write::{ActionSpec, MAX_ACTION_ITEMS, ParamPoint, ParameterSpec, add_action, add_parameter, tag_elements}; /// Most objects one evaluation graph is read with. const MAX_NODES: usize = 10_000; diff --git a/crates/doc/src/dynblock/marks.rs b/crates/doc/src/dynblock/marks.rs new file mode 100644 index 0000000000..d969ba0367 --- /dev/null +++ b/crates/doc/src/dynblock/marks.rs @@ -0,0 +1,58 @@ +//! What the Block Editor shows of a dynamic block's parameters and actions: each one's +//! geometry and label, in block coordinates, for the editor to draw. + +use cadcraft_geom::Vec3; +use serde::Serialize; + +use super::{Cursor, ParameterKind, dynamic_block, section, sections}; +use crate::Drawing; + +/// One parameter or action as the Block Editor draws it. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum Mark { + /// A linear parameter: a dimension from `base` to `end`, its line `offset` to the left of + /// base → end, its label in the middle; arrows at the ends that have grips. + Linear { node: i32, base: Vec3, end: Vec3, offset: f64, label: String, base_grip: bool, end_grip: bool }, + /// A point parameter: a marker at `at` and its label at `label_at`. + Point { node: i32, at: Vec3, label_at: Vec3, label: String, grip: bool }, + /// Another parameter: its name at `at`. + Parameter { node: i32, at: Vec3, label: String }, + /// An action: a badge with its name at `at`. + Action { node: i32, at: Vec3, name: String }, +} + +/// Block `name`'s parameters and actions as the Block Editor draws them (empty when it has none). +pub fn marks(d: &Drawing, name: &str) -> Vec { + let Some(m) = dynamic_block(d, name) else { return Vec::new() }; + let mut out = Vec::new(); + for p in &m.parameters { + let tags = d.foreign.objects.iter().find(|o| o.handle == p.handle).map(|o| o.tags.as_slice()).unwrap_or_default(); + let secs = sections(tags); + let label = p.kind.label().unwrap_or(&p.element).to_string(); + let grip = |i: usize| p.grips.get(i).is_some_and(|g| *g != 0); + out.push(match &p.kind { + ParameterKind::Linear { base, end, .. } => { + // The label's offset (140) after its name and description (305, 306). + let mut c = Cursor::new(section(&secs, "AcDbBlockLinearParameter")); + c.next(306); + Mark::Linear { node: p.node, base: *base, end: *end, offset: c.real(140), label, base_grip: grip(0), end_grip: grip(1) } + } + ParameterKind::Point { at, .. } => { + let label_at = Cursor::new(section(&secs, "AcDbBlockPointParameter")).point(1011); + Mark::Point { node: p.node, at: *at, label_at, label, grip: grip(0) } + } + ParameterKind::Polar { base, .. } + | ParameterKind::Xy { base, .. } + | ParameterKind::Rotation { base, .. } + | ParameterKind::Alignment { base, .. } + | ParameterKind::Flip { base, .. } => Mark::Parameter { node: p.node, at: *base, label }, + ParameterKind::Visibility { at, .. } | ParameterKind::Lookup { at, .. } | ParameterKind::BasePoint { at } => { + Mark::Parameter { node: p.node, at: *at, label } + } + ParameterKind::Other { .. } => continue, + }); + } + out.extend(m.actions.iter().map(|a| Mark::Action { node: a.node, at: a.at, name: a.name.clone() })); + out +} diff --git a/crates/doc/src/dynblock/write.rs b/crates/doc/src/dynblock/write.rs new file mode 100644 index 0000000000..f501d68e1a --- /dev/null +++ b/crates/doc/src/dynblock/write.rs @@ -0,0 +1,618 @@ +//! Authoring dynamic blocks: adding parameters and actions to a block, written as the objects +//! the [reader](super::dynamic_block) reads (BPARAMETER, BACTION in the Block Editor). +//! +//! Everything lands in the block's kept [`Foreign`](crate::foreign::Foreign) data, laid out as +//! AutoCAD lays out its own (observed in files it saves): the BLOCK_RECORD's extension dictionary +//! gets an `ACAD_ENHANCEDBLOCK` evaluation graph and a purge preventer, and each parameter or +//! action is a node of the graph. A parameter brings its grips, each grip two location +//! components (its X and Y), and the graph's edges say what is evaluated after what: a +//! parameter before its location components and its actions, a grip before its parameter. +//! A graph read from a file is extended the same way. + +use cadcraft_geom::{Vec2, Vec3}; + +use crate::foreign::ForeignObject; +use crate::{Drawing, EntityStore, Handle, RawTag}; + +use super::{ParameterKind, dynamic_block}; + +/// The graph `AcDbEvalGraph` is extended only up to this many nodes. +const MAX_NODES: usize = super::MAX_NODES; + +/// Most frame points and selected objects one action is written with. +pub const MAX_ACTION_ITEMS: usize = 10_000; + +/// The application name of element tags: the xdata pairing a block's objects with their +/// copies in references. +const ETAG: &str = "AcDbBlockRepETag"; + +/// The value AutoCAD gives a grip location component it hasn't evaluated yet (a linear +/// parameter's end grip). +const UNSET: f64 = 1.797_693_134_862_314e99; + +/// A parameter to add. +#[derive(Clone, Debug, PartialEq)] +pub enum ParameterSpec { + /// A distance from `base` to `end` (Distance1), its label `label_offset` from the line (to + /// its left, looking from base to end), with 0, 1 (end) or 2 grips. + Linear { base: Vec3, end: Vec3, label: Option, label_offset: f64, grips: u8 }, + /// A position (Position1), its label at `label_at`, with 0 or 1 grip. + Point { at: Vec3, label: Option, label_at: Vec3, grips: u8 }, +} + +/// Which point of a two-point parameter an action follows. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ParamPoint { + Base, + #[default] + End, +} + +/// An action to add, following the parameter with graph id `parameter`. +#[derive(Clone, Debug, PartialEq)] +pub enum ActionSpec { + /// Moves the listed vertices of `vertices`' objects (inside `frame`, a rectangle's two corners + /// or a polygon) and the other selected objects whole. + Stretch { parameter: i32, point: ParamPoint, frame: Vec, selection: Vec, vertices: Vec<(Handle, Vec)>, at: Vec3 }, + /// Moves the selected objects. + Move { parameter: i32, point: ParamPoint, selection: Vec, at: Vec3 }, +} + +/// One node of the evaluation graph: its index, flags, graph id, object and the first and last +/// of its incoming and outgoing edges (edge indices, -1 for none). +#[derive(Clone, Debug, PartialEq)] +struct Node { + index: i32, + flags: i32, + id: i32, + handle: Handle, + links: [i32; 4], +} + +/// One edge: its index, flags, kind (1 from a parameter, 2 from a grip), the nodes it joins +/// (indices) and its neighbours in their lists: previous and next incoming of `to`, previous and +/// next outgoing of `from`, then one more link AutoCAD leaves at -1. +#[derive(Clone, Debug, PartialEq)] +struct Edge { + index: i32, + flags: i32, + kind: i32, + from: i32, + to: i32, + links: [i32; 5], +} + +/// An evaluation graph object being extended. +struct Graph { + handle: Handle, + /// Its groups before `100 AcDbEvalGraph`, as they were. + head: Vec, + nodes: Vec, + edges: Vec, +} + +fn tag(code: i32, value: impl ToString) -> RawTag { + RawTag { code, value: value.to_string() } +} + +fn real(code: i32, v: f64) -> RawTag { + tag(code, format!("{v:?}")) +} + +fn point(out: &mut Vec, code: i32, p: Vec3) { + out.extend([real(code, p.x), real(code + 10, p.y), real(code + 20, p.z)]); +} + +impl Graph { + /// The graph object `o` read back into nodes and edges, or `None` when its groups aren't + /// laid out as a graph (it is then left alone). + fn read(o: &ForeignObject) -> Option { + let at = o.tags.iter().position(|t| t.code == 100 && t.value.eq_ignore_ascii_case("AcDbEvalGraph"))?; + let head = o.tags.get(..at)?.to_vec(); + let body = o.tags.get(at + 1..)?; + let int = |t: Option<&RawTag>, code: i32| t.filter(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()); + let mut i = body.iter().position(|t| t.code != 96 && t.code != 97).unwrap_or(body.len()); + let (mut nodes, mut edges) = (Vec::new(), Vec::new()); + while body.get(i).is_some_and(|t| t.code == 91) { + if nodes.len() >= MAX_NODES { + return None; + } + let g = |k: usize| body.get(i + k); + let handle = g(3).filter(|t| t.code == 360).and_then(|t| Handle::parse_hex(&t.value))?; + let links = [int(g(4), 92)?, int(g(5), 92)?, int(g(6), 92)?, int(g(7), 92)?]; + nodes.push(Node { index: int(g(0), 91)?, flags: int(g(1), 93)?, id: int(g(2), 95)?, handle, links }); + i += 8; + } + while body.get(i).is_some_and(|t| t.code == 92) { + if edges.len() >= MAX_NODES.saturating_mul(16) { + return None; + } + let g = |k: usize| body.get(i + k); + let links = [int(g(5), 92)?, int(g(6), 92)?, int(g(7), 92)?, int(g(8), 92)?, int(g(9), 92)?]; + edges.push(Edge { index: int(g(0), 92)?, flags: int(g(1), 93)?, kind: int(g(2), 94)?, from: int(g(3), 91)?, to: int(g(4), 91)?, links }); + i += 10; + } + // Anything after the edges is a layout this doesn't know. + if i != body.len() { + return None; + } + Some(Graph { handle: o.handle, head, nodes, edges }) + } + + /// A new, empty graph owned by dictionary `dict`. + fn new(handle: Handle, dict: Handle) -> Graph { + let head = vec![tag(5, handle.hex()), tag(102, "{ACAD_REACTORS"), tag(330, dict.hex()), tag(102, "}"), tag(330, dict.hex())]; + Graph { handle, head, nodes: Vec::new(), edges: Vec::new() } + } + + fn tags(&self) -> Vec { + let mut out = self.head.clone(); + out.push(tag(100, "AcDbEvalGraph")); + out.push(tag(96, self.nodes.len())); + out.push(tag(97, self.nodes.len())); + for n in &self.nodes { + out.extend([tag(91, n.index), tag(93, n.flags), tag(95, n.id), tag(360, n.handle.hex())]); + out.extend(n.links.iter().map(|l| tag(92, l))); + } + for e in &self.edges { + out.extend([tag(92, e.index), tag(93, e.flags), tag(94, e.kind), tag(91, e.from), tag(91, e.to)]); + out.extend(e.links.iter().map(|l| tag(92, l))); + } + out + } + + /// The next free graph id. + fn next_id(&self) -> i32 { + self.nodes.iter().map(|n| n.id).max().unwrap_or(0).saturating_add(1) + } + + /// Add node `id` for object `handle`; its index. + fn add_node(&mut self, id: i32, handle: Handle) -> i32 { + let index = self.nodes.iter().map(|n| n.index).max().map_or(0, |m| m.saturating_add(1)); + self.nodes.push(Node { index, flags: 32, id, handle, links: [-1; 4] }); + index + } + + fn node_mut(&mut self, index: i32) -> Option<&mut Node> { + self.nodes.iter_mut().find(|n| n.index == index) + } + + fn edge_mut(&mut self, index: i32) -> Option<&mut Edge> { + self.edges.iter_mut().find(|e| e.index == index) + } + + /// The index of the node with graph id `id`. + fn index_of(&self, id: i32) -> Option { + self.nodes.iter().find(|n| n.id == id).map(|n| n.index) + } + + /// Add an edge of `kind` from node index `from` to `to`, last in both nodes' lists. + fn link(&mut self, from: i32, to: i32, kind: i32) { + let index = self.edges.iter().map(|e| e.index).max().map_or(0, |m| m.saturating_add(1)); + let last_out = self.node_mut(from).map_or(-1, |n| n.links[3]); + let last_in = self.node_mut(to).map_or(-1, |n| n.links[1]); + self.edges.push(Edge { index, flags: 0, kind, from, to, links: [last_in, -1, last_out, -1, -1] }); + if let Some(e) = self.edge_mut(last_out) { + e.links[3] = index; + } + if let Some(e) = self.edge_mut(last_in) { + e.links[1] = index; + } + if let Some(n) = self.node_mut(from) { + if n.links[2] < 0 { + n.links[2] = index; + } + n.links[3] = index; + } + if let Some(n) = self.node_mut(to) { + if n.links[0] < 0 { + n.links[0] = index; + } + n.links[1] = index; + } + } +} + +/// The groups every node object starts with: its handle, owner and graph id. +fn node_head(h: Handle, graph: Handle, id: i32) -> Vec { + vec![tag(5, h.hex()), tag(330, graph.hex()), tag(100, "AcDbEvalExpr"), tag(90, id), tag(98, 33), tag(99, 301)] +} + +/// [`node_head`] and the block element: its name and a flag AutoCAD writes (`1071`). +fn element_head(h: Handle, graph: Handle, id: i32, name: &str, flag: i32) -> Vec { + let mut out = node_head(h, graph, id); + out.extend([tag(100, "AcDbBlockElement"), tag(300, name), tag(98, 33), tag(99, 301), tag(1071, flag)]); + out +} + +/// The block being authored: its record's kept data, graph and the objects made so far. +struct Author<'a> { + d: &'a mut Drawing, + record: String, + graph: Graph, + /// New objects to add after the graph. + new: Vec, + /// Classes the new objects need: (DXF name, C++ name). + classes: Vec<(&'static str, &'static str)>, +} + +impl<'a> Author<'a> { + /// Open block `name`'s graph for authoring, making the dictionary, graph and purge preventer + /// when it has none. + fn open(d: &'a mut Drawing, name: &str) -> Result, String> { + let record = name.trim().to_ascii_uppercase(); + if record.is_empty() || record.starts_with('*') { + return Err(format!("\"{name}\" can't have parameters or actions.")); + } + let key = ("BLOCK_RECORD".to_string(), record.clone()); + let xdict = d.foreign.records.get(&key).and_then(|x| x.xdict); + let mut new = Vec::new(); + let mut classes = Vec::new(); + let graph = match xdict.and_then(|x| dict_entry(d, x, "ACAD_ENHANCEDBLOCK")) { + Some(g) => { + let o = d.foreign.objects.iter().find(|o| o.handle == g).ok_or("The block's evaluation graph is missing.")?; + Graph::read(o).ok_or("The block's evaluation graph can't be extended.")? + } + None => { + let rec = record_handle(d, &record); + let dict = match xdict { + Some(x) if d.foreign.objects.iter().any(|o| o.handle == x) => x, + _ => { + let x = d.new_handle(); + let tags = vec![tag(5, x.hex()), tag(330, rec.hex()), tag(100, "AcDbDictionary"), tag(280, 1), tag(281, 1)]; + new.push(ForeignObject { handle: x, kind: "DICTIONARY".into(), tags }); + x + } + }; + let (g, pp) = (d.new_handle(), d.new_handle()); + let mut tags = vec![tag(5, pp.hex()), tag(102, "{ACAD_REACTORS"), tag(330, dict.hex()), tag(102, "}"), tag(330, dict.hex())]; + tags.extend([tag(100, "AcDbDynamicBlockPurgePreventer"), tag(70, 1)]); + new.push(ForeignObject { handle: pp, kind: "ACDB_DYNAMICBLOCKPURGEPREVENTER_VERSION".into(), tags }); + classes.push(("ACAD_EVALUATION_GRAPH", "AcDbEvalGraph")); + classes.push(("ACDB_DYNAMICBLOCKPURGEPREVENTER_VERSION", "AcDbDynamicBlockPurgePreventer")); + let f = std::sync::Arc::make_mut(&mut d.foreign); + // The dictionary's entries: in the new dictionary, or added to the one it had. + let entries = + [tag(3, "ACAD_ENHANCEDBLOCK"), tag(360, g.hex()), tag(3, "AcDbDynamicBlockRoundTripPurgePreventer"), tag(360, pp.hex())]; + match new.iter_mut().find(|o| o.handle == dict) { + Some(o) => o.tags.extend(entries), + None => { + if let Some(o) = f.objects.iter_mut().find(|o| o.handle == dict) { + o.tags.extend(entries); + } + } + } + let extra = f.records.entry(key).or_default(); + extra.xdict = Some(dict); + if !extra.xdata.iter().any(|t| t.code == 1001 && t.value.eq_ignore_ascii_case("AcDbDynamicBlockTrueName")) { + extra.xdata.extend([tag(1001, "AcDbDynamicBlockTrueName"), tag(1000, name.trim())]); + extra.xdata.extend([tag(1001, "AcDbDynamicBlockGUID"), tag(1000, guid(name.trim(), g))]); + } + Graph::new(g, dict) + } + }; + Ok(Author { d, record, graph, new, classes }) + } + + /// Write the graph and the new objects back into the drawing's kept data. + fn finish(self) { + let Author { d, graph, new, classes, .. } = self; + let f = std::sync::Arc::make_mut(&mut d.foreign); + let tags = graph.tags(); + match f.objects.iter_mut().find(|o| o.handle == graph.handle) { + Some(o) => o.tags = tags, + None => f.objects.push(ForeignObject { handle: graph.handle, kind: "ACAD_EVALUATION_GRAPH".into(), tags }), + } + f.objects.extend(new); + for (name, cpp) in classes { + if !f.classes.iter().any(|c| c.iter().any(|t| t.code == 1 && t.value.eq_ignore_ascii_case(name))) { + f.classes.push(vec![tag(1, name), tag(2, cpp), tag(3, "ObjectDBX Classes"), tag(90, 1153), tag(91, 0), tag(280, 0), tag(281, 0)]); + } + } + } + + fn class(&mut self, name: &'static str, cpp: &'static str) { + if !self.classes.iter().any(|(n, _)| *n == name) { + self.classes.push((name, cpp)); + } + } + + /// Add object `kind` with `tags` as graph node `id`; its index. + fn node(&mut self, kind: &str, h: Handle, id: i32, tags: Vec) -> i32 { + self.new.push(ForeignObject { handle: h, kind: kind.into(), tags }); + self.graph.add_node(id, h) + } + + /// A grip at `at` with its two location components (`x_name`, `y_name`, both valued + /// `value`), linked after parameter node `param`: the grip's graph id. + fn grip(&mut self, param: i32, at: Vec3, name: &str, [x_name, y_name]: [&str; 2], value: f64, linear: Option) -> i32 { + let (gh, gid) = (self.d.new_handle(), self.graph.next_id()); + let (xid, yid) = (gid.saturating_add(1), gid.saturating_add(2)); + let mut tags = element_head(gh, self.graph.handle, gid, name, 0); + tags.extend([tag(100, "AcDbBlockGrip"), tag(91, xid), tag(92, yid)]); + point(&mut tags, 1010, at); + tags.extend([tag(280, 1), tag(93, -1)]); + let kind = match linear { + Some(dir) => { + tags.extend([tag(100, "AcDbBlockLinearGrip"), real(140, dir.x), real(141, dir.y), real(142, dir.z)]); + self.class("BLOCKLINEARGRIP", "AcDbBlockLinearGrip"); + "BLOCKLINEARGRIP" + } + None => { + tags.push(tag(100, "AcDbBlockXYGrip")); + self.class("BLOCKXYGRIP", "AcDbBlockXYGrip"); + "BLOCKXYGRIP" + } + }; + let grip = self.node(kind, gh, gid, tags); + self.class("BLOCKGRIPLOCATIONCOMPONENT", "AcDbBlockGripExpr"); + for (id, comp) in [(xid, x_name), (yid, y_name)] { + let h = self.d.new_handle(); + let mut tags = node_head(h, self.graph.handle, id); + tags.extend([tag(1, ""), tag(70, 40), real(140, value), tag(100, "AcDbBlockGripExpr"), tag(91, 1), tag(300, comp)]); + let c = self.node("BLOCKGRIPLOCATIONCOMPONENT", h, id, tags); + self.graph.link(param, c, 1); + } + self.graph.link(grip, param, 2); + gid + } + + /// An element name not used in the block yet: `base`, else `base` and the lowest free number. + fn element_name(&self, base: &str) -> String { + let used: Vec = dynamic_block(self.d, &self.record) + .map(|m| m.parameters.iter().map(|p| p.element.clone()).chain(m.actions.iter().map(|a| a.name.clone())).collect()) + .unwrap_or_default(); + let free = |n: &str| !used.iter().any(|u| u.eq_ignore_ascii_case(n)); + if free(base) { + return base.to_string(); + } + (1..).map(|i| format!("{base}{i}")).find(|n| free(n)).unwrap_or_else(|| base.to_string()) + } +} + +/// The handle the kept data uses for block `record`'s BLOCK_RECORD (a new one, registered, +/// when none refers to it yet). +fn record_handle(d: &mut Drawing, record: &str) -> Handle { + if let Some(h) = d.foreign.targets.iter().find(|(_, (k, n))| k == "BLOCK_RECORD" && n == record).map(|(h, _)| *h) { + return h; + } + let h = d.new_handle(); + std::sync::Arc::make_mut(&mut d.foreign).targets.insert(h, ("BLOCK_RECORD".to_string(), record.to_string())); + h +} + +/// A GUID for block `name`'s dynamic data, made from its name and graph (stable for a drawing). +fn guid(name: &str, graph: Handle) -> String { + // FNV-1a over the name and handle, spread over 128 bits. + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + let mut word = || { + for b in name.bytes().chain(graph.0.to_le_bytes()) { + h ^= u64::from(b); + h = h.wrapping_mul(0x0100_0000_01b3); + } + h + }; + let (a, b) = (word(), word()); + format!("{{{:08X}-{:04X}-{:04X}-{:04X}-{:012X}}}", a >> 32, (a >> 16) & 0xFFFF, a & 0xFFFF, b >> 48, b & 0xFFFF_FFFF_FFFF) +} + +/// A property name not used by the block's parameters yet: `prefix` and the lowest number from 1. +fn free_label(d: &Drawing, record: &str, prefix: &str) -> String { + let used: Vec = + dynamic_block(d, record).map(|m| m.parameters.iter().flat_map(|p| p.kind.label().map(str::to_string)).collect()).unwrap_or_default(); + (1..).map(|i| format!("{prefix}{i}")).find(|n| !used.iter().any(|u| u.eq_ignore_ascii_case(n))).unwrap_or_else(|| format!("{prefix}1")) +} + +fn finite(p: Vec3) -> bool { + p.x.is_finite() && p.y.is_finite() && p.z.is_finite() +} + +/// Add parameter `spec` to block `name` (any case); its graph id. +pub fn add_parameter(d: &mut Drawing, name: &str, spec: &ParameterSpec) -> Result { + match spec { + ParameterSpec::Linear { base, end, label, label_offset, grips } => { + if !finite(*base) || !finite(*end) || !label_offset.is_finite() { + return Err("Invalid point.".into()); + } + if (*end - *base).len() <= 1e-9 { + return Err("The endpoint must differ from the start point.".into()); + } + if *grips > 2 { + return Err("A linear parameter has 0, 1 or 2 grips.".into()); + } + let record = name.trim().to_ascii_uppercase(); + let label = label.clone().unwrap_or_else(|| free_label(d, &record, "Distance")); + let mut a = Author::open(d, name)?; + let element = a.element_name("Linear"); + let (h, id) = (a.d.new_handle(), a.graph.next_id()); + let param = a.graph.add_node(id, h); + let first_grip = a.new.len(); + let dir = *end - *base; + let end_grip = if *grips >= 1 { a.grip(param, *end, "End Grip", ["UpdatedEndX", "UpdatedEndY"], UNSET, Some(dir)) } else { 0 }; + let base_grip = if *grips >= 2 { a.grip(param, *base, "Base Grip", ["UpdatedBaseX", "UpdatedBaseY"], 0.0, Some(-dir)) } else { 0 }; + let mut tags = element_head(h, a.graph.handle, id, &element, if *grips == 2 { 32 } else { 1 }); + tags.extend([tag(100, "AcDbBlockParameter"), tag(280, 1), tag(281, 0), tag(100, "AcDbBlock2PtParameter")]); + point(&mut tags, 1010, *base); + point(&mut tags, 1011, *end); + tags.extend([tag(170, 4), tag(91, base_grip), tag(91, end_grip), tag(91, 0), tag(91, 0)]); + // Each grip's connections: a count, the grip and the value it changes. + let connections = [ + (171, 92, 301, base_grip, "DisplacementX"), + (172, 93, 302, base_grip, "DisplacementY"), + (173, 94, 303, end_grip, "DisplacementX"), + (174, 95, 304, end_grip, "DisplacementY"), + ]; + for (count, id_code, name_code, grip, value) in connections { + if grip == 0 { + tags.push(tag(count, 0)); + } else { + tags.extend([tag(count, 1), tag(id_code, grip), tag(name_code, value)]); + } + } + tags.extend([tag(177, 0), tag(100, "AcDbBlockLinearParameter"), tag(305, &label), tag(306, ""), real(140, *label_offset), tag(307, "")]); + tags.extend([tag(96, 1), real(141, 0.0), real(142, 0.0), real(143, 0.0), tag(175, 0)]); + // The parameter's object goes before its grips, as AutoCAD lists them. + a.new.insert(first_grip, ForeignObject { handle: h, kind: "BLOCKLINEARPARAMETER".into(), tags }); + a.class("BLOCKLINEARPARAMETER", "AcDbBlockLinearParameter"); + a.finish(); + Ok(id) + } + ParameterSpec::Point { at, label, label_at, grips } => { + if !finite(*at) || !finite(*label_at) { + return Err("Invalid point.".into()); + } + if *grips > 1 { + return Err("A point parameter has 0 or 1 grip.".into()); + } + let record = name.trim().to_ascii_uppercase(); + let label = label.clone().unwrap_or_else(|| free_label(d, &record, "Position")); + let mut a = Author::open(d, name)?; + let element = a.element_name("Point"); + let (h, id) = (a.d.new_handle(), a.graph.next_id()); + let param = a.graph.add_node(id, h); + let first_grip = a.new.len(); + let grip = if *grips == 1 { a.grip(param, *at, "Grip", ["UpdatedX", "UpdatedY"], 0.0, None) } else { 0 }; + let mut tags = element_head(h, a.graph.handle, id, &element, if *grips == 1 { 0 } else { 1 }); + tags.extend([tag(100, "AcDbBlockParameter"), tag(280, 1), tag(281, 0), tag(100, "AcDbBlock1PtParameter")]); + point(&mut tags, 1010, *at); + tags.push(tag(93, grip)); + if grip == 0 { + tags.extend([tag(170, 0), tag(171, 0)]); + } else { + tags.extend([tag(170, 1), tag(91, grip), tag(301, "DisplacementX"), tag(171, 1), tag(92, grip), tag(302, "DisplacementY")]); + } + tags.extend([tag(100, "AcDbBlockPointParameter"), tag(303, &label), tag(304, "")]); + point(&mut tags, 1011, *label_at); + a.new.insert(first_grip, ForeignObject { handle: h, kind: "BLOCKPOINTPARAMETER".into(), tags }); + a.class("BLOCKPOINTPARAMETER", "AcDbBlockPointParameter"); + a.finish(); + Ok(id) + } + } +} + +/// Add action `spec` to block `name` (any case); its graph id. The parameter it follows must be +/// one the action can follow (a linear or point parameter for a stretch or move). +pub fn add_action(d: &mut Drawing, name: &str, spec: &ActionSpec) -> Result { + let (parameter, point_of, selection, at) = match spec { + ActionSpec::Stretch { parameter, point, selection, at, .. } | ActionSpec::Move { parameter, point, selection, at } => { + (*parameter, *point, selection, *at) + } + }; + if !finite(at) { + return Err("Invalid point.".into()); + } + if selection.is_empty() { + return Err("An action needs objects to act on.".into()); + } + if selection.len() > MAX_ACTION_ITEMS { + return Err(format!("An action acts on at most {MAX_ACTION_ITEMS} objects.")); + } + let m = dynamic_block(d, name).ok_or("The block has no parameters; add one first (BPARAMETER).")?; + let p = m.parameters.iter().find(|p| p.node == parameter).ok_or_else(|| format!("No parameter {parameter} in the block."))?; + let connections = match (&p.kind, point_of) { + (ParameterKind::Linear { .. }, ParamPoint::End) => ["EndXDelta", "EndYDelta"], + (ParameterKind::Linear { .. }, ParamPoint::Base) => ["BaseXDelta", "BaseYDelta"], + (ParameterKind::Point { .. }, _) => ["XDelta", "YDelta"], + _ => return Err(format!("A {} can't be followed by this action yet.", p.element)), + }; + let mut a = Author::open(d, name)?; + let pindex = a.graph.index_of(parameter).ok_or_else(|| format!("No parameter {parameter} in the block."))?; + let (h, id) = (a.d.new_handle(), a.graph.next_id()); + let (kind, cpp, element) = match spec { + ActionSpec::Stretch { .. } => ("BLOCKSTRETCHACTION", "AcDbBlockStretchAction", a.element_name("Stretch")), + ActionSpec::Move { .. } => ("BLOCKMOVEACTION", "AcDbBlockMoveAction", a.element_name("Move")), + }; + let mut tags = element_head(h, a.graph.handle, id, &element, 0); + tags.extend([tag(100, "AcDbBlockAction"), tag(70, 0), tag(71, selection.len())]); + tags.extend(selection.iter().map(|s| tag(330, s.hex()))); + point(&mut tags, 1010, at); + tags.push(tag(100, if kind == "BLOCKSTRETCHACTION" { "AcDbBlockStretchAction" } else { "AcDbBlockMoveAction" })); + tags.extend([tag(92, parameter), tag(301, connections[0]), tag(93, parameter), tag(302, connections[1])]); + if let ActionSpec::Stretch { frame, vertices, .. } = spec { + if frame.len() < 2 || frame.len() > MAX_ACTION_ITEMS || frame.iter().any(|p| !p.is_finite()) { + return Err("A stretch frame needs two corners or a polygon.".into()); + } + if vertices.len() > MAX_ACTION_ITEMS || vertices.iter().map(|(_, v)| v.len()).sum::() > MAX_ACTION_ITEMS.saturating_mul(16) { + return Err("Too many vertices in the stretch frame.".into()); + } + tags.push(tag(72, frame.len())); + for p in frame { + tags.extend([real(1011, p.x), real(1021, p.y)]); + } + tags.push(tag(73, vertices.len())); + for (h, idx) in vertices { + tags.extend([tag(331, h.hex()), tag(74, idx.len())]); + tags.extend(idx.iter().map(|i| tag(94, i))); + } + tags.push(tag(75, 0)); + } + tags.extend([real(140, 1.0), real(141, 0.0), tag(280, 0)]); + let node = a.node(kind, h, id, tags); + a.graph.link(pindex, node, 1); + a.class(kind, cpp); + a.finish(); + Ok(id) +} + +/// Give every object of `store`, block `name`'s objects, an element tag (`AcDbBlockRepETag` +/// xdata: `1070 1`, `1071` tag, `1005` the object itself) when it has none or has another +/// object's (a copy), and keep the next free tag on the block's record, as AutoCAD does. Only for +/// blocks with dynamic data. +pub fn tag_elements(d: &mut Drawing, name: &str, store: &mut EntityStore) { + let key = ("BLOCK_RECORD".to_string(), name.trim().to_ascii_uppercase()); + if dynamic_block(d, name).is_none() { + return; + } + // The tag an object carries, if it is its own. + let own = |xd: &[RawTag], h: Handle| -> Option { + let at = xd.iter().position(|t| t.code == 1001 && t.value.eq_ignore_ascii_case(ETAG))?; + let app: Vec<&RawTag> = xd.iter().skip(at + 1).take_while(|t| t.code != 1001).collect(); + let mine = app.iter().find(|t| t.code == 1005).and_then(|t| Handle::parse_hex(&t.value)) == Some(h); + app.iter().find(|t| t.code == 1071).and_then(|t| t.value.trim().parse().ok()).filter(|_| mine) + }; + let mut seen = std::collections::HashSet::new(); + let mut retag = Vec::new(); + for e in store.iter() { + match own(&e.common.xdata, e.handle) { + Some(t) if seen.insert(t) => {} + _ => retag.push(e.handle), + } + } + let record_next = d.foreign.records.get(&key).and_then(|x| { + let at = x.xdata.iter().position(|t| t.code == 1001 && t.value.eq_ignore_ascii_case(ETAG))?; + x.xdata.iter().skip(at + 1).take_while(|t| t.code != 1001).find(|t| t.code == 1071).and_then(|t| t.value.trim().parse::().ok()) + }); + let mut next = seen.iter().max().map_or(0, |m| m.saturating_add(1)).max(record_next.unwrap_or(0)); + for h in retag { + let t = next; + next = next.saturating_add(1); + store.modify(h, |e| { + strip_app(&mut e.common.xdata, ETAG); + e.common.xdata.extend([tag(1001, ETAG), tag(1070, 1), tag(1071, t), tag(1005, h.hex())]); + }); + } + let f = std::sync::Arc::make_mut(&mut d.foreign); + let x = f.records.entry(key).or_default(); + strip_app(&mut x.xdata, ETAG); + x.xdata.extend([tag(1001, ETAG), tag(1070, 1), tag(1071, next)]); +} + +/// Remove application `app`'s xdata from `xd`. +fn strip_app(xd: &mut Vec, app: &str) { + let Some(at) = xd.iter().position(|t| t.code == 1001 && t.value.eq_ignore_ascii_case(app)) else { return }; + let end = xd.iter().skip(at + 1).position(|t| t.code == 1001).map_or(xd.len(), |n| at + 1 + n); + xd.drain(at..end); +} + +/// The object entry `key` of dictionary `dict` names. +fn dict_entry(d: &Drawing, dict: Handle, key: &str) -> Option { + let o = d.foreign.objects.iter().find(|o| o.handle == dict)?; + let mut tags = o.tags.iter(); + while let Some(t) = tags.next() { + if t.code == 3 && t.value.eq_ignore_ascii_case(key) { + return tags.next().filter(|t| t.code == 350 || t.code == 360).and_then(|t| Handle::parse_hex(&t.value)); + } + } + None +} diff --git a/crates/engine/src/blockedit.rs b/crates/engine/src/blockedit.rs index fae52757e7..1d2588fce7 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -103,6 +103,27 @@ fn refers_to(d: &Drawing, store: &EntityStore, name: &str) -> bool { } impl BlockEdit { + /// The block's base point, which is the editor's origin. + pub fn base(&self) -> Vec2 { + self.base + } + + /// The edited block's parameters and actions as the editor draws them, in the editor's + /// coordinates (`editor` is the editor's drawing). + pub fn marks(&self, editor: &Drawing) -> Vec { + use cadcraft_doc::dynblock::Mark; + let off = self.base.to3(0.0); + let mut out = cadcraft_doc::dynblock::marks(editor, &self.name); + for m in &mut out { + match m { + Mark::Linear { base, end, .. } => (*base, *end) = (*base - off, *end - off), + Mark::Point { at, label_at, .. } => (*at, *label_at) = (*at - off, *label_at - off), + Mark::Parameter { at, .. } | Mark::Action { at, .. } => *at = *at - off, + } + } + out + } + /// The editor's objects in block coordinates, ready to be the block's: unchanged objects are /// the block's own, the others are moved back from the editor's origin to the base point. fn block_objects(&self, editor: &Drawing) -> EntityStore { @@ -170,6 +191,10 @@ impl BlockEdit { } b.base.x = self.base.x; b.base.y = self.base.y; + let mut entities = entities; + // A dynamic block's objects carry element tags, which its references' copies are paired + // with; objects added in the editor get theirs here. + cadcraft_doc::dynblock::tag_elements(&mut d, name, &mut entities); b.entities = entities; d.blocks.insert(key, Arc::new(b)); Ok(d) diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index ca4cfffecc..05951a62b1 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -18,6 +18,7 @@ use super::has_doc; use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; mod attedit; +mod bauthor; mod burst; mod description; mod dyngrip; @@ -87,6 +88,7 @@ pub fn specs() -> Vec { .chain(xref::specs()) .chain(refedit::specs()) .chain(bedit::specs()) + .chain(bauthor::specs()) .collect() } diff --git a/crates/engine/src/cmd/blocks/bauthor.rs b/crates/engine/src/cmd/blocks/bauthor.rs new file mode 100644 index 0000000000..a49acd9a15 --- /dev/null +++ b/crates/engine/src/cmd/blocks/bauthor.rs @@ -0,0 +1,664 @@ +//! BPARAMETER and BACTION: authoring a dynamic block in the Block Editor. A parameter is a +//! property references to the block can change (a distance, a position); an action is what +//! changing it does to the block's objects (stretch them, move them). Both are written into the +//! block's dynamic data ([`cadcraft_doc::dynblock::add_parameter`], [`add_action`]) as AutoCAD +//! writes its own, so the block works as a dynamic block here and in AutoCAD. Only while the +//! Block Editor is open on a block; points are in the editor's coordinates (the block's base point +//! at the origin). + +use cadcraft_doc::dynblock::{ActionSpec, Mark, ParamPoint, ParameterSpec, add_action, add_parameter, marks}; +use cadcraft_doc::{Drawing, EntityKind, Handle}; +use cadcraft_geom::{Vec2, Vec3}; +use serde_json::{Value, json}; + +use crate::cmd::curves::{KW, handle_value}; +use crate::cmd::machines::{SelOutcome, SelectPhase}; +use crate::cmd::{CommandSpec, bad, point_param, points_param, str_param}; +use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; + +pub(super) fn specs() -> Vec { + vec![ + CommandSpec::new("bparameter", "Parameter", run_bparameter) + .menu(&["Tools", "Block Editor", "Parameter"]) + .alias(&["-bparameter"]) + .params( + "{type: \"linear\"|\"point\", linear: start: [x,y], end: [x,y], labelAt?: [x,y] (where the label goes; default on the line); point: at: [x,y], labelAt?: [x,y]; label?: property name (default Distance1/Position1…), grips?: 0|1|2 (linear, default 2) or 0|1 (point, default 1)} → {node, element, label} (editor coordinates)", + ) + .enabled(authoring) + .interactive(|_| Ok(Box::new(BparameterM::default()))), + CommandSpec::new("baction", "Action", run_baction) + .menu(&["Tools", "Block Editor", "Action"]) + .alias(&["-baction"]) + .params( + "{parameter: graph id or property name (\"Distance1\"), type: \"stretch\"|\"move\", point?: \"start\"|\"second\" (which end of a linear parameter it follows, default second), handles: [objects], frame?: [[x,y],[x,y]] (stretch: corners) | polygon?: [[x,y]…] (stretch: a crossing polygon), at?: [x,y] (where the action shows; default the parameter's point)} → {node, name} (editor coordinates)", + ) + .enabled(authoring) + .interactive(|_| Ok(Box::new(BactionM::default()))), + ] +} + +/// The Block Editor is open on a block (parameters and actions belong to a block). +fn authoring(s: &Session) -> std::result::Result<(), String> { + match s.state() { + Ok(st) => match &st.block_edit { + Some(be) if be.current => Err("Parameters and actions can be added to a block only; this editor is open on the drawing itself.".into()), + Some(_) => Ok(()), + None => Err("Open a block in the Block Editor first (BEDIT).".into()), + }, + Err(e) => Err(e.to_string()), + } +} + +/// The block being edited and where its base point is (the editor's origin). +fn editing(s: &Session) -> Result<(String, Vec2)> { + authoring(s).map_err(EngineError::Other)?; + let st = s.state()?; + let be = st.block_edit.as_ref().ok_or_else(|| EngineError::Other("The Block Editor is not open.".into()))?; + Ok((be.name.clone(), be.base())) +} + +fn to_block(p: Vec2, base: Vec2) -> Vec3 { + (p + base).to3(0.0) +} + +fn grips_param(cmd: &str, p: &Value, most: u8, default: u8) -> Result { + match p.get("grips") { + None | Some(Value::Null) => Ok(default), + Some(v) => v.as_u64().and_then(|g| u8::try_from(g).ok()).filter(|g| *g <= most).ok_or_else(|| bad(cmd, format!("`grips` is 0 to {most}"))), + } +} + +/// How far `at` is to the left of the line from `a` to `b` (negative: to its right). +fn offset_of(a: Vec2, b: Vec2, at: Vec2) -> f64 { + let d = b - a; + let len = d.len(); + if len <= 1e-12 { 0.0 } else { (d.x * (at.y - a.y) - d.y * (at.x - a.x)) / len } +} + +fn run_bparameter(s: &mut Session, p: &Value) -> Result { + let (block, base) = editing(s)?; + let label = str_param(p, "label").map(str::trim).filter(|l| !l.is_empty()).map(str::to_string); + let spec = match str_param(p, "type").map(str::to_ascii_lowercase).as_deref() { + Some("linear") => { + let start = point_param(p, "start").ok_or_else(|| bad("bparameter", "`start` ([x, y]) is required"))?; + let end = point_param(p, "end").ok_or_else(|| bad("bparameter", "`end` ([x, y]) is required"))?; + let label_offset = point_param(p, "labelAt").map_or(0.0, |at| offset_of(start, end, at)); + ParameterSpec::Linear { + base: to_block(start, base), + end: to_block(end, base), + label, + label_offset, + grips: grips_param("bparameter", p, 2, 2)?, + } + } + Some("point") => { + let at = point_param(p, "at").ok_or_else(|| bad("bparameter", "`at` ([x, y]) is required"))?; + let label_at = point_param(p, "labelAt").unwrap_or(at); + ParameterSpec::Point { at: to_block(at, base), label, label_at: to_block(label_at, base), grips: grips_param("bparameter", p, 1, 1)? } + } + Some(other) if ["alignment", "base", "polar", "xy", "rotation", "flip", "visibility", "lookup"].contains(&other) => { + return Err(bad("bparameter", format!("{other} parameters are not available yet"))); + } + _ => return Err(bad("bparameter", "`type` is \"linear\" or \"point\"")), + }; + let node = add_parameter(s.doc_mut()?, &block, &spec).map_err(|e| bad("bparameter", e))?; + let m = cadcraft_doc::dynblock::dynamic_block(s.doc()?, &block); + let made = m.as_ref().and_then(|m| m.parameters.iter().find(|p| p.node == node)); + Ok(json!({ "node": node, "element": made.map(|p| p.element.clone()), "label": made.and_then(|p| p.kind.label().map(str::to_string)) })) +} + +/// A parameter of the edited block as BACTION follows it, in editor coordinates. +#[derive(Clone, Debug, PartialEq)] +enum Followed { + Linear { node: i32, base: Vec2, end: Vec2 }, + Point { node: i32, at: Vec2 }, +} + +impl Followed { + fn node(&self) -> i32 { + match self { + Followed::Linear { node, .. } | Followed::Point { node, .. } => *node, + } + } +} + +/// The parameters of `block` an action can follow, in editor coordinates. +fn followable(d: &Drawing, block: &str, base: Vec2) -> Vec { + marks(d, block) + .into_iter() + .filter_map(|m| match m { + Mark::Linear { node, base: b, end, .. } => Some(Followed::Linear { node, base: b.xy() - base, end: end.xy() - base }), + Mark::Point { node, at, .. } => Some(Followed::Point { node, at: at.xy() - base }), + _ => None, + }) + .collect() +} + +/// The parameter named by `v`: its graph id, or its property name ("Distance1"). +fn parameter_named(d: &Drawing, block: &str, base: Vec2, v: &Value) -> Result { + let list = followable(d, block, base); + let m = cadcraft_doc::dynblock::dynamic_block(d, block); + let node = match v { + Value::Number(n) => n.as_i64().and_then(|n| i32::try_from(n).ok()), + Value::String(t) => t.trim().parse::().ok().or_else(|| { + m.as_ref()? + .parameters + .iter() + .find(|p| p.kind.label().is_some_and(|l| l.eq_ignore_ascii_case(t.trim())) || p.element.eq_ignore_ascii_case(t.trim())) + .map(|p| p.node) + }), + _ => None, + }; + let node = node.ok_or_else(|| bad("baction", format!("no parameter {v} in the block")))?; + match list.into_iter().find(|f| f.node() == node) { + Some(f) => Ok(f), + None if m.is_some_and(|m| m.parameters.iter().any(|p| p.node == node)) => { + Err(bad("baction", "that parameter can't have stretch or move actions yet")) + } + None => Err(bad("baction", format!("no parameter {v} in the block"))), + } +} + +/// How far `p` is from the segment from `a` to `b`. +fn segment_distance(a: Vec2, b: Vec2, p: Vec2) -> f64 { + let d = b - a; + let t = if d.len2() <= 1e-24 { 0.0 } else { ((p - a).dot(d) / d.len2()).clamp(0.0, 1.0) }; + (a + d * t).dist(p) +} + +/// Whether `p` is inside the stretch frame: a box's two corners, or a polygon. +fn in_frame(frame: &[Vec2], p: Vec2) -> bool { + match frame { + [a, b] => cadcraft_geom::Bounds2::new(*a, *b).contains(p), + poly => cadcraft_geom::point_in_polygon(poly, p), + } +} + +/// What a stretch with `frame` does to each of `handles` (editor objects): lines and polylines +/// move their vertices inside it (listed; left out with none inside), other objects move whole when their +/// first grip (a circle's centre, a text's insertion point) is inside, else not at all and they +/// are left out. Returns (selection, vertex lists). +fn stretch_lists(d: &Drawing, handles: &[Handle], frame: &[Vec2]) -> (Vec, Vec<(Handle, Vec)>) { + let (mut selection, mut vertices) = (Vec::new(), Vec::new()); + for h in handles { + let Some(e) = d.entity(*h) else { continue }; + let listed: Option> = match &e.kind { + EntityKind::Line(l) => { + Some([l.a.xy(), l.b.xy()].iter().enumerate().filter(|(_, p)| in_frame(frame, **p)).map(|(i, _)| i as i32).collect()) + } + EntityKind::LwPolyline(pl) => { + Some(pl.vertices.iter().enumerate().filter(|(_, v)| in_frame(frame, v.p)).filter_map(|(i, _)| i32::try_from(i).ok()).collect()) + } + k => { + if !k.grips().first().is_some_and(|p| in_frame(frame, *p)) { + continue; + } + None + } + }; + // A line or polyline with no vertex inside wouldn't change. + if listed.as_ref().is_some_and(Vec::is_empty) { + continue; + } + selection.push(*h); + if let Some(v) = listed { + vertices.push((*h, v)); + } + } + (selection, vertices) +} + +/// Add the action: `kind` "stretch" or "move" following `param` (at its `point`), on `handles`. +fn add( + s: &mut Session, + param: &Followed, + kind: &str, + point: ParamPoint, + handles: &[Handle], + frame: Option>, + at: Option, +) -> Result { + let (block, base) = editing(s)?; + if handles.len() > cadcraft_doc::dynblock::MAX_ACTION_ITEMS { + return Err(bad("baction", "too many objects")); + } + let missing: Vec = handles.iter().filter(|h| s.doc().ok().and_then(|d| d.entity(**h)).is_none()).map(|h| h.hex()).collect(); + if !missing.is_empty() { + return Err(bad("baction", format!("no such object in the block: {}", missing.join(", ")))); + } + let shown = match param { + Followed::Linear { base: b, end, .. } => { + if point == ParamPoint::Base { + *b + } else { + *end + } + } + Followed::Point { at, .. } => *at, + }; + let at = to_block(at.unwrap_or(shown), base); + let spec = match kind { + "stretch" => { + let frame = frame.ok_or_else(|| bad("baction", "a stretch needs `frame` (two corners) or `polygon`"))?; + if frame.len() < 2 || frame.len() > cadcraft_doc::dynblock::MAX_ACTION_ITEMS || frame.iter().any(|p| !p.is_finite()) { + return Err(bad("baction", "`frame` needs two corners, `polygon` three or more points")); + } + let (selection, vertices) = stretch_lists(s.doc()?, handles, &frame); + if selection.is_empty() { + return Err(bad("baction", "none of the objects is in the stretch frame")); + } + let frame = frame.iter().map(|p| *p + base).collect(); + ActionSpec::Stretch { parameter: param.node(), point, frame, selection, vertices, at } + } + "move" => ActionSpec::Move { parameter: param.node(), point, selection: handles.to_vec(), at }, + "array" | "scale" | "rotate" | "flip" | "polarstretch" | "lookup" => { + return Err(bad("baction", format!("{kind} actions are not available yet"))); + } + _ => return Err(bad("baction", "`type` is \"stretch\" or \"move\"")), + }; + let node = add_action(s.doc_mut()?, &block, &spec).map_err(|e| bad("baction", e))?; + let name = cadcraft_doc::dynblock::dynamic_block(s.doc()?, &block).and_then(|m| m.actions.into_iter().find(|a| a.node == node)).map(|a| a.name); + Ok(json!({ "node": node, "name": name })) +} + +fn run_baction(s: &mut Session, p: &Value) -> Result { + let (block, base) = editing(s)?; + let which = p.get("parameter").ok_or_else(|| bad("baction", "`parameter` (graph id or property name) is required"))?; + let param = parameter_named(s.doc()?, &block, base, which)?; + let kind = str_param(p, "type").map(|t| t.trim().to_ascii_lowercase().replace(' ', "")).ok_or_else(|| bad("baction", "`type` is required"))?; + let point = match str_param(p, "point").map(str::to_ascii_lowercase).as_deref() { + None | Some("second") | Some("end") => ParamPoint::End, + Some("start") | Some("base") => ParamPoint::Base, + Some(o) => return Err(bad("baction", format!("`point` is \"start\" or \"second\", not \"{o}\""))), + }; + let handles: Vec = match p.get("handles") { + Some(Value::Array(a)) => { + a.iter().map(|v| handle_value(v).ok_or_else(|| bad("baction", format!("{v} is not an object handle")))).collect::>()? + } + Some(_) => return Err(bad("baction", "`handles` is an array of object handles")), + None => s.selection(), + }; + if handles.is_empty() { + return Err(bad("baction", "`handles`: the objects the action acts on")); + } + let frame = match (points_param(p, "frame"), points_param(p, "polygon")) { + (Some(f), _) if f.len() == 2 => Some(f), + (Some(_), _) => return Err(bad("baction", "`frame` is two corners")), + (None, Some(poly)) if poly.len() >= 3 => Some(poly), + (None, Some(_)) => return Err(bad("baction", "`polygon` needs three or more points")), + (None, None) => None, + }; + add(s, ¶m, &kind, point, &handles, frame, point_param(p, "at")) +} + +/// Read keyword input: `text` (any case, an optional leading `_`) against `options`, each +/// (keyword, its shortcut). The keyword's own spelling, when one matches. +fn keyword<'a>(text: &str, options: &[(&'a str, &str)]) -> Option<&'a str> { + let t = text.trim(); + let t = t.strip_prefix('_').unwrap_or(t); + options.iter().find(|(k, short)| t.eq_ignore_ascii_case(k) || t.eq_ignore_ascii_case(short)).map(|(k, _)| *k) +} + +fn text_of(i: &Input) -> Option<&str> { + match i { + Input::Keyword(t) | Input::Text(t) => Some(t.as_str()), + _ => None, + } +} + +/// Options AutoCAD offers that are not available yet: answered with a message. +fn not_yet(s: &mut Session, what: &str) -> Result { + s.echo(format!("{what} is not available yet.")); + Ok(Step::Continue) +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum PStage { + #[default] + Type, + Start, + End, + LinearLabel, + LinearGrips, + Location, + PointLabel, + PointGrips, + /// Typing the property name, then back to the stage it was asked at. + Label(&'static str), +} + +/// BPARAMETER's prompts, as AutoCAD asks them on the command line. +#[derive(Default)] +struct BparameterM { + stage: PStage, + linear: bool, + start: Vec2, + end: Vec2, + label_at: Vec2, + label: Option, +} + +const TYPES: &[(&str, &str)] = &[ + ("Alignment", "A"), + ("Base", "B"), + ("pOint", "O"), + ("Linear", "L"), + ("Polar", "P"), + ("Xy", "X"), + ("Rotation", "R"), + ("Flip", "F"), + ("Visibility", "V"), + ("looKup", "K"), +]; + +impl BparameterM { + fn make(&self, s: &mut Session, grips: u8) -> Result { + let label = self.label.clone(); + let p = if self.linear { + json!({ "type": "linear", "start": [self.start.x, self.start.y], "end": [self.end.x, self.end.y], "labelAt": [self.label_at.x, self.label_at.y], "label": label, "grips": grips }) + } else { + json!({ "type": "point", "at": [self.start.x, self.start.y], "labelAt": [self.label_at.x, self.label_at.y], "label": label, "grips": grips }) + }; + run_bparameter(s, &p).map(|_| Step::Done) + } + + /// The option keywords of the first point's prompt. + fn options(&self, i: &Input) -> Option<&'static str> { + let opts: &[(&str, &str)] = if self.linear { + &[("Name", "N"), ("Label", "L"), ("Chain", "C"), ("Description", "D"), ("Base", "B"), ("Palette", "P"), ("Value set", "V")] + } else { + &[("Name", "N"), ("Label", "L"), ("Chain", "C"), ("Description", "D"), ("Palette", "P")] + }; + text_of(i).and_then(|t| keyword(t, opts)) + } +} + +impl Interactive for BparameterM { + fn name(&self) -> &'static str { + "BPARAMETER" + } + fn prompt(&self, _s: &Session) -> Prompt { + match self.stage { + PStage::Type => Prompt::new("Enter parameter type", KW).kw(&TYPES.iter().map(|(k, _)| *k).collect::>()), + PStage::Start => Prompt::new("Specify start point", Accept::POINT) + .kw(&["Name", "Label", "Chain", "Description", "Base", "Palette", "Value set"]) + .deferred(), + PStage::End => Prompt::new("Specify endpoint", Accept::POINT).base(self.start), + PStage::LinearLabel | PStage::PointLabel => Prompt::new("Specify label location", Accept::POINT), + PStage::LinearGrips => Prompt::new("Enter number of grips", KW).kw(&["0", "1", "2"]).default("2"), + PStage::Location => Prompt::new("Specify parameter location", Accept::POINT).kw(&["Name", "Label", "Chain", "Description", "Palette"]), + PStage::PointGrips => Prompt::new("Enter number of grips", KW).kw(&["0", "1"]).default("1"), + PStage::Label(what) => Prompt::new(format!("Enter {what} property label"), Accept::TEXT), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if matches!(i, Input::Cancel) { + return Ok(Step::Cancel); + } + match self.stage { + PStage::Type => { + let Some(t) = text_of(&i) else { return Ok(Step::Continue) }; + match keyword(t, TYPES) { + Some("Linear") => (self.linear, self.stage) = (true, PStage::Start), + Some("pOint") => (self.linear, self.stage) = (false, PStage::Location), + Some(other) => return Err(EngineError::Other(format!("{other} parameters are not available yet."))), + None => s.echo("Invalid option keyword."), + } + } + PStage::Start | PStage::Location => match (&i, self.options(&i)) { + (Input::Point(p), _) => { + self.start = *p; + self.stage = if self.linear { PStage::End } else { PStage::PointLabel }; + } + (_, Some("Label")) => self.stage = PStage::Label(if self.linear { "distance" } else { "position" }), + (_, Some(other)) => return not_yet(s, other), + _ => {} + }, + PStage::End => { + if let Input::Point(p) = i { + if (p - self.start).len() <= 1e-9 { + s.echo("The endpoint must differ from the start point."); + } else { + self.end = p; + self.stage = PStage::LinearLabel; + } + } + } + PStage::LinearLabel | PStage::PointLabel => { + if let Input::Point(p) = i { + self.label_at = p; + self.stage = if self.stage == PStage::LinearLabel { PStage::LinearGrips } else { PStage::PointGrips }; + } + } + PStage::LinearGrips | PStage::PointGrips => { + let most = if self.stage == PStage::LinearGrips { 2 } else { 1 }; + let grips = match &i { + Input::Enter => Some(most), + _ => text_of(&i).and_then(|t| t.trim().parse::().ok()).filter(|g| *g <= most), + }; + match grips { + Some(g) => return self.make(s, g), + None => s.echo(format!("Enter 0 to {most}.")), + } + } + PStage::Label(_) => { + match &i { + Input::Text(t) | Input::Keyword(t) if !t.trim().is_empty() => self.label = Some(t.trim().to_string()), + _ => {} + } + self.stage = if self.linear { PStage::Start } else { PStage::Location }; + } + } + Ok(Step::Continue) + } + fn preview(&self, _s: &Session, cursor: Vec2) -> Vec { + match self.stage { + PStage::End => vec![crate::cmd::helpers::line(self.start, cursor)], + PStage::LinearLabel => { + vec![crate::cmd::helpers::line(self.start, self.end), crate::cmd::helpers::line((self.start + self.end) * 0.5, cursor)] + } + PStage::PointLabel => vec![crate::cmd::helpers::line(self.start, cursor)], + _ => Vec::new(), + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum AStage { + #[default] + Parameter, + Type, + Point, + Corner, + Opposite, + Polygon, + Objects, + Location, +} + +/// BACTION's prompts, as AutoCAD asks them on the command line. +#[derive(Default)] +struct BactionM { + stage: AStage, + param: Option, + kind: &'static str, + point: ParamPoint, + frame: Vec, + select: SelectPhase, + picked: Vec, +} + +impl BactionM { + /// After the parameter (and its action type): what the action asks next. + fn after_type(&mut self) { + self.stage = match (&self.param, self.kind) { + (Some(Followed::Linear { .. }), _) => AStage::Point, + (_, "stretch") => AStage::Corner, + _ => AStage::Objects, + }; + } + fn after_point(&mut self) { + self.stage = if self.kind == "stretch" { AStage::Corner } else { AStage::Objects }; + } +} + +impl Interactive for BactionM { + fn name(&self) -> &'static str { + "BACTION" + } + fn prompt(&self, _s: &Session) -> Prompt { + match self.stage { + AStage::Parameter => Prompt::new("Select parameter", Accept::POINT), + AStage::Type => match self.param { + Some(Followed::Point { .. }) => Prompt::new("Enter action type", KW).kw(&["Move", "sTretch"]), + _ => Prompt::new("Enter action type", KW).kw(&["Array", "Move", "Scale", "sTretch"]), + }, + AStage::Point => Prompt::new("Specify parameter point to associate with action or enter", Accept::POINT) + .kw(&["sTart point", "Second point"]) + .default("Second"), + AStage::Corner => Prompt::new("Specify first corner of stretch frame", Accept::POINT).kw(&["CPolygon"]), + AStage::Opposite => match self.frame.first() { + Some(c) => Prompt::new("Specify opposite corner", Accept::POINT).corner(*c), + None => Prompt::new("Specify opposite corner", Accept::POINT), + }, + AStage::Polygon => { + Prompt::new(if self.frame.is_empty() { "Specify first polygon point" } else { "Specify endpoint of line" }, Accept::POINT) + .kw(if self.frame.is_empty() { &[] } else { &["Undo"] }) + .base_opt(self.frame.last().copied()) + } + AStage::Objects => self.select.prompt(), + AStage::Location => Prompt::new("Specify action location", Accept::POINT).kw(&["Multiplier", "Offset"]), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if matches!(i, Input::Cancel) { + return Ok(Step::Cancel); + } + match self.stage { + AStage::Parameter => { + let (block, base) = editing(s)?; + let found = match &i { + Input::Point(p) => { + let reach = (s.pixel_size() * s.settings.pickbox.max(1.0) * 3.0).max(1e-9); + let near = |f: &Followed| match f { + Followed::Linear { base, end, .. } => segment_distance(*base, *end, *p), + Followed::Point { at, .. } => (*at - *p).len(), + }; + let list = followable(s.doc()?, &block, base); + list.into_iter().map(|f| (near(&f), f)).filter(|(d, _)| *d <= reach).min_by(|a, b| a.0.total_cmp(&b.0)).map(|(_, f)| f) + } + Input::Text(t) | Input::Keyword(t) => parameter_named(s.doc()?, &block, base, &Value::String(t.clone())).ok(), + Input::Enter => return Ok(Step::Done), + _ => return Ok(Step::Continue), + }; + match found { + Some(f) => { + self.param = Some(f); + self.stage = AStage::Type; + } + None => s.echo("No linear or point parameter there."), + } + } + AStage::Type => { + let Some(t) = text_of(&i) else { return Ok(Step::Continue) }; + let opts: &[(&str, &str)] = if matches!(self.param, Some(Followed::Point { .. })) { + &[("Move", "M"), ("sTretch", "T")] + } else { + &[("Array", "A"), ("Move", "M"), ("Scale", "S"), ("sTretch", "T")] + }; + match keyword(t, opts) { + Some("Move") => self.kind = "move", + Some("sTretch") => self.kind = "stretch", + Some(other) => return Err(EngineError::Other(format!("{other} actions are not available yet."))), + None => { + s.echo("Invalid option keyword."); + return Ok(Step::Continue); + } + } + self.after_type(); + } + AStage::Point => { + match (&i, &self.param) { + (Input::Enter, _) => self.point = ParamPoint::End, + (Input::Point(p), Some(Followed::Linear { base, end, .. })) => { + self.point = if (*p - *base).len() < (*p - *end).len() { ParamPoint::Base } else { ParamPoint::End }; + } + _ => match text_of(&i) + .and_then(|t| keyword(t, &[("sTart point", "T"), ("Second point", "S"), ("Start", "Start"), ("Second", "Second")])) + { + Some("sTart point" | "Start") => self.point = ParamPoint::Base, + Some(_) => self.point = ParamPoint::End, + None => return Ok(Step::Continue), + }, + } + self.after_point(); + } + AStage::Corner => match &i { + Input::Point(p) => { + self.frame = vec![*p]; + self.stage = AStage::Opposite; + } + _ => { + if text_of(&i).and_then(|t| keyword(t, &[("CPolygon", "CP")])).is_some() { + self.frame.clear(); + self.stage = AStage::Polygon; + } + } + }, + AStage::Opposite => { + if let Input::Point(p) = i { + self.frame.push(p); + s.echo("Specify objects to stretch"); + self.stage = AStage::Objects; + } + } + AStage::Polygon => match &i { + Input::Point(p) if self.frame.len() < cadcraft_doc::dynblock::MAX_ACTION_ITEMS => self.frame.push(*p), + Input::Enter if self.frame.len() >= 3 => { + s.echo("Specify objects to stretch"); + self.stage = AStage::Objects; + } + Input::Enter => s.echo("A polygon needs three or more points."), + _ => { + if text_of(&i).and_then(|t| keyword(t, &[("Undo", "U")])).is_some() { + self.frame.pop(); + } + } + }, + AStage::Objects => match self.select.feed(s, &i)? { + SelOutcome::More => {} + SelOutcome::Empty => return Ok(Step::Done), + SelOutcome::Done(hs) => { + self.picked = hs; + self.stage = AStage::Location; + } + }, + AStage::Location => match &i { + Input::Point(p) => { + let Some(param) = self.param.clone() else { return Ok(Step::Done) }; + let frame = (self.kind == "stretch").then(|| self.frame.clone()); + return add(s, ¶m, self.kind, self.point, &self.picked, frame, Some(*p)).map(|_| Step::Done); + } + _ => { + if let Some(k) = text_of(&i).and_then(|t| keyword(t, &[("Multiplier", "M"), ("Offset", "O")])) { + return not_yet(s, k); + } + } + }, + } + Ok(Step::Continue) + } + fn preview(&self, _s: &Session, cursor: Vec2) -> Vec { + match (self.stage, self.frame.first()) { + (AStage::Opposite, Some(c)) => { + vec![crate::cmd::helpers::lwpoly(crate::cmd::helpers::rect_vertices(*c, cursor), true)] + } + (AStage::Polygon, Some(_)) => { + let mut pts = self.frame.clone(); + pts.push(cursor); + vec![crate::cmd::helpers::lwpoly(pts.into_iter().map(cadcraft_geom::PolyVertex::new).collect(), true)] + } + _ => Vec::new(), + } + } +} diff --git a/crates/engine/src/cmd/blocks/bedit.rs b/crates/engine/src/cmd/blocks/bedit.rs index c570fa107c..dcce630039 100644 --- a/crates/engine/src/cmd/blocks/bedit.rs +++ b/crates/engine/src/cmd/blocks/bedit.rs @@ -159,7 +159,7 @@ fn open_closed(s: &mut Session, name: &str, create: bool) -> Result { let dynamic = |be: &crate::blockedit::BlockEdit| crate::blockedit::has_dynamic_data(&be.host.doc, if be.current { "*Model_Space" } else { &be.name }); if s.state().is_ok_and(|st| st.block_edit.as_ref().is_some_and(dynamic)) { - s.echo("This is a dynamic block: its parameters and actions are kept but can't be edited in CADCraft yet."); + s.echo("This is a dynamic block: BPARAMETER and BACTION add linear and point parameters with stretch and move actions; its other parameters and actions are kept as they are."); } Ok(json!({ "block": name, "new": new })) } diff --git a/crates/engine/tests/block_authoring.rs b/crates/engine/tests/block_authoring.rs new file mode 100644 index 0000000000..2d83e1bb9b --- /dev/null +++ b/crates/engine/tests/block_authoring.rs @@ -0,0 +1,169 @@ +//! Authoring dynamic blocks in the Block Editor (BPARAMETER, BACTION): parameters and actions +//! added to a block make its references dynamic, here and in files saved for AutoCAD. + +use cadcraft_engine::doc::dynblock::{ActionKind, Mark, ParameterKind, dynamic_block}; +use cadcraft_engine::doc::{EntityKind, Handle}; +use cadcraft_engine::geom::{Vec2, Vec3}; +use cadcraft_engine::{Input, Session}; +use serde_json::{Value, json}; + +fn h(v: &Value) -> Handle { + cadcraft_engine::cmd::curves::handle_value(v).unwrap() +} + +/// Block "Box": a 10 × 5 rectangle from (5,5) and a circle on its right edge, base point (5,5), +/// and a reference at (100,0). Returns (rectangle, circle, reference): the block's objects. +fn boxed(s: &mut Session) -> (Value, Value, Value) { + let made = |v: Value| if v["handle"].is_null() { v["handles"][0].clone() } else { v["handle"].clone() }; + let r = made(s.execute("rectang", &json!({ "p1": [5, 5], "p2": [15, 10] })).unwrap()); + let c = made(s.execute("circle", &json!({ "center": [15, 7.5], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "Box", "base": [5, 5], "handles": [r, c], "keep": "delete" })).unwrap(); + let i = s.execute("insert", &json!({ "name": "Box", "at": [100, 0] })).unwrap()["handle"].clone(); + let d = s.doc().unwrap(); + let b = d.block("Box").unwrap(); + let of = |rect: bool| json!(b.entities.iter().find(|e| matches!(e.kind, EntityKind::LwPolyline(_)) == rect).unwrap().handle.hex()); + (of(true), of(false), i) +} + +/// The rectangle's corners in reference `i`'s block (block coordinates). +fn corners(s: &Session, i: &Value) -> Vec<(f64, f64)> { + let d = s.doc().unwrap(); + let EntityKind::Insert(ins) = &d.entity(h(i)).unwrap().kind else { panic!() }; + let b = d.block(&ins.block).unwrap(); + b.entities + .iter() + .find_map(|e| if let EntityKind::LwPolyline(p) = &e.kind { Some(p.vertices.iter().map(|v| (v.p.x, v.p.y)).collect()) } else { None }) + .unwrap() +} + +#[test] +fn a_linear_stretch_authored_in_json_drives_references() { + let mut s = Session::new(); + let (r, c, i) = boxed(&mut s); + assert!(s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0] })).is_err(), "only in the Block Editor"); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + let p = s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0], "labelAt": [5, -2] })).unwrap(); + assert_eq!(p, json!({ "node": 1, "element": "Linear", "label": "Distance1" })); + let a = s + .execute("baction", &json!({ "parameter": "Distance1", "type": "stretch", "frame": [[8, -1], [12, 6]], "handles": [r, c], "at": [12, -2] })) + .unwrap(); + assert_eq!(a, json!({ "node": 8, "name": "Stretch" })); + + // The editor draws them where they were given. + let st = s.state().unwrap(); + let marks = st.block_edit.as_ref().unwrap().marks(&st.doc); + assert!( + matches!(&marks[0], Mark::Linear { base, end, offset, label, base_grip: true, end_grip: true, .. } + if *base == Vec3::ZERO && *end == Vec3::new(10.0, 0.0, 0.0) && *offset == -2.0 && label == "Distance1"), + "{marks:?}" + ); + assert!(matches!(&marks[1], Mark::Action { at, name, .. } if *at == Vec3::new(12.0, -2.0, 0.0) && name == "Stretch"), "{marks:?}"); + + s.execute("bclose", &json!({})).unwrap(); + // Stored in block coordinates: the base point (5,5) added back. + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let ParameterKind::Linear { base, end, .. } = &m.parameters[0].kind else { panic!() }; + assert_eq!((*base, *end), (Vec3::new(5.0, 5.0, 0.0), Vec3::new(15.0, 5.0, 0.0))); + let ActionKind::Stretch { frame, vertices, .. } = &m.actions[0].kind else { panic!() }; + assert_eq!(frame, &[Vec2::new(13.0, 4.0), Vec2::new(17.0, 11.0)]); + assert_eq!(vertices, &[(h(&r), vec![1, 2])], "the rectangle's right edge; the circle moves whole"); + assert_eq!(m.actions[0].selection, [h(&r), h(&c)]); + + s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Distance1", "value": "15" })).unwrap(); + assert_eq!(corners(&s, &i), [(5.0, 5.0), (20.0, 5.0), (20.0, 10.0), (5.0, 10.0)]); +} + +#[test] +fn bparameter_and_baction_ask_as_autocad_does() { + let mut s = Session::new(); + let (r, _, i) = boxed(&mut s); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + s.script("BPARAMETER L 0,0 10,0 5,-2\n").unwrap(); + assert_eq!(s.current_prompt().map(|p| p.message), Some("Enter number of grips".to_string())); + s.script("\n").unwrap(); + assert!(s.running.is_none(), "Enter takes the default two grips"); + s.script("BACTION 10,0\nT\n\n8,-1 12,6\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Select objects"); + s.input(Input::Pick(vec![h(&r)])).unwrap(); + s.script("\n12,-2\n").unwrap(); + assert!(s.running.is_none()); + // A point parameter and a move of the circle, its prompts' own order. + s.script("BPARAMETER O\n10,2.5 11,3.5 1\n").unwrap(); + s.script("BACTION 10,2.5\nM\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Select objects", "a point parameter asks no parameter point"); + let circle = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Circle(_))).unwrap().handle; + s.input(Input::Pick(vec![circle])).unwrap(); + s.script("\n12,1\n").unwrap(); + s.script("BCLOSE\n\n").unwrap(); + + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let names: Vec<_> = m.parameters.iter().map(|p| p.kind.label().unwrap_or("-")).chain(m.actions.iter().map(|a| a.name.as_str())).collect(); + assert_eq!(names, ["Distance1", "Position1", "Stretch", "Move"]); + s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Distance1", "value": "12" })).unwrap(); + assert_eq!(corners(&s, &i), [(5.0, 5.0), (17.0, 5.0), (17.0, 10.0), (5.0, 10.0)]); +} + +#[test] +fn types_not_available_yet_say_so() { + let mut s = Session::new(); + boxed(&mut s); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + for t in ["polar", "xy", "rotation", "flip", "visibility", "lookup", "base", "alignment"] { + let e = s.execute("bparameter", &json!({ "type": t, "start": [0, 0], "end": [1, 0] })).unwrap_err().to_string(); + assert!(e.contains("not available yet"), "{t}: {e}"); + } + s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0] })).unwrap(); + let e = s.execute("baction", &json!({ "parameter": 1, "type": "scale", "handles": [] })).unwrap_err().to_string(); + assert!(e.contains("handles"), "{e}"); + let any = s.doc().unwrap().model.iter().next().unwrap().handle.hex(); + let e = s.execute("baction", &json!({ "parameter": 1, "type": "scale", "handles": [any] })).unwrap_err().to_string(); + assert!(e.contains("not available yet"), "{e}"); +} + +#[test] +fn hostile_authoring_params_never_panic() { + let mut s = Session::new(); + let (r, _, _) = boxed(&mut s); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + for p in [ + json!(null), + json!([]), + json!({ "type": 5 }), + json!({ "type": "linear" }), + json!({ "type": "linear", "start": [0, 0], "end": [0, 0] }), + json!({ "type": "linear", "start": [1e308, 0], "end": [-1e308, 0], "labelAt": [1e308, 1e308] }), + json!({ "type": "linear", "start": [0, 0], "end": [1, 0], "grips": 3 }), + json!({ "type": "linear", "start": [0, 0], "end": [1, 0], "grips": -1 }), + json!({ "type": "point", "at": "nan,nan" }), + json!({ "type": "point", "at": [0, 0], "grips": 2 }), + json!({ "type": "point", "at": [0, 0], "label": 7 }), + ] { + let _ = s.execute("bparameter", &p); + } + s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0] })).unwrap(); + let many: Vec = (0..20_001).map(|_| r.clone()).collect(); + let poly: Vec<[f64; 2]> = (0..20_001).map(|i| [i as f64, (i % 2) as f64]).collect(); + for p in [ + json!(null), + json!({ "parameter": 99, "type": "move", "handles": [r] }), + json!({ "parameter": "Nope", "type": "move", "handles": [r] }), + json!({ "parameter": [], "type": "move", "handles": [r] }), + json!({ "parameter": 1, "type": "move", "handles": ["zz"] }), + json!({ "parameter": 1, "type": "move", "handles": ["FFFFFF"] }), + json!({ "parameter": 1, "type": "move", "handles": many }), + json!({ "parameter": 1, "type": "stretch", "handles": [r] }), + json!({ "parameter": 1, "type": "stretch", "handles": [r], "frame": [[0, 0]] }), + json!({ "parameter": 1, "type": "stretch", "handles": [r], "polygon": poly }), + json!({ "parameter": 1, "type": "stretch", "handles": [r], "frame": [[100, 100], [101, 101]] }), + json!({ "parameter": 1, "type": "move", "point": "middle", "handles": [r] }), + ] { + assert!(s.execute("baction", &p).is_err(), "{p}"); + } + // Cancelling either command midway changes nothing. + let before = s.doc().unwrap().foreign.clone(); + s.script("BPARAMETER L 0,0\n").unwrap(); + s.input(Input::Cancel).unwrap(); + s.script("BACTION 5,0\nT\n").unwrap(); + s.input(Input::Cancel).unwrap(); + assert_eq!(s.doc().unwrap().foreign, before); +} diff --git a/crates/io/tests/dynblock_author.rs b/crates/io/tests/dynblock_author.rs new file mode 100644 index 0000000000..54c17a7efc --- /dev/null +++ b/crates/io/tests/dynblock_author.rs @@ -0,0 +1,317 @@ +//! Authoring dynamic blocks: parameters and actions added in CADCraft are written as the +//! evaluation graph objects the reader reads, survive a save, and drive references. +//! +//! The fixture is synthetic, written for this test: a BOX block (a 10 × 5 rectangle and a +//! circle on its right edge) with one reference. + +use cadcraft_doc::dynblock::{ + ActionKind, ActionSpec, ParamPoint, ParameterKind, ParameterSpec, add_action, add_parameter, dynamic_block, set_property, tag_elements, +}; +use cadcraft_doc::{Drawing, EntityKind, Handle}; +use cadcraft_geom::{Vec2, Vec3}; +use cadcraft_io::{read_dxf, write_dxf}; + +/// DXF text from lines of `code value` (the value may be empty). +fn dxf(src: &str) -> String { + let mut out = String::new(); + for line in src.lines().map(str::trim).filter(|l| !l.is_empty()) { + let (code, value) = line.split_once(' ').unwrap_or((line, "")); + out.push_str(&format!("{code}\n{value}\n")); + } + out +} + +const BOX: &str = " +0 SECTION +2 BLOCKS +0 BLOCK +2 BOX +70 0 +10 0 +20 0 +30 0 +0 LWPOLYLINE +5 30 +8 0 +90 4 +70 1 +10 0 +20 0 +10 10 +20 0 +10 10 +20 5 +10 0 +20 5 +0 CIRCLE +5 31 +8 0 +10 10 +20 2.5 +30 0 +40 1 +0 ENDBLK +0 ENDSEC +0 SECTION +2 ENTITIES +0 INSERT +5 40 +8 0 +2 BOX +10 100 +20 0 +30 0 +0 ENDSEC +0 EOF +"; + +fn h(hex: &str) -> Handle { + Handle::parse_hex(hex).unwrap() +} + +fn box_drawing() -> Drawing { + read_dxf(dxf(BOX).as_bytes()).unwrap() +} + +fn v(x: f64, y: f64) -> Vec3 { + Vec3::new(x, y, 0.0) +} + +fn linear(grips: u8) -> ParameterSpec { + ParameterSpec::Linear { base: v(0.0, 0.0), end: v(10.0, 0.0), label: None, label_offset: -2.0, grips } +} + +/// BOX with a linear parameter (2 grips) stretching the rectangle's right edge. +fn stretchy() -> (Drawing, i32, i32) { + let mut d = box_drawing(); + let p = add_parameter(&mut d, "box", &linear(2)).unwrap(); + let frame = vec![Vec2::new(8.0, -1.0), Vec2::new(12.0, 6.0)]; + let spec = ActionSpec::Stretch { + parameter: p, + point: ParamPoint::End, + frame, + selection: vec![h("30")], + vertices: vec![(h("30"), vec![1, 2])], + at: v(12.0, -2.0), + }; + let a = add_action(&mut d, "BOX", &spec).unwrap(); + (d, p, a) +} + +/// The graph's node and edge lists as written: per node (index, id, links), per edge (kind, +/// from, to, links). +fn graph(d: &Drawing) -> (Vec<(i32, i32, Vec)>, Vec<(i32, i32, i32, Vec)>) { + let g = d.foreign.objects.iter().find(|o| o.kind == "ACAD_EVALUATION_GRAPH").unwrap(); + let at = g.tags.iter().position(|t| t.value == "AcDbEvalGraph").unwrap(); + let ints: Vec<(i32, i32)> = g.tags[at + 1..].iter().filter(|t| t.code != 360).map(|t| (t.code, t.value.parse().unwrap())).collect(); + let mut nodes = Vec::new(); + let mut edges = Vec::new(); + let mut i = 2; + while ints.get(i).is_some_and(|t| t.0 == 91) { + nodes.push((ints[i].1, ints[i + 2].1, ints[i + 3..i + 7].iter().map(|t| t.1).collect())); + i += 7; + } + while i < ints.len() { + edges.push((ints[i + 2].1, ints[i + 3].1, ints[i + 4].1, ints[i + 5..i + 10].iter().map(|t| t.1).collect())); + i += 10; + } + (nodes, edges) +} + +#[test] +fn an_authored_linear_stretch_reads_back() { + let (d, p, a) = stretchy(); + assert_eq!((p, a), (1, 8), "parameter, 2 grips × (grip + 2 components), then the action"); + let m = dynamic_block(&d, "BOX").expect("BOX is dynamic now"); + let param = &m.parameters[0]; + assert_eq!((param.node, param.element.as_str(), param.show_properties), (1, "Linear", true)); + assert_eq!(param.grips, [5, 2], "base grip, end grip"); + let ParameterKind::Linear { base, end, label, .. } = ¶m.kind else { panic!("{param:?}") }; + assert_eq!((*base, *end, label.as_str()), (v(0.0, 0.0), v(10.0, 0.0), "Distance1")); + let act = &m.actions[0]; + assert_eq!((act.node, act.name.as_str(), act.at), (8, "Stretch", v(12.0, -2.0))); + assert_eq!(act.selection, [h("30")]); + assert_eq!(act.connections, [(1, "EndXDelta".to_string()), (1, "EndYDelta".to_string())]); + let ActionKind::Stretch { frame, vertices, multiplier, angle_offset } = &act.kind else { panic!("{act:?}") }; + assert_eq!(frame, &[Vec2::new(8.0, -1.0), Vec2::new(12.0, 6.0)]); + assert_eq!(vertices, &[(h("30"), vec![1, 2])]); + assert_eq!((*multiplier, *angle_offset), (1.0, 0.0)); + assert_eq!(m.other.len(), 6, "{:?}", m.other); + assert_eq!(m.other.iter().filter(|o| *o == "BLOCKLINEARGRIP").count(), 2); +} + +/// The graph is laid out as AutoCAD lays out the same block (nodes in creation order, each +/// edge in its from-node's outgoing list and its to-node's incoming list). +#[test] +fn the_graph_links_nodes_as_autocad_does() { + let (d, _, _) = stretchy(); + let (nodes, edges) = graph(&d); + let want_nodes = vec![ + (0, 1, vec![2, 5, 0, 6]), + (1, 2, vec![-1, -1, 2, 2]), + (2, 3, vec![0, 0, -1, -1]), + (3, 4, vec![1, 1, -1, -1]), + (4, 5, vec![-1, -1, 5, 5]), + (5, 6, vec![3, 3, -1, -1]), + (6, 7, vec![4, 4, -1, -1]), + (7, 8, vec![6, 6, -1, -1]), + ]; + assert_eq!(nodes, want_nodes); + let want_edges = vec![ + (1, 0, 2, vec![-1, -1, -1, 1, -1]), + (1, 0, 3, vec![-1, -1, 0, 3, -1]), + (2, 1, 0, vec![-1, 5, -1, -1, -1]), + (1, 0, 5, vec![-1, -1, 1, 4, -1]), + (1, 0, 6, vec![-1, -1, 3, 6, -1]), + (2, 4, 0, vec![2, -1, -1, -1, -1]), + (1, 0, 7, vec![-1, -1, 4, -1, -1]), + ]; + assert_eq!(edges, want_edges); + // The record's dictionary holds the graph and the purge preventer. + let x = d.foreign.records.get(&("BLOCK_RECORD".to_string(), "BOX".to_string())).unwrap(); + let dict = d.foreign.objects.iter().find(|o| Some(o.handle) == x.xdict).unwrap(); + let keys: Vec<&str> = dict.tags.iter().filter(|t| t.code == 3).map(|t| t.value.as_str()).collect(); + assert_eq!(keys, ["ACAD_ENHANCEDBLOCK", "AcDbDynamicBlockRoundTripPurgePreventer"]); + assert!(x.xdata.iter().any(|t| t.value == "AcDbDynamicBlockTrueName")); + for c in ["ACAD_EVALUATION_GRAPH", "BLOCKLINEARPARAMETER", "BLOCKLINEARGRIP", "BLOCKGRIPLOCATIONCOMPONENT", "BLOCKSTRETCHACTION"] { + assert!(d.foreign.classes.iter().any(|k| k.iter().any(|t| t.code == 1 && t.value == c)), "class {c}"); + } +} + +#[test] +fn an_authored_block_survives_a_save() { + let (mut d, _, _) = stretchy(); + let mut store = d.block("BOX").unwrap().entities.clone(); + tag_elements(&mut d, "BOX", &mut store); + let mut b = (**d.block("BOX").unwrap()).clone(); + b.entities = store; + d.blocks.insert("BOX".into(), std::sync::Arc::new(b)); + let before = dynamic_block(&d, "BOX").unwrap(); + let text = write_dxf(&d); + for t in ["ACAD_EVALUATION_GRAPH", "BLOCKSTRETCHACTION", "AcDbDynamicBlockRoundTripPurgePreventer", "AcDbBlockRepETag"] { + assert!(text.contains(t), "{t} written"); + } + let again = read_dxf(text.as_bytes()).unwrap(); + let after = dynamic_block(&again, "BOX").expect("still dynamic after a save"); + assert_eq!(after.parameters.len(), 1); + assert_eq!(after.parameters[0].kind, before.parameters[0].kind); + assert_eq!(after.actions[0].kind, before.actions[0].kind); + assert_eq!(after.actions[0].selection, before.actions[0].selection, "the block's objects keep their handles"); +} + +/// The rectangle's corners in reference `insert`'s block. +fn rect(d: &Drawing, insert: Handle) -> Vec<(f64, f64)> { + let EntityKind::Insert(i) = &d.entity(insert).unwrap().kind else { panic!() }; + let b = d.block(&i.block).unwrap(); + b.entities + .iter() + .find_map(|e| if let EntityKind::LwPolyline(pl) = &e.kind { Some(pl.vertices.iter().map(|v| (v.p.x, v.p.y)).collect()) } else { None }) + .unwrap() +} + +#[test] +fn a_reference_to_an_authored_block_stretches() { + let (mut d, _, _) = stretchy(); + set_property(&mut d, h("40"), "Distance1", "15").unwrap(); + assert_eq!(rect(&d, h("40")), [(0.0, 0.0), (15.0, 0.0), (15.0, 5.0), (0.0, 5.0)]); +} + +#[test] +fn a_point_parameter_moves_the_circle() { + let mut d = box_drawing(); + let p = add_parameter(&mut d, "BOX", &ParameterSpec::Point { at: v(10.0, 2.5), label: None, label_at: v(11.0, 3.5), grips: 1 }).unwrap(); + let a = + add_action(&mut d, "BOX", &ActionSpec::Move { parameter: p, point: ParamPoint::End, selection: vec![h("31")], at: v(12.0, 1.0) }).unwrap(); + assert_eq!((p, a), (1, 5)); + let m = dynamic_block(&d, "BOX").unwrap(); + let ParameterKind::Point { at, label, .. } = &m.parameters[0].kind else { panic!() }; + assert_eq!((*at, label.as_str()), (v(10.0, 2.5), "Position1")); + assert_eq!(m.parameters[0].grips, [2]); + assert_eq!(m.actions[0].connections, [(1, "XDelta".to_string()), (1, "YDelta".to_string())]); + assert!(matches!(m.actions[0].kind, ActionKind::Move { multiplier: 1.0, .. })); + set_property(&mut d, h("40"), "Position1 X", "13").unwrap(); + let EntityKind::Insert(i) = &d.entity(h("40")).unwrap().kind else { panic!() }; + let c = d.block(&i.block).unwrap().entities.iter().find_map(|e| if let EntityKind::Circle(c) = &e.kind { Some(c.center) } else { None }).unwrap(); + assert_eq!((c.x, c.y), (13.0, 2.5)); +} + +#[test] +fn names_and_labels_count_up_and_grips_follow_the_count() { + let mut d = box_drawing(); + let first = add_parameter(&mut d, "BOX", &linear(0)).unwrap(); + let second = add_parameter(&mut d, "BOX", &linear(1)).unwrap(); + let third = add_parameter(&mut d, "BOX", &ParameterSpec::Point { at: v(1.0, 1.0), label: Some("Hinge".into()), label_at: v(2.0, 2.0), grips: 0 }) + .unwrap(); + assert_eq!((first, second, third), (1, 2, 6), "no grips, then one grip with two components"); + let m = dynamic_block(&d, "BOX").unwrap(); + let names: Vec<_> = m.parameters.iter().map(|p| (p.element.as_str(), p.kind.label().unwrap_or("-"), p.grips.clone())).collect(); + assert_eq!(names, [("Linear", "Distance1", vec![0, 0]), ("Linear1", "Distance2", vec![0, 3]), ("Point", "Hinge", vec![0])]); + let p = second; + let a = + add_action(&mut d, "BOX", &ActionSpec::Move { parameter: p, point: ParamPoint::Base, selection: vec![h("31")], at: v(0.0, 0.0) }).unwrap(); + let b = add_action(&mut d, "BOX", &ActionSpec::Move { parameter: p, point: ParamPoint::End, selection: vec![h("31")], at: v(0.0, 0.0) }).unwrap(); + let m = dynamic_block(&d, "BOX").unwrap(); + let acts: Vec<_> = m.actions.iter().map(|x| (x.node, x.name.as_str(), x.connections[0].1.as_str())).collect(); + assert_eq!(acts, [(a, "Move", "BaseXDelta"), (b, "Move1", "EndXDelta")]); +} + +#[test] +fn bad_authoring_is_refused_and_changes_nothing() { + let (d0, p, _) = stretchy(); + let bad_params = [ + ParameterSpec::Linear { base: v(1.0, 1.0), end: v(1.0, 1.0), label: None, label_offset: 0.0, grips: 2 }, + ParameterSpec::Linear { base: v(f64::NAN, 0.0), end: v(1.0, 1.0), label: None, label_offset: 0.0, grips: 2 }, + ParameterSpec::Linear { base: v(0.0, 0.0), end: v(1.0, 1.0), label: None, label_offset: f64::INFINITY, grips: 2 }, + ParameterSpec::Linear { base: v(0.0, 0.0), end: v(1.0, 1.0), label: None, label_offset: 0.0, grips: 3 }, + ParameterSpec::Point { at: v(0.0, 0.0), label: None, label_at: v(0.0, 0.0), grips: 2 }, + ]; + for spec in &bad_params { + let mut d = d0.clone(); + assert!(add_parameter(&mut d, "BOX", spec).is_err(), "{spec:?}"); + assert_eq!(d.foreign, d0.foreign, "{spec:?} changed the drawing"); + } + let mv = |parameter, selection: Vec| ActionSpec::Move { parameter, point: ParamPoint::End, selection, at: v(0.0, 0.0) }; + let st = |frame: Vec| ActionSpec::Stretch { + parameter: p, + point: ParamPoint::End, + frame, + selection: vec![h("30")], + vertices: vec![], + at: v(0.0, 0.0), + }; + let bad_actions = [ + mv(99, vec![h("30")]), + mv(p, vec![]), + mv(p, vec![h("30"); 20_000]), + st(vec![Vec2::new(0.0, 0.0)]), + st(vec![Vec2::new(f64::NAN, 0.0), Vec2::new(1.0, 1.0)]), + ]; + for spec in &bad_actions { + let mut d = d0.clone(); + assert!(add_action(&mut d, "BOX", spec).is_err(), "{spec:?}"); + assert_eq!(d.foreign, d0.foreign, "{spec:?} changed the drawing"); + } + let mut d = box_drawing(); + assert!(add_action(&mut d, "BOX", &mv(1, vec![h("30")])).is_err(), "no parameters yet"); + assert!(add_parameter(&mut d, "*Model_Space", &linear(2)).is_err()); + assert!(add_parameter(&mut d, "", &linear(2)).is_err()); +} + +#[test] +fn element_tags_are_unique_and_the_record_keeps_the_next() { + let (mut d, _, _) = stretchy(); + let mut store = d.block("BOX").unwrap().entities.clone(); + // A copy carrying the rectangle's tag gets one of its own. + let mut copy = (**store.get(h("30")).unwrap()).clone(); + tag_elements(&mut d, "BOX", &mut store); + copy.handle = h("32"); + copy.common.xdata = store.get(h("30")).unwrap().common.xdata.clone(); + store.push(copy); + tag_elements(&mut d, "BOX", &mut store); + let tag_of = |e: &cadcraft_doc::Entity| e.common.xdata.iter().find(|t| t.code == 1071).map(|t| t.value.clone()).unwrap(); + let self_of = |e: &cadcraft_doc::Entity| e.common.xdata.iter().find(|t| t.code == 1005).map(|t| t.value.clone()).unwrap(); + let tags: Vec<_> = store.iter().map(|e| (tag_of(e), self_of(e))).collect(); + assert_eq!(tags, [("0".into(), "30".into()), ("1".into(), "31".into()), ("2".into(), "32".into())]); + let x = d.foreign.records.get(&("BLOCK_RECORD".to_string(), "BOX".to_string())).unwrap(); + assert_eq!(x.xdata.iter().rev().find(|t| t.code == 1071).map(|t| t.value.as_str()), Some("3")); +} diff --git a/crates/ui-egui/src/canvas/blockedit.rs b/crates/ui-egui/src/canvas/blockedit.rs index e8d981b749..e9c5dec174 100644 --- a/crates/ui-egui/src/canvas/blockedit.rs +++ b/crates/ui-egui/src/canvas/blockedit.rs @@ -1,9 +1,13 @@ //! The Block Editor on the canvas (BEDIT): a tint over the drawing area so the editor can't be -//! mistaken for the drawing, the block's base point marked at the origin, and a bar with the -//! block's name and Save Block, Save Block As and Close Block Editor. +//! mistaken for the drawing, the block's base point marked at the origin, the block's +//! parameters and actions (BPARAMETER, BACTION) drawn as the editor shows them, and a bar with +//! the block's name and Save Block, Save Block As and Close Block Editor. +use std::sync::Arc; + +use cadcraft_engine::doc::dynblock::Mark; use cadcraft_engine::geom::Vec2; -use egui::{Rect, RichText, Stroke, vec2}; +use egui::{Align2, Color32, FontId, Painter, Pos2, Rect, RichText, Shape, Stroke, vec2}; use serde_json::json; use super::Xf; @@ -39,6 +43,7 @@ pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, p: &egui::Painter, xf p.line_segment([o - vec2(12.0, 0.0), o + vec2(12.0, 0.0)], st); p.line_segment([o - vec2(0.0, 12.0), o + vec2(0.0, 12.0)], st); } + paint_marks(app, ctx, p, xf); let mut action: Option<(&str, bool)> = None; egui::Area::new(id()).order(egui::Order::Foreground).pivot(egui::Align2::CENTER_TOP).fixed_pos(rect.center_top() + vec2(0.0, 8.0)).show( ctx, @@ -75,3 +80,81 @@ pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, p: &egui::Painter, xf None => {} } } + +/// The edited block's parameters and actions, worked out once per drawing revision. +fn marks(app: &CadApp, ctx: &egui::Context) -> Arc> { + type Cache = Option<((u64, u64), Arc>)>; + let Ok(st) = app.session.state() else { return Arc::default() }; + let Some(be) = &st.block_edit else { return Arc::default() }; + let key = (st.uid, st.revision); + let cid = egui::Id::new("cadcraft-block-editor-marks"); + if let Some((k, m)) = ctx.data(|d| d.get_temp::(cid)).flatten() + && k == key + { + return m; + } + let m = Arc::new(be.marks(&st.doc)); + ctx.data_mut(|d| d.insert_temp::(cid, Some((key, m.clone())))); + m +} + +/// A filled arrow at `at` pointing along screen direction `u`, as a linear parameter's grip. +fn arrow(p: &Painter, at: Pos2, u: egui::Vec2, color: Color32) { + let n = vec2(-u.y, u.x); + let (len, half) = (9.0, 5.0); + p.add(Shape::convex_polygon(vec![at - u * (len * 0.4) + n * half, at + u * (len * 0.6), at - u * (len * 0.4) - n * half], color, Stroke::NONE)); +} + +/// Draw each parameter and action of the edited block: a linear parameter as a dimension with +/// its label and arrow grips, a point parameter as a marker with its label, other parameters by +/// name, and actions as badges. +fn paint_marks(app: &CadApp, ctx: &egui::Context, p: &Painter, xf: &Xf) { + let t = Tokens::get(); + let line = Stroke::new(1.0, t.accent); + let font = FontId::proportional(12.0); + let to = |v: cadcraft_engine::geom::Vec3| xf.to_screen(v.xy()); + for m in marks(app, ctx).iter() { + match m { + Mark::Linear { base, end, offset, label, base_grip, end_grip, .. } => { + let (a, b) = (base.xy(), end.xy()); + let dir = (b - a).normalized(); + let shift = Vec2::new(-dir.y, dir.x) * *offset; + let (da, db) = (xf.to_screen(a + shift), xf.to_screen(b + shift)); + let (sa, sb) = (to(*base), to(*end)); + p.line_segment([sa, da], line); + p.line_segment([sb, db], line); + p.line_segment([da, db], line); + let along = sb - sa; + let u = if along.length() > 1e-6 { along / along.length() } else { vec2(1.0, 0.0) }; + if *base_grip { + arrow(p, sa, -u, t.grip_dyn); + } + if *end_grip { + arrow(p, sb, u, t.grip_dyn); + } + p.text(da + (db - da) * 0.5, Align2::CENTER_BOTTOM, label, font.clone(), t.accent); + } + Mark::Point { at, label_at, label, grip, .. } => { + let (s, l) = (to(*at), to(*label_at)); + p.line_segment([s, l], line); + if *grip { + p.rect_filled(Rect::from_center_size(s, vec2(8.0, 8.0)), 0.0, t.grip_dyn); + } else { + p.rect_stroke(Rect::from_center_size(s, vec2(8.0, 8.0)), 0.0, line, egui::StrokeKind::Middle); + } + p.text(l, Align2::LEFT_BOTTOM, label, font.clone(), t.accent); + } + Mark::Parameter { at, label, .. } => { + p.text(to(*at), Align2::LEFT_BOTTOM, label, font.clone(), t.accent); + } + Mark::Action { at, name, .. } => { + let c = to(*at); + let g = p.layout_no_wrap(name.clone(), font.clone(), t.text); + let r = Rect::from_center_size(c, g.size() + vec2(8.0, 4.0)); + p.rect_filled(r, 3.0, t.cmd_bg); + p.rect_stroke(r, 3.0, Stroke::new(1.0, t.warn), egui::StrokeKind::Middle); + p.galley(r.min + vec2(4.0, 2.0), g, t.text); + } + } + } +} From 65d2b46e9f9f09a09960742281f24b27aea42769 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 21 Oct 2026 12:01:03 -0600 Subject: [PATCH 02/47] Docs: F3 and the blocks row list the dynamic-block authoring that landed BPARAMETER and BACTION have no menu entry, as in AutoCAD (the Block Editor's tools start them). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/blocks/bauthor.rs | 2 -- docs/gaps.md | 5 +++-- docs/target-app-parity.md | 5 +++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/blocks/bauthor.rs b/crates/engine/src/cmd/blocks/bauthor.rs index a49acd9a15..7de433e3b7 100644 --- a/crates/engine/src/cmd/blocks/bauthor.rs +++ b/crates/engine/src/cmd/blocks/bauthor.rs @@ -19,7 +19,6 @@ use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, St pub(super) fn specs() -> Vec { vec![ CommandSpec::new("bparameter", "Parameter", run_bparameter) - .menu(&["Tools", "Block Editor", "Parameter"]) .alias(&["-bparameter"]) .params( "{type: \"linear\"|\"point\", linear: start: [x,y], end: [x,y], labelAt?: [x,y] (where the label goes; default on the line); point: at: [x,y], labelAt?: [x,y]; label?: property name (default Distance1/Position1…), grips?: 0|1|2 (linear, default 2) or 0|1 (point, default 1)} → {node, element, label} (editor coordinates)", @@ -27,7 +26,6 @@ pub(super) fn specs() -> Vec { .enabled(authoring) .interactive(|_| Ok(Box::new(BparameterM::default()))), CommandSpec::new("baction", "Action", run_baction) - .menu(&["Tools", "Block Editor", "Action"]) .alias(&["-baction"]) .params( "{parameter: graph id or property name (\"Distance1\"), type: \"stretch\"|\"move\", point?: \"start\"|\"second\" (which end of a linear parameter it follows, default second), handles: [objects], frame?: [[x,y],[x,y]] (stretch: corners) | polygon?: [[x,y]…] (stretch: a crossing polygon), at?: [x,y] (where the action shows; default the parameter's point)} → {node, name} (editor coordinates)", diff --git a/docs/gaps.md b/docs/gaps.md index b270525d63..f700a6f785 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where CADCraft falls short of AutoCAD -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (BEDIT in the Block Editor switches blocks: F3 updated) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (BEDIT in the Block Editor switches blocks; dynamic-block authoring started: BPARAMETER linear/point, BACTION stretch/move; F3 updated) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first), and remove or update a row in the same PR @@ -26,7 +26,7 @@ do them first. |---|---|---|---|---| | F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | | F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | -| F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | +| F3 | **[alpha blocker]** (dynamic-block authoring is beta) Dynamic-block authoring has started: in the Block Editor, BPARAMETER adds linear and point parameters and BACTION stretch and move actions (AutoCAD's prompts, JSON forms), written so AutoCAD opens the block as a dynamic block (DXF and DWG), and the editor draws them. Missing: the other parameters (polar, XY, rotation, flip, alignment, base point, visibility, lookup) and actions (scale, rotate, flip, array, polar stretch, lookup), visibility states and lookup tables (BVSTATE, BLOOKUPTABLE), selecting and editing parameters and actions in the editor, the Name/Chain/Value set options, Authoring Palettes, BTESTBLOCK. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips); BEDIT (which, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS, BCLOSE and REFEDIT edit block definitions | issue #185 offers help | High: standard libraries are dynamic | 30–50 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | | F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 | @@ -156,6 +156,7 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | | 2026-10-22 | minor | APPLOAD typed or from Tools ▸ Load Application opens a `.lsp` file browser starting in the last-used folder (kept in the preferences); a picked file loads interactively like a typed name (routines that ask for input wait), the web says to drop the file (no file system), and the JSON form `{path}` reads the path as given and returns the commands the file defined, never opening a dialog (#1820): E1 narrowed | +| 2026-10-21 | minor | F3: dynamic-block authoring started. In the Block Editor BPARAMETER adds linear and point parameters, BACTION stretch and move actions, with AutoCAD's prompts and JSON forms; AutoCAD opens the result as a dynamic block from DXF and DWG; the editor draws them (40–65 → 30–50 h) | | 2026-10-16 | minor | ALIASEDIT typed or from Tools ▸ Customize opens the Command Aliases dialog (user aliases next to the built-in ones; Add, Edit, Remove; OK, Cancel, Apply), #1381: U12 and E5 narrowed | | 2026-10-16 | minor | MOCORO (Tools ▸ Express Tools ▸ Move/Copy/Rotate): select objects and a base point once, then Move, Copy, Rotate, Scale, Base and Undo until eXit, one undo step; JSON form `{base, ops}`: E3 narrowed | | 2026-10-16 | minor | MLEDIT Merged Tee (MT): the first multiline's outer elements stop at the second one's near side, which opens, and its inner elements run on to the second one's inner element: F21 narrowed, hours unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6b5407d603..22b85689cf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity: CADCraft vs AutoCAD 2027 -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (COMPAREEXPORT; numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (dynamic-block authoring started; blocks evidence updated, numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 The authoritative assessment of how close CADCraft is to AutoCAD, and how much Opus 5.5 work remains. [ROADMAP.md](../ROADMAP.md) summarises it, [gaps.md](gaps.md) lists every shortfall, @@ -154,7 +154,7 @@ presence: an option that prints "not available yet" doesn't count. | Text and MTEXT | 6% | 35% | 30–45 | TrueType, formatting codes, stacking; MTEXT prompt options (#408), indents, tabs, bullets, numbering and columns (#547), annotative scaling (#468); editor is a dialog, not in place; no fields or SPELL (open PR #551), no SHX | [gaps](gaps.md#features) | | Leaders, tables, fields | 4% | 25% | 25–35 | MLEADER options and block content (#408), native MULTILEADER in DXF (#459); tables with cell styles, formulas, breaking and CSV data links (#534); no MLEADEREDIT/ALIGN/COLLECT, no FIELD | [gaps](gaps.md#features) | | Hatch and gradients | 5% | 35% | 15–25 | pick points with islands; 23 patterns of ~85; gradients render flat; origin, gap tolerance, separate hatches, island styles and HATCHEDIT options (#451); Hatch and Gradient / Hatch Edit dialogs (no Preview or Inherit Properties) | [gaps](gaps.md#features) | -| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT; dynamic block references read and edited; no dynamic-block authoring, XCLIP, DesignCenter | [gaps](gaps.md#features) | +| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT; dynamic block references read and edited; dynamic-block authoring started (linear and point parameters, stretch and move actions); no XCLIP, DesignCenter | [gaps](gaps.md#features) | | Layouts, viewports, plotting | 9% | 35% | 35–50 | layouts, per-VP layers, page setups, plot styles (CTB/STB), Plot dialog (#160), Plot Preview and PUBLISH (#186), plotter devices (#564), PDF with text, layers and sheets (#567, #571), polygonal/object/clipped viewports (#453), annotative scales (#468); no MVIEW Restore, no system printers | [gaps](gaps.md#features) | | Inquiry and utilities | 4% | 30% | 30–45 | DIST, AREA, ID, LIST, MEASUREGEOM, CAL, FIND, COUNT across layouts, QuickCalc, COMPARE (#563) and COMPAREEXPORT, MASSPROP on regions (#510), autosave/recovery, AUDIT, RECOVER (#406), OPTIONS (#23); no SPELL (open PR #551), ETRANSMIT | [gaps](gaps.md#features) | | Parametric constraints | 2% | 50% | 20–30 | all 12 geometric and the dimensional constraints, own solver; DOF report, G2 Smooth, ellipse/spline/block geometry and CONSTRAINTINFER landed (#546) | [geometry-parity](geometry-parity.md#constraint-solver--50) | @@ -225,6 +225,7 @@ DWG/DXF corpus (files from people who own them); black-box checks in AutoCAD of |---|---|---| | 2026-10-24 | minor | Inquiry and utilities row: COMPAREEXPORT exports a comparison to a new drawing; parity percentages and hours not re-measured | | 2026-10-22 | minor | Draw row: RECTANG gained a centre construction mode (`Center` keyword, `center: true`) beside its corner mode (#1127); parity percentages and hours not re-measured | +| 2026-10-21 | minor | Blocks row evidence: dynamic-block authoring started (BPARAMETER linear/point, BACTION stretch/move); percentages and hours not re-measured | | 2026-10-12 | minor | Hatch row evidence: Hatch and Gradient / Hatch Edit dialogs; percentages and hours not re-measured | | 2026-10-12 | minor | Blocks row evidence: Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); percentages and hours not re-measured | | 2026-10-11 | minor | Evidence text of the feature-area rows refreshed for merged work (#397, #406, #408, #417, #420, #433, #448, #451, #453, #459, #468, #507, #510, #525, #534, #546, #547, #558, #563, #564, #567, #571); parity percentages and hours not re-measured | From d30a082ec22841900069ca353b65f45780e3e9b5 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 21 Oct 2026 12:09:31 -0600 Subject: [PATCH 03/47] i18n(uk): Parameter and Action command labels Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/uk.tsv | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 3f2de02df1..985ca6a864 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -96,6 +96,8 @@ Block Attribute Manager... Диспетчер атрибутів блоків... Block Description... Опис блока... Block Editor Редактор блоків + Parameter Параметр + Action Дія Block Reference Посилання на блок Block... Блок... Blocks Блоки From 64c0cf20fa5b3627626a7fed8104c95a06ed1e8b Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 21 Oct 2026 15:00:00 -0600 Subject: [PATCH 04/47] Dynamic blocks: a linear parameter between points infinitely far apart is refused Two finite points such as 1e308 and -1e308 are an infinite distance apart; the direction was written into the grips as -inf, which no DXF reader parses. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/write.rs | 4 +++- crates/engine/tests/block_authoring.rs | 3 +++ crates/io/tests/dynblock_author.rs | 1 + 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/dynblock/write.rs b/crates/doc/src/dynblock/write.rs index f501d68e1a..474d7ef2a7 100644 --- a/crates/doc/src/dynblock/write.rs +++ b/crates/doc/src/dynblock/write.rs @@ -411,7 +411,9 @@ fn finite(p: Vec3) -> bool { pub fn add_parameter(d: &mut Drawing, name: &str, spec: &ParameterSpec) -> Result { match spec { ParameterSpec::Linear { base, end, label, label_offset, grips } => { - if !finite(*base) || !finite(*end) || !label_offset.is_finite() { + // Two finite points far apart can still be infinitely far from each other, and the + // direction is written into the grips. + if !finite(*base) || !finite(*end) || !finite(*end - *base) || !label_offset.is_finite() { return Err("Invalid point.".into()); } if (*end - *base).len() <= 1e-9 { diff --git a/crates/engine/tests/block_authoring.rs b/crates/engine/tests/block_authoring.rs index 2d83e1bb9b..a5121889bb 100644 --- a/crates/engine/tests/block_authoring.rs +++ b/crates/engine/tests/block_authoring.rs @@ -132,6 +132,7 @@ fn hostile_authoring_params_never_panic() { json!({ "type": "linear" }), json!({ "type": "linear", "start": [0, 0], "end": [0, 0] }), json!({ "type": "linear", "start": [1e308, 0], "end": [-1e308, 0], "labelAt": [1e308, 1e308] }), + json!({ "type": "linear", "start": [1e308, 0], "end": [-1e308, 0] }), json!({ "type": "linear", "start": [0, 0], "end": [1, 0], "grips": 3 }), json!({ "type": "linear", "start": [0, 0], "end": [1, 0], "grips": -1 }), json!({ "type": "point", "at": "nan,nan" }), @@ -140,6 +141,8 @@ fn hostile_authoring_params_never_panic() { ] { let _ = s.execute("bparameter", &p); } + let far = s.execute("bparameter", &json!({ "type": "linear", "start": [1e308, 0], "end": [-1e308, 0] })); + assert!(far.is_err(), "an infinite distance between finite points is refused: {far:?}"); s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0] })).unwrap(); let many: Vec = (0..20_001).map(|_| r.clone()).collect(); let poly: Vec<[f64; 2]> = (0..20_001).map(|i| [i as f64, (i % 2) as f64]).collect(); diff --git a/crates/io/tests/dynblock_author.rs b/crates/io/tests/dynblock_author.rs index 54c17a7efc..f557678e13 100644 --- a/crates/io/tests/dynblock_author.rs +++ b/crates/io/tests/dynblock_author.rs @@ -262,6 +262,7 @@ fn bad_authoring_is_refused_and_changes_nothing() { ParameterSpec::Linear { base: v(1.0, 1.0), end: v(1.0, 1.0), label: None, label_offset: 0.0, grips: 2 }, ParameterSpec::Linear { base: v(f64::NAN, 0.0), end: v(1.0, 1.0), label: None, label_offset: 0.0, grips: 2 }, ParameterSpec::Linear { base: v(0.0, 0.0), end: v(1.0, 1.0), label: None, label_offset: f64::INFINITY, grips: 2 }, + ParameterSpec::Linear { base: v(1e308, 0.0), end: v(-1e308, 0.0), label: None, label_offset: 0.0, grips: 2 }, ParameterSpec::Linear { base: v(0.0, 0.0), end: v(1.0, 1.0), label: None, label_offset: 0.0, grips: 3 }, ParameterSpec::Point { at: v(0.0, 0.0), label: None, label_at: v(0.0, 0.0), grips: 2 }, ]; From 27ce8f77ad36f3b78122ef548c46110614c7e6e0 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 25 Oct 2026 09:50:58 -0600 Subject: [PATCH 05/47] Dynamic blocks: a grip's location components name their own parameter Each BLOCKGRIPLOCATIONCOMPONENT names the parameter it reads (AcDbBlockGripExpr 91: the parameter's graph id), as AutoCAD writes it. The writer always wrote 1, the first parameter's id, so in a block with a second parameter AutoCAD evaluated none of them: a reference listed no dynamic properties. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/write.rs | 4 +++- crates/io/tests/dynblock_author.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/dynblock/write.rs b/crates/doc/src/dynblock/write.rs index 474d7ef2a7..43755d2fe9 100644 --- a/crates/doc/src/dynblock/write.rs +++ b/crates/doc/src/dynblock/write.rs @@ -346,10 +346,12 @@ impl<'a> Author<'a> { }; let grip = self.node(kind, gh, gid, tags); self.class("BLOCKGRIPLOCATIONCOMPONENT", "AcDbBlockGripExpr"); + // Each component names the parameter it reads (its graph id). + let owner = self.graph.nodes.iter().find(|n| n.index == param).map_or(0, |n| n.id); for (id, comp) in [(xid, x_name), (yid, y_name)] { let h = self.d.new_handle(); let mut tags = node_head(h, self.graph.handle, id); - tags.extend([tag(1, ""), tag(70, 40), real(140, value), tag(100, "AcDbBlockGripExpr"), tag(91, 1), tag(300, comp)]); + tags.extend([tag(1, ""), tag(70, 40), real(140, value), tag(100, "AcDbBlockGripExpr"), tag(91, owner), tag(300, comp)]); let c = self.node("BLOCKGRIPLOCATIONCOMPONENT", h, id, tags); self.graph.link(param, c, 1); } diff --git a/crates/io/tests/dynblock_author.rs b/crates/io/tests/dynblock_author.rs index f557678e13..d48b2728ed 100644 --- a/crates/io/tests/dynblock_author.rs +++ b/crates/io/tests/dynblock_author.rs @@ -316,3 +316,31 @@ fn element_tags_are_unique_and_the_record_keeps_the_next() { let x = d.foreign.records.get(&("BLOCK_RECORD".to_string(), "BOX".to_string())).unwrap(); assert_eq!(x.xdata.iter().rev().find(|t| t.code == 1071).map(|t| t.value.as_str()), Some("3")); } + +/// Each grip location component names the parameter it reads (`AcDbBlockGripExpr` 91), as +/// AutoCAD writes it: a second parameter's components name it, not the first. AutoCAD evaluated +/// no parameter of a block whose later components named the first. +#[test] +fn grip_components_name_their_own_parameter() { + let mut d = box_drawing(); + let first = add_parameter(&mut d, "BOX", &linear(1)).unwrap(); + let second = add_parameter(&mut d, "BOX", &ParameterSpec::Point { at: v(10.0, 2.5), label: None, label_at: v(11.0, 3.5), grips: 1 }).unwrap(); + let owners: Vec<(String, i32)> = d + .foreign + .objects + .iter() + .filter(|o| o.kind == "BLOCKGRIPLOCATIONCOMPONENT") + .map(|o| { + let at = o.tags.iter().position(|t| t.value == "AcDbBlockGripExpr").unwrap(); + let owner = o.tags[at + 1..].iter().find(|t| t.code == 91).unwrap().value.parse().unwrap(); + let name = o.tags.iter().find(|t| t.code == 300).unwrap().value.clone(); + (name, owner) + }) + .collect(); + let want: Vec<(String, i32)> = [("UpdatedEndX", first), ("UpdatedEndY", first), ("UpdatedX", second), ("UpdatedY", second)] + .iter() + .map(|(n, o)| (n.to_string(), *o)) + .collect(); + assert_eq!(owners, want); + assert_eq!((first, second), (1, 5)); +} From c4c53392568926b9435afcad691ebf7379e9a58a Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:28:11 -0600 Subject: [PATCH 06/47] Block Editor: the marks cache id uses egui 0.37's Id::unique Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/blockedit.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/blockedit.rs b/crates/ui-egui/src/canvas/blockedit.rs index e9c5dec174..1720ed3757 100644 --- a/crates/ui-egui/src/canvas/blockedit.rs +++ b/crates/ui-egui/src/canvas/blockedit.rs @@ -87,7 +87,7 @@ fn marks(app: &CadApp, ctx: &egui::Context) -> Arc> { let Ok(st) = app.session.state() else { return Arc::default() }; let Some(be) = &st.block_edit else { return Arc::default() }; let key = (st.uid, st.revision); - let cid = egui::Id::new("cadcraft-block-editor-marks"); + let cid = egui::Id::unique("cadcraft-block-editor-marks"); if let Some((k, m)) = ctx.data(|d| d.get_temp::(cid)).flatten() && k == key { From 4da3598fe7168c01ae4858e497b7c19c64f369d0 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:07:22 -0600 Subject: [PATCH 07/47] Dynamic blocks: BSAVEAS gives a dynamic block's copy its own graph Saved under another name, the copy had the original's objects but none of its dynamic data: no graph, no parameters or actions, and its marks empty. It now gets a copy of the original's evaluation graph (the objects its extension dictionary owns) with new handles, its own true name and GUID, and its own objects with new handles, so no two blocks share one and the copy's actions select the copy's objects. The original is untouched. Co-Authored-By: Claude Sonnet 5.5 --- crates/doc/src/dynblock.rs | 2 + crates/doc/src/dynblock/copy.rs | 166 +++++++++++++++++++++++++ crates/doc/src/dynblock/write.rs | 6 +- crates/engine/src/blockedit.rs | 4 + crates/engine/tests/block_authoring.rs | 34 +++++ 5 files changed, 209 insertions(+), 3 deletions(-) create mode 100644 crates/doc/src/dynblock/copy.rs diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index 48064917b0..8100fd0c79 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -21,11 +21,13 @@ use crate::foreign::ForeignObject; use crate::{Drawing, Handle, RawTag}; mod apply; +mod copy; mod grips; mod marks; mod reference; mod write; pub use apply::{drag_grip, set_property}; +pub use copy::copy_definition; pub use grips::{DynGrip, GripPart, GripShape, grips}; pub use marks::{Mark, marks}; pub use reference::{CustomProperty, Reference, Value, custom_properties, reference}; diff --git a/crates/doc/src/dynblock/copy.rs b/crates/doc/src/dynblock/copy.rs new file mode 100644 index 0000000000..3d846848bd --- /dev/null +++ b/crates/doc/src/dynblock/copy.rs @@ -0,0 +1,166 @@ +//! Saving a dynamic block under another name (BSAVEAS): the copy gets its own evaluation graph, +//! made from the original's objects with new handles, and its own copies of the block's objects +//! (no two blocks share a handle), so references to either change as AutoCAD would change them. + +use std::collections::{HashMap, HashSet}; + +use crate::foreign::{ForeignExtra, ForeignObject}; +use crate::{Drawing, EntityKind, EntityStore, Handle, RawTag}; + +use super::write::{dict_entry, guid, record_handle}; +use super::{MAX_NODES, dynamic_block}; + +/// Most objects of one block's dynamic data that are copied. +const MAX_COPIED: usize = 8 * MAX_NODES; + +/// Group codes whose values are handles: the object's own (5), owners and pointers (330 to 369) +/// and 390 to 399. +fn is_handle_code(code: i32) -> bool { + code == 5 || (330..=369).contains(&code) || (390..=399).contains(&code) +} + +/// The owner of an object: its first 330 group outside the `{ACAD_REACTORS` ... `}` groups. +fn owner_of(o: &ForeignObject) -> Option { + let mut inside = false; + for t in &o.tags { + match t.code { + 102 => inside = t.value.starts_with('{'), + 330 if !inside => return Handle::parse_hex(&t.value), + _ => {} + } + } + None +} + +/// `root` and the objects it owns, directly or not (at most [`MAX_COPIED`]). +fn owned_subtree(d: &Drawing, root: Handle) -> Vec { + let mut children: HashMap> = HashMap::new(); + for o in &d.foreign.objects { + if let Some(owner) = owner_of(o) { + children.entry(owner).or_default().push(o.handle); + } + } + let mut out = vec![root]; + let mut seen: HashSet = HashSet::from([root]); + let mut at = 0; + while let Some(h) = out.get(at).copied() { + at += 1; + for c in children.get(&h).into_iter().flatten() { + if out.len() < MAX_COPIED && seen.insert(*c) { + out.push(*c); + } + } + } + out +} + +/// The handle `h` names, as `map` has it. +fn mapped(map: &HashMap, value: &str) -> Option { + Handle::parse_hex(value).and_then(|h| map.get(&h)).copied() +} + +/// Every handle in `tags` that `map` has, as the new one. +fn retarget(tags: &mut [RawTag], map: &HashMap) { + for t in tags.iter_mut().filter(|t| is_handle_code(t.code)) { + if let Some(n) = mapped(map, &t.value) { + t.value = n.hex(); + } + } +} + +/// The objects of `store` again with new handles (added to `map`): each one's element tag names +/// the object itself, and a hatch's sources are the new copies. +fn rehandle(d: &mut Drawing, store: &EntityStore, map: &mut HashMap) -> EntityStore { + for e in store.iter() { + let n = d.new_handle(); + map.insert(e.handle, n); + } + let mut out = EntityStore::new(); + for e in store.iter() { + let mut c = (**e).clone(); + c.handle = map.get(&e.handle).copied().unwrap_or(e.handle); + for t in c.common.xdata.iter_mut().filter(|t| t.code == 1005) { + if let Some(n) = mapped(map, &t.value) { + t.value = n.hex(); + } + } + if let EntityKind::Hatch(h) = &mut c.kind { + for l in &mut h.loops { + l.sources = l.sources.iter().map(|s| map.get(s).copied().unwrap_or(*s)).collect(); + } + } + out.push(c); + } + out +} + +/// The kept extras of the objects of `store` (reactors within the block; not their extension +/// dictionaries), for their new handles. +fn entity_extras(d: &Drawing, store: &EntityStore, map: &HashMap) -> Vec<(Handle, ForeignExtra)> { + store + .iter() + .filter_map(|e| { + let mut x = d.foreign.entities.get(&e.handle)?.clone(); + x.xdict = None; + x.reactors = x.reactors.iter().filter_map(|r| map.get(r).copied()).collect(); + Some((map.get(&e.handle).copied()?, x)) + }) + .collect() +} + +/// Block record xdata `xdata` with the dynamic block's true name and GUID replaced. +fn rename_in_xdata(xdata: &mut [RawTag], name: &str, guid: &str) { + let mut app = String::new(); + for t in xdata { + match t.code { + 1001 => app = t.value.to_ascii_uppercase(), + 1000 if app == "ACDBDYNAMICBLOCKTRUENAME" => t.value = name.to_string(), + 1000 if app == "ACDBDYNAMICBLOCKGUID" => t.value = guid.to_string(), + _ => {} + } + } +} + +/// Make block `to` a copy of dynamic block `from` (BSAVEAS): `store`, the objects it is saved +/// with, get new handles; the copy has its own evaluation graph and objects, made from the +/// original's with new handles, and its own true name and GUID. Nothing changes when `from` has no +/// dynamic data or is `to`. +pub fn copy_definition(d: &mut Drawing, from: &str, to: &str, store: &mut EntityStore) { + let (from_name, to_name) = (from.trim().to_ascii_uppercase(), to.trim().to_ascii_uppercase()); + let key = |n: &str| ("BLOCK_RECORD".to_string(), n.to_string()); + if from_name == to_name || dynamic_block(d, from).is_none() { + return; + } + let Some(source) = d.foreign.records.get(&key(&from_name)).cloned() else { return }; + let Some(xdict) = source.xdict else { return }; + let graph = dict_entry(d, xdict, "ACAD_ENHANCEDBLOCK"); + let owned = owned_subtree(d, xdict); + let owned_set: HashSet = owned.iter().copied().collect(); + let mut map: HashMap = owned.iter().map(|h| (*h, d.new_handle())).collect(); + let old_record = d.foreign.targets.iter().find(|(_, (k, n))| k == "BLOCK_RECORD" && *n == from_name).map(|(h, _)| *h); + let new_record = record_handle(d, &to_name); + map.extend(old_record.map(|h| (h, new_record))); + let entities = rehandle(d, store, &mut map); + let extras = entity_extras(d, store, &map); + let copies: Vec = d + .foreign + .objects + .iter() + .filter(|o| owned_set.contains(&o.handle)) + .map(|o| { + let mut c = o.clone(); + retarget(&mut c.tags, &map); + c.handle = map.get(&o.handle).copied().unwrap_or(o.handle); + c + }) + .collect(); + let mut record = source; + record.xdict = map.get(&xdict).copied(); + let new_graph = graph.and_then(|g| map.get(&g).copied()).unwrap_or(new_record); + rename_in_xdata(&mut record.xdata, to.trim(), &guid(to.trim(), new_graph)); + let f = std::sync::Arc::make_mut(&mut d.foreign); + f.objects.extend(copies); + f.records.insert(key(&to_name), record); + f.entities.extend(extras); + *store = entities; +} diff --git a/crates/doc/src/dynblock/write.rs b/crates/doc/src/dynblock/write.rs index 43755d2fe9..9cfe99c2ba 100644 --- a/crates/doc/src/dynblock/write.rs +++ b/crates/doc/src/dynblock/write.rs @@ -374,7 +374,7 @@ impl<'a> Author<'a> { /// The handle the kept data uses for block `record`'s BLOCK_RECORD (a new one, registered, /// when none refers to it yet). -fn record_handle(d: &mut Drawing, record: &str) -> Handle { +pub(super) fn record_handle(d: &mut Drawing, record: &str) -> Handle { if let Some(h) = d.foreign.targets.iter().find(|(_, (k, n))| k == "BLOCK_RECORD" && n == record).map(|(h, _)| *h) { return h; } @@ -384,7 +384,7 @@ fn record_handle(d: &mut Drawing, record: &str) -> Handle { } /// A GUID for block `name`'s dynamic data, made from its name and graph (stable for a drawing). -fn guid(name: &str, graph: Handle) -> String { +pub(super) fn guid(name: &str, graph: Handle) -> String { // FNV-1a over the name and handle, spread over 128 bits. let mut h: u64 = 0xcbf2_9ce4_8422_2325; let mut word = || { @@ -610,7 +610,7 @@ fn strip_app(xd: &mut Vec, app: &str) { } /// The object entry `key` of dictionary `dict` names. -fn dict_entry(d: &Drawing, dict: Handle, key: &str) -> Option { +pub(super) fn dict_entry(d: &Drawing, dict: Handle, key: &str) -> Option { let o = d.foreign.objects.iter().find(|o| o.handle == dict)?; let mut tags = o.tags.iter(); while let Some(t) = tags.next() { diff --git a/crates/engine/src/blockedit.rs b/crates/engine/src/blockedit.rs index 1d2588fce7..02caddbb7a 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -192,6 +192,10 @@ impl BlockEdit { b.base.x = self.base.x; b.base.y = self.base.y; let mut entities = entities; + // Saved under another name, a dynamic block's copy has its own graph and objects. + if !name.eq_ignore_ascii_case(&self.name) { + cadcraft_doc::dynblock::copy_definition(&mut d, &self.name, name, &mut entities); + } // A dynamic block's objects carry element tags, which its references' copies are paired // with; objects added in the editor get theirs here. cadcraft_doc::dynblock::tag_elements(&mut d, name, &mut entities); diff --git a/crates/engine/tests/block_authoring.rs b/crates/engine/tests/block_authoring.rs index a5121889bb..771fb03d8b 100644 --- a/crates/engine/tests/block_authoring.rs +++ b/crates/engine/tests/block_authoring.rs @@ -73,6 +73,40 @@ fn a_linear_stretch_authored_in_json_drives_references() { assert_eq!(corners(&s, &i), [(5.0, 5.0), (20.0, 5.0), (20.0, 10.0), (5.0, 10.0)]); } +/// Saved under another name (BSAVEAS), a dynamic block keeps its parameters and actions in a graph +/// of its own, with objects of its own: references to the copy change as the original's do, and +/// the original is as it was. +#[test] +fn bsaveas_gives_a_dynamic_block_its_own_graph() { + let mut s = Session::new(); + let (r, c, i) = boxed(&mut s); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0], "labelAt": [5, -2] })).unwrap(); + s.execute("baction", &json!({ "parameter": "Distance1", "type": "stretch", "frame": [[8, -1], [12, 6]], "handles": [r, c], "at": [12, -2] })) + .unwrap(); + s.execute("bsaveas", &json!({ "name": "Box2" })).unwrap(); + s.execute("bclose", &json!({})).unwrap(); + let d = s.doc().unwrap(); + let (a, b) = (dynamic_block(d, "Box").unwrap(), dynamic_block(d, "Box2").expect("the copy has dynamic data")); + assert_eq!((b.parameters.len(), b.actions.len()), (a.parameters.len(), a.actions.len())); + assert_ne!(a.parameters[0].handle, b.parameters[0].handle, "its own graph objects"); + assert_ne!(a.actions[0].handle, b.actions[0].handle); + // The copy's action acts on the copy's objects, not the original's. + let (own, copy) = (d.block("Box").unwrap(), d.block("Box2").unwrap()); + let handles = |blk: &cadcraft_engine::doc::Block| blk.entities.iter().map(|e| e.handle).collect::>(); + assert!(handles(own).iter().all(|h| !handles(copy).contains(h)), "no handle in two blocks"); + assert_eq!(b.actions[0].selection.len(), 2); + assert!(b.actions[0].selection.iter().all(|h| handles(copy).contains(h)), "{:?} in {:?}", b.actions[0].selection, handles(copy)); + assert_eq!(a.actions[0].selection, [h(&r), h(&c)], "the original's action is unchanged"); + + // A reference to the copy stretches; the original's reference does too. + let j = s.execute("insert", &json!({ "name": "Box2", "at": [200, 0] })).unwrap()["handle"].clone(); + s.execute("blocks.reference.set", &json!({ "handle": j, "name": "Distance1", "value": "15" })).unwrap(); + assert_eq!(corners(&s, &j), [(5.0, 5.0), (20.0, 5.0), (20.0, 10.0), (5.0, 10.0)]); + s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Distance1", "value": "12" })).unwrap(); + assert_eq!(corners(&s, &i), [(5.0, 5.0), (17.0, 5.0), (17.0, 10.0), (5.0, 10.0)]); +} + #[test] fn bparameter_and_baction_ask_as_autocad_does() { let mut s = Session::new(); From 60eaa8739ef129658559596c8b45b22eb8cf2b61 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Thu, 29 Oct 2026 12:11:40 -0600 Subject: [PATCH 08/47] Dynamic blocks: BSAVEAS leaves the edited block as it was and the editor on the copy The editor's changes to the edited block's graph belong to the copy: the block stays as the drawing had it (restore_definition), a replaced block's old graph is removed first (also when the saved block isn't dynamic), and the editor, with each undo and redo step, takes the copy's graph and the handles its objects got, so a later BSAVE keeps them instead of writing the old graph over the copy. Co-Authored-By: Claude Sonnet 5.5 --- crates/doc/src/dynblock.rs | 2 +- crates/doc/src/dynblock/copy.rs | 67 ++++++++++++++++++---- crates/doc/src/dynblock/write.rs | 4 +- crates/engine/src/blockedit.rs | 30 ++++++++-- crates/engine/tests/block_authoring.rs | 78 +++++++++++++++++++++----- 5 files changed, 149 insertions(+), 32 deletions(-) diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index 8100fd0c79..003d8faa91 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -27,7 +27,7 @@ mod marks; mod reference; mod write; pub use apply::{drag_grip, set_property}; -pub use copy::copy_definition; +pub use copy::{copy_definition, remap_handles, restore_definition}; pub use grips::{DynGrip, GripPart, GripShape, grips}; pub use marks::{Mark, marks}; pub use reference::{CustomProperty, Reference, Value, custom_properties, reference}; diff --git a/crates/doc/src/dynblock/copy.rs b/crates/doc/src/dynblock/copy.rs index 3d846848bd..a394810dd3 100644 --- a/crates/doc/src/dynblock/copy.rs +++ b/crates/doc/src/dynblock/copy.rs @@ -7,7 +7,7 @@ use std::collections::{HashMap, HashSet}; use crate::foreign::{ForeignExtra, ForeignObject}; use crate::{Drawing, EntityKind, EntityStore, Handle, RawTag}; -use super::write::{dict_entry, guid, record_handle}; +use super::write::{ETAG, dict_entry, guid, record_handle, strip_app}; use super::{MAX_NODES, dynamic_block}; /// Most objects of one block's dynamic data that are copied. @@ -68,13 +68,18 @@ fn retarget(tags: &mut [RawTag], map: &HashMap) { } } -/// The objects of `store` again with new handles (added to `map`): each one's element tag names -/// the object itself, and a hatch's sources are the new copies. +/// The objects of `store` again with new handles (added to `map`). fn rehandle(d: &mut Drawing, store: &EntityStore, map: &mut HashMap) -> EntityStore { for e in store.iter() { let n = d.new_handle(); map.insert(e.handle, n); } + remap_handles(store, map) +} + +/// The objects of `store` again with the handles `map` gives them: each one's element tag names +/// the object itself, and a hatch's sources are the new copies. +pub fn remap_handles(store: &EntityStore, map: &HashMap) -> EntityStore { let mut out = EntityStore::new(); for e in store.iter() { let mut c = (**e).clone(); @@ -108,6 +113,41 @@ fn entity_extras(d: &Drawing, store: &EntityStore, map: &HashMap .collect() } +/// The applications whose record xdata make a block dynamic. +const DYNAMIC_APPS: [&str; 3] = ["AcDbDynamicBlockTrueName", "AcDbDynamicBlockGUID", ETAG]; + +/// Block `name`'s (upper case) dynamic data removed: the objects its extension dictionary owns +/// and its record's dynamic data. What a redefined block's old graph would point at is gone. +fn remove_definition(d: &mut Drawing, name: &str) { + let key = ("BLOCK_RECORD".to_string(), name.to_string()); + let Some(xdict) = d.foreign.records.get(&key).and_then(|x| x.xdict) else { return }; + let owned: HashSet = owned_subtree(d, xdict).into_iter().collect(); + let f = std::sync::Arc::make_mut(&mut d.foreign); + f.objects.retain(|o| !owned.contains(&o.handle)); + let empty = f.records.get_mut(&key).is_some_and(|x| { + x.xdict = None; + DYNAMIC_APPS.iter().for_each(|app| strip_app(&mut x.xdata, app)); + x.is_empty() + }); + if empty { + f.records.remove(&key); + } +} + +/// Block `name`'s dynamic data in `d` as `host` has it (BSAVEAS leaves the edited block as it +/// was: the editor's changes to its graph belong to the copy only). +pub fn restore_definition(d: &mut Drawing, host: &Drawing, name: &str) { + let name = name.trim().to_ascii_uppercase(); + remove_definition(d, &name); + let key = ("BLOCK_RECORD".to_string(), name); + let Some(record) = host.foreign.records.get(&key) else { return }; + let owned: HashSet = record.xdict.map(|x| owned_subtree(host, x)).unwrap_or_default().into_iter().collect(); + let objects: Vec = host.foreign.objects.iter().filter(|o| owned.contains(&o.handle)).cloned().collect(); + let f = std::sync::Arc::make_mut(&mut d.foreign); + f.objects.extend(objects); + f.records.insert(key, record.clone()); +} + /// Block record xdata `xdata` with the dynamic block's true name and GUID replaced. fn rename_in_xdata(xdata: &mut [RawTag], name: &str, guid: &str) { let mut app = String::new(); @@ -123,16 +163,21 @@ fn rename_in_xdata(xdata: &mut [RawTag], name: &str, guid: &str) { /// Make block `to` a copy of dynamic block `from` (BSAVEAS): `store`, the objects it is saved /// with, get new handles; the copy has its own evaluation graph and objects, made from the -/// original's with new handles, and its own true name and GUID. Nothing changes when `from` has no -/// dynamic data or is `to`. -pub fn copy_definition(d: &mut Drawing, from: &str, to: &str, store: &mut EntityStore) { +/// original's with new handles, and its own true name and GUID. What `to` had of dynamic data goes +/// first (a block replaced by one that isn't dynamic keeps none). Returns the handles the objects +/// of `store` got, by their old ones; nothing changes when `from` has no dynamic data or is `to`. +pub fn copy_definition(d: &mut Drawing, from: &str, to: &str, store: &mut EntityStore) -> HashMap { let (from_name, to_name) = (from.trim().to_ascii_uppercase(), to.trim().to_ascii_uppercase()); let key = |n: &str| ("BLOCK_RECORD".to_string(), n.to_string()); - if from_name == to_name || dynamic_block(d, from).is_none() { - return; + if from_name == to_name { + return HashMap::new(); + } + remove_definition(d, &to_name); + if dynamic_block(d, from).is_none() { + return HashMap::new(); } - let Some(source) = d.foreign.records.get(&key(&from_name)).cloned() else { return }; - let Some(xdict) = source.xdict else { return }; + let Some(source) = d.foreign.records.get(&key(&from_name)).cloned() else { return HashMap::new() }; + let Some(xdict) = source.xdict else { return HashMap::new() }; let graph = dict_entry(d, xdict, "ACAD_ENHANCEDBLOCK"); let owned = owned_subtree(d, xdict); let owned_set: HashSet = owned.iter().copied().collect(); @@ -162,5 +207,7 @@ pub fn copy_definition(d: &mut Drawing, from: &str, to: &str, store: &mut Entity f.objects.extend(copies); f.records.insert(key(&to_name), record); f.entities.extend(extras); + let made = store.iter().filter_map(|e| Some((e.handle, *map.get(&e.handle)?))).collect(); *store = entities; + made } diff --git a/crates/doc/src/dynblock/write.rs b/crates/doc/src/dynblock/write.rs index 9cfe99c2ba..847fac66cd 100644 --- a/crates/doc/src/dynblock/write.rs +++ b/crates/doc/src/dynblock/write.rs @@ -24,7 +24,7 @@ pub const MAX_ACTION_ITEMS: usize = 10_000; /// The application name of element tags: the xdata pairing a block's objects with their /// copies in references. -const ETAG: &str = "AcDbBlockRepETag"; +pub(super) const ETAG: &str = "AcDbBlockRepETag"; /// The value AutoCAD gives a grip location component it hasn't evaluated yet (a linear /// parameter's end grip). @@ -603,7 +603,7 @@ pub fn tag_elements(d: &mut Drawing, name: &str, store: &mut EntityStore) { } /// Remove application `app`'s xdata from `xd`. -fn strip_app(xd: &mut Vec, app: &str) { +pub(super) fn strip_app(xd: &mut Vec, app: &str) { let Some(at) = xd.iter().position(|t| t.code == 1001 && t.value.eq_ignore_ascii_case(app)) else { return }; let end = xd.iter().skip(at + 1).position(|t| t.code == 1001).map_or(xd.len(), |n| at + 1 + n); xd.drain(at..end); diff --git a/crates/engine/src/blockedit.rs b/crates/engine/src/blockedit.rs index 02caddbb7a..e5775bac5b 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -153,12 +153,22 @@ impl BlockEdit { /// The drawing with the editor's objects saved into block `name` (the edited block, or a new /// name for BSAVEAS), from `editor`, the editor's drawing. pub fn compose(&self, editor: &Drawing, name: &str) -> Result { + self.compose_mapped(editor, name).map(|(d, _)| d) + } + + /// [`BlockEdit::compose`], and the handles the saved objects got when a dynamic block is saved + /// under another name (they are a copy's, with a graph of their own), by their old ones. + pub fn compose_mapped( + &self, + editor: &Drawing, + name: &str, + ) -> Result<(Drawing, std::collections::HashMap)> { // The drawing itself: the editor's drawing is the drawing. if self.current { if !name.eq_ignore_ascii_case(CURRENT_DRAWING) { return Err(EngineError::Other("The current drawing can't be saved as a block from the Block Editor; use WBLOCK or BLOCK.".into())); } - return Ok(editor.clone()); + return Ok((editor.clone(), std::collections::HashMap::new())); } if refers_to(editor, &editor.model, name) { return Err(EngineError::Other(format!("Block \"{name}\" can't contain a reference to itself."))); @@ -192,16 +202,20 @@ impl BlockEdit { b.base.x = self.base.x; b.base.y = self.base.y; let mut entities = entities; - // Saved under another name, a dynamic block's copy has its own graph and objects. + // Saved under another name, a dynamic block's copy has its own graph and objects; the + // edited block stays as the drawing has it (the editor's changes to its graph are the + // copy's). + let mut remap = std::collections::HashMap::new(); if !name.eq_ignore_ascii_case(&self.name) { - cadcraft_doc::dynblock::copy_definition(&mut d, &self.name, name, &mut entities); + remap = cadcraft_doc::dynblock::copy_definition(&mut d, &self.name, name, &mut entities); + cadcraft_doc::dynblock::restore_definition(&mut d, host, &self.name); } // A dynamic block's objects carry element tags, which its references' copies are paired // with; objects added in the editor get theirs here. cadcraft_doc::dynblock::tag_elements(&mut d, name, &mut entities); b.entities = entities; d.blocks.insert(key, Arc::new(b)); - Ok(d) + Ok((d, remap)) } } @@ -318,7 +332,7 @@ impl DocState { pub fn save_block_editor(&mut self, as_name: Option<&str>) -> Result<()> { let Some(be) = &self.block_edit else { return Err(EngineError::Other("The Block Editor is not open.".into())) }; let name = as_name.unwrap_or(&be.name).to_string(); - let d = be.compose(&self.doc, &name)?; + let (d, remap) = be.compose_mapped(&self.doc, &name)?; let original = d.block(&name).map(|b| b.entities.clone()).unwrap_or_default(); let name = d.block(&name).map(|b| b.name.clone()).unwrap_or(name); // When BSAVEAS saves the block under another name, the editor's drawing and each undo and @@ -333,6 +347,12 @@ impl DocState { keep_description(editor, &d, &was); editor.blocks.retain(|k, _| !k.eq_ignore_ascii_case(&name)); editor.blocks.insert(name.clone(), b.clone()); + // A dynamic block's copy: the editor edits it from here on, with its graph and + // the handles its objects got. + if !remap.is_empty() { + editor.foreign = d.foreign.clone(); + editor.model = cadcraft_doc::dynblock::remap_handles(&editor.model, &remap); + } }; reconcile(&mut self.doc); for step in self.undo.iter_mut().chain(self.redo.iter_mut()) { diff --git a/crates/engine/tests/block_authoring.rs b/crates/engine/tests/block_authoring.rs index 771fb03d8b..9f2a800fbd 100644 --- a/crates/engine/tests/block_authoring.rs +++ b/crates/engine/tests/block_authoring.rs @@ -73,9 +73,15 @@ fn a_linear_stretch_authored_in_json_drives_references() { assert_eq!(corners(&s, &i), [(5.0, 5.0), (20.0, 5.0), (20.0, 10.0), (5.0, 10.0)]); } +/// The handles of block `name`'s objects. +fn block_handles(s: &Session, name: &str) -> Vec { + s.doc().unwrap().block(name).unwrap().entities.iter().map(|e| e.handle).collect() +} + /// Saved under another name (BSAVEAS), a dynamic block keeps its parameters and actions in a graph -/// of its own, with objects of its own: references to the copy change as the original's do, and -/// the original is as it was. +/// of its own, with objects of its own, and what was unsaved in the editor (a new object and an +/// action on it) is the copy's: the original is as the drawing had it. The editor goes on with the +/// copy, so a later BSAVE keeps its graph and handles; references to either change as before. #[test] fn bsaveas_gives_a_dynamic_block_its_own_graph() { let mut s = Session::new(); @@ -84,20 +90,33 @@ fn bsaveas_gives_a_dynamic_block_its_own_graph() { s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0], "labelAt": [5, -2] })).unwrap(); s.execute("baction", &json!({ "parameter": "Distance1", "type": "stretch", "frame": [[8, -1], [12, 6]], "handles": [r, c], "at": [12, -2] })) .unwrap(); + s.execute("bsave", &json!({})).unwrap(); + // Unsaved: a new circle, moved by the distance. + let made = |v: Value| if v["handle"].is_null() { v["handles"][0].clone() } else { v["handle"].clone() }; + let n = made(s.execute("circle", &json!({ "center": [2, 2], "radius": 0.5 })).unwrap()); + s.execute("baction", &json!({ "parameter": "Distance1", "type": "move", "handles": [n], "at": [2, -4] })).unwrap(); s.execute("bsaveas", &json!({ "name": "Box2" })).unwrap(); + let check = |s: &Session| { + let d = s.doc().unwrap(); + let (a, b) = (dynamic_block(d, "Box").unwrap(), dynamic_block(d, "Box2").expect("the copy has dynamic data")); + assert_eq!((a.parameters.len(), a.actions.len()), (1, 1), "the original keeps what the drawing had"); + assert_eq!((b.parameters.len(), b.actions.len()), (1, 2), "the copy has what the editor had"); + assert_ne!(a.parameters[0].handle, b.parameters[0].handle, "its own graph objects"); + let (own, copy) = (block_handles(s, "Box"), block_handles(s, "Box2")); + assert!(own.iter().all(|h| !copy.contains(h)), "no handle in two blocks"); + assert_eq!(a.actions[0].selection, [h(&r), h(&c)], "the original's action is unchanged"); + for act in &a.actions { + assert!(act.selection.iter().all(|x| own.contains(x)), "the original's graph names only its own objects"); + } + for act in &b.actions { + assert!(act.selection.iter().all(|x| copy.contains(x)), "{:?} in {:?}", act.selection, copy); + } + }; + check(&s); + // The editor edits the copy now: saving again keeps its graph and handles. + s.execute("bsave", &json!({})).unwrap(); s.execute("bclose", &json!({})).unwrap(); - let d = s.doc().unwrap(); - let (a, b) = (dynamic_block(d, "Box").unwrap(), dynamic_block(d, "Box2").expect("the copy has dynamic data")); - assert_eq!((b.parameters.len(), b.actions.len()), (a.parameters.len(), a.actions.len())); - assert_ne!(a.parameters[0].handle, b.parameters[0].handle, "its own graph objects"); - assert_ne!(a.actions[0].handle, b.actions[0].handle); - // The copy's action acts on the copy's objects, not the original's. - let (own, copy) = (d.block("Box").unwrap(), d.block("Box2").unwrap()); - let handles = |blk: &cadcraft_engine::doc::Block| blk.entities.iter().map(|e| e.handle).collect::>(); - assert!(handles(own).iter().all(|h| !handles(copy).contains(h)), "no handle in two blocks"); - assert_eq!(b.actions[0].selection.len(), 2); - assert!(b.actions[0].selection.iter().all(|h| handles(copy).contains(h)), "{:?} in {:?}", b.actions[0].selection, handles(copy)); - assert_eq!(a.actions[0].selection, [h(&r), h(&c)], "the original's action is unchanged"); + check(&s); // A reference to the copy stretches; the original's reference does too. let j = s.execute("insert", &json!({ "name": "Box2", "at": [200, 0] })).unwrap()["handle"].clone(); @@ -107,6 +126,37 @@ fn bsaveas_gives_a_dynamic_block_its_own_graph() { assert_eq!(corners(&s, &i), [(5.0, 5.0), (17.0, 5.0), (17.0, 10.0), (5.0, 10.0)]); } +/// A dynamic block replaced by BSAVEAS with a block that isn't dynamic keeps none of its old graph. +#[test] +fn bsaveas_over_a_dynamic_block_leaves_none_of_its_old_graph() { + let mut s = Session::new(); + let (r, c, _) = boxed(&mut s); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0], "labelAt": [5, -2] })).unwrap(); + s.execute("baction", &json!({ "parameter": "Distance1", "type": "stretch", "frame": [[8, -1], [12, 6]], "handles": [r, c], "at": [12, -2] })) + .unwrap(); + s.execute("bsave", &json!({})).unwrap(); + s.execute("bclose", &json!({})).unwrap(); + let graph_objects = s.doc().unwrap().foreign.objects.len(); + // A copy, with a graph of its own. + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + s.execute("bsaveas", &json!({ "name": "Box2" })).unwrap(); + s.execute("bclose", &json!({})).unwrap(); + assert!(dynamic_block(s.doc().unwrap(), "Box2").is_some()); + assert!(s.doc().unwrap().foreign.objects.len() > graph_objects, "the copy's graph objects"); + // Plain block "Plain" replaces it. + let made = |v: Value| if v["handle"].is_null() { v["handles"][0].clone() } else { v["handle"].clone() }; + let ci = made(s.execute("circle", &json!({ "center": [50, 50], "radius": 2 })).unwrap()); + s.execute("block", &json!({ "name": "Plain", "base": [50, 50], "handles": [ci], "keep": "delete" })).unwrap(); + s.execute("bedit", &json!({ "name": "Plain" })).unwrap(); + s.execute("bsaveas", &json!({ "name": "Box2", "replace": true })).unwrap(); + s.execute("bclose", &json!({})).unwrap(); + let d = s.doc().unwrap(); + assert!(dynamic_block(d, "Box2").is_none(), "Box2 is the plain block now"); + assert_eq!(d.foreign.objects.len(), graph_objects, "only Box's graph is left"); + assert!(dynamic_block(d, "Box").is_some(), "Box is untouched"); +} + #[test] fn bparameter_and_baction_ask_as_autocad_does() { let mut s = Session::new(); From fc204c2553c173f92b9ec28e0fa4d65eb9227453 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:06:04 -0600 Subject: [PATCH 09/47] BSAVEAS of a dynamic block: the copy starts a new Block Editor history --- crates/engine/src/blockedit.rs | 11 +++++++++-- crates/engine/tests/block_authoring.rs | 4 +++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/blockedit.rs b/crates/engine/src/blockedit.rs index e5775bac5b..04b51a98fb 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -355,8 +355,15 @@ impl DocState { } }; reconcile(&mut self.doc); - for step in self.undo.iter_mut().chain(self.redo.iter_mut()) { - reconcile(&mut step.doc); + if remap.is_empty() { + for step in self.undo.iter_mut().chain(self.redo.iter_mut()) { + reconcile(&mut step.doc); + } + } else { + // Older steps hold the handles and graph from before the copy; they can't be + // remapped consistently, so the copy starts a new history. + self.undo.clear(); + self.redo.clear(); } } let editor = self.doc.clone(); diff --git a/crates/engine/tests/block_authoring.rs b/crates/engine/tests/block_authoring.rs index 9f2a800fbd..1775d9cfc6 100644 --- a/crates/engine/tests/block_authoring.rs +++ b/crates/engine/tests/block_authoring.rs @@ -113,7 +113,9 @@ fn bsaveas_gives_a_dynamic_block_its_own_graph() { } }; check(&s); - // The editor edits the copy now: saving again keeps its graph and handles. + // The editor edits the copy now: saving again keeps its graph and handles. Its history from + // before the copy is gone, so an undo can't bring back handles the copy doesn't have. + let _ = s.execute("undo", &json!({})); s.execute("bsave", &json!({})).unwrap(); s.execute("bclose", &json!({})).unwrap(); check(&s); From d777e8beb44412d2708797f4ad1ce591b559a1d5 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 25 Oct 2026 10:28:41 -0600 Subject: [PATCH 10/47] Dynamic blocks: author visibility parameters and states (BPARAMETER Visibility, BVSTATE, BVHIDE, BVSHOW) In the Block Editor, BPARAMETER adds a visibility parameter (one per block; one state, VisibilityState0, showing every object). BVSTATE makes, picks, deletes (and in JSON renames) states: a new state shows nothing, everything, or what the current state shows. BVHIDE and BVSHOW hide or show objects in the current state or all of them. Prompts are AutoCAD's -BVSTATE, BVHIDE and BVSHOW prompts; BVSTATE asks the same until it has a dialog. As AutoCAD keeps them: an object drawn in the editor shows in the state shown only, and a parameter added there is active (its grips shown) in that state only. The editor hides what the state shown hides, or with BVMODE 1 leaves it to pick and dims it; parameters the state leaves out aren't drawn. The editor's bar picks the state and offers Visibility States, Make Visible and Make Invisible. AutoCAD opens the result from DXF and DWG with its states, and shows each state's objects. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock.rs | 5 +- crates/doc/src/dynblock/write.rs | 190 +++++++++- crates/engine/src/blockedit.rs | 107 +++++- crates/engine/src/cmd/blocks.rs | 2 + crates/engine/src/cmd/blocks/bauthor.rs | 50 ++- crates/engine/src/cmd/blocks/bedit.rs | 5 +- crates/engine/src/cmd/blocks/bvstate.rs | 478 ++++++++++++++++++++++++ crates/engine/src/settings.rs | 4 + crates/engine/src/sysvars.rs | 6 + crates/engine/tests/block_authoring.rs | 169 ++++++++- crates/io/tests/dynblock_author.rs | 73 +++- crates/ui-egui/src/canvas/blockedit.rs | 100 ++++- crates/ui-egui/src/i18n/uk.tsv | 3 + 13 files changed, 1159 insertions(+), 33 deletions(-) create mode 100644 crates/engine/src/cmd/blocks/bvstate.rs diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index 003d8faa91..80eeaa43ec 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -31,7 +31,10 @@ pub use copy::{copy_definition, remap_handles, restore_definition}; pub use grips::{DynGrip, GripPart, GripShape, grips}; pub use marks::{Mark, marks}; pub use reference::{CustomProperty, Reference, Value, custom_properties, reference}; -pub use write::{ActionSpec, MAX_ACTION_ITEMS, ParamPoint, ParameterSpec, add_action, add_parameter, tag_elements}; +pub use write::{ + ActionSpec, MAX_ACTION_ITEMS, MAX_VISIBILITY_STATES, ParamPoint, ParameterSpec, add_action, add_parameter, adopt_objects, parameter_objects, + set_visibility, tag_elements, +}; /// Most objects one evaluation graph is read with. const MAX_NODES: usize = 10_000; diff --git a/crates/doc/src/dynblock/write.rs b/crates/doc/src/dynblock/write.rs index 847fac66cd..355f14c1db 100644 --- a/crates/doc/src/dynblock/write.rs +++ b/crates/doc/src/dynblock/write.rs @@ -14,7 +14,7 @@ use cadcraft_geom::{Vec2, Vec3}; use crate::foreign::ForeignObject; use crate::{Drawing, EntityStore, Handle, RawTag}; -use super::{ParameterKind, dynamic_block}; +use super::{ParameterKind, VisibilityState, dynamic_block}; /// The graph `AcDbEvalGraph` is extended only up to this many nodes. const MAX_NODES: usize = super::MAX_NODES; @@ -38,6 +38,18 @@ pub enum ParameterSpec { Linear { base: Vec3, end: Vec3, label: Option, label_offset: f64, grips: u8 }, /// A position (Position1), its label at `label_at`, with 0 or 1 grip. Point { at: Vec3, label: Option, label_at: Vec3, grips: u8 }, + /// Named visibility states (Visibility1) of `objects`, at `at`, with 0 or 1 grip: one state, + /// `VisibilityState0`, showing them all. A block has one at most. + Visibility { at: Vec3, label: Option, objects: Vec, grips: u8 }, +} + +/// What a grip is: a linear parameter's (pointing along `Vec3`), a point's, or a visibility +/// parameter's (a list to pick from). +#[derive(Clone, Copy, Debug, PartialEq)] +enum GripKind { + Linear(Vec3), + Xy, + Visibility, } /// Which point of a two-point parameter an action follows. @@ -325,26 +337,36 @@ impl<'a> Author<'a> { /// A grip at `at` with its two location components (`x_name`, `y_name`, both valued /// `value`), linked after parameter node `param`: the grip's graph id. - fn grip(&mut self, param: i32, at: Vec3, name: &str, [x_name, y_name]: [&str; 2], value: f64, linear: Option) -> i32 { + fn grip(&mut self, param: i32, at: Vec3, name: &str, [x_name, y_name]: [&str; 2], value: f64, kind: GripKind) -> i32 { let (gh, gid) = (self.d.new_handle(), self.graph.next_id()); let (xid, yid) = (gid.saturating_add(1), gid.saturating_add(2)); let mut tags = element_head(gh, self.graph.handle, gid, name, 0); tags.extend([tag(100, "AcDbBlockGrip"), tag(91, xid), tag(92, yid)]); point(&mut tags, 1010, at); - tags.extend([tag(280, 1), tag(93, -1)]); - let kind = match linear { - Some(dir) => { + // A visibility grip is the only one AutoCAD writes 280 0 on. + tags.extend([tag(280, i32::from(kind != GripKind::Visibility)), tag(93, -1)]); + let dxf = match kind { + GripKind::Linear(dir) => { tags.extend([tag(100, "AcDbBlockLinearGrip"), real(140, dir.x), real(141, dir.y), real(142, dir.z)]); self.class("BLOCKLINEARGRIP", "AcDbBlockLinearGrip"); "BLOCKLINEARGRIP" } - None => { + GripKind::Xy => { tags.push(tag(100, "AcDbBlockXYGrip")); self.class("BLOCKXYGRIP", "AcDbBlockXYGrip"); "BLOCKXYGRIP" } + GripKind::Visibility => { + tags.push(tag(100, "AcDbBlockVisibilityGrip")); + self.class("BLOCKVISIBILITYGRIP", "AcDbBlockVisibilityGrip"); + "BLOCKVISIBILITYGRIP" + } }; - let grip = self.node(kind, gh, gid, tags); + let grip = self.node(dxf, gh, gid, tags); + // AutoCAD links a visibility grip to its parameter before the location components. + if kind == GripKind::Visibility { + self.graph.link(grip, param, 1); + } self.class("BLOCKGRIPLOCATIONCOMPONENT", "AcDbBlockGripExpr"); // Each component names the parameter it reads (its graph id). let owner = self.graph.nodes.iter().find(|n| n.index == param).map_or(0, |n| n.id); @@ -355,7 +377,9 @@ impl<'a> Author<'a> { let c = self.node("BLOCKGRIPLOCATIONCOMPONENT", h, id, tags); self.graph.link(param, c, 1); } - self.graph.link(grip, param, 2); + if kind != GripKind::Visibility { + self.graph.link(grip, param, 2); + } gid } @@ -432,8 +456,10 @@ pub fn add_parameter(d: &mut Drawing, name: &str, spec: &ParameterSpec) -> Resul let param = a.graph.add_node(id, h); let first_grip = a.new.len(); let dir = *end - *base; - let end_grip = if *grips >= 1 { a.grip(param, *end, "End Grip", ["UpdatedEndX", "UpdatedEndY"], UNSET, Some(dir)) } else { 0 }; - let base_grip = if *grips >= 2 { a.grip(param, *base, "Base Grip", ["UpdatedBaseX", "UpdatedBaseY"], 0.0, Some(-dir)) } else { 0 }; + let end_grip = + if *grips >= 1 { a.grip(param, *end, "End Grip", ["UpdatedEndX", "UpdatedEndY"], UNSET, GripKind::Linear(dir)) } else { 0 }; + let base_grip = + if *grips >= 2 { a.grip(param, *base, "Base Grip", ["UpdatedBaseX", "UpdatedBaseY"], 0.0, GripKind::Linear(-dir)) } else { 0 }; let mut tags = element_head(h, a.graph.handle, id, &element, if *grips == 2 { 32 } else { 1 }); tags.extend([tag(100, "AcDbBlockParameter"), tag(280, 1), tag(281, 0), tag(100, "AcDbBlock2PtParameter")]); point(&mut tags, 1010, *base); @@ -475,7 +501,7 @@ pub fn add_parameter(d: &mut Drawing, name: &str, spec: &ParameterSpec) -> Resul let (h, id) = (a.d.new_handle(), a.graph.next_id()); let param = a.graph.add_node(id, h); let first_grip = a.new.len(); - let grip = if *grips == 1 { a.grip(param, *at, "Grip", ["UpdatedX", "UpdatedY"], 0.0, None) } else { 0 }; + let grip = if *grips == 1 { a.grip(param, *at, "Grip", ["UpdatedX", "UpdatedY"], 0.0, GripKind::Xy) } else { 0 }; let mut tags = element_head(h, a.graph.handle, id, &element, if *grips == 1 { 0 } else { 1 }); tags.extend([tag(100, "AcDbBlockParameter"), tag(280, 1), tag(281, 0), tag(100, "AcDbBlock1PtParameter")]); point(&mut tags, 1010, *at); @@ -492,7 +518,149 @@ pub fn add_parameter(d: &mut Drawing, name: &str, spec: &ParameterSpec) -> Resul a.finish(); Ok(id) } + ParameterSpec::Visibility { at, label, objects, grips } => { + if !finite(*at) { + return Err("Invalid point.".into()); + } + if *grips > 1 { + return Err("A visibility parameter has 0 or 1 grip.".into()); + } + if objects.len() > MAX_ACTION_ITEMS { + return Err(format!("A visibility parameter controls at most {MAX_ACTION_ITEMS} objects.")); + } + let record = name.trim().to_ascii_uppercase(); + let m = dynamic_block(d, &record); + if m.as_ref().is_some_and(|m| m.parameters.iter().any(|p| matches!(p.kind, ParameterKind::Visibility { .. }))) { + return Err("The block already has a visibility parameter.".into()); + } + // The other parameters and their grips show in the first state. + let active: Vec = m.map(|m| parameter_objects(&m, None)).unwrap_or_default(); + let label = label.clone().unwrap_or_else(|| free_label(d, &record, "Visibility")); + let mut a = Author::open(d, name)?; + let element = a.element_name("Visibility State"); + let (h, id) = (a.d.new_handle(), a.graph.next_id()); + let param = a.graph.add_node(id, h); + let first_grip = a.new.len(); + let grip = if *grips == 1 { a.grip(param, *at, "Grip", ["UpdatedX", "UpdatedY"], 0.0, GripKind::Visibility) } else { 0 }; + let mut tags = element_head(h, a.graph.handle, id, &element, 16); + tags.extend([tag(100, "AcDbBlockParameter"), tag(280, 1), tag(281, 0), tag(100, "AcDbBlock1PtParameter")]); + point(&mut tags, 1010, *at); + tags.extend([tag(93, grip), tag(170, 0), tag(171, 0)]); + let state = VisibilityState { name: "VisibilityState0".into(), visible: objects.clone(), active }; + tags.extend(visibility_tags(&label, "", objects, std::slice::from_ref(&state))); + a.new.insert(first_grip, ForeignObject { handle: h, kind: "BLOCKVISIBILITYPARAMETER".into(), tags }); + a.class("BLOCKVISIBILITYPARAMETER", "AcDbBlockVisibilityParameter"); + a.finish(); + Ok(id) + } + } +} + +/// Most visibility states one parameter is written with. +pub const MAX_VISIBILITY_STATES: usize = 1_000; + +/// The visibility parameter's own section: label, description, the objects it controls and its +/// states (each the objects shown in it and the parameters and grips active in it). +fn visibility_tags(label: &str, description: &str, controlled: &[Handle], states: &[VisibilityState]) -> Vec { + let mut out = vec![tag(100, "AcDbBlockVisibilityParameter"), tag(281, 1), tag(301, label), tag(302, description), tag(91, 0)]; + out.push(tag(93, controlled.len())); + out.extend(controlled.iter().map(|h| tag(331, h.hex()))); + out.push(tag(92, states.len())); + for s in states { + out.extend([tag(303, &s.name), tag(94, s.visible.len())]); + out.extend(s.visible.iter().map(|h| tag(332, h.hex()))); + out.push(tag(95, s.active.len())); + out.extend(s.active.iter().map(|h| tag(333, h.hex()))); + } + out +} + +/// The objects of block `m`'s parameters other than its visibility parameter, and their grips +/// (all of them, or parameter `only`'s): what a visibility state lists as active in it. +pub fn parameter_objects(m: &super::DynamicBlock, only: Option) -> Vec { + let grip = |id: &i32| m.grip_objects.iter().find(|(g, _)| g == id).map(|(_, h)| *h); + m.parameters + .iter() + .filter(|p| !matches!(p.kind, ParameterKind::Visibility { .. }) && only.is_none_or(|n| n == p.node)) + .flat_map(|p| std::iter::once(p.handle).chain(p.grips.iter().filter(|g| **g != 0).filter_map(grip))) + .collect() +} + +/// Keep block `name`'s visibility parameter in step with `objects`, the block's objects: as +/// AutoCAD does, one it doesn't control yet (drawn in the Block Editor) becomes controlled and +/// shown in state `current` only (the first state when `None` or not found), and objects no +/// longer in the block leave its lists. Nothing happens without a visibility parameter. +pub fn adopt_objects(d: &mut Drawing, name: &str, objects: &[Handle], current: Option<&str>) -> Result<(), String> { + let Some(m) = dynamic_block(d, name) else { return Ok(()) }; + let Some(ParameterKind::Visibility { controlled, states, .. }) = + m.parameters.into_iter().map(|p| p.kind).find(|k| matches!(k, ParameterKind::Visibility { .. })) + else { + return Ok(()); + }; + let alive: std::collections::HashSet = objects.iter().copied().collect(); + let known: std::collections::HashSet = controlled.iter().copied().collect(); + let new: Vec = objects.iter().filter(|h| !known.contains(h)).copied().collect(); + let gone = controlled.iter().any(|h| !alive.contains(h)) || states.iter().any(|s| s.visible.iter().any(|h| !alive.contains(h))); + if new.is_empty() && !gone { + return Ok(()); + } + let at = current.and_then(|c| states.iter().position(|s| s.name.eq_ignore_ascii_case(c))).unwrap_or(0); + let mut controlled: Vec = controlled.into_iter().filter(|h| alive.contains(h)).collect(); + controlled.extend(new.iter().copied()); + let mut states = states; + for (i, s) in states.iter_mut().enumerate() { + s.visible.retain(|h| alive.contains(h)); + if i == at { + s.visible.extend(new.iter().copied()); + } + } + set_visibility(d, name, &controlled, &states) +} + +/// Rewrite block `name`'s visibility parameter: the objects it `controlled` and its `states` +/// (in order; the first is the one new references start in). +pub fn set_visibility(d: &mut Drawing, name: &str, controlled: &[Handle], states: &[VisibilityState]) -> Result<(), String> { + if states.is_empty() { + return Err("A visibility parameter needs at least one visibility state.".into()); + } + if states.len() > MAX_VISIBILITY_STATES { + return Err(format!("A visibility parameter has at most {MAX_VISIBILITY_STATES} states.")); + } + let too_many = |v: &[Handle]| v.len() > MAX_ACTION_ITEMS; + if too_many(controlled) || states.iter().any(|s| too_many(&s.visible) || too_many(&s.active)) { + return Err(format!("A visibility state lists at most {MAX_ACTION_ITEMS} objects.")); + } + for (i, s) in states.iter().enumerate() { + if s.name.trim().is_empty() { + return Err("A visibility state needs a name.".into()); + } + if states.iter().take(i).any(|o| o.name.eq_ignore_ascii_case(&s.name)) { + return Err(format!("Visibility state \"{}\" already exists.", s.name)); + } + } + let m = dynamic_block(d, name).ok_or("The block has no visibility parameter.")?; + let (handle, label, description) = m + .parameters + .iter() + .find_map(|p| match &p.kind { + ParameterKind::Visibility { label, description, .. } => Some((p.handle, label.clone(), description.clone())), + _ => None, + }) + .ok_or("The block has no visibility parameter.")?; + let f = std::sync::Arc::make_mut(&mut d.foreign); + let o = f.objects.iter_mut().find(|o| o.handle == handle).ok_or("The block's visibility parameter is missing.")?; + let at = o + .tags + .iter() + .position(|t| t.code == 100 && t.value.eq_ignore_ascii_case("AcDbBlockVisibilityParameter")) + .ok_or("The block's visibility parameter can't be changed.")?; + // Its section is the object's last; anything after it would be a layout this doesn't know. + if o.tags.iter().skip(at + 1).any(|t| t.code == 100) { + return Err("The block's visibility parameter can't be changed.".into()); } + o.tags.truncate(at); + o.tags.extend(visibility_tags(&label, &description, controlled, states)); + Ok(()) } /// Add action `spec` to block `name` (any case); its graph id. The parameter it follows must be diff --git a/crates/engine/src/blockedit.rs b/crates/engine/src/blockedit.rs index 04b51a98fb..cfe8bd1919 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -60,6 +60,8 @@ pub struct BlockEdit { base: Vec2, /// The editor is open on the drawing itself ([`CURRENT_DRAWING`]). pub current: bool, + /// The visibility state the editor shows (BVSTATE Set); `None` for the block's first. + pub visibility: Option, } /// Why a block can't be opened in the Block Editor, if it can't. @@ -114,6 +116,14 @@ impl BlockEdit { use cadcraft_doc::dynblock::Mark; let off = self.base.to3(0.0); let mut out = cadcraft_doc::dynblock::marks(editor, &self.name); + // Parameters the visibility state shown leaves out aren't drawn, as in AutoCAD. + let inactive = self.inactive_parameters(editor); + if !inactive.is_empty() { + out.retain(|m| match m { + Mark::Linear { node, .. } | Mark::Point { node, .. } | Mark::Parameter { node, .. } => !inactive.contains(node), + Mark::Action { .. } => true, + }); + } for m in &mut out { match m { Mark::Linear { base, end, .. } => (*base, *end) = (*base - off, *end - off), @@ -124,6 +134,51 @@ impl BlockEdit { out } + /// The visibility state the editor shows: its name, the objects it hides (none without a + /// visibility parameter). `editor` is the editor's drawing. + pub fn visibility_state(&self, editor: &Drawing) -> Option<(String, Vec)> { + use cadcraft_doc::dynblock::ParameterKind; + let m = cadcraft_doc::dynblock::dynamic_block(editor, &self.name)?; + let (controlled, states) = m.parameters.into_iter().find_map(|p| match p.kind { + ParameterKind::Visibility { controlled, states, .. } => Some((controlled, states)), + _ => None, + })?; + let state = self.visibility.as_deref().and_then(|v| states.iter().find(|s| s.name.eq_ignore_ascii_case(v))).or(states.first())?; + let shown: std::collections::HashSet<_> = state.visible.iter().copied().collect(); + Some((state.name.clone(), controlled.into_iter().filter(|h| !shown.contains(h)).collect())) + } + + /// Graph ids of the parameters the visibility state the editor shows doesn't list as active + /// (the visibility parameter itself always shows). + fn inactive_parameters(&self, editor: &Drawing) -> Vec { + use cadcraft_doc::dynblock::ParameterKind; + let Some(m) = cadcraft_doc::dynblock::dynamic_block(editor, &self.name) else { return Vec::new() }; + let Some(states) = m.parameters.iter().find_map(|p| match &p.kind { + ParameterKind::Visibility { states, .. } => Some(states), + _ => None, + }) else { + return Vec::new(); + }; + let Some(state) = self.visibility.as_deref().and_then(|v| states.iter().find(|s| s.name.eq_ignore_ascii_case(v))).or(states.first()) else { + return Vec::new(); + }; + m.parameters + .iter() + .filter(|p| !matches!(p.kind, ParameterKind::Visibility { .. }) && !state.active.contains(&p.handle)) + .map(|p| p.node) + .collect() + } + + /// Hide in `editor` (the editor's drawing) what the visibility state it shows hides, and show + /// the rest, as AutoCAD's Block Editor does with BVMODE 0; with `bvmode` (1) hide nothing. + pub fn show_visibility_state(&self, editor: &mut Drawing, bvmode: bool) { + let hidden = if bvmode { Vec::new() } else { self.visibility_state(editor).map(|(_, h)| h).unwrap_or_default() }; + let hidden: std::collections::BTreeSet<_> = hidden.into_iter().filter(|h| editor.model.get(*h).is_some()).collect(); + if editor.hidden_objects != hidden { + editor.hidden_objects = hidden; + } + } + /// The editor's objects in block coordinates, ready to be the block's: unchanged objects are /// the block's own, the others are moved back from the editor's origin to the base point. fn block_objects(&self, editor: &Drawing) -> EntityStore { @@ -210,6 +265,9 @@ impl BlockEdit { remap = cadcraft_doc::dynblock::copy_definition(&mut d, &self.name, name, &mut entities); cadcraft_doc::dynblock::restore_definition(&mut d, host, &self.name); } + // Objects drawn in the editor show in the visibility state it shows only, as in AutoCAD. + let handles: Vec = entities.iter().map(|e| e.handle).collect(); + cadcraft_doc::dynblock::adopt_objects(&mut d, name, &handles, self.visibility.as_deref()).map_err(EngineError::Other)?; // A dynamic block's objects carry element tags, which its references' copies are paired // with; objects added in the editor get theirs here. cadcraft_doc::dynblock::tag_elements(&mut d, name, &mut entities); @@ -271,6 +329,12 @@ impl DocState { /// Open the Block Editor on block `name` (BEDIT). /// With `create`, a name no block has yet starts a new, empty block, which BSAVE creates. pub fn open_block_editor(&mut self, name: &str, create: bool) -> Result<()> { + self.open_block_editor_with(name, create, false) + } + + /// [`DocState::open_block_editor`] with BVMODE `bvmode`: objects the first visibility state + /// hides are hidden (false) or left shown for the canvas to dim (true). + pub fn open_block_editor_with(&mut self, name: &str, create: bool, bvmode: bool) -> Result<()> { if let Some(open) = self.block_editor() { return Err(EngineError::Other(format!("The Block Editor is already open on \"{open}\"; close it first (BCLOSE)."))); } @@ -284,6 +348,7 @@ impl DocState { original: EntityStore::new(), base: Vec2::ZERO, current: true, + visibility: None, }); return Ok(()); } @@ -304,9 +369,20 @@ impl DocState { d.constraints.clear(); d.hidden_objects.clear(); let host = Box::new(self.clone()); - let editor = Arc::new(d); - self.doc = editor.clone(); - self.enter_block_editor(BlockEdit { name: block.name.clone(), host, saved: editor, original: block.entities.clone(), base, current: false }); + let mut be = BlockEdit { + name: block.name.clone(), + host, + saved: self.doc.clone(), + original: block.entities.clone(), + base, + current: false, + visibility: None, + }; + // The editor shows the block's first visibility state (its other objects hidden). + be.show_visibility_state(&mut d, bvmode); + be.saved = Arc::new(d); + self.doc = be.saved.clone(); + self.enter_block_editor(be); Ok(()) } @@ -331,6 +407,15 @@ impl DocState { /// (BSAVEAS), which the editor then edits. One undo step in the drawing. pub fn save_block_editor(&mut self, as_name: Option<&str>) -> Result<()> { let Some(be) = &self.block_edit else { return Err(EngineError::Other("The Block Editor is not open.".into())) }; + // Objects drawn in the editor join its visibility states here too, so the editor and the + // block agree. + let handles: Vec = self.doc.model.iter().map(|e| e.handle).collect(); + let mut d = (*self.doc).clone(); + cadcraft_doc::dynblock::adopt_objects(&mut d, &be.name, &handles, be.visibility.as_deref()).map_err(EngineError::Other)?; + if !Arc::ptr_eq(&d.foreign, &self.doc.foreign) { + self.doc = Arc::new(d); + } + let Some(be) = &self.block_edit else { return Ok(()) }; let name = as_name.unwrap_or(&be.name).to_string(); let (d, remap) = be.compose_mapped(&self.doc, &name)?; let original = d.block(&name).map(|b| b.entities.clone()).unwrap_or_default(); @@ -406,3 +491,19 @@ impl DocState { Ok(()) } } + +impl crate::Session { + /// Show in the Block Editor what the visibility state it shows shows (BVSTATE): the other + /// objects hidden, or with BVMODE 1 left for the canvas to dim. Nothing outside the editor. + pub(crate) fn refresh_block_visibility(&mut self) -> Result<()> { + let bvmode = self.settings.bvmode; + let st = self.state()?; + let Some(be) = &st.block_edit else { return Ok(()) }; + let hidden = if bvmode { Vec::new() } else { be.visibility_state(&st.doc).map(|(_, h)| h).unwrap_or_default() }; + let hidden: std::collections::BTreeSet<_> = hidden.into_iter().filter(|h| st.doc.model.get(*h).is_some()).collect(); + if hidden != st.doc.hidden_objects { + self.doc_mut()?.hidden_objects = hidden; + } + Ok(()) + } +} diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 05951a62b1..1079ec0b68 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -20,6 +20,7 @@ use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, St mod attedit; mod bauthor; mod burst; +mod bvstate; mod description; mod dyngrip; mod extract; @@ -89,6 +90,7 @@ pub fn specs() -> Vec { .chain(refedit::specs()) .chain(bedit::specs()) .chain(bauthor::specs()) + .chain(bvstate::specs()) .collect() } diff --git a/crates/engine/src/cmd/blocks/bauthor.rs b/crates/engine/src/cmd/blocks/bauthor.rs index 7de433e3b7..73e03ae1a8 100644 --- a/crates/engine/src/cmd/blocks/bauthor.rs +++ b/crates/engine/src/cmd/blocks/bauthor.rs @@ -21,7 +21,7 @@ pub(super) fn specs() -> Vec { CommandSpec::new("bparameter", "Parameter", run_bparameter) .alias(&["-bparameter"]) .params( - "{type: \"linear\"|\"point\", linear: start: [x,y], end: [x,y], labelAt?: [x,y] (where the label goes; default on the line); point: at: [x,y], labelAt?: [x,y]; label?: property name (default Distance1/Position1…), grips?: 0|1|2 (linear, default 2) or 0|1 (point, default 1)} → {node, element, label} (editor coordinates)", + "{type: \"linear\"|\"point\"|\"visibility\", linear: start: [x,y], end: [x,y], labelAt?: [x,y] (where the label goes; default on the line); point: at: [x,y], labelAt?: [x,y]; visibility: at: [x,y] (one state, VisibilityState0, showing every object; one per block); label?: property name (default Distance1/Position1/Visibility1…), grips?: 0|1|2 (linear, default 2) or 0|1 (point, visibility, default 1)} → {node, element, label} (editor coordinates)", ) .enabled(authoring) .interactive(|_| Ok(Box::new(BparameterM::default()))), @@ -94,12 +94,22 @@ fn run_bparameter(s: &mut Session, p: &Value) -> Result { let label_at = point_param(p, "labelAt").unwrap_or(at); ParameterSpec::Point { at: to_block(at, base), label, label_at: to_block(label_at, base), grips: grips_param("bparameter", p, 1, 1)? } } - Some(other) if ["alignment", "base", "polar", "xy", "rotation", "flip", "visibility", "lookup"].contains(&other) => { + Some("visibility") => { + let at = point_param(p, "at").ok_or_else(|| bad("bparameter", "`at` ([x, y]) is required"))?; + let objects = s.doc()?.model.iter().map(|e| e.handle).collect(); + ParameterSpec::Visibility { at: to_block(at, base), label, objects, grips: grips_param("bparameter", p, 1, 1)? } + } + Some(other) if ["alignment", "base", "polar", "xy", "rotation", "flip", "lookup"].contains(&other) => { return Err(bad("bparameter", format!("{other} parameters are not available yet"))); } - _ => return Err(bad("bparameter", "`type` is \"linear\" or \"point\"")), + _ => return Err(bad("bparameter", "`type` is \"linear\", \"point\" or \"visibility\"")), }; + let visibility = matches!(spec, ParameterSpec::Visibility { .. }); let node = add_parameter(s.doc_mut()?, &block, &spec).map_err(|e| bad("bparameter", e))?; + // A parameter added after visibility states shows its grips in the state the editor shows. + if !visibility { + super::bvstate::parameter_added(s, node)?; + } let m = cadcraft_doc::dynblock::dynamic_block(s.doc()?, &block); let made = m.as_ref().and_then(|m| m.parameters.iter().find(|p| p.node == node)); Ok(json!({ "node": node, "element": made.map(|p| p.element.clone()), "label": made.and_then(|p| p.kind.label().map(str::to_string)) })) @@ -321,6 +331,7 @@ enum PStage { Location, PointLabel, PointGrips, + VisibilityGrips, /// Typing the property name, then back to the stage it was asked at. Label(&'static str), } @@ -330,6 +341,7 @@ enum PStage { struct BparameterM { stage: PStage, linear: bool, + visibility: bool, start: Vec2, end: Vec2, label_at: Vec2, @@ -352,7 +364,9 @@ const TYPES: &[(&str, &str)] = &[ impl BparameterM { fn make(&self, s: &mut Session, grips: u8) -> Result { let label = self.label.clone(); - let p = if self.linear { + let p = if self.visibility { + json!({ "type": "visibility", "at": [self.start.x, self.start.y], "label": label, "grips": grips }) + } else if self.linear { json!({ "type": "linear", "start": [self.start.x, self.start.y], "end": [self.end.x, self.end.y], "labelAt": [self.label_at.x, self.label_at.y], "label": label, "grips": grips }) } else { json!({ "type": "point", "at": [self.start.x, self.start.y], "labelAt": [self.label_at.x, self.label_at.y], "label": label, "grips": grips }) @@ -364,6 +378,8 @@ impl BparameterM { fn options(&self, i: &Input) -> Option<&'static str> { let opts: &[(&str, &str)] = if self.linear { &[("Name", "N"), ("Label", "L"), ("Chain", "C"), ("Description", "D"), ("Base", "B"), ("Palette", "P"), ("Value set", "V")] + } else if self.visibility { + &[("Name", "N"), ("Label", "L"), ("Description", "D"), ("Palette", "P")] } else { &[("Name", "N"), ("Label", "L"), ("Chain", "C"), ("Description", "D"), ("Palette", "P")] }; @@ -384,8 +400,11 @@ impl Interactive for BparameterM { PStage::End => Prompt::new("Specify endpoint", Accept::POINT).base(self.start), PStage::LinearLabel | PStage::PointLabel => Prompt::new("Specify label location", Accept::POINT), PStage::LinearGrips => Prompt::new("Enter number of grips", KW).kw(&["0", "1", "2"]).default("2"), + PStage::Location if self.visibility => { + Prompt::new("Specify parameter location", Accept::POINT).kw(&["Name", "Label", "Description", "Palette"]) + } PStage::Location => Prompt::new("Specify parameter location", Accept::POINT).kw(&["Name", "Label", "Chain", "Description", "Palette"]), - PStage::PointGrips => Prompt::new("Enter number of grips", KW).kw(&["0", "1"]).default("1"), + PStage::PointGrips | PStage::VisibilityGrips => Prompt::new("Enter number of grips", KW).kw(&["0", "1"]).default("1"), PStage::Label(what) => Prompt::new(format!("Enter {what} property label"), Accept::TEXT), } } @@ -399,6 +418,7 @@ impl Interactive for BparameterM { match keyword(t, TYPES) { Some("Linear") => (self.linear, self.stage) = (true, PStage::Start), Some("pOint") => (self.linear, self.stage) = (false, PStage::Location), + Some("Visibility") => (self.visibility, self.stage) = (true, PStage::Location), Some(other) => return Err(EngineError::Other(format!("{other} parameters are not available yet."))), None => s.echo("Invalid option keyword."), } @@ -406,9 +426,23 @@ impl Interactive for BparameterM { PStage::Start | PStage::Location => match (&i, self.options(&i)) { (Input::Point(p), _) => { self.start = *p; - self.stage = if self.linear { PStage::End } else { PStage::PointLabel }; + self.stage = if self.linear { + PStage::End + } else if self.visibility { + PStage::VisibilityGrips + } else { + PStage::PointLabel + }; + } + (_, Some("Label")) => { + self.stage = PStage::Label(if self.linear { + "distance" + } else if self.visibility { + "visibility" + } else { + "position" + }) } - (_, Some("Label")) => self.stage = PStage::Label(if self.linear { "distance" } else { "position" }), (_, Some(other)) => return not_yet(s, other), _ => {} }, @@ -428,7 +462,7 @@ impl Interactive for BparameterM { self.stage = if self.stage == PStage::LinearLabel { PStage::LinearGrips } else { PStage::PointGrips }; } } - PStage::LinearGrips | PStage::PointGrips => { + PStage::LinearGrips | PStage::PointGrips | PStage::VisibilityGrips => { let most = if self.stage == PStage::LinearGrips { 2 } else { 1 }; let grips = match &i { Input::Enter => Some(most), diff --git a/crates/engine/src/cmd/blocks/bedit.rs b/crates/engine/src/cmd/blocks/bedit.rs index dcce630039..1557cc8e30 100644 --- a/crates/engine/src/cmd/blocks/bedit.rs +++ b/crates/engine/src/cmd/blocks/bedit.rs @@ -145,7 +145,8 @@ fn open(s: &mut Session, name: &str, create: bool, save: Option) -> Result /// [`open`] with the Block Editor closed. fn open_closed(s: &mut Session, name: &str, create: bool) -> Result { let new = create && !name.eq_ignore_ascii_case(crate::blockedit::CURRENT_DRAWING) && s.doc()?.block(name).is_none(); - s.state_mut()?.open_block_editor(name, create)?; + let bvmode = s.settings.bvmode; + s.state_mut()?.open_block_editor_with(name, create, bvmode)?; let name = s.state()?.block_editor().unwrap_or(name).to_string(); // The block's objects with room around them (and the editor's bar above them). s.zoom_extents()?; @@ -159,7 +160,7 @@ fn open_closed(s: &mut Session, name: &str, create: bool) -> Result { let dynamic = |be: &crate::blockedit::BlockEdit| crate::blockedit::has_dynamic_data(&be.host.doc, if be.current { "*Model_Space" } else { &be.name }); if s.state().is_ok_and(|st| st.block_edit.as_ref().is_some_and(dynamic)) { - s.echo("This is a dynamic block: BPARAMETER and BACTION add linear and point parameters with stretch and move actions; its other parameters and actions are kept as they are."); + s.echo("This is a dynamic block: BPARAMETER and BACTION add linear, point and visibility parameters with stretch and move actions, BVSTATE, BVHIDE and BVSHOW edit visibility states; its other parameters and actions are kept as they are."); } Ok(json!({ "block": name, "new": new })) } diff --git a/crates/engine/src/cmd/blocks/bvstate.rs b/crates/engine/src/cmd/blocks/bvstate.rs new file mode 100644 index 0000000000..bf3a5d573c --- /dev/null +++ b/crates/engine/src/cmd/blocks/bvstate.rs @@ -0,0 +1,478 @@ +//! BVSTATE, BVHIDE and BVSHOW: the visibility states of a dynamic block in the Block Editor. +//! A block's visibility parameter (BPARAMETER Visibility) names sets of its objects; a reference +//! shows one set at a time. The editor shows one state, hiding the objects that state hides; +//! BVSTATE makes, picks and deletes states, BVHIDE and BVSHOW change what a state shows. As in +//! AutoCAD, an object drawn in the editor shows in the state the editor shows only, and so do the +//! grips of a parameter added there. + +use cadcraft_doc::Handle; +use cadcraft_doc::dynblock::{ParameterKind, VisibilityState, adopt_objects, dynamic_block, parameter_objects, set_visibility}; +use serde_json::{Value, json}; + +use crate::cmd::curves::{KW, handle_value}; +use crate::cmd::machines::{SelOutcome, SelectPhase}; +use crate::cmd::{CommandSpec, bad, str_param}; +use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; + +pub(super) fn specs() -> Vec { + vec![ + CommandSpec::new("bvstate", "Visibility States", run_bvstate) + .alias(&["-bvstate"]) + .params( + "{new?: name, visibility?: \"hide\"|\"show\"|\"current\" (what the new state shows: nothing, every object, or what the current state shows; default current) | set?: name (the state the editor shows) | delete?: name or [names] | rename?: name, to: new name} → {current, states} (no option: just the list)", + ) + .enabled(visibility_editing) + .interactive(|_| Ok(Box::new(BvstateM::default()))), + CommandSpec::new("bvhide", "Make Invisible", |s, p| run_hide_show(s, p, false)) + .params("{handles?: [objects] (default the selection), all?: bool (in every state; default the current one)} → {current, hidden}") + .enabled(visibility_editing) + .interactive(|_| Ok(Box::new(BvhideM::new(false)))), + CommandSpec::new("bvshow", "Make Visible", |s, p| run_hide_show(s, p, true)) + .params("{handles?: [objects] (default the selection), all?: bool (in every state; default the current one)} → {current, shown}") + .enabled(visibility_editing) + .interactive(|_| Ok(Box::new(BvhideM::new(true)))), + ] +} + +/// The Block Editor is open on a block (visibility states belong to a block). +fn visibility_editing(s: &Session) -> std::result::Result<(), String> { + match s.state() { + Ok(st) => match &st.block_edit { + Some(be) if be.current => Err("Visibility states belong to a block; this editor is open on the drawing itself.".into()), + Some(_) => Ok(()), + None => Err("Open a block in the Block Editor first (BEDIT).".into()), + }, + Err(e) => Err(e.to_string()), + } +} + +/// The edited block's visibility parameter: the block, the objects it controls, its states and +/// the index of the one the editor shows. Objects drawn in the editor since are adopted first. +struct Vis { + block: String, + controlled: Vec, + states: Vec, + current: usize, +} + +fn read(s: &mut Session) -> Result { + visibility_editing(s).map_err(EngineError::Other)?; + let (block, shown) = { + let be = s.state()?.block_edit.as_ref().ok_or_else(|| EngineError::Other("The Block Editor is not open.".into()))?; + (be.name.clone(), be.visibility.clone()) + }; + let objects: Vec = s.doc()?.model.iter().map(|e| e.handle).collect(); + let none = || EngineError::Other("The block has no visibility parameter; add one first (BPARAMETER Visibility).".into()); + // A doc change only when there is something to adopt. + let mut d = s.doc()?.clone(); + adopt_objects(&mut d, &block, &objects, shown.as_deref()).map_err(EngineError::Other)?; + if !std::sync::Arc::ptr_eq(&d.foreign, &s.doc()?.foreign) { + *s.doc_mut()? = d; + } + let m = dynamic_block(s.doc()?, &block).ok_or_else(none)?; + let (controlled, states) = m + .parameters + .into_iter() + .find_map(|p| match p.kind { + ParameterKind::Visibility { controlled, states, .. } => Some((controlled, states)), + _ => None, + }) + .ok_or_else(none)?; + let current = shown.as_deref().and_then(|v| states.iter().position(|s| s.name.eq_ignore_ascii_case(v))).unwrap_or(0); + Ok(Vis { block, controlled, states, current }) +} + +impl Vis { + fn current_name(&self) -> String { + self.states.get(self.current).map(|s| s.name.clone()).unwrap_or_default() + } + + fn find(&self, name: &str) -> Option { + self.states.iter().position(|s| s.name.eq_ignore_ascii_case(name.trim())) + } + + /// Write the states back and show the current one in the editor. + fn write(self, s: &mut Session) -> Result { + set_visibility(s.doc_mut()?, &self.block, &self.controlled, &self.states).map_err(EngineError::Other)?; + let current = self.current_name(); + show(s, Some(current.clone()))?; + Ok(self.summary(current)) + } + + fn summary(&self, current: String) -> Value { + json!({ "current": current, "states": self.states.iter().map(|s| s.name.clone()).collect::>() }) + } +} + +/// Make `state` the one the editor shows and hide what it hides. +fn show(s: &mut Session, state: Option) -> Result<()> { + if let Some(be) = s.state_mut()?.block_edit.as_mut() { + be.visibility = state; + } + s.refresh_block_visibility() +} + +/// A parameter just added (graph id `node`) to the edited block: active in the state the editor +/// shows only, as AutoCAD adds it, so references show its grips in that state. +pub(super) fn parameter_added(s: &mut Session, node: i32) -> Result<()> { + let Ok(mut v) = read(s) else { return Ok(()) }; + let Some(m) = dynamic_block(s.doc()?, &v.block) else { return Ok(()) }; + let added = parameter_objects(&m, Some(node)); + if added.is_empty() { + return Ok(()); + } + if let Some(state) = v.states.get_mut(v.current) { + let new: Vec = added.into_iter().filter(|h| !state.active.contains(h)).collect(); + state.active.extend(new); + } + v.write(s).map(|_| ()) +} + +/// What a new state shows. +#[derive(Clone, Copy, Debug, PartialEq)] +enum NewShows { + Nothing, + Everything, + Current, +} + +fn new_state(s: &mut Session, name: &str, shows: NewShows) -> Result { + let name = name.trim(); + if name.is_empty() { + return Err(bad("bvstate", "a visibility state needs a name")); + } + let mut v = read(s)?; + if v.find(name).is_some() { + return Err(bad("bvstate", format!("visibility state \"{name}\" already exists"))); + } + let state = match shows { + NewShows::Nothing => VisibilityState { name: name.to_string(), visible: Vec::new(), active: Vec::new() }, + NewShows::Everything => { + let active = dynamic_block(s.doc()?, &v.block).map(|m| parameter_objects(&m, None)).unwrap_or_default(); + VisibilityState { name: name.to_string(), visible: v.controlled.clone(), active } + } + NewShows::Current => VisibilityState { name: name.to_string(), ..v.states.get(v.current).cloned().unwrap_or_default() }, + }; + v.states.push(state); + // The new state is the one the editor shows. + v.current = v.states.len().saturating_sub(1); + v.write(s) +} + +fn set_state(s: &mut Session, name: &str) -> Result { + let mut v = read(s)?; + v.current = v.find(name).ok_or_else(|| bad("bvstate", format!("no visibility state \"{}\"", name.trim())))?; + v.write(s) +} + +fn delete_states(s: &mut Session, names: &[String]) -> Result { + let mut v = read(s)?; + let shown = v.current_name(); + for n in names { + if v.find(n).is_none() { + return Err(bad("bvstate", format!("no visibility state \"{}\"", n.trim()))); + } + } + v.states.retain(|st| !names.iter().any(|n| n.trim().eq_ignore_ascii_case(&st.name))); + if v.states.is_empty() { + return Err(bad("bvstate", "a block keeps at least one visibility state")); + } + // The editor keeps the state it showed, else shows the first. + v.current = v.find(&shown).unwrap_or(0); + v.write(s) +} + +fn rename_state(s: &mut Session, from: &str, to: &str) -> Result { + let to = to.trim(); + if to.is_empty() { + return Err(bad("bvstate", "`to`: the state's new name")); + } + let mut v = read(s)?; + let i = v.find(from).ok_or_else(|| bad("bvstate", format!("no visibility state \"{}\"", from.trim())))?; + if v.find(to).is_some_and(|j| j != i) { + return Err(bad("bvstate", format!("visibility state \"{to}\" already exists"))); + } + if let Some(st) = v.states.get_mut(i) { + st.name = to.to_string(); + } + v.write(s) +} + +fn run_bvstate(s: &mut Session, p: &Value) -> Result { + if let Some(name) = str_param(p, "new") { + let shows = match str_param(p, "visibility").map(|t| t.trim().to_ascii_lowercase()).as_deref() { + None | Some("current") => NewShows::Current, + Some("hide") | Some("hideall") | Some("hide all") => NewShows::Nothing, + Some("show") | Some("showall") | Some("show all") => NewShows::Everything, + Some(o) => return Err(bad("bvstate", format!("`visibility` is \"hide\", \"show\" or \"current\", not \"{o}\""))), + }; + return new_state(s, name, shows); + } + if let Some(name) = str_param(p, "set") { + return set_state(s, name); + } + if let Some(from) = str_param(p, "rename") { + let to = str_param(p, "to").ok_or_else(|| bad("bvstate", "`to`: the state's new name"))?; + return rename_state(s, from, to); + } + match p.get("delete") { + Some(Value::String(n)) => return delete_states(s, std::slice::from_ref(n)), + Some(Value::Array(a)) => { + let names: Vec = a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect(); + if names.len() != a.len() || names.is_empty() { + return Err(bad("bvstate", "`delete` is a state name or a list of names")); + } + return delete_states(s, &names); + } + Some(_) => return Err(bad("bvstate", "`delete` is a state name or a list of names")), + None => {} + } + let v = read(s)?; + let current = v.current_name(); + Ok(v.summary(current)) +} + +/// BVHIDE (`visible` false) or BVSHOW: `handles` in the current state, or in every state. +fn hide_show(s: &mut Session, handles: &[Handle], all: bool, visible: bool) -> Result { + let cmd = if visible { "bvshow" } else { "bvhide" }; + if handles.is_empty() { + return Err(bad(cmd, "`handles`: the objects to change")); + } + if handles.len() > cadcraft_doc::dynblock::MAX_ACTION_ITEMS { + return Err(bad(cmd, "too many objects")); + } + let missing: Vec = handles.iter().filter(|h| s.doc().ok().and_then(|d| d.model.get(**h)).is_none()).map(|h| h.hex()).collect(); + if !missing.is_empty() { + return Err(bad(cmd, format!("no such object in the block: {}", missing.join(", ")))); + } + let mut v = read(s)?; + let current = v.current; + for (i, st) in v.states.iter_mut().enumerate() { + if !all && i != current { + continue; + } + if visible { + let new: Vec = handles.iter().filter(|h| !st.visible.contains(h)).copied().collect(); + st.visible.extend(new); + } else { + st.visible.retain(|h| !handles.contains(h)); + } + } + let n = handles.len(); + // A hidden object can't stay selected; nothing is selected afterwards. + s.set_selection(Vec::new()); + let mut out = v.write(s)?; + out[if visible { "shown" } else { "hidden" }] = json!(n); + Ok(out) +} + +fn run_hide_show(s: &mut Session, p: &Value, visible: bool) -> Result { + let cmd = if visible { "bvshow" } else { "bvhide" }; + let handles: Vec = match p.get("handles") { + Some(Value::Array(a)) => { + a.iter().map(|v| handle_value(v).ok_or_else(|| bad(cmd, format!("{v} is not an object handle")))).collect::>()? + } + Some(_) => return Err(bad(cmd, "`handles` is an array of object handles")), + None => s.selection(), + }; + let all = match p.get("all") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad(cmd, "`all` is true or false")), + }; + hide_show(s, &handles, all, visible) +} + +/// Read keyword input: `text` (any case, an optional leading `_`) against `options`, each +/// (keyword, its shortcut). +fn keyword<'a>(text: &str, options: &[(&'a str, &str)]) -> Option<&'a str> { + let t = text.trim(); + let t = t.strip_prefix('_').unwrap_or(t); + options.iter().find(|(k, short)| t.eq_ignore_ascii_case(k) || t.eq_ignore_ascii_case(short)).map(|(k, _)| *k) +} + +fn text_of(i: &Input) -> Option<&str> { + match i { + Input::Keyword(t) | Input::Text(t) => Some(t.as_str()), + _ => None, + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum VStage { + #[default] + Option, + NewName, + NewShows, + Set, + Delete, +} + +/// -BVSTATE's prompts, as AutoCAD asks them on the command line (BVSTATE's dialog isn't here +/// yet, so BVSTATE asks the same). +#[derive(Default)] +struct BvstateM { + stage: VStage, + name: String, +} + +const NEW_SHOWS: &[(&str, &str)] = &[("Hide all", "H"), ("Show all", "S"), ("Current visibility", "C")]; + +impl Interactive for BvstateM { + fn name(&self) -> &'static str { + "BVSTATE" + } + fn begin(&mut self, s: &mut Session) -> Result { + let v = read(s)?; + s.echo(format!("Current visibility state: {}", v.current_name())); + Ok(Step::Continue) + } + fn prompt(&self, _s: &Session) -> Prompt { + match self.stage { + VStage::Option => Prompt::new("Enter an option", KW).kw(&["New", "Set", "Delete"]).default("New"), + VStage::NewName => Prompt::new("Enter name of new visibility state", Accept::TEXT), + VStage::NewShows => Prompt::new("Enter object visibility for new state", KW) + .kw(&["Hide all", "Show all", "Current visibility"]) + .default("Current visibility"), + VStage::Set => Prompt::new("Enter visibility state name to make current or", Accept::TEXT).kw(&["?"]), + VStage::Delete => Prompt::new("Enter visibility state name(s) to delete", Accept::TEXT), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if matches!(i, Input::Cancel) { + return Ok(Step::Cancel); + } + match self.stage { + VStage::Option => { + let choice = match &i { + Input::Enter => Some("New"), + _ => text_of(&i).and_then(|t| keyword(t, &[("New", "N"), ("Set", "S"), ("Delete", "D")])), + }; + match choice { + Some("New") => self.stage = VStage::NewName, + Some("Set") => self.stage = VStage::Set, + Some(_) => self.stage = VStage::Delete, + None => s.echo("Invalid option keyword."), + } + } + VStage::NewName => { + let Some(t) = text_of(&i).map(str::trim).filter(|t| !t.is_empty()) else { + return Ok(Step::Cancel); + }; + let exists = read(s)?.find(t).is_some(); + if exists { + s.echo(format!("Visibility state \"{t}\" already exists.")); + } else { + self.name = t.to_string(); + self.stage = VStage::NewShows; + } + } + VStage::NewShows => { + let shows = match &i { + Input::Enter => Some(NewShows::Current), + _ => text_of(&i).and_then(|t| keyword(t, NEW_SHOWS)).map(|k| match k { + "Hide all" => NewShows::Nothing, + "Show all" => NewShows::Everything, + _ => NewShows::Current, + }), + }; + match shows { + Some(shows) => return new_state(s, &self.name, shows).map(|_| Step::Done), + None => s.echo("Invalid option keyword."), + } + } + VStage::Set => match text_of(&i).map(str::trim) { + Some("?") => { + let v = read(s)?; + for st in &v.states { + s.echo(format!(" {}", st.name)); + } + } + Some(t) if !t.is_empty() => { + if read(s)?.find(t).is_some() { + return set_state(s, t).map(|_| Step::Done); + } + s.echo(format!("Visibility state \"{t}\" not found.")); + } + _ => return Ok(Step::Cancel), + }, + VStage::Delete => { + let Some(t) = text_of(&i).map(str::trim).filter(|t| !t.is_empty()) else { + return Ok(Step::Cancel); + }; + let names: Vec = t.split(',').map(|n| n.trim().to_string()).filter(|n| !n.is_empty()).collect(); + match delete_states(s, &names) { + Ok(_) => return Ok(Step::Done), + Err(e) => s.echo(e.to_string()), + } + } + } + Ok(Step::Continue) + } +} + +/// BVHIDE's or BVSHOW's prompts, as AutoCAD asks them. +struct BvhideM { + show: bool, + select: SelectPhase, + picked: Vec, + asking: bool, +} + +impl BvhideM { + fn new(show: bool) -> Self { + BvhideM { show, select: SelectPhase::default(), picked: Vec::new(), asking: false } + } +} + +impl Interactive for BvhideM { + fn name(&self) -> &'static str { + if self.show { "BVSHOW" } else { "BVHIDE" } + } + fn begin(&mut self, s: &mut Session) -> Result { + read(s)?; + s.echo(if self.show { "Select objects to make visible:" } else { "Select objects to hide:" }); + self.select = SelectPhase::begin(s); + if self.select.done { + self.picked = self.select.picked.clone(); + self.asking = true; + } + Ok(Step::Continue) + } + fn prompt(&self, _s: &Session) -> Prompt { + if self.asking { + let msg = + if self.show { "Make visible for current state or all visibility states" } else { "Hide for current state or all visibility states" }; + Prompt::new(msg, KW).kw(&["Current", "All"]).default("Current") + } else { + self.select.prompt() + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if matches!(i, Input::Cancel) { + return Ok(Step::Cancel); + } + if !self.asking { + match self.select.feed(s, &i)? { + SelOutcome::More => {} + SelOutcome::Empty => return Ok(Step::Done), + SelOutcome::Done(hs) => { + self.picked = hs; + self.asking = true; + } + } + return Ok(Step::Continue); + } + let all = match &i { + Input::Enter => Some(false), + _ => text_of(&i).and_then(|t| keyword(t, &[("Current", "C"), ("All", "A")])).map(|k| k == "All"), + }; + match all { + Some(all) => hide_show(s, &self.picked, all, self.show).map(|_| Step::Done), + None => { + s.echo("Invalid option keyword."); + Ok(Step::Continue) + } + } + } +} diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rs index 32507162ff..abe09c2c3e 100644 --- a/crates/engine/src/settings.rs +++ b/crates/engine/src/settings.rs @@ -71,6 +71,9 @@ pub struct Settings { /// FILEDIA: kept for routines that switch file dialogs off around a script; no command reads it yet. pub filedia: bool, pub pickadd: bool, + /// BVMODE: objects the Block Editor's visibility state hides are hidden (false, 0) or shown + /// dimmed and can be picked (true, 1), as BVSHOW needs them. + pub bvmode: bool, /// PICKDRAG: false = two-click windows (0), true = clicks or dragging (2). /// Drag-only mode (1) is not supported yet. pub pickdrag: bool, @@ -165,6 +168,7 @@ impl Default for Settings { cmdecho: true, filedia: true, pickadd: true, + bvmode: false, pickdrag: true, pickstyle: 1, gripsize: 5.0, diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index 945a694bce..45b3102241 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -38,6 +38,7 @@ const SESSION_VARS: &[&str] = &[ "PLOTTRANSPARENCYOVERRIDE", "SELECTIONCYCLING", "SELECTSIMILARMODE", + "BVMODE", "OBJECTISOLATIONMODE", "QPMODE", "HIGHLIGHT", @@ -135,6 +136,7 @@ pub fn get(s: &Session, name: &str) -> Option { "CMDECHO" => json!(i32::from(st.cmdecho)), "FILEDIA" => json!(i32::from(st.filedia)), "PICKADD" => json!(i32::from(st.pickadd)), + "BVMODE" => json!(i32::from(st.bvmode)), "PICKDRAG" => json!(i32::from(st.pickdrag) * 2), "PICKSTYLE" => json!(st.pickstyle), "GRIPSIZE" => json!(st.gripsize), @@ -353,6 +355,10 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> { "CMDECHO" => st.cmdecho = small(v, 1).ok_or_else(bad)? == 1, "FILEDIA" => st.filedia = small(v, 1).ok_or_else(bad)? == 1, "PICKADD" => st.pickadd = as_bool(v).ok_or_else(bad)?, + "BVMODE" => { + st.bvmode = as_bool(v).ok_or_else(bad)?; + s.refresh_block_visibility()?; + } "PICKDRAG" => st.pickdrag = as_i(v).filter(|b| matches!(b, 0 | 2)).map(|b| b == 2).ok_or_else(bad)?, "PICKSTYLE" => st.pickstyle = as_i(v).filter(|b| (0..=3).contains(b)).and_then(|b| u8::try_from(b).ok()).ok_or_else(bad)?, "GRIPSIZE" => st.gripsize = as_f64(v).ok_or_else(bad)?.clamp(1.0, 255.0), diff --git a/crates/engine/tests/block_authoring.rs b/crates/engine/tests/block_authoring.rs index 1775d9cfc6..1fe67a490d 100644 --- a/crates/engine/tests/block_authoring.rs +++ b/crates/engine/tests/block_authoring.rs @@ -1,7 +1,7 @@ //! Authoring dynamic blocks in the Block Editor (BPARAMETER, BACTION): parameters and actions //! added to a block make its references dynamic, here and in files saved for AutoCAD. -use cadcraft_engine::doc::dynblock::{ActionKind, Mark, ParameterKind, dynamic_block}; +use cadcraft_engine::doc::dynblock::{ActionKind, Mark, ParameterKind, dynamic_block, parameter_objects}; use cadcraft_engine::doc::{EntityKind, Handle}; use cadcraft_engine::geom::{Vec2, Vec3}; use cadcraft_engine::{Input, Session}; @@ -194,7 +194,7 @@ fn types_not_available_yet_say_so() { let mut s = Session::new(); boxed(&mut s); s.execute("bedit", &json!({ "name": "Box" })).unwrap(); - for t in ["polar", "xy", "rotation", "flip", "visibility", "lookup", "base", "alignment"] { + for t in ["polar", "xy", "rotation", "flip", "lookup", "base", "alignment"] { let e = s.execute("bparameter", &json!({ "type": t, "start": [0, 0], "end": [1, 0] })).unwrap_err().to_string(); assert!(e.contains("not available yet"), "{t}: {e}"); } @@ -256,3 +256,168 @@ fn hostile_authoring_params_never_panic() { s.input(Input::Cancel).unwrap(); assert_eq!(s.doc().unwrap().foreign, before); } + +/// The edited block's visibility states: (name, visible objects, active parameter objects). +fn states(s: &Session) -> Vec<(String, Vec, Vec)> { + let st = s.state().unwrap(); + let name = st.block_edit.as_ref().map_or("Box".to_string(), |b| b.name.clone()); + let m = dynamic_block(s.doc().unwrap(), &name).unwrap(); + m.parameters + .into_iter() + .find_map(|p| match p.kind { + ParameterKind::Visibility { states, .. } => Some(states.into_iter().map(|s| (s.name, s.visible, s.active)).collect()), + _ => None, + }) + .unwrap() +} + +fn hidden(s: &Session) -> Vec { + s.doc().unwrap().hidden_objects.iter().copied().collect() +} + +/// A parameter's object and its grips' (what a visibility state lists as active). +fn param_objects(s: &Session, node: i32) -> Vec { + parameter_objects(&dynamic_block(s.doc().unwrap(), "Box").unwrap(), Some(node)) +} + +/// The states AutoCAD made in the same steps (recorded with -BVSTATE, BVHIDE and BVSHOW): +/// Hide all hides objects and parameters; Show all shows them all; Current visibility copies; +/// an object drawn or a parameter added shows in the state the editor shows only. +#[test] +fn visibility_states_follow_autocads_rules() { + let mut s = Session::new(); + let (r, c, i) = boxed(&mut s); + let (r, c) = (h(&r), h(&c)); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + assert!(s.execute("bvstate", &json!({})).is_err(), "no visibility parameter yet"); + s.execute("bparameter", &json!({ "type": "linear", "start": [0, -1], "end": [10, -1] })).unwrap(); + let v = s.execute("bparameter", &json!({ "type": "visibility", "at": [0, 6] })).unwrap(); + assert_eq!(v["label"], "Visibility1"); + let linear = param_objects(&s, 1); + assert_eq!(linear.len(), 3, "the parameter and its two grips"); + assert_eq!(states(&s), [("VisibilityState0".to_string(), vec![r, c], linear.clone())]); + + let out = s.execute("bvstate", &json!({ "new": "Hid", "visibility": "hide" })).unwrap(); + assert_eq!(out, json!({ "current": "Hid", "states": ["VisibilityState0", "Hid"] })); + assert_eq!(hidden(&s), [r, c], "the editor shows the new state"); + s.execute("bvshow", &json!({ "handles": [c.hex()] })).unwrap(); + assert_eq!(hidden(&s), [r]); + s.execute("bvstate", &json!({ "new": "Shown", "visibility": "show" })).unwrap(); + s.execute("bvhide", &json!({ "handles": [r.hex()] })).unwrap(); + s.execute("bvstate", &json!({ "new": "Copy" })).unwrap(); + s.execute("bvhide", &json!({ "handles": [c.hex()], "all": true })).unwrap(); + s.execute("bvstate", &json!({ "set": "hid" })).unwrap(); + let p = s.execute("bparameter", &json!({ "type": "point", "at": [2, 2] })).unwrap()["node"].as_i64().unwrap() as i32; + let point = param_objects(&s, p); + let line = s.execute("line", &json!({ "points": [[0, 0], [10, 5]] })).unwrap(); + let line = h(&if line["handle"].is_null() { line["handles"][0].clone() } else { line["handle"].clone() }); + s.execute("bsave", &json!({})).unwrap(); + let want = [ + ("VisibilityState0".to_string(), vec![r], linear.clone()), + ("Hid".to_string(), vec![line], point), + ("Shown".to_string(), vec![], linear.clone()), + ("Copy".to_string(), vec![], linear.clone()), + ]; + assert_eq!(states(&s), want); + + // Rename and delete; the last state stays. + s.execute("bvstate", &json!({ "rename": "Copy", "to": "Spare" })).unwrap(); + let out = s.execute("bvstate", &json!({ "delete": ["Spare", "Shown"] })).unwrap(); + assert_eq!(out, json!({ "current": "Hid", "states": ["VisibilityState0", "Hid"] })); + assert!(s.execute("bvstate", &json!({ "delete": ["VisibilityState0", "Hid"] })).is_err()); + assert!(s.execute("bvstate", &json!({ "new": "hid" })).is_err(), "names are case-insensitive"); + s.execute("bclose", &json!({})).unwrap(); + assert!(s.doc().unwrap().hidden_objects.is_empty(), "the editor's hiding stays in the editor"); + + // A reference shows each state's objects. + s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Visibility1", "value": "Hid" })).unwrap(); + let d = s.doc().unwrap(); + let EntityKind::Insert(ins) = &d.entity(h(&i)).unwrap().kind else { panic!() }; + let shown: Vec = d.block(&ins.block).unwrap().entities.iter().map(|e| e.common.visible).collect(); + assert_eq!(shown, [false, false, true], "only the line drawn in Hid"); +} + +#[test] +fn visibility_commands_ask_as_autocad_does() { + let mut s = Session::new(); + let (r, c, _) = boxed(&mut s); + let (r, c) = (h(&r), h(&c)); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + s.script("BPARAMETER V\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Specify parameter location"); + s.script("0,6\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Enter number of grips"); + s.script("\n").unwrap(); + assert!(s.running.is_none()); + s.script("-BVSTATE\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Enter an option"); + s.script("N\nHid\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Enter object visibility for new state"); + s.script("H\n").unwrap(); + assert!(s.running.is_none()); + assert_eq!(hidden(&s), [r, c]); + s.script("BVSTATE\nS\n?\n").unwrap(); + s.script("VisibilityState0\n").unwrap(); + assert!(s.running.is_none()); + assert!(hidden(&s).is_empty()); + s.script("BVHIDE\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Select objects"); + s.input(Input::Pick(vec![c])).unwrap(); + s.script("\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Hide for current state or all visibility states"); + s.script("A\n").unwrap(); + assert_eq!(hidden(&s), [c]); + // BVMODE 1 leaves hidden objects on the canvas (dimmed there) so BVSHOW can pick them. + s.execute("setvar", &json!({ "name": "BVMODE", "value": 1 })).unwrap(); + assert!(hidden(&s).is_empty()); + s.script("BVSHOW\n").unwrap(); + s.input(Input::Pick(vec![c])).unwrap(); + s.script("\n\n").unwrap(); + assert!(s.running.is_none()); + assert_eq!(s.execute("getvar", &json!({ "name": "BVMODE" })).unwrap()["value"], json!(1)); + s.execute("setvar", &json!({ "name": "BVMODE", "value": 0 })).unwrap(); + assert!(hidden(&s).is_empty(), "the circle shows in the current state again"); + s.script("BVHIDE\n").unwrap(); + s.input(Input::Pick(vec![c])).unwrap(); + s.script("\nA\n").unwrap(); + assert_eq!(hidden(&s), [c]); + s.script("BVSTATE\nD\nHid\n").unwrap(); + assert_eq!(states(&s), [("VisibilityState0".to_string(), vec![r], vec![])]); +} + +#[test] +fn hostile_visibility_params_never_panic() { + let mut s = Session::new(); + let (r, _, _) = boxed(&mut s); + assert!(s.execute("bvhide", &json!({ "handles": [r] })).is_err(), "only in the Block Editor"); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + s.execute("bparameter", &json!({ "type": "visibility", "at": [0, 6] })).unwrap(); + assert!(s.execute("bparameter", &json!({ "type": "visibility", "at": [0, 6] })).is_err(), "one per block"); + let many: Vec = (0..20_001).map(|_| r.clone()).collect(); + for (cmd, p) in [ + ("bvstate", json!(null)), + ("bvstate", json!({ "new": "" })), + ("bvstate", json!({ "new": 5 })), + ("bvstate", json!({ "new": "X", "visibility": "sideways" })), + ("bvstate", json!({ "set": "Nope" })), + ("bvstate", json!({ "delete": 7 })), + ("bvstate", json!({ "delete": [] })), + ("bvstate", json!({ "delete": "Nope" })), + ("bvstate", json!({ "rename": "VisibilityState0" })), + ("bvstate", json!({ "rename": "Nope", "to": "X" })), + ("bvhide", json!({ "handles": [] })), + ("bvhide", json!({ "handles": ["zz"] })), + ("bvhide", json!({ "handles": ["FFFFFF"] })), + ("bvhide", json!({ "handles": many })), + ("bvshow", json!({ "handles": [r], "all": "yes" })), + ("bparameter", json!({ "type": "visibility", "at": [f64::MAX, 0], "grips": 9 })), + ] { + let _ = s.execute(cmd, &p); + } + for i in 0..50 { + s.execute("bvstate", &json!({ "new": format!("S{i}"), "visibility": "show" })).unwrap(); + } + s.script("BVSTATE\nD\n,,,\n").unwrap(); + s.input(Input::Cancel).unwrap(); + assert!(s.running.is_none()); +} diff --git a/crates/io/tests/dynblock_author.rs b/crates/io/tests/dynblock_author.rs index d48b2728ed..7d59984c86 100644 --- a/crates/io/tests/dynblock_author.rs +++ b/crates/io/tests/dynblock_author.rs @@ -5,7 +5,8 @@ //! circle on its right edge) with one reference. use cadcraft_doc::dynblock::{ - ActionKind, ActionSpec, ParamPoint, ParameterKind, ParameterSpec, add_action, add_parameter, dynamic_block, set_property, tag_elements, + ActionKind, ActionSpec, MAX_VISIBILITY_STATES, ParamPoint, ParameterKind, ParameterSpec, VisibilityState, add_action, add_parameter, + dynamic_block, set_property, set_visibility, tag_elements, }; use cadcraft_doc::{Drawing, EntityKind, Handle}; use cadcraft_geom::{Vec2, Vec3}; @@ -344,3 +345,73 @@ fn grip_components_name_their_own_parameter() { assert_eq!(owners, want); assert_eq!((first, second), (1, 5)); } + +/// BOX with a visibility parameter (one grip) over both of its objects. +fn visible() -> (Drawing, i32) { + let mut d = box_drawing(); + let spec = ParameterSpec::Visibility { at: v(0.0, 6.0), label: None, objects: vec![h("30"), h("31")], grips: 1 }; + let p = add_parameter(&mut d, "BOX", &spec).unwrap(); + (d, p) +} + +#[test] +fn an_authored_visibility_parameter_reads_back_and_links_as_autocad_does() { + let (d, p) = visible(); + let m = dynamic_block(&d, "BOX").unwrap(); + let param = &m.parameters[0]; + assert_eq!((p, param.element.as_str(), param.grips.as_slice()), (1, "Visibility State", [2].as_slice())); + let ParameterKind::Visibility { at, label, controlled, states, .. } = ¶m.kind else { panic!("{param:?}") }; + assert_eq!((*at, label.as_str(), controlled.as_slice()), (v(0.0, 6.0), "Visibility1", [h("30"), h("31")].as_slice())); + assert_eq!(states.len(), 1); + assert_eq!((states[0].name.as_str(), states[0].visible.as_slice()), ("VisibilityState0", [h("30"), h("31")].as_slice())); + assert!(states[0].active.is_empty(), "no other parameters to show"); + // AutoCAD's own layout: the grip feeds the parameter first, then the parameter its two + // location components, every edge of kind 1. + let (nodes, edges) = graph(&d); + assert_eq!(nodes, vec![(0, 1, vec![0, 0, 1, 2]), (1, 2, vec![-1, -1, 0, 0]), (2, 3, vec![1, 1, -1, -1]), (3, 4, vec![2, 2, -1, -1])]); + assert_eq!(edges, vec![(1, 1, 0, vec![-1, -1, -1, -1, -1]), (1, 0, 2, vec![-1, -1, -1, 2, -1]), (1, 0, 3, vec![-1, -1, 1, -1, -1])]); + for c in ["BLOCKVISIBILITYPARAMETER", "BLOCKVISIBILITYGRIP"] { + assert!(d.foreign.classes.iter().any(|k| k.iter().any(|t| t.code == 1 && t.value == c)), "class {c}"); + } + let mut again = d.clone(); + let second = ParameterSpec::Visibility { at: v(0.0, 0.0), label: None, objects: Vec::new(), grips: 0 }; + assert!(add_parameter(&mut again, "BOX", &second).is_err(), "one visibility parameter per block"); +} + +#[test] +fn visibility_states_survive_a_save_and_drive_references() { + let (mut d, _) = visible(); + let states = vec![ + VisibilityState { name: "Both".into(), visible: vec![h("30"), h("31")], active: Vec::new() }, + VisibilityState { name: "Circle only".into(), visible: vec![h("31")], active: Vec::new() }, + ]; + set_visibility(&mut d, "BOX", &[h("30"), h("31")], &states).unwrap(); + let again = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + let m = dynamic_block(&again, "BOX").unwrap(); + let ParameterKind::Visibility { states: read, .. } = &m.parameters[0].kind else { panic!() }; + assert_eq!(read, &states); + + set_property(&mut d, h("40"), "Visibility1", "Circle only").unwrap(); + let EntityKind::Insert(i) = &d.entity(h("40")).unwrap().kind else { panic!() }; + let b = d.block(&i.block).unwrap(); + let shown: Vec = b.entities.iter().map(|e| e.common.visible).collect(); + assert_eq!(shown, [false, true], "the rectangle hidden, the circle shown"); +} + +#[test] +fn bad_visibility_states_are_refused() { + let (mut d, _) = visible(); + let st = |n: &str| VisibilityState { name: n.into(), visible: Vec::new(), active: Vec::new() }; + assert!(set_visibility(&mut d, "BOX", &[], &[]).is_err(), "no states"); + assert!(set_visibility(&mut d, "BOX", &[], &[st("A"), st("a")]).is_err(), "names are case-insensitive"); + assert!(set_visibility(&mut d, "BOX", &[], &[st(" ")]).is_err(), "a name"); + assert!(set_visibility(&mut box_drawing(), "BOX", &[], &[st("A")]).is_err(), "no visibility parameter"); + let many: Vec = (0..=MAX_VISIBILITY_STATES).map(|i| st(&i.to_string())).collect(); + assert!(set_visibility(&mut d, "BOX", &[], &many).is_err()); + let before = d.foreign.clone(); + let hostile = ParameterSpec::Visibility { at: v(f64::NAN, 0.0), label: None, objects: Vec::new(), grips: 0 }; + assert!(add_parameter(&mut d, "BOX", &hostile).is_err()); + let hostile = ParameterSpec::Visibility { at: v(0.0, 0.0), label: None, objects: Vec::new(), grips: 2 }; + assert!(add_parameter(&mut box_drawing(), "BOX", &hostile).is_err()); + assert_eq!(d.foreign, before); +} diff --git a/crates/ui-egui/src/canvas/blockedit.rs b/crates/ui-egui/src/canvas/blockedit.rs index 1720ed3757..aa2da87d34 100644 --- a/crates/ui-egui/src/canvas/blockedit.rs +++ b/crates/ui-egui/src/canvas/blockedit.rs @@ -1,12 +1,17 @@ //! The Block Editor on the canvas (BEDIT): a tint over the drawing area so the editor can't be //! mistaken for the drawing, the block's base point marked at the origin, the block's //! parameters and actions (BPARAMETER, BACTION) drawn as the editor shows them, and a bar with -//! the block's name and Save Block, Save Block As and Close Block Editor. +//! the block's name and Save Block, Save Block As and Close Block Editor. A block with visibility +//! states gets the state shown (picked from a list, as AutoCAD's Visibility panel offers it), +//! Visibility States, Make Visible and Make Invisible; with BVMODE 1 the objects the state hides +//! are drawn dimmed. use std::sync::Arc; -use cadcraft_engine::doc::dynblock::Mark; +use cadcraft_engine::doc::Handle; +use cadcraft_engine::doc::dynblock::{Mark, ParameterKind, dynamic_block}; use cadcraft_engine::geom::Vec2; +use cadcraft_render::DisplayList; use egui::{Align2, Color32, FontId, Painter, Pos2, Rect, RichText, Shape, Stroke, vec2}; use serde_json::json; @@ -24,6 +29,59 @@ fn editing(app: &CadApp) -> Option<(String, bool)> { st.block_editor().map(|n| (n.to_string(), st.block_unsaved())) } +/// The edited block's visibility states: their names, the one shown, and what it hides. +#[derive(Clone, Default)] +struct States { + names: Vec, + current: String, + hidden: Vec, +} + +/// [`States`] when the block has a visibility parameter, worked out once per drawing revision +/// and state shown. +fn states(app: &CadApp, ctx: &egui::Context) -> Option> { + type Cache = Option<((u64, u64, Option), Option>)>; + let st = app.session.state().ok()?; + let be = st.block_edit.as_ref()?; + let key = (st.uid, st.revision, be.visibility.clone()); + let cid = egui::Id::unique("cadcraft-block-editor-states"); + if let Some((k, v)) = ctx.data(|d| d.get_temp::(cid)).flatten() + && k == key + { + return v; + } + let names: Option> = dynamic_block(&st.doc, &be.name).and_then(|m| { + m.parameters.into_iter().find_map(|p| match p.kind { + ParameterKind::Visibility { states, .. } => Some(states.into_iter().map(|s| s.name).collect()), + _ => None, + }) + }); + let v = names.zip(be.visibility_state(&st.doc)).map(|(names, (current, hidden))| Arc::new(States { names, current, hidden })); + ctx.data_mut(|d| d.insert_temp::(cid, Some((key, v.clone())))); + v +} + +/// The objects the visibility state hides, dimmed (BVMODE 1 leaves them on the canvas to pick). +fn paint_dimmed(app: &CadApp, ctx: &egui::Context, p: &Painter, xf: &Xf, hidden: &[Handle]) { + type Cache = Option<((u64, u64, usize, i64), Arc)>; + let Ok(st) = app.session.state() else { return }; + let band = xf.scale.max(1e-300).log2().round() as i64; + let key = (st.uid, st.revision, hidden.len(), band); + let cid = egui::Id::unique("cadcraft-block-editor-dimmed"); + let list = match ctx.data(|d| d.get_temp::(cid)).flatten() { + Some((k, l)) if k == key => l, + _ => { + let opts = cadcraft_render::Options { tolerance: 0.5 / xf.scale.max(1e-12), ..Default::default() }; + let l = Arc::new(cadcraft_render::build_entities(&st.doc, hidden.iter().filter_map(|h| st.doc.entity(*h)).map(|e| e.as_ref()), &opts)); + ctx.data_mut(|d| d.insert_temp::(cid, Some((key, l.clone())))); + l + } + }; + // The canvas colour drawn over them, a little wider, fades them toward the background. + let all: Vec = (0..list.prims.len()).collect(); + super::draw_highlight(p, xf, &list, &all, Tokens::get().canvas.gamma_multiply(0.7), super::Look { width: 2.0, dashed: false }); +} + /// Tint the drawing area while the Block Editor is open (under the drawing). pub(super) fn wash(app: &CadApp, p: &egui::Painter, rect: Rect) { if editing(app).is_some() { @@ -44,7 +102,15 @@ pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, p: &egui::Painter, xf p.line_segment([o - vec2(0.0, 12.0), o + vec2(0.0, 12.0)], st); } paint_marks(app, ctx, p, xf); + let vis = states(app, ctx); + if app.session.settings.bvmode + && let Some(v) = &vis + && !v.hidden.is_empty() + { + paint_dimmed(app, ctx, p, xf, &v.hidden); + } let mut action: Option<(&str, bool)> = None; + let mut pick: Option = None; egui::Area::new(id()).order(egui::Order::Foreground).pivot(egui::Align2::CENTER_TOP).fixed_pos(rect.center_top() + vec2(0.0, 8.0)).show( ctx, |ui| { @@ -67,10 +133,32 @@ pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, p: &egui::Painter, xf if ui.button(crate::tl!("Close Block Editor")).clicked() { action = Some(("bclose", true)); } + if let Some(v) = &vis { + ui.separator(); + egui::ComboBox::from_id_salt("cadcraft-block-editor-state").selected_text(v.current.as_str()).show_ui(ui, |ui| { + for n in &v.names { + if ui.selectable_label(*n == v.current, n.as_str()).clicked() && *n != v.current { + pick = Some(n.clone()); + } + } + }); + if ui.button(crate::tl!("Visibility States")).clicked() { + action = Some(("bvstate", true)); + } + if ui.button(crate::tl!("Make Visible")).clicked() { + action = Some(("bvshow", true)); + } + if ui.button(crate::tl!("Make Invisible")).clicked() { + action = Some(("bvhide", true)); + } + } }); }); }, ); + if let Some(n) = pick { + let _ = app.run("bvstate", json!({ "set": n })); + } match action { // Prompting commands start like a menu item; BSAVE needs no answer. Some((id, true)) => app.start(id), @@ -81,12 +169,14 @@ pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, p: &egui::Painter, xf } } -/// The edited block's parameters and actions, worked out once per drawing revision. +/// The edited block's parameters and actions, worked out once per drawing revision and +/// visibility state shown. fn marks(app: &CadApp, ctx: &egui::Context) -> Arc> { - type Cache = Option<((u64, u64), Arc>)>; + type Cache = Option<((u64, u64, Option), Arc>)>; let Ok(st) = app.session.state() else { return Arc::default() }; let Some(be) = &st.block_edit else { return Arc::default() }; - let key = (st.uid, st.revision); + // The visibility state shown decides which parameters show. + let key = (st.uid, st.revision, be.visibility.clone()); let cid = egui::Id::unique("cadcraft-block-editor-marks"); if let Some((k, m)) = ctx.data(|d| d.get_temp::(cid)).flatten() && k == key diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 985ca6a864..8fd0ffa142 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -98,6 +98,9 @@ Block Editor Редактор блоків Parameter Параметр Action Дія + Visibility States Стани видимості + Make Visible Зробити видимим + Make Invisible Зробити невидимим Block Reference Посилання на блок Block... Блок... Blocks Блоки From aa953e5f4a6926e66139b041b0b78ece97f675fd Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 25 Oct 2026 10:28:42 -0600 Subject: [PATCH 11/47] Docs: F3 and the blocks row list visibility authoring Co-Authored-By: Claude Opus 5.5 --- docs/gaps.md | 5 +++-- docs/target-app-parity.md | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index f700a6f785..4a4decd677 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where CADCraft falls short of AutoCAD -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (BEDIT in the Block Editor switches blocks; dynamic-block authoring started: BPARAMETER linear/point, BACTION stretch/move; F3 updated) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (BEDIT in the Block Editor switches blocks; dynamic-block authoring started: BPARAMETER linear/point, BACTION stretch/move; visibility parameters and states, BVSTATE, BVHIDE, BVSHOW, BVMODE; F3 updated) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first), and remove or update a row in the same PR @@ -26,7 +26,7 @@ do them first. |---|---|---|---|---| | F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | | F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | -| F3 | **[alpha blocker]** (dynamic-block authoring is beta) Dynamic-block authoring has started: in the Block Editor, BPARAMETER adds linear and point parameters and BACTION stretch and move actions (AutoCAD's prompts, JSON forms), written so AutoCAD opens the block as a dynamic block (DXF and DWG), and the editor draws them. Missing: the other parameters (polar, XY, rotation, flip, alignment, base point, visibility, lookup) and actions (scale, rotate, flip, array, polar stretch, lookup), visibility states and lookup tables (BVSTATE, BLOOKUPTABLE), selecting and editing parameters and actions in the editor, the Name/Chain/Value set options, Authoring Palettes, BTESTBLOCK. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips); BEDIT (which, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS, BCLOSE and REFEDIT edit block definitions | issue #185 offers help | High: standard libraries are dynamic | 30–50 | +| F3 | **[alpha blocker]** (dynamic-block authoring is beta) Dynamic-block authoring has started: in the Block Editor, BPARAMETER adds linear, point and visibility parameters and BACTION stretch and move actions; BVSTATE (as -BVSTATE: New, Set, Delete; JSON also renames), BVHIDE and BVSHOW edit visibility states, the editor shows the state picked on its bar and hides (BVMODE 0) or dims (BVMODE 1) what it hides (AutoCAD's prompts, JSON forms), all written so AutoCAD opens the block as a dynamic block (DXF and DWG), and the editor draws them. Missing: the other parameters (polar, XY, rotation, flip, alignment, base point, lookup) and actions (scale, rotate, flip, array, polar stretch, lookup), the Visibility States dialog (BVSTATE asks on the command line), lookup tables (BLOOKUPTABLE), selecting and editing parameters and actions in the editor, the Name/Chain/Value set options, Authoring Palettes, BTESTBLOCK. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips); BEDIT (which, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS, BCLOSE and REFEDIT edit block definitions | issue #185 offers help | High: standard libraries are dynamic | 30–50 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | | F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 | @@ -156,6 +156,7 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | | 2026-10-22 | minor | APPLOAD typed or from Tools ▸ Load Application opens a `.lsp` file browser starting in the last-used folder (kept in the preferences); a picked file loads interactively like a typed name (routines that ask for input wait), the web says to drop the file (no file system), and the JSON form `{path}` reads the path as given and returns the commands the file defined, never opening a dialog (#1820): E1 narrowed | +| 2026-10-25 | minor | F3: visibility authoring. BPARAMETER adds a visibility parameter; BVSTATE (New with Hide all / Show all / Current visibility, Set, Delete), BVHIDE and BVSHOW (current or all states) edit its states with AutoCAD's prompts; objects drawn and parameters added show in the state shown, as AutoCAD keeps them; BVMODE; AutoCAD reads the states from DXF and DWG. A grip's location components now name their own parameter (AutoCAD evaluated no parameter of a block with a second one) | | 2026-10-21 | minor | F3: dynamic-block authoring started. In the Block Editor BPARAMETER adds linear and point parameters, BACTION stretch and move actions, with AutoCAD's prompts and JSON forms; AutoCAD opens the result as a dynamic block from DXF and DWG; the editor draws them (40–65 → 30–50 h) | | 2026-10-16 | minor | ALIASEDIT typed or from Tools ▸ Customize opens the Command Aliases dialog (user aliases next to the built-in ones; Add, Edit, Remove; OK, Cancel, Apply), #1381: U12 and E5 narrowed | | 2026-10-16 | minor | MOCORO (Tools ▸ Express Tools ▸ Move/Copy/Rotate): select objects and a base point once, then Move, Copy, Rotate, Scale, Base and Undo until eXit, one undo step; JSON form `{base, ops}`: E3 narrowed | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 22b85689cf..cf38018857 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -154,7 +154,7 @@ presence: an option that prints "not available yet" doesn't count. | Text and MTEXT | 6% | 35% | 30–45 | TrueType, formatting codes, stacking; MTEXT prompt options (#408), indents, tabs, bullets, numbering and columns (#547), annotative scaling (#468); editor is a dialog, not in place; no fields or SPELL (open PR #551), no SHX | [gaps](gaps.md#features) | | Leaders, tables, fields | 4% | 25% | 25–35 | MLEADER options and block content (#408), native MULTILEADER in DXF (#459); tables with cell styles, formulas, breaking and CSV data links (#534); no MLEADEREDIT/ALIGN/COLLECT, no FIELD | [gaps](gaps.md#features) | | Hatch and gradients | 5% | 35% | 15–25 | pick points with islands; 23 patterns of ~85; gradients render flat; origin, gap tolerance, separate hatches, island styles and HATCHEDIT options (#451); Hatch and Gradient / Hatch Edit dialogs (no Preview or Inherit Properties) | [gaps](gaps.md#features) | -| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT; dynamic block references read and edited; dynamic-block authoring started (linear and point parameters, stretch and move actions); no XCLIP, DesignCenter | [gaps](gaps.md#features) | +| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT; dynamic block references read and edited; dynamic-block authoring started (linear, point and visibility parameters, visibility states, stretch and move actions); no XCLIP, DesignCenter | [gaps](gaps.md#features) | | Layouts, viewports, plotting | 9% | 35% | 35–50 | layouts, per-VP layers, page setups, plot styles (CTB/STB), Plot dialog (#160), Plot Preview and PUBLISH (#186), plotter devices (#564), PDF with text, layers and sheets (#567, #571), polygonal/object/clipped viewports (#453), annotative scales (#468); no MVIEW Restore, no system printers | [gaps](gaps.md#features) | | Inquiry and utilities | 4% | 30% | 30–45 | DIST, AREA, ID, LIST, MEASUREGEOM, CAL, FIND, COUNT across layouts, QuickCalc, COMPARE (#563) and COMPAREEXPORT, MASSPROP on regions (#510), autosave/recovery, AUDIT, RECOVER (#406), OPTIONS (#23); no SPELL (open PR #551), ETRANSMIT | [gaps](gaps.md#features) | | Parametric constraints | 2% | 50% | 20–30 | all 12 geometric and the dimensional constraints, own solver; DOF report, G2 Smooth, ellipse/spline/block geometry and CONSTRAINTINFER landed (#546) | [geometry-parity](geometry-parity.md#constraint-solver--50) | @@ -225,6 +225,7 @@ DWG/DXF corpus (files from people who own them); black-box checks in AutoCAD of |---|---|---| | 2026-10-24 | minor | Inquiry and utilities row: COMPAREEXPORT exports a comparison to a new drawing; parity percentages and hours not re-measured | | 2026-10-22 | minor | Draw row: RECTANG gained a centre construction mode (`Center` keyword, `center: true`) beside its corner mode (#1127); parity percentages and hours not re-measured | +| 2026-10-25 | minor | Blocks row evidence: visibility parameters and states authored (BVSTATE, BVHIDE, BVSHOW); percentages and hours not re-measured | | 2026-10-21 | minor | Blocks row evidence: dynamic-block authoring started (BPARAMETER linear/point, BACTION stretch/move); percentages and hours not re-measured | | 2026-10-12 | minor | Hatch row evidence: Hatch and Gradient / Hatch Edit dialogs; percentages and hours not re-measured | | 2026-10-12 | minor | Blocks row evidence: Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); percentages and hours not re-measured | From 9627ade997d53ed1ccc8100234f297d88aa621e7 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 25 Oct 2026 13:11:07 -0600 Subject: [PATCH 12/47] Dynamic blocks: the Visibility States dialog and Object Visibility on the Block Editor's menu BVSTATE typed, or Visibility States on the Block Editor's bar, opens a Visibility States dialog like AutoCAD's: the block's states with the one shown checked, Set current (or double-click), New... (a name and Hide all / Show all / Leave unchanged), Rename in place, Delete (not the state shown), Move Up and Move Down. Changes stay in the dialog until OK, which runs them as one step (`bvstate {ops}`, all or nothing); Cancel changes nothing. -BVSTATE keeps the command-line form, and `bvstate {order}` reorders states. Right-clicking a selection in the Block Editor offers Object Visibility: Hide or Show for the Current State or All States. It is greyed out when the block has no visibility parameter; a submenu none of whose items can run is now greyed out in every menu. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/blocks/bvstate.rs | 86 ++++- crates/engine/tests/block_authoring.rs | 16 +- crates/ui-egui/src/bvstate.rs | 472 ++++++++++++++++++++++++ crates/ui-egui/src/context_menu.rs | 47 ++- crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/i18n/uk.tsv | 19 + crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/src/menus.rs | 24 +- docs/gaps.md | 4 +- 9 files changed, 651 insertions(+), 22 deletions(-) create mode 100644 crates/ui-egui/src/bvstate.rs diff --git a/crates/engine/src/cmd/blocks/bvstate.rs b/crates/engine/src/cmd/blocks/bvstate.rs index bf3a5d573c..a73f4d181d 100644 --- a/crates/engine/src/cmd/blocks/bvstate.rs +++ b/crates/engine/src/cmd/blocks/bvstate.rs @@ -6,7 +6,9 @@ //! grips of a parameter added there. use cadcraft_doc::Handle; -use cadcraft_doc::dynblock::{ParameterKind, VisibilityState, adopt_objects, dynamic_block, parameter_objects, set_visibility}; +use cadcraft_doc::dynblock::{ + MAX_VISIBILITY_STATES, ParameterKind, VisibilityState, adopt_objects, dynamic_block, parameter_objects, set_visibility, +}; use serde_json::{Value, json}; use crate::cmd::curves::{KW, handle_value}; @@ -19,7 +21,7 @@ pub(super) fn specs() -> Vec { CommandSpec::new("bvstate", "Visibility States", run_bvstate) .alias(&["-bvstate"]) .params( - "{new?: name, visibility?: \"hide\"|\"show\"|\"current\" (what the new state shows: nothing, every object, or what the current state shows; default current) | set?: name (the state the editor shows) | delete?: name or [names] | rename?: name, to: new name} → {current, states} (no option: just the list)", + "{new?: name, visibility?: \"hide\"|\"show\"|\"current\" (what the new state shows: nothing, every object, or what the current state shows; default current) | set?: name (the state the editor shows) | delete?: name or [names] | rename?: name, to: new name | order?: [every state's name, in the new order] | ops?: [any of these, run in turn as one step (the Visibility States dialog's OK)]} → {current, states} (no option: just the list)", ) .enabled(visibility_editing) .interactive(|_| Ok(Box::new(BvstateM::default()))), @@ -198,7 +200,71 @@ fn rename_state(s: &mut Session, from: &str, to: &str) -> Result { v.write(s) } +/// Most operations one `ops` list runs. +const MAX_OPS: usize = 1_000; + fn run_bvstate(s: &mut Session, p: &Value) -> Result { + match p.get("ops") { + None | Some(Value::Null) => one_op(s, p), + Some(Value::Array(ops)) if ops.len() <= MAX_OPS => { + if ops.iter().any(|op| !op.is_object() || op.get("ops").is_some()) { + return Err(bad("bvstate", "each of `ops` is one operation: {new}, {set}, {delete}, {rename, to} or {order}")); + } + // All or nothing: a refused operation leaves the states as they were. + let before = s.doc()?.clone(); + let shown = s.state()?.block_edit.as_ref().and_then(|b| b.visibility.clone()); + for op in ops { + if let Err(e) = one_op(s, op) { + *s.doc_mut()? = before; + show(s, shown)?; + return Err(e); + } + } + let v = read(s)?; + let current = v.current_name(); + Ok(v.summary(current)) + } + Some(_) => Err(bad("bvstate", format!("`ops` is a list of at most {MAX_OPS} operations"))), + } +} + +/// Put the states in the order of `names` (every state once). +fn order_states(s: &mut Session, names: &[String]) -> Result { + let mut v = read(s)?; + let shown = v.current_name(); + let mut states = Vec::with_capacity(v.states.len()); + for n in names { + let i = v.find(n).ok_or_else(|| bad("bvstate", format!("no visibility state \"{}\"", n.trim())))?; + if states.iter().any(|st: &VisibilityState| st.name.eq_ignore_ascii_case(n.trim())) { + return Err(bad("bvstate", format!("\"{}\" is listed twice in `order`", n.trim()))); + } + states.push(v.states.get(i).cloned().unwrap_or_default()); + } + if states.len() != v.states.len() { + return Err(bad("bvstate", "`order` lists every visibility state once")); + } + v.states = states; + v.current = v.find(&shown).unwrap_or(0); + v.write(s) +} + +/// A list of names, or one name. +fn names_param(p: &Value, key: &str) -> Result>> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(n)) => Ok(Some(vec![n.clone()])), + Some(Value::Array(a)) if a.len() <= MAX_VISIBILITY_STATES => { + let names: Vec = a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect(); + if names.len() != a.len() || names.is_empty() { + return Err(bad("bvstate", format!("`{key}` is a state name or a list of names"))); + } + Ok(Some(names)) + } + Some(_) => Err(bad("bvstate", format!("`{key}` is a state name or a list of names"))), + } +} + +fn one_op(s: &mut Session, p: &Value) -> Result { if let Some(name) = str_param(p, "new") { let shows = match str_param(p, "visibility").map(|t| t.trim().to_ascii_lowercase()).as_deref() { None | Some("current") => NewShows::Current, @@ -215,17 +281,11 @@ fn run_bvstate(s: &mut Session, p: &Value) -> Result { let to = str_param(p, "to").ok_or_else(|| bad("bvstate", "`to`: the state's new name"))?; return rename_state(s, from, to); } - match p.get("delete") { - Some(Value::String(n)) => return delete_states(s, std::slice::from_ref(n)), - Some(Value::Array(a)) => { - let names: Vec = a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect(); - if names.len() != a.len() || names.is_empty() { - return Err(bad("bvstate", "`delete` is a state name or a list of names")); - } - return delete_states(s, &names); - } - Some(_) => return Err(bad("bvstate", "`delete` is a state name or a list of names")), - None => {} + if let Some(names) = names_param(p, "delete")? { + return delete_states(s, &names); + } + if let Some(names) = names_param(p, "order")? { + return order_states(s, &names); } let v = read(s)?; let current = v.current_name(); diff --git a/crates/engine/tests/block_authoring.rs b/crates/engine/tests/block_authoring.rs index 1fe67a490d..388c222f1a 100644 --- a/crates/engine/tests/block_authoring.rs +++ b/crates/engine/tests/block_authoring.rs @@ -405,6 +405,14 @@ fn hostile_visibility_params_never_panic() { ("bvstate", json!({ "delete": "Nope" })), ("bvstate", json!({ "rename": "VisibilityState0" })), ("bvstate", json!({ "rename": "Nope", "to": "X" })), + ("bvstate", json!({ "ops": 5 })), + ("bvstate", json!({ "ops": [{ "ops": [] }] })), + ("bvstate", json!({ "ops": [7] })), + ("bvstate", json!({ "ops": (0..1_001).map(|_| json!({})).collect::>() })), + ("bvstate", json!({ "order": ["Nope"] })), + ("bvstate", json!({ "order": ["VisibilityState0", "VisibilityState0"] })), + ("bvstate", json!({ "order": [] })), + ("bvstate", json!({ "order": 3 })), ("bvhide", json!({ "handles": [] })), ("bvhide", json!({ "handles": ["zz"] })), ("bvhide", json!({ "handles": ["FFFFFF"] })), @@ -417,7 +425,13 @@ fn hostile_visibility_params_never_panic() { for i in 0..50 { s.execute("bvstate", &json!({ "new": format!("S{i}"), "visibility": "show" })).unwrap(); } - s.script("BVSTATE\nD\n,,,\n").unwrap(); + // Reordering keeps every state and the one shown. + s.execute("bvstate", &json!({ "set": "S3" })).unwrap(); + let mut names: Vec = (0..50).rev().map(|i| format!("S{i}")).collect(); + names.push("VisibilityState0".into()); + let out = s.execute("bvstate", &json!({ "order": names })).unwrap(); + assert_eq!((&out["current"], &out["states"][0], &out["states"][50]), (&json!("S3"), &json!("S49"), &json!("VisibilityState0"))); + s.script("-BVSTATE\nD\n,,,\n").unwrap(); s.input(Input::Cancel).unwrap(); assert!(s.running.is_none()); } diff --git a/crates/ui-egui/src/bvstate.rs b/crates/ui-egui/src/bvstate.rs new file mode 100644 index 0000000000..204a560693 --- /dev/null +++ b/crates/ui-egui/src/bvstate.rs @@ -0,0 +1,472 @@ +//! The Visibility States dialog: BVSTATE typed, or Visibility States on the Block Editor's bar, +//! while the Block Editor is open on a block with a visibility parameter. It lists the block's +//! states with the one the editor shows checked, and makes (New…), renames, deletes, reorders +//! (Move Up, Move Down) and picks (Set current) states, as AutoCAD's dialog does. Changes are +//! kept in the dialog until OK, which runs them as one BVSTATE step (`bvstate {ops}`); Cancel +//! changes nothing. JSON calls and -BVSTATE skip it. + +use cadcraft_engine::doc::dynblock::{ParameterKind, dynamic_block}; +use egui::{RichText, Stroke, vec2}; +use serde_json::{Value, json}; + +use crate::CadApp; +use crate::theme::Tokens; + +/// What a new state shows, as the New Visibility State dialog offers it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum NewShows { + Hide, + Show, + #[default] + Unchanged, +} + +impl NewShows { + fn param(self) -> &'static str { + match self { + NewShows::Hide => "hide", + NewShows::Show => "show", + NewShows::Unchanged => "current", + } + } +} + +/// The New Visibility State dialog's fields. +#[derive(Clone, Debug, Default)] +pub struct NewState { + pub name: String, + pub shows: NewShows, + pub error: Option, +} + +/// The dialog's state while it is open: the states as they will be after OK. +#[derive(Clone, Debug, Default)] +pub struct State { + /// The states, in order. + pub names: Vec, + /// The state the editor will show (checked). + pub current: String, + /// The row picked in the list. + pub selected: usize, + /// The changes made so far, as `bvstate` operations, run in turn on OK. + pub ops: Vec, + /// The row being renamed and the name typed. + pub renaming: Option<(usize, String)>, + /// The New Visibility State dialog, while open. + pub new: Option, + /// Why the last change or OK was refused. + pub error: Option, +} + +impl State { + fn has(&self, name: &str, except: Option) -> bool { + self.names.iter().enumerate().any(|(i, n)| Some(i) != except && n.eq_ignore_ascii_case(name.trim())) + } + + /// A name no state has: "VisibilityState" and the lowest free number. + fn free_name(&self) -> String { + (0..).map(|i| format!("VisibilityState{i}")).find(|n| !self.has(n, None)).unwrap_or_default() + } + + fn set_current(&mut self, i: usize) { + if let Some(n) = self.names.get(i).cloned() + && n != self.current + { + self.ops.push(json!({ "set": n })); + self.current = n; + } + } + + /// Add state `new` (it becomes the one shown, as AutoCAD makes it); `Err` with why not. + fn add(&mut self, new: &NewState) -> Result<(), String> { + let name = new.name.trim(); + if name.is_empty() { + return Err(crate::i18n::t("A visibility state needs a name.").to_string()); + } + if self.has(name, None) { + return Err(format!("{} \"{name}\"", crate::i18n::t("A visibility state already has the name"))); + } + self.ops.push(json!({ "new": name, "visibility": new.shows.param() })); + self.names.push(name.to_string()); + self.current = name.to_string(); + self.selected = self.names.len().saturating_sub(1); + Ok(()) + } + + /// Rename row `i` to `to`; `Err` with why not. + fn rename(&mut self, i: usize, to: &str) -> Result<(), String> { + let to = to.trim(); + let Some(old) = self.names.get(i).cloned() else { return Ok(()) }; + if to == old { + return Ok(()); + } + if to.is_empty() { + return Err(crate::i18n::t("A visibility state needs a name.").to_string()); + } + if self.has(to, Some(i)) { + return Err(format!("{} \"{to}\"", crate::i18n::t("A visibility state already has the name"))); + } + self.ops.push(json!({ "rename": old, "to": to })); + if self.current == old { + self.current = to.to_string(); + } + if let Some(n) = self.names.get_mut(i) { + *n = to.to_string(); + } + Ok(()) + } + + /// Whether row `i` can be deleted: not the state shown, and not the last one. + fn deletable(&self, i: usize) -> bool { + self.names.len() > 1 && self.names.get(i).is_some_and(|n| *n != self.current) + } + + fn delete(&mut self, i: usize) { + if !self.deletable(i) { + return; + } + let n = self.names.remove(i); + self.ops.push(json!({ "delete": n })); + self.selected = self.selected.min(self.names.len().saturating_sub(1)); + } + + /// Move row `i` one place up (`up`) or down. + fn shift(&mut self, i: usize, up: bool) { + let j = if up { i.checked_sub(1) } else { i.checked_add(1).filter(|j| *j < self.names.len()) }; + let Some(j) = j else { return }; + self.names.swap(i, j); + self.selected = j; + self.ops.push(json!({ "order": self.names })); + } +} + +/// The edited block's states and the one the editor shows, when the Block Editor is open on a +/// block with a visibility parameter. +fn current_states(app: &CadApp) -> Option<(Vec, String)> { + let st = app.session.state().ok()?; + let be = st.block_edit.as_ref()?; + let m = dynamic_block(&st.doc, &be.name)?; + let names: Vec = m.parameters.into_iter().find_map(|p| match p.kind { + ParameterKind::Visibility { states, .. } => Some(states.into_iter().map(|s| s.name).collect()), + _ => None, + })?; + let current = be.visibility_state(&st.doc).map(|(n, _)| n).or_else(|| names.first().cloned())?; + Some((names, current)) +} + +/// BVSTATE typed or from the Block Editor's bar without parameters opens the dialog when the +/// edited block has visibility states; otherwise BVSTATE runs and says why it can't. +pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option> { + if id != "bvstate" || !params.is_null() { + return None; + } + let (names, current) = current_states(app)?; + let selected = names.iter().position(|n| *n == current).unwrap_or(0); + app.bvstate = State { names, current, selected, ..State::default() }; + app.ui.dialog = Some("bvstate".into()); + Some(Ok(Value::Null)) +} + +/// The Visibility States window (and New Visibility State over it). +pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { + let t = Tokens::get(); + let (mut ok, mut cancel) = (false, false); + let mut st = std::mem::take(&mut app.bvstate); + let modal = st.new.is_some(); + egui::Window::new(crate::tl!("Visibility States")) + .id(egui::Id::new("Visibility States")) + .open(open) + .collapsible(false) + .resizable(false) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.add_enabled_ui(!modal, |ui| { + ui.label(crate::tl!("Visibility states:")); + ui.horizontal_top(|ui| { + egui::Frame::new().fill(t.field).stroke(Stroke::new(1.0, t.border)).corner_radius(4.0).inner_margin(4.0).show(ui, |ui| { + ui.set_min_size(vec2(300.0, 230.0)); + egui::ScrollArea::vertical().id_salt("bvstate-list").max_height(230.0).min_scrolled_height(230.0).show(ui, |ui| { + ui.set_width(300.0); + list(ui, &mut st); + }); + }); + ui.vertical(|ui| { + let w = vec2(120.0, 0.0); + let i = st.selected; + let is_current = st.names.get(i).is_some_and(|n| *n == st.current); + if ui.add_enabled(!is_current, egui::Button::new(crate::tl!("Set current")).min_size(w)).clicked() { + st.set_current(i); + } + if ui.add(egui::Button::new(crate::tl!("New...")).min_size(w)).clicked() { + st.new = Some(NewState { name: st.free_name(), ..NewState::default() }); + } + if ui.add_enabled(st.renaming.is_none(), egui::Button::new(crate::tl!("Rename")).min_size(w)).clicked() { + st.renaming = st.names.get(i).map(|n| (i, n.clone())); + } + if ui.add_enabled(st.deletable(i), egui::Button::new(crate::tl!("Delete")).min_size(w)).clicked() { + st.delete(i); + } + ui.add_space(18.0); + if ui.add_enabled(i > 0, egui::Button::new(crate::tl!("Move Up")).min_size(w)).clicked() { + st.shift(i, true); + } + if ui.add_enabled(i + 1 < st.names.len(), egui::Button::new(crate::tl!("Move Down")).min_size(w)).clicked() { + st.shift(i, false); + } + }); + }); + if let Some(e) = &st.error { + ui.colored_label(t.warn, e); + } + ui.separator(); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(crate::tl!("Cancel")).clicked() { + cancel = true; + } + if ui.button(crate::tl!("OK")).clicked() { + ok = true; + } + }); + }); + }); + }); + if st.new.is_some() { + new_dialog(ctx, &mut st); + } + if ok { + // A rename still being typed counts. + if let Some((i, to)) = st.renaming.take() + && let Err(e) = st.rename(i, &to) + { + st.error = Some(e); + app.bvstate = st; + return; + } + if !st.ops.is_empty() + && let Err(e) = app.run("bvstate", json!({ "ops": st.ops })) + { + st.error = Some(e); + app.bvstate = st; + return; + } + *open = false; + } + if cancel { + *open = false; + } + app.bvstate = st; +} + +/// The states, the one shown checked; the row being renamed is a text box. +fn list(ui: &mut egui::Ui, st: &mut State) { + let t = Tokens::get(); + ui.with_layout(egui::Layout::top_down_justified(egui::Align::Min), |ui| { + for i in 0..st.names.len() { + let name = st.names.get(i).cloned().unwrap_or_default(); + if let Some((r, typed)) = &mut st.renaming + && *r == i + { + let edit = ui.add(egui::TextEdit::singleline(typed).desired_width(280.0)); + edit.request_focus(); + if ui.input(|k| k.key_pressed(egui::Key::Escape)) { + st.renaming = None; + } else if edit.lost_focus() { + let to = typed.clone(); + st.renaming = None; + st.error = st.rename(i, &to).err(); + } + continue; + } + let check = if name == st.current { "✔ " } else { " " }; + let row = ui.selectable_label(st.selected == i, RichText::new(format!("{check}{name}")).color(t.text)); + if row.clicked() { + st.selected = i; + st.error = None; + } + // Double-click shows that state, as Set current does. + if row.double_clicked() { + st.set_current(i); + } + } + }); +} + +/// The New Visibility State dialog: a name and what the new state shows. +fn new_dialog(ctx: &egui::Context, st: &mut State) { + let Some(mut new) = st.new.take() else { return }; + let t = Tokens::get(); + let (mut ok, mut cancel) = (false, false); + let mut open = true; + egui::Window::new(crate::tl!("New Visibility State")) + .id(egui::Id::new("New Visibility State")) + .open(&mut open) + .collapsible(false) + .resizable(false) + .order(egui::Order::Foreground) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.set_min_width(460.0); + ui.label(crate::tl!("Visibility state name:")); + let edit = ui.add(egui::TextEdit::singleline(&mut new.name).desired_width(460.0)); + if edit.changed() { + new.error = None; + } + if edit.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + ok = true; + } + ui.add_space(6.0); + ui.group(|ui| { + ui.label(crate::tl!("Visibility options for new states")); + ui.radio_value(&mut new.shows, NewShows::Hide, crate::tl!("Hide all existing objects in new state")); + ui.radio_value(&mut new.shows, NewShows::Show, crate::tl!("Show all existing objects in new state")); + ui.radio_value(&mut new.shows, NewShows::Unchanged, crate::tl!("Leave visibility of existing objects unchanged in new state")); + }); + if let Some(e) = &new.error { + ui.colored_label(t.warn, e); + } + ui.separator(); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(crate::tl!("Cancel")).clicked() { + cancel = true; + } + if ui.button(crate::tl!("OK")).clicked() { + ok = true; + } + }); + }); + }); + if ok { + match st.add(&new) { + Ok(()) => return, + Err(e) => new.error = Some(e), + } + } + if cancel || !open { + return; + } + st.new = Some(new); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn state() -> State { + State { names: vec!["A".into(), "B".into(), "C".into()], current: "A".into(), ..State::default() } + } + + #[test] + fn changes_become_bvstate_operations_in_order() { + let mut st = state(); + st.add(&NewState { name: "D".into(), shows: NewShows::Hide, error: None }).unwrap(); + assert_eq!((st.current.as_str(), st.selected), ("D", 3), "a new state is the one shown"); + st.rename(1, "Bee").unwrap(); + st.shift(1, true); + st.delete(2); + st.set_current(0); + assert_eq!(st.names, ["Bee", "A", "D"]); + assert_eq!(st.current, "Bee"); + assert_eq!( + st.ops, + vec![ + json!({ "new": "D", "visibility": "hide" }), + json!({ "rename": "B", "to": "Bee" }), + json!({ "order": ["Bee", "A", "C", "D"] }), + json!({ "delete": "C" }), + json!({ "set": "Bee" }), + ] + ); + } + + /// An app in the Block Editor on block "B" (a rectangle and a circle); with `visibility`, the + /// block has a visibility parameter. Returns (app, rectangle, circle). + fn editing(visibility: bool) -> (CadApp, String, String) { + let mut app = CadApp::new(cadcraft_engine::Session::empty(), crate::Services::default()); + let s = &mut app.session; + s.execute("new", &Value::Null).unwrap(); + let made = |v: Value| if v["handle"].is_null() { v["handles"][0].clone() } else { v["handle"].clone() }; + let r = made(s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 5] })).unwrap()); + let c = made(s.execute("circle", &json!({ "center": [5, 2.5], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [r, c], "keep": "delete" })).unwrap(); + s.execute("bedit", &json!({ "name": "B" })).unwrap(); + if visibility { + s.execute("bparameter", &json!({ "type": "visibility", "at": [0, 6] })).unwrap(); + } + // The editor's objects (the block's, with the block's handles). + let d = app.session.doc().unwrap(); + let of = + |rect: bool| d.model.iter().find(|e| matches!(e.kind, cadcraft_engine::doc::EntityKind::LwPolyline(_)) == rect).unwrap().handle.hex(); + let (r, c) = (of(true), of(false)); + (app, r, c) + } + + /// Object Visibility ▸ in the right-click menu's entries, if there. + fn object_visibility(app: &CadApp) -> Option { + crate::context_menu::entries(app) + .into_iter() + .flatten() + .find(|e| matches!(e, crate::menus::Entry::Sub { label, .. } if label == "Object Visibility")) + } + + #[test] + fn the_shortcut_menu_hides_and_shows_selected_objects() { + let (mut app, _, c) = editing(false); + let h = cadcraft_engine::cmd::curves::handle_value(&json!(c)).unwrap(); + assert!(object_visibility(&app).is_none(), "only with a selection"); + app.session.set_selection(vec![h]); + assert!(!object_visibility(&app).unwrap().enabled(), "greyed out without a visibility parameter"); + app.session.execute("bparameter", &json!({ "type": "visibility", "at": [0, 6] })).unwrap(); + app.session.set_selection(vec![h]); + assert!(object_visibility(&app).unwrap().enabled()); + crate::context_menu::choose(&mut app, "visibility:hide"); + assert!(app.session.doc().unwrap().hidden_objects.contains(&h)); + app.session.execute("setvar", &json!({ "name": "BVMODE", "value": 1 })).unwrap(); + app.session.set_selection(vec![h]); + crate::context_menu::choose(&mut app, "visibility:show-all"); + app.session.execute("setvar", &json!({ "name": "BVMODE", "value": 0 })).unwrap(); + assert!(app.session.doc().unwrap().hidden_objects.is_empty()); + } + + #[test] + fn bvstate_opens_the_dialog_and_ok_applies_its_changes_as_one_step() { + let (mut app, _, _) = editing(false); + assert!(route(&mut app, "bvstate", &Value::Null).is_none(), "no visibility parameter: BVSTATE says why"); + let (mut app, _, _) = editing(true); + assert!(route(&mut app, "bvstate", &json!({ "set": "X" })).is_none(), "JSON calls skip the dialog"); + assert!(route(&mut app, "bvstate", &Value::Null).is_some()); + assert_eq!(app.ui.dialog.as_deref(), Some("bvstate")); + assert_eq!((app.bvstate.names.clone(), app.bvstate.current.clone()), (vec!["VisibilityState0".to_string()], "VisibilityState0".to_string())); + let mut st = app.bvstate.clone(); + st.add(&NewState { name: "Empty".into(), shows: NewShows::Hide, error: None }).unwrap(); + st.rename(0, "Full").unwrap(); + let before = app.session.state().unwrap().undo.len(); + app.run("bvstate", json!({ "ops": st.ops })).unwrap(); + assert_eq!(app.session.state().unwrap().undo.len(), before + 1, "one undo step"); + let out = app.session.execute("bvstate", &json!({})).unwrap(); + assert_eq!(out, json!({ "current": "Empty", "states": ["Full", "Empty"] })); + // A refused operation undoes the ones before it. + let bad = json!({ "ops": [{ "new": "Third" }, { "delete": "Nope" }] }); + assert!(app.run("bvstate", bad).is_err()); + assert_eq!(app.session.execute("bvstate", &json!({})).unwrap()["states"], json!(["Full", "Empty"])); + } + + #[test] + fn refused_changes_say_why_and_change_nothing() { + let mut st = state(); + assert!(st.add(&NewState { name: "b".into(), ..NewState::default() }).is_err(), "names are case-insensitive"); + assert!(st.add(&NewState { name: " ".into(), ..NewState::default() }).is_err()); + assert!(st.rename(0, "c").is_err()); + assert!(!st.deletable(0), "the state shown can't be deleted"); + st.delete(0); + st.shift(0, true); + st.shift(2, false); + st.rename(9, "X").unwrap(); + assert_eq!(st.names, ["A", "B", "C"]); + assert!(st.ops.is_empty()); + assert_eq!(st.free_name(), "VisibilityState0"); + } +} diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index bbaf48df35..65f57434bc 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -1,7 +1,9 @@ //! The canvas's right-click menus, after AutoCAD's shortcut menus: //! //! - **No command running** ([`entries`]): Repeat the last command, Recent Commands, the -//! Clipboard and Isolate; with a selection the editing commands, Draw Order, Group, the edit +//! Clipboard and Isolate; in the Block Editor with a selection, Object Visibility (hide or show +//! the objects in the current or every visibility state; greyed out without a visibility +//! parameter); with a selection the editing commands, Draw Order, Group, the edit //! commands of the selected object type, Select Similar and Deselect All; then Undo/Redo, //! Pan/Zoom, Quick Select, Find, Properties and Options. //! - **While a command runs** ([`command_entries`]): a quick right-click is Enter; holding the @@ -53,6 +55,8 @@ pub const TYPE: &str = "type:"; pub const KEYWORD: &str = "keyword:"; /// An object snap menu item ([`choose_snap`]). pub const SNAP: &str = "snap:"; +/// An Object Visibility item: BVHIDE or BVSHOW on the selection ([`choose_visibility`]). +pub const VISIBILITY: &str = "visibility:"; fn item(app: &CadApp, id: &str, label: Option<&str>) -> Option { let spec = find_command(id)?; @@ -97,6 +101,10 @@ pub fn entries(app: &CadApp) -> Vec> { .collect(); first.extend(sub("Recent Commands", recent)); push(&mut groups, first); + let selected = !app.session.selection().is_empty(); + if selected { + push(&mut groups, visibility_entries(app).into_iter().collect()); + } // In the Block Editor: save the block or go back to the drawing. if app.session.state().is_ok_and(|st| st.block_edit.is_some()) { push(&mut groups, items(app, &["bsave", "bsaveas", "bclose"])); @@ -104,7 +112,6 @@ pub fn entries(app: &CadApp) -> Vec> { let mut clip: Vec = sub("Clipboard", items(app, CLIPBOARD)).into_iter().collect(); clip.extend(sub("Isolate", items(app, ISOLATE))); push(&mut groups, clip); - let selected = !app.session.selection().is_empty(); if selected { let mut edit: Vec = EDIT.iter().filter_map(|(id, label)| item(app, id, *label)).collect(); edit.extend(sub("Draw Order", items(app, DRAW_ORDER))); @@ -121,6 +128,40 @@ pub fn entries(app: &CadApp) -> Vec> { groups } +/// Object Visibility ▸ in the Block Editor (AutoCAD's shortcut menu there): hide or show the +/// selected objects in the current visibility state or all of them. Its items are greyed out when +/// the block has no visibility parameter. +fn visibility_entries(app: &CadApp) -> Option { + use cadcraft_engine::doc::dynblock::{ParameterKind, dynamic_block}; + let st = app.session.state().ok()?; + let be = st.block_edit.as_ref()?; + let has = !be.current + && dynamic_block(&st.doc, &be.name).is_some_and(|m| m.parameters.iter().any(|p| matches!(p.kind, ParameterKind::Visibility { .. }))); + let item = |label: &str, id: &str| Entry::Item { label: label.into(), id: format!("{VISIBILITY}{id}"), shortcut: None, enabled: has }; + Some(Entry::Sub { + label: "Object Visibility".into(), + children: vec![ + item("Hide for Current State", "hide"), + item("Show for Current State", "show"), + item("Hide for All States", "hide-all"), + item("Show for All States", "show-all"), + ], + }) +} + +/// Run an Object Visibility item on the selection. +fn choose_visibility(app: &mut CadApp, what: &str) { + let (cmd, all) = match what { + "hide" => ("bvhide", false), + "show" => ("bvshow", false), + "hide-all" => ("bvhide", true), + "show-all" => ("bvshow", true), + _ => return, + }; + let handles: Vec = app.session.selection().iter().map(|h| h.hex()).collect(); + let _ = app.run(cmd, serde_json::json!({ "handles": handles, "all": all })); +} + /// The edit commands of the selected objects' type (when they are all of one type), with their /// labels: Edit Text for text, Block Editor and Edit Attributes for block references, Hatch Edit, /// Polyline Edit, Spline Edit… @@ -213,6 +254,8 @@ pub fn choose(app: &mut CadApp, id: &str) { } } else if let Some(s) = id.strip_prefix(SNAP) { choose_snap(app, s); + } else if let Some(v) = id.strip_prefix(VISIBILITY) { + choose_visibility(app, v); } else { activate(app, id); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index acdddb5520..46ec8a09f6 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -28,6 +28,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "commands" => commands(app, ctx, &mut open), "blocks" => blocks(app, ctx, &mut open), "bedit" => crate::bedit::dialog(app, ctx, &mut open), + "bvstate" => crate::bvstate::dialog(app, ctx, &mut open), "authoring" => crate::bedit::authoring_dialog(app, ctx, &mut open), "stylesmanager" => crate::plotstyles::dialog(app, ctx, &mut open), o if o == "options" || o.starts_with("options:") => crate::options::dialog(app, ctx, o, &mut open), diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8fd0ffa142..2adef405e4 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -101,6 +101,25 @@ Visibility States Стани видимості Make Visible Зробити видимим Make Invisible Зробити невидимим + Visibility states: Стани видимості: + Set current Зробити поточним + New... Створити... + Rename Перейменувати + Move Up Вгору + Move Down Вниз + New Visibility State Новий стан видимості + Visibility state name: Назва стану видимості: + Visibility options for new states Видимість у новому стані + Hide all existing objects in new state Приховати всі наявні об'єкти в новому стані + Show all existing objects in new state Показати всі наявні об'єкти в новому стані + Leave visibility of existing objects unchanged in new state Залишити видимість наявних об'єктів без змін у новому стані + Object Visibility Видимість об'єктів + Hide for Current State Приховати в поточному стані + Show for Current State Показати в поточному стані + Hide for All States Приховати в усіх станах + Show for All States Показати в усіх станах + A visibility state needs a name. Стан видимості потребує назви. + A visibility state already has the name Уже є стан видимості з назвою Block Reference Посилання на блок Block... Блок... Blocks Блоки diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 22e325cbe2..53cf2b0605 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -12,6 +12,7 @@ pub mod aliasdlg; pub mod animation; pub mod autosave; pub mod bedit; +pub mod bvstate; pub mod canvas; pub mod capture; pub mod chrome; @@ -292,6 +293,8 @@ pub struct CadApp { /// The startup update check and its prompt (desktop; [`updates_ui`]). #[cfg(not(target_arch = "wasm32"))] pub updates_rt: updates_ui::Runtime, + /// The Visibility States dialog ([`bvstate`]). + pub bvstate: bvstate::State, } impl CadApp { @@ -344,6 +347,7 @@ impl CadApp { bedit: bedit::State::default(), #[cfg(not(target_arch = "wasm32"))] updates_rt: updates_ui::Runtime::default(), + bvstate: bvstate::State::default(), } } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 58055542fc..8ea08db1b3 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -95,6 +95,9 @@ fn route_ui_subsystems(app: &mut CadApp, id: &str, params: &Value) -> Option }, } +impl Entry { + /// An item that can run, or a submenu with one. + pub fn enabled(&self) -> bool { + match self { + Entry::Item { enabled, .. } => *enabled, + Entry::Sub { children, .. } => children.iter().any(Entry::enabled), + } + } +} + /// The full menu tree from the command registry plus UI commands, in registration order. pub fn tree(app: &CadApp) -> Vec<(String, Vec)> { let mut out: Vec<(String, Vec)> = MENUS.iter().map(|m| (m.to_string(), Vec::new())).collect(); @@ -652,10 +665,13 @@ pub(crate) fn entry_ui(ui: &mut egui::Ui, e: &Entry, clicked: &mut Option { - ui.menu_button(crate::i18n::menu(label), |ui| { - for c in children { - entry_ui(ui, c, clicked); - } + // A submenu none of whose items can run is greyed out. + ui.add_enabled_ui(children.iter().any(Entry::enabled), |ui| { + ui.menu_button(crate::i18n::menu(label), |ui| { + for c in children { + entry_ui(ui, c, clicked); + } + }); }); } } diff --git a/docs/gaps.md b/docs/gaps.md index 4a4decd677..a40d07cbd5 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -26,7 +26,7 @@ do them first. |---|---|---|---|---| | F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | | F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | -| F3 | **[alpha blocker]** (dynamic-block authoring is beta) Dynamic-block authoring has started: in the Block Editor, BPARAMETER adds linear, point and visibility parameters and BACTION stretch and move actions; BVSTATE (as -BVSTATE: New, Set, Delete; JSON also renames), BVHIDE and BVSHOW edit visibility states, the editor shows the state picked on its bar and hides (BVMODE 0) or dims (BVMODE 1) what it hides (AutoCAD's prompts, JSON forms), all written so AutoCAD opens the block as a dynamic block (DXF and DWG), and the editor draws them. Missing: the other parameters (polar, XY, rotation, flip, alignment, base point, lookup) and actions (scale, rotate, flip, array, polar stretch, lookup), the Visibility States dialog (BVSTATE asks on the command line), lookup tables (BLOOKUPTABLE), selecting and editing parameters and actions in the editor, the Name/Chain/Value set options, Authoring Palettes, BTESTBLOCK. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips); BEDIT (which, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS, BCLOSE and REFEDIT edit block definitions | issue #185 offers help | High: standard libraries are dynamic | 30–50 | +| F3 | **[alpha blocker]** (dynamic-block authoring is beta) Dynamic-block authoring has started: in the Block Editor, BPARAMETER adds linear, point and visibility parameters and BACTION stretch and move actions; BVSTATE (the Visibility States dialog: Set current, New, Rename, Delete, Move Up, Move Down; -BVSTATE: New, Set, Delete), BVHIDE and BVSHOW (also Object Visibility on the editor's right-click menu) edit visibility states, the editor shows the state picked on its bar and hides (BVMODE 0) or dims (BVMODE 1) what it hides (AutoCAD's prompts, JSON forms), all written so AutoCAD opens the block as a dynamic block (DXF and DWG), and the editor draws them. Missing: the other parameters (polar, XY, rotation, flip, alignment, base point, lookup) and actions (scale, rotate, flip, array, polar stretch, lookup), lookup tables (BLOOKUPTABLE), selecting and editing parameters and actions in the editor, the Name/Chain/Value set options, Authoring Palettes, BTESTBLOCK. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips); BEDIT (which, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS, BCLOSE and REFEDIT edit block definitions | issue #185 offers help | High: standard libraries are dynamic | 30–50 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | | F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 | @@ -156,7 +156,7 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | | 2026-10-22 | minor | APPLOAD typed or from Tools ▸ Load Application opens a `.lsp` file browser starting in the last-used folder (kept in the preferences); a picked file loads interactively like a typed name (routines that ask for input wait), the web says to drop the file (no file system), and the JSON form `{path}` reads the path as given and returns the commands the file defined, never opening a dialog (#1820): E1 narrowed | -| 2026-10-25 | minor | F3: visibility authoring. BPARAMETER adds a visibility parameter; BVSTATE (New with Hide all / Show all / Current visibility, Set, Delete), BVHIDE and BVSHOW (current or all states) edit its states with AutoCAD's prompts; objects drawn and parameters added show in the state shown, as AutoCAD keeps them; BVMODE; AutoCAD reads the states from DXF and DWG. A grip's location components now name their own parameter (AutoCAD evaluated no parameter of a block with a second one) | +| 2026-10-25 | minor | F3: visibility authoring. BPARAMETER adds a visibility parameter; BVSTATE (the Visibility States dialog, or -BVSTATE's New with Hide all / Show all / Current visibility, Set, Delete), BVHIDE and BVSHOW (current or all states; also the right-click menu's Object Visibility) edit its states with AutoCAD's prompts; objects drawn and parameters added show in the state shown, as AutoCAD keeps them; BVMODE; AutoCAD reads the states from DXF and DWG. A grip's location components now name their own parameter (AutoCAD evaluated no parameter of a block with a second one) | | 2026-10-21 | minor | F3: dynamic-block authoring started. In the Block Editor BPARAMETER adds linear and point parameters, BACTION stretch and move actions, with AutoCAD's prompts and JSON forms; AutoCAD opens the result as a dynamic block from DXF and DWG; the editor draws them (40–65 → 30–50 h) | | 2026-10-16 | minor | ALIASEDIT typed or from Tools ▸ Customize opens the Command Aliases dialog (user aliases next to the built-in ones; Add, Edit, Remove; OK, Cancel, Apply), #1381: U12 and E5 narrowed | | 2026-10-16 | minor | MOCORO (Tools ▸ Express Tools ▸ Move/Copy/Rotate): select objects and a base point once, then Move, Copy, Rotate, Scale, Base and Undo until eXit, one undo step; JSON form `{base, ops}`: E3 narrowed | From 879689bc0664d65f05a960d5ff8efb0d12795d69 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 25 Oct 2026 13:38:02 -0600 Subject: [PATCH 13/47] Dynamic blocks: a Visibility Mode button in the Block Editor, and BVMODE 1 dims hidden parameters The Block Editor's bar gets Visibility Mode (BVMODE), as AutoCAD's Visibility panel has it: on, the objects the visibility state shown hides are drawn dimmed and can be picked; off, they aren't drawn. With it on, parameters the state leaves out are drawn dimmed too instead of not at all. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/marks.rs | 10 +++++ crates/engine/src/blockedit.rs | 18 ++++----- crates/ui-egui/src/canvas/blockedit.rs | 54 ++++++++++++++++++-------- crates/ui-egui/src/i18n/uk.tsv | 1 + 4 files changed, 57 insertions(+), 26 deletions(-) diff --git a/crates/doc/src/dynblock/marks.rs b/crates/doc/src/dynblock/marks.rs index d969ba0367..b9f3cca5b5 100644 --- a/crates/doc/src/dynblock/marks.rs +++ b/crates/doc/src/dynblock/marks.rs @@ -22,6 +22,16 @@ pub enum Mark { Action { node: i32, at: Vec3, name: String }, } +impl Mark { + /// The graph id of the parameter this marks (`None` for an action). + pub fn parameter_node(&self) -> Option { + match self { + Mark::Linear { node, .. } | Mark::Point { node, .. } | Mark::Parameter { node, .. } => Some(*node), + Mark::Action { .. } => None, + } + } +} + /// Block `name`'s parameters and actions as the Block Editor draws them (empty when it has none). pub fn marks(d: &Drawing, name: &str) -> Vec { let Some(m) = dynamic_block(d, name) else { return Vec::new() }; diff --git a/crates/engine/src/blockedit.rs b/crates/engine/src/blockedit.rs index cfe8bd1919..cc771612ba 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -113,17 +113,17 @@ impl BlockEdit { /// The edited block's parameters and actions as the editor draws them, in the editor's /// coordinates (`editor` is the editor's drawing). pub fn marks(&self, editor: &Drawing) -> Vec { + // Parameters the visibility state shown leaves out aren't drawn, as in AutoCAD. + let inactive = self.inactive_parameters(editor); + self.all_marks(editor).into_iter().filter(|m| m.parameter_node().is_none_or(|n| !inactive.contains(&n))).collect() + } + + /// [`BlockEdit::marks`] with the parameters the visibility state shown leaves out too (BVMODE 1 + /// draws them dimmed; [`BlockEdit::inactive_parameters`] names them). + pub fn all_marks(&self, editor: &Drawing) -> Vec { use cadcraft_doc::dynblock::Mark; let off = self.base.to3(0.0); let mut out = cadcraft_doc::dynblock::marks(editor, &self.name); - // Parameters the visibility state shown leaves out aren't drawn, as in AutoCAD. - let inactive = self.inactive_parameters(editor); - if !inactive.is_empty() { - out.retain(|m| match m { - Mark::Linear { node, .. } | Mark::Point { node, .. } | Mark::Parameter { node, .. } => !inactive.contains(node), - Mark::Action { .. } => true, - }); - } for m in &mut out { match m { Mark::Linear { base, end, .. } => (*base, *end) = (*base - off, *end - off), @@ -150,7 +150,7 @@ impl BlockEdit { /// Graph ids of the parameters the visibility state the editor shows doesn't list as active /// (the visibility parameter itself always shows). - fn inactive_parameters(&self, editor: &Drawing) -> Vec { + pub fn inactive_parameters(&self, editor: &Drawing) -> Vec { use cadcraft_doc::dynblock::ParameterKind; let Some(m) = cadcraft_doc::dynblock::dynamic_block(editor, &self.name) else { return Vec::new() }; let Some(states) = m.parameters.iter().find_map(|p| match &p.kind { diff --git a/crates/ui-egui/src/canvas/blockedit.rs b/crates/ui-egui/src/canvas/blockedit.rs index aa2da87d34..843b52242c 100644 --- a/crates/ui-egui/src/canvas/blockedit.rs +++ b/crates/ui-egui/src/canvas/blockedit.rs @@ -2,8 +2,8 @@ //! mistaken for the drawing, the block's base point marked at the origin, the block's //! parameters and actions (BPARAMETER, BACTION) drawn as the editor shows them, and a bar with //! the block's name and Save Block, Save Block As and Close Block Editor. A block with visibility -//! states gets the state shown (picked from a list, as AutoCAD's Visibility panel offers it), -//! Visibility States, Make Visible and Make Invisible; with BVMODE 1 the objects the state hides +//! states gets Visibility Mode (BVMODE), the state shown (picked from a list, as AutoCAD's +//! Visibility panel offers it), Visibility States, Make Visible and Make Invisible; with BVMODE 1 the objects the state hides //! are drawn dimmed. use std::sync::Arc; @@ -111,6 +111,8 @@ pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, p: &egui::Painter, xf } let mut action: Option<(&str, bool)> = None; let mut pick: Option = None; + let bvmode = app.session.settings.bvmode; + let mut toggle_mode = false; egui::Area::new(id()).order(egui::Order::Foreground).pivot(egui::Align2::CENTER_TOP).fixed_pos(rect.center_top() + vec2(0.0, 8.0)).show( ctx, |ui| { @@ -135,6 +137,14 @@ pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, p: &egui::Painter, xf } if let Some(v) = &vis { ui.separator(); + // BVMODE: whether objects the state hides show dimmed (on) or not at all. + if ui + .selectable_label(bvmode, crate::tl!("Visibility Mode")) + .on_hover_text(crate::tl!("Show the objects this visibility state hides, dimmed (BVMODE)")) + .clicked() + { + toggle_mode = true; + } egui::ComboBox::from_id_salt("cadcraft-block-editor-state").selected_text(v.current.as_str()).show_ui(ui, |ui| { for n in &v.names { if ui.selectable_label(*n == v.current, n.as_str()).clicked() && *n != v.current { @@ -156,6 +166,9 @@ pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, p: &egui::Painter, xf }); }, ); + if toggle_mode { + let _ = app.run("setvar", json!({ "name": "BVMODE", "value": i32::from(!bvmode) })); + } if let Some(n) = pick { let _ = app.run("bvstate", json!({ "set": n })); } @@ -169,21 +182,22 @@ pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, p: &egui::Painter, xf } } -/// The edited block's parameters and actions, worked out once per drawing revision and -/// visibility state shown. -fn marks(app: &CadApp, ctx: &egui::Context) -> Arc> { - type Cache = Option<((u64, u64, Option), Arc>)>; +/// The edited block's parameters and actions and, with BVMODE 1, the graph ids of the parameters +/// the visibility state shown leaves out (drawn dimmed; without BVMODE they aren't drawn), worked +/// out once per drawing revision, visibility state shown and BVMODE. +fn marks(app: &CadApp, ctx: &egui::Context) -> Arc<(Vec, Vec)> { + type Cache = Option<((u64, u64, Option, bool), Arc<(Vec, Vec)>)>; let Ok(st) = app.session.state() else { return Arc::default() }; let Some(be) = &st.block_edit else { return Arc::default() }; - // The visibility state shown decides which parameters show. - let key = (st.uid, st.revision, be.visibility.clone()); + let bvmode = app.session.settings.bvmode; + let key = (st.uid, st.revision, be.visibility.clone(), bvmode); let cid = egui::Id::unique("cadcraft-block-editor-marks"); if let Some((k, m)) = ctx.data(|d| d.get_temp::(cid)).flatten() && k == key { return m; } - let m = Arc::new(be.marks(&st.doc)); + let m = Arc::new(if bvmode { (be.all_marks(&st.doc), be.inactive_parameters(&st.doc)) } else { (be.marks(&st.doc), Vec::new()) }); ctx.data_mut(|d| d.insert_temp::(cid, Some((key, m.clone())))); m } @@ -200,10 +214,16 @@ fn arrow(p: &Painter, at: Pos2, u: egui::Vec2, color: Color32) { /// name, and actions as badges. fn paint_marks(app: &CadApp, ctx: &egui::Context, p: &Painter, xf: &Xf) { let t = Tokens::get(); - let line = Stroke::new(1.0, t.accent); let font = FontId::proportional(12.0); let to = |v: cadcraft_engine::geom::Vec3| xf.to_screen(v.xy()); - for m in marks(app, ctx).iter() { + let marks = marks(app, ctx); + let (all, inactive) = &*marks; + for m in all { + // A parameter the visibility state leaves out shows dimmed (BVMODE 1). + let dim = m.parameter_node().is_some_and(|n| inactive.contains(&n)); + let fade = |c: Color32| if dim { c.gamma_multiply(0.35) } else { c }; + let (accent, grip_dyn) = (fade(t.accent), fade(t.grip_dyn)); + let line = Stroke::new(1.0, accent); match m { Mark::Linear { base, end, offset, label, base_grip, end_grip, .. } => { let (a, b) = (base.xy(), end.xy()); @@ -217,25 +237,25 @@ fn paint_marks(app: &CadApp, ctx: &egui::Context, p: &Painter, xf: &Xf) { let along = sb - sa; let u = if along.length() > 1e-6 { along / along.length() } else { vec2(1.0, 0.0) }; if *base_grip { - arrow(p, sa, -u, t.grip_dyn); + arrow(p, sa, -u, grip_dyn); } if *end_grip { - arrow(p, sb, u, t.grip_dyn); + arrow(p, sb, u, grip_dyn); } - p.text(da + (db - da) * 0.5, Align2::CENTER_BOTTOM, label, font.clone(), t.accent); + p.text(da + (db - da) * 0.5, Align2::CENTER_BOTTOM, label, font.clone(), accent); } Mark::Point { at, label_at, label, grip, .. } => { let (s, l) = (to(*at), to(*label_at)); p.line_segment([s, l], line); if *grip { - p.rect_filled(Rect::from_center_size(s, vec2(8.0, 8.0)), 0.0, t.grip_dyn); + p.rect_filled(Rect::from_center_size(s, vec2(8.0, 8.0)), 0.0, grip_dyn); } else { p.rect_stroke(Rect::from_center_size(s, vec2(8.0, 8.0)), 0.0, line, egui::StrokeKind::Middle); } - p.text(l, Align2::LEFT_BOTTOM, label, font.clone(), t.accent); + p.text(l, Align2::LEFT_BOTTOM, label, font.clone(), accent); } Mark::Parameter { at, label, .. } => { - p.text(to(*at), Align2::LEFT_BOTTOM, label, font.clone(), t.accent); + p.text(to(*at), Align2::LEFT_BOTTOM, label, font.clone(), accent); } Mark::Action { at, name, .. } => { let c = to(*at); diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 2adef405e4..e6575864ab 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -113,6 +113,7 @@ Hide all existing objects in new state Приховати всі наявні об'єкти в новому стані Show all existing objects in new state Показати всі наявні об'єкти в новому стані Leave visibility of existing objects unchanged in new state Залишити видимість наявних об'єктів без змін у новому стані + Visibility Mode Режим видимості Object Visibility Видимість об'єктів Hide for Current State Приховати в поточному стані Show for Current State Показати в поточному стані From f9743cb51891079ee22557f40b403696727af571 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 25 Oct 2026 13:49:33 -0600 Subject: [PATCH 14/47] Dynamic blocks: the Block Editor draws a visibility or lookup parameter's list grip A visibility or lookup parameter with a grip is drawn as AutoCAD draws it in the Block Editor: a triangle pointing down at the parameter, its label beside it (`Mark::List`). Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/marks.rs | 10 ++++++---- crates/engine/src/blockedit.rs | 2 +- crates/io/tests/dynblock_author.rs | 5 ++++- crates/ui-egui/src/canvas/blockedit.rs | 9 +++++++++ 4 files changed, 20 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/dynblock/marks.rs b/crates/doc/src/dynblock/marks.rs index b9f3cca5b5..62365c57ed 100644 --- a/crates/doc/src/dynblock/marks.rs +++ b/crates/doc/src/dynblock/marks.rs @@ -16,6 +16,9 @@ pub enum Mark { Linear { node: i32, base: Vec3, end: Vec3, offset: f64, label: String, base_grip: bool, end_grip: bool }, /// A point parameter: a marker at `at` and its label at `label_at`. Point { node: i32, at: Vec3, label_at: Vec3, label: String, grip: bool }, + /// A visibility or lookup parameter: a list grip (a triangle pointing down) at `at` when it + /// has one, its label beside it. + List { node: i32, at: Vec3, label: String, grip: bool }, /// Another parameter: its name at `at`. Parameter { node: i32, at: Vec3, label: String }, /// An action: a badge with its name at `at`. @@ -26,7 +29,7 @@ impl Mark { /// The graph id of the parameter this marks (`None` for an action). pub fn parameter_node(&self) -> Option { match self { - Mark::Linear { node, .. } | Mark::Point { node, .. } | Mark::Parameter { node, .. } => Some(*node), + Mark::Linear { node, .. } | Mark::Point { node, .. } | Mark::List { node, .. } | Mark::Parameter { node, .. } => Some(*node), Mark::Action { .. } => None, } } @@ -57,9 +60,8 @@ pub fn marks(d: &Drawing, name: &str) -> Vec { | ParameterKind::Rotation { base, .. } | ParameterKind::Alignment { base, .. } | ParameterKind::Flip { base, .. } => Mark::Parameter { node: p.node, at: *base, label }, - ParameterKind::Visibility { at, .. } | ParameterKind::Lookup { at, .. } | ParameterKind::BasePoint { at } => { - Mark::Parameter { node: p.node, at: *at, label } - } + ParameterKind::Visibility { at, .. } | ParameterKind::Lookup { at, .. } => Mark::List { node: p.node, at: *at, label, grip: grip(0) }, + ParameterKind::BasePoint { at } => Mark::Parameter { node: p.node, at: *at, label }, ParameterKind::Other { .. } => continue, }); } diff --git a/crates/engine/src/blockedit.rs b/crates/engine/src/blockedit.rs index cc771612ba..bcd8e10e90 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -128,7 +128,7 @@ impl BlockEdit { match m { Mark::Linear { base, end, .. } => (*base, *end) = (*base - off, *end - off), Mark::Point { at, label_at, .. } => (*at, *label_at) = (*at - off, *label_at - off), - Mark::Parameter { at, .. } | Mark::Action { at, .. } => *at = *at - off, + Mark::List { at, .. } | Mark::Parameter { at, .. } | Mark::Action { at, .. } => *at = *at - off, } } out diff --git a/crates/io/tests/dynblock_author.rs b/crates/io/tests/dynblock_author.rs index 7d59984c86..8c05864405 100644 --- a/crates/io/tests/dynblock_author.rs +++ b/crates/io/tests/dynblock_author.rs @@ -5,7 +5,7 @@ //! circle on its right edge) with one reference. use cadcraft_doc::dynblock::{ - ActionKind, ActionSpec, MAX_VISIBILITY_STATES, ParamPoint, ParameterKind, ParameterSpec, VisibilityState, add_action, add_parameter, + ActionKind, ActionSpec, MAX_VISIBILITY_STATES, Mark, ParamPoint, ParameterKind, ParameterSpec, VisibilityState, add_action, add_parameter, dynamic_block, set_property, set_visibility, tag_elements, }; use cadcraft_doc::{Drawing, EntityKind, Handle}; @@ -373,6 +373,9 @@ fn an_authored_visibility_parameter_reads_back_and_links_as_autocad_does() { for c in ["BLOCKVISIBILITYPARAMETER", "BLOCKVISIBILITYGRIP"] { assert!(d.foreign.classes.iter().any(|k| k.iter().any(|t| t.code == 1 && t.value == c)), "class {c}"); } + // The Block Editor draws it with its list grip. + let marks = cadcraft_doc::dynblock::marks(&d, "BOX"); + assert!(matches!(&marks[..], [Mark::List { node: 1, grip: true, label, .. }] if label == "Visibility1"), "{marks:?}"); let mut again = d.clone(); let second = ParameterSpec::Visibility { at: v(0.0, 0.0), label: None, objects: Vec::new(), grips: 0 }; assert!(add_parameter(&mut again, "BOX", &second).is_err(), "one visibility parameter per block"); diff --git a/crates/ui-egui/src/canvas/blockedit.rs b/crates/ui-egui/src/canvas/blockedit.rs index 843b52242c..6365d1bfe1 100644 --- a/crates/ui-egui/src/canvas/blockedit.rs +++ b/crates/ui-egui/src/canvas/blockedit.rs @@ -254,6 +254,15 @@ fn paint_marks(app: &CadApp, ctx: &egui::Context, p: &Painter, xf: &Xf) { } p.text(l, Align2::LEFT_BOTTOM, label, font.clone(), accent); } + Mark::List { at, label, grip, .. } => { + // A list grip: a triangle pointing down, the label to its right. + let s = to(*at); + if *grip { + let pts = vec![s + vec2(-6.0, -5.0), s + vec2(6.0, -5.0), s + vec2(0.0, 6.0)]; + p.add(Shape::convex_polygon(pts, grip_dyn, Stroke::new(1.0, fade(t.canvas)))); + } + p.text(s + vec2(8.0, 0.0), Align2::LEFT_CENTER, label, font.clone(), accent); + } Mark::Parameter { at, label, .. } => { p.text(to(*at), Align2::LEFT_BOTTOM, label, font.clone(), accent); } From a4d84e2b8419e881a53209cad834a9df6ea6cc72 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 25 Oct 2026 14:34:22 -0600 Subject: [PATCH 15/47] Dynamic blocks: pick, move and erase parameters and actions in the Block Editor In the Block Editor a click picks a parameter or action (Shift+click unpicks it, Escape unpicks all); picked ones are drawn heavier with grips at their points: a linear parameter's ends and label line, a point parameter's location and label, a visibility or lookup parameter's location, an action's location. Clicking a grip moves that point. MOVE, ERASE, Delete and the right-click menu's Erase and Move act on the picked ones with the selected objects. JSON: blocks.element.select, .move, .point, .points, .erase. As AutoCAD does it (recorded in its files): erasing a parameter erases its grips, their location components and the actions that follow it; the graph's nodes close up and keep their ids. Moving a parameter moves its points, grips and label; moving an action moves where it shows, not its frame. The graph's 96/97 groups are the highest id handed out, not the node count: with the count there AutoCAD took a block with an erased parameter as static when read from DXF. Checked in AutoCAD from DXF and DWG: blocks with an erased parameter, an erased action, and a moved parameter and action with a dragged end stay dynamic with the expected properties, and the moved block stretches. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock.rs | 2 + crates/doc/src/dynblock/edit.rs | 337 ++++++++++++++++++++ crates/doc/src/dynblock/write.rs | 63 ++-- crates/engine/src/blockedit.rs | 59 ++++ crates/engine/src/cmd/blocks.rs | 2 + crates/engine/src/cmd/blocks/belement.rs | 218 +++++++++++++ crates/engine/src/cmd/edit.rs | 10 +- crates/engine/src/cmd/modify/select_then.rs | 10 + crates/engine/src/cmd/modify/transform.rs | 6 +- crates/engine/src/session/interactive.rs | 2 + crates/engine/tests/block_elements.rs | 162 ++++++++++ crates/ui-egui/src/canvas.rs | 4 + crates/ui-egui/src/canvas/blockedit.rs | 120 ++++++- crates/ui-egui/src/context_menu.rs | 4 + docs/gaps.md | 3 +- 15 files changed, 962 insertions(+), 40 deletions(-) create mode 100644 crates/doc/src/dynblock/edit.rs create mode 100644 crates/engine/src/cmd/blocks/belement.rs create mode 100644 crates/engine/tests/block_elements.rs diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index 80eeaa43ec..367d651b54 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -22,12 +22,14 @@ use crate::{Drawing, Handle, RawTag}; mod apply; mod copy; +mod edit; mod grips; mod marks; mod reference; mod write; pub use apply::{drag_grip, set_property}; pub use copy::{copy_definition, remap_handles, restore_definition}; +pub use edit::{ElementPoint, element_points, erase_elements, move_element, set_element_point}; pub use grips::{DynGrip, GripPart, GripShape, grips}; pub use marks::{Mark, marks}; pub use reference::{CustomProperty, Reference, Value, custom_properties, reference}; diff --git a/crates/doc/src/dynblock/edit.rs b/crates/doc/src/dynblock/edit.rs new file mode 100644 index 0000000000..d621567977 --- /dev/null +++ b/crates/doc/src/dynblock/edit.rs @@ -0,0 +1,337 @@ +//! Editing a dynamic block's parameters and actions in the Block Editor: moving them, dragging +//! one of their points, erasing them. As AutoCAD does it (observed in files it saves): +//! +//! - Moving a parameter moves its points, its grips and its label; moving an action moves only +//! where it shows (its frame and selection stay). +//! - Erasing a parameter erases its grips, their location components and the actions that follow +//! it; erasing an action erases only it. The graph keeps every other node's id; node and edge +//! indices close up and the edges are linked again in their order. + +use cadcraft_geom::{Vec2, Vec3}; + +use super::write::{Graph, dict_entry, finite, real}; +use super::{ParameterKind, dynamic_block}; +use crate::foreign::ForeignObject; +use crate::{Drawing, Handle, RawTag}; + +/// A point of a parameter or action that can be dragged on its own. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ElementPoint { + /// A linear parameter's start point. + Base, + /// A linear parameter's endpoint. + End, + /// Where a one-point parameter is (a point, visibility or lookup parameter), or where an + /// action shows. + At, + /// A point parameter's label, or the line of a linear parameter's label (its offset). + Label, +} + +/// The block's graph object and its graph. +fn graph(d: &Drawing, block: &str) -> Result { + let key = ("BLOCK_RECORD".to_string(), block.trim().to_ascii_uppercase()); + let xdict = d.foreign.records.get(&key).and_then(|x| x.xdict).ok_or("The block has no parameters or actions.")?; + let g = dict_entry(d, xdict, "ACAD_ENHANCEDBLOCK").ok_or("The block has no parameters or actions.")?; + let o = d.foreign.objects.iter().find(|o| o.handle == g).ok_or("The block's evaluation graph is missing.")?; + Graph::read(o).ok_or_else(|| "The block's evaluation graph can't be changed.".to_string()) +} + +fn object_mut(d: &mut Drawing, h: Handle) -> Option<&mut ForeignObject> { + std::sync::Arc::make_mut(&mut d.foreign).objects.iter_mut().find(|o| o.handle == h) +} + +/// The groups of section `marker` (from its `100` marker to the next one) of `tags`. +fn section_range(tags: &[RawTag], marker: &str) -> Option> { + let start = tags.iter().position(|t| t.code == 100 && t.value.eq_ignore_ascii_case(marker))? + 1; + let end = tags.iter().skip(start).position(|t| t.code == 100).map_or(tags.len(), |n| start + n); + Some(start..end) +} + +/// The index of the first group `code` in section `marker`. +fn find(tags: &[RawTag], marker: &str, code: i32) -> Option { + let r = section_range(tags, marker)?; + let start = r.start; + tags.get(r)?.iter().position(|t| t.code == code).map(|i| start + i) +} + +/// The point at group `code` (x; y and z follow) in section `marker`. +fn point_at(tags: &[RawTag], marker: &str, code: i32) -> Option { + let i = find(tags, marker, code)?; + let v = |k: usize| tags.get(i + k).filter(|t| t.code == code + 10 * k as i32).and_then(|t| t.value.trim().parse::().ok()); + Some(Vec3::new(v(0)?, v(1)?, v(2).unwrap_or(0.0))) +} + +/// Set the point at group `code` in section `marker`; whether it was there. +fn set_point(tags: &mut [RawTag], marker: &str, code: i32, p: Vec3) -> bool { + let Some(i) = find(tags, marker, code) else { return false }; + for (k, v) in [p.x, p.y, p.z].into_iter().enumerate() { + let c = code + 10 * k as i32; + if let Some(t) = tags.get_mut(i + k).filter(|t| t.code == c) { + *t = real(c, v); + } + } + true +} + +/// Set the real at group `code` in section `marker`. +fn set_real(tags: &mut [RawTag], marker: &str, code: i32, v: f64) { + if let Some(i) = find(tags, marker, code) + && let Some(t) = tags.get_mut(i) + { + *t = real(code, v); + } +} + +/// Element graph id `node` of `block`: its object's kind and handle, and its grips' handles by +/// grip id (a linear parameter's base grip first). +struct Element { + kind: String, + handle: Handle, + param: Option, + grips: Vec, +} + +fn element(d: &Drawing, block: &str, node: i32) -> Result { + let g = graph(d, block)?; + let n = g.nodes.iter().find(|n| n.id == node).ok_or_else(|| format!("No parameter or action {node} in the block."))?; + let o = d.foreign.objects.iter().find(|o| o.handle == n.handle).ok_or("The block's parameter is missing.")?; + let m = dynamic_block(d, block); + let p = m.as_ref().and_then(|m| m.parameters.iter().find(|p| p.node == node)); + let grips = match (&m, p) { + (Some(m), Some(p)) => p.grips.iter().filter_map(|id| m.grip_objects.iter().find(|(g, _)| g == id).map(|(_, h)| *h)).collect(), + _ => Vec::new(), + }; + Ok(Element { kind: o.kind.clone(), handle: o.handle, param: p.map(|p| p.kind.clone()), grips }) +} + +fn is_action(kind: &str) -> bool { + kind.starts_with("BLOCK") && kind.ends_with("ACTION") +} + +/// Move a grip object to `at`, and point a linear grip along `dir`. +fn move_grip(d: &mut Drawing, grip: Handle, at: Vec3, dir: Option) { + if let Some(o) = object_mut(d, grip) { + set_point(&mut o.tags, "AcDbBlockGrip", 1010, at); + if let Some(dir) = dir { + for (code, v) in [(140, dir.x), (141, dir.y), (142, dir.z)] { + set_real(&mut o.tags, "AcDbBlockLinearGrip", code, v); + } + } + } +} + +/// Move parameter or action `node` of block `block` (any case) by `delta`. +pub fn move_element(d: &mut Drawing, block: &str, node: i32, delta: Vec3) -> Result<(), String> { + if !finite(delta) { + return Err("Invalid displacement.".into()); + } + let e = element(d, block, node)?; + let shifted = |tags: &[RawTag], marker: &str, code: i32| point_at(tags, marker, code).map(|p| p + delta).filter(|p| finite(*p)); + let tags = d.foreign.objects.iter().find(|o| o.handle == e.handle).map(|o| o.tags.clone()).unwrap_or_default(); + match (&e.param, e.kind.as_str()) { + (_, k) if is_action(k) => { + set_element_point(d, block, node, ElementPoint::At, shifted(&tags, "AcDbBlockAction", 1010).ok_or("Invalid point.")?) + } + (Some(ParameterKind::Linear { base, end, .. }), _) => { + let (b, n) = (*base + delta, *end + delta); + if !finite(b) || !finite(n) { + return Err("Invalid point.".into()); + } + if let Some(o) = object_mut(d, e.handle) { + set_point(&mut o.tags, "AcDbBlock2PtParameter", 1010, b); + set_point(&mut o.tags, "AcDbBlock2PtParameter", 1011, n); + } + if let [bg, eg] = e.grips[..] { + move_grip(d, bg, b, None); + move_grip(d, eg, n, None); + } + Ok(()) + } + (Some(ParameterKind::Point { .. }), _) => { + let label = shifted(&tags, "AcDbBlockPointParameter", 1011).ok_or("Invalid point.")?; + set_element_point(d, block, node, ElementPoint::At, shifted(&tags, "AcDbBlock1PtParameter", 1010).ok_or("Invalid point.")?)?; + set_element_point(d, block, node, ElementPoint::Label, label) + } + (Some(ParameterKind::Visibility { .. } | ParameterKind::Lookup { .. }), _) => { + set_element_point(d, block, node, ElementPoint::At, shifted(&tags, "AcDbBlock1PtParameter", 1010).ok_or("Invalid point.")?) + } + _ => Err("This parameter can't be moved yet.".into()), + } +} + +/// Put point `which` of parameter or action `node` of block `block` (any case) at `to` (block +/// coordinates). A linear parameter's grips turn with it; its label stays as far from its line. +pub fn set_element_point(d: &mut Drawing, block: &str, node: i32, which: ElementPoint, to: Vec3) -> Result<(), String> { + if !finite(to) { + return Err("Invalid point.".into()); + } + let e = element(d, block, node)?; + let none = || format!("That point of the {} can't be moved.", e.kind.to_ascii_lowercase()); + match (&e.param, which) { + (None, ElementPoint::At) if is_action(&e.kind) => { + let o = object_mut(d, e.handle).ok_or("The block's action is missing.")?; + set_point(&mut o.tags, "AcDbBlockAction", 1010, to); + Ok(()) + } + (Some(ParameterKind::Linear { base, end, .. }), ElementPoint::Base | ElementPoint::End) => { + let (b, n) = if which == ElementPoint::Base { (to, *end) } else { (*base, to) }; + let dir = n - b; + if !finite(dir) || dir.len() <= 1e-9 { + return Err("The endpoint must differ from the start point.".into()); + } + if let Some(o) = object_mut(d, e.handle) { + set_point(&mut o.tags, "AcDbBlock2PtParameter", if which == ElementPoint::Base { 1010 } else { 1011 }, to); + } + if let [bg, eg] = e.grips[..] { + move_grip(d, bg, b, Some(-dir)); + move_grip(d, eg, n, Some(dir)); + } + Ok(()) + } + (Some(ParameterKind::Linear { base, end, .. }), ElementPoint::Label) => { + let (a, b, p) = (base.xy(), end.xy(), to.xy()); + let u = b - a; + let len = u.len(); + let offset = if len <= 1e-12 { 0.0 } else { (u.x * (p.y - a.y) - u.y * (p.x - a.x)) / len }; + let o = object_mut(d, e.handle).ok_or("The block's parameter is missing.")?; + set_real(&mut o.tags, "AcDbBlockLinearParameter", 140, offset); + Ok(()) + } + (Some(ParameterKind::Point { .. } | ParameterKind::Visibility { .. } | ParameterKind::Lookup { .. }), ElementPoint::At) => { + if let Some(o) = object_mut(d, e.handle) { + set_point(&mut o.tags, "AcDbBlock1PtParameter", 1010, to); + } + if let Some(g) = e.grips.first() { + move_grip(d, *g, to, None); + } + Ok(()) + } + (Some(ParameterKind::Point { .. }), ElementPoint::Label) => { + let o = object_mut(d, e.handle).ok_or("The block's parameter is missing.")?; + set_point(&mut o.tags, "AcDbBlockPointParameter", 1011, to); + Ok(()) + } + _ => Err(none()), + } +} + +/// Erase parameters and actions `nodes` of block `block` (any case), as AutoCAD erases them: a +/// parameter takes its grips, their location components and its actions along. Returns the +/// graph ids erased (the parameters' and actions'; grips and components aren't listed). +pub fn erase_elements(d: &mut Drawing, block: &str, nodes: &[i32]) -> Result, String> { + let mut g = graph(d, block)?; + let kind_of = |h: Handle| d.foreign.objects.iter().find(|o| o.handle == h).map(|o| o.kind.clone()).unwrap_or_default(); + let index_of = |g: &Graph, id: i32| g.nodes.iter().find(|n| n.id == id).map(|n| n.index); + let mut gone: Vec = Vec::new(); // node indices + let mut erased: Vec = Vec::new(); // graph ids + for id in nodes { + let Some(i) = index_of(&g, *id) else { return Err(format!("No parameter or action {id} in the block.")) }; + let kind = g.nodes.iter().find(|n| n.index == i).map(|n| kind_of(n.handle)).unwrap_or_default(); + if kind.contains("GRIP") { + return Err(format!("{id} is a grip; erase its parameter.")); + } + let take = |i: i32, gone: &mut Vec| { + if !gone.contains(&i) { + gone.push(i); + } + }; + take(i, &mut gone); + if !erased.contains(id) { + erased.push(*id); + } + if is_action(&kind) { + continue; + } + // A parameter: what it feeds (components, actions) and the grips that feed it. + for e in &g.edges { + let (other, outgoing) = if e.from == i { + (e.to, true) + } else if e.to == i { + (e.from, false) + } else { + continue; + }; + let Some(n) = g.nodes.iter().find(|n| n.index == other) else { continue }; + let k = kind_of(n.handle); + let follows = outgoing && (k == "BLOCKGRIPLOCATIONCOMPONENT" || is_action(&k)); + let grip = !outgoing && k.contains("GRIP") && k != "BLOCKGRIPLOCATIONCOMPONENT"; + if follows || grip { + take(other, &mut gone); + if is_action(&k) && !erased.contains(&n.id) { + erased.push(n.id); + } + } + // A grip's components hang off the parameter, so they are caught above. + } + } + let handles: Vec = g.nodes.iter().filter(|n| gone.contains(&n.index)).map(|n| n.handle).collect(); + // What stays, its indices closed up and its edges linked again in their order. + let kept: Vec<_> = g.nodes.iter().filter(|n| !gone.contains(&n.index)).cloned().collect(); + let renumber: Vec<(i32, i32)> = kept.iter().zip(0..).map(|(n, i)| (n.index, i)).collect(); + let new_index = |old: i32| renumber.iter().find(|(o, _)| *o == old).map(|(_, n)| *n); + let edges: Vec<(i32, i32, i32)> = g.edges.iter().filter_map(|e| Some((new_index(e.from)?, new_index(e.to)?, e.kind))).collect(); + g.nodes = kept; + for (n, i) in g.nodes.iter_mut().zip(0..) { + n.index = i; + n.links = [-1; 4]; + } + g.edges.clear(); + for (from, to, kind) in edges { + g.link(from, to, kind); + } + let erased_handles: Vec = handles.clone(); + let f = std::sync::Arc::make_mut(&mut d.foreign); + let tags = g.tags(); + if let Some(o) = f.objects.iter_mut().find(|o| o.handle == g.handle) { + o.tags = tags; + } + f.objects.retain(|o| !handles.contains(&o.handle)); + // Visibility states no longer list what was erased. + drop_from_states(d, block, &erased_handles)?; + Ok(erased) +} + +/// Remove `handles` from the visibility parameter's state lists (parameters and grips shown). +fn drop_from_states(d: &mut Drawing, block: &str, handles: &[Handle]) -> Result<(), String> { + let Some(m) = dynamic_block(d, block) else { return Ok(()) }; + let Some(ParameterKind::Visibility { controlled, states, .. }) = + m.parameters.into_iter().map(|p| p.kind).find(|k| matches!(k, ParameterKind::Visibility { .. })) + else { + return Ok(()); + }; + if !states.iter().any(|s| s.active.iter().any(|h| handles.contains(h))) { + return Ok(()); + } + let mut states = states; + for s in &mut states { + s.active.retain(|h| !handles.contains(h)); + } + super::set_visibility(d, block, &controlled, &states) +} + +/// A parameter or action's points the Block Editor can drag, in block coordinates. +pub fn element_points(d: &Drawing, block: &str, node: i32) -> Vec<(ElementPoint, Vec3)> { + let Ok(e) = element(d, block, node) else { return Vec::new() }; + let Some(tags) = d.foreign.objects.iter().find(|o| o.handle == e.handle).map(|o| &o.tags) else { return Vec::new() }; + match &e.param { + None if is_action(&e.kind) => point_at(tags, "AcDbBlockAction", 1010).map(|p| vec![(ElementPoint::At, p)]).unwrap_or_default(), + Some(ParameterKind::Linear { base, end, .. }) => { + // The label's grip: the middle of its line, `offset` to the left of base → end. + let offset = + find(tags, "AcDbBlockLinearParameter", 140).and_then(|i| tags.get(i)).and_then(|t| t.value.trim().parse::().ok()).unwrap_or(0.0); + let (a, b) = (base.xy(), end.xy()); + let u = b - a; + let n = if u.len() > 1e-12 { Vec2::new(-u.y, u.x) * (1.0 / u.len()) } else { Vec2::ZERO }; + let mid = (a + b) * 0.5 + n * offset; + vec![(ElementPoint::Base, *base), (ElementPoint::End, *end), (ElementPoint::Label, mid.to3(base.z))] + } + Some(ParameterKind::Point { at, .. }) => { + let mut v = vec![(ElementPoint::At, *at)]; + v.extend(point_at(tags, "AcDbBlockPointParameter", 1011).map(|p| (ElementPoint::Label, p))); + v + } + Some(ParameterKind::Visibility { at, .. } | ParameterKind::Lookup { at, .. }) => vec![(ElementPoint::At, *at)], + _ => Vec::new(), + } +} diff --git a/crates/doc/src/dynblock/write.rs b/crates/doc/src/dynblock/write.rs index 355f14c1db..cf1ff4b3eb 100644 --- a/crates/doc/src/dynblock/write.rs +++ b/crates/doc/src/dynblock/write.rs @@ -73,41 +73,44 @@ pub enum ActionSpec { /// One node of the evaluation graph: its index, flags, graph id, object and the first and last /// of its incoming and outgoing edges (edge indices, -1 for none). #[derive(Clone, Debug, PartialEq)] -struct Node { - index: i32, - flags: i32, - id: i32, - handle: Handle, - links: [i32; 4], +pub(super) struct Node { + pub(super) index: i32, + pub(super) flags: i32, + pub(super) id: i32, + pub(super) handle: Handle, + pub(super) links: [i32; 4], } /// One edge: its index, flags, kind (1 from a parameter, 2 from a grip), the nodes it joins /// (indices) and its neighbours in their lists: previous and next incoming of `to`, previous and /// next outgoing of `from`, then one more link AutoCAD leaves at -1. #[derive(Clone, Debug, PartialEq)] -struct Edge { - index: i32, - flags: i32, - kind: i32, - from: i32, - to: i32, - links: [i32; 5], +pub(super) struct Edge { + pub(super) index: i32, + pub(super) flags: i32, + pub(super) kind: i32, + pub(super) from: i32, + pub(super) to: i32, + pub(super) links: [i32; 5], } /// An evaluation graph object being extended. -struct Graph { - handle: Handle, +pub(super) struct Graph { + pub(super) handle: Handle, /// Its groups before `100 AcDbEvalGraph`, as they were. - head: Vec, - nodes: Vec, - edges: Vec, + pub(super) head: Vec, + /// The highest graph id handed out (96, 97), which AutoCAD keeps after nodes are erased: + /// ids aren't used again. + pub(super) last_id: i32, + pub(super) nodes: Vec, + pub(super) edges: Vec, } -fn tag(code: i32, value: impl ToString) -> RawTag { +pub(super) fn tag(code: i32, value: impl ToString) -> RawTag { RawTag { code, value: value.to_string() } } -fn real(code: i32, v: f64) -> RawTag { +pub(super) fn real(code: i32, v: f64) -> RawTag { tag(code, format!("{v:?}")) } @@ -118,11 +121,12 @@ fn point(out: &mut Vec, code: i32, p: Vec3) { impl Graph { /// The graph object `o` read back into nodes and edges, or `None` when its groups aren't /// laid out as a graph (it is then left alone). - fn read(o: &ForeignObject) -> Option { + pub(super) fn read(o: &ForeignObject) -> Option { let at = o.tags.iter().position(|t| t.code == 100 && t.value.eq_ignore_ascii_case("AcDbEvalGraph"))?; let head = o.tags.get(..at)?.to_vec(); let body = o.tags.get(at + 1..)?; let int = |t: Option<&RawTag>, code: i32| t.filter(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()); + let last_id = body.iter().take_while(|t| t.code == 96 || t.code == 97).filter_map(|t| t.value.trim().parse::().ok()).max().unwrap_or(0); let mut i = body.iter().position(|t| t.code != 96 && t.code != 97).unwrap_or(body.len()); let (mut nodes, mut edges) = (Vec::new(), Vec::new()); while body.get(i).is_some_and(|t| t.code == 91) { @@ -148,20 +152,21 @@ impl Graph { if i != body.len() { return None; } - Some(Graph { handle: o.handle, head, nodes, edges }) + Some(Graph { handle: o.handle, head, last_id, nodes, edges }) } /// A new, empty graph owned by dictionary `dict`. fn new(handle: Handle, dict: Handle) -> Graph { let head = vec![tag(5, handle.hex()), tag(102, "{ACAD_REACTORS"), tag(330, dict.hex()), tag(102, "}"), tag(330, dict.hex())]; - Graph { handle, head, nodes: Vec::new(), edges: Vec::new() } + Graph { handle, head, last_id: 0, nodes: Vec::new(), edges: Vec::new() } } - fn tags(&self) -> Vec { + pub(super) fn tags(&self) -> Vec { let mut out = self.head.clone(); out.push(tag(100, "AcDbEvalGraph")); - out.push(tag(96, self.nodes.len())); - out.push(tag(97, self.nodes.len())); + let last = self.nodes.iter().map(|n| n.id).max().unwrap_or(0).max(self.last_id); + out.push(tag(96, last)); + out.push(tag(97, last)); for n in &self.nodes { out.extend([tag(91, n.index), tag(93, n.flags), tag(95, n.id), tag(360, n.handle.hex())]); out.extend(n.links.iter().map(|l| tag(92, l))); @@ -175,7 +180,7 @@ impl Graph { /// The next free graph id. fn next_id(&self) -> i32 { - self.nodes.iter().map(|n| n.id).max().unwrap_or(0).saturating_add(1) + self.nodes.iter().map(|n| n.id).max().unwrap_or(0).max(self.last_id).saturating_add(1) } /// Add node `id` for object `handle`; its index. @@ -199,7 +204,7 @@ impl Graph { } /// Add an edge of `kind` from node index `from` to `to`, last in both nodes' lists. - fn link(&mut self, from: i32, to: i32, kind: i32) { + pub(super) fn link(&mut self, from: i32, to: i32, kind: i32) { let index = self.edges.iter().map(|e| e.index).max().map_or(0, |m| m.saturating_add(1)); let last_out = self.node_mut(from).map_or(-1, |n| n.links[3]); let last_in = self.node_mut(to).map_or(-1, |n| n.links[1]); @@ -429,7 +434,7 @@ fn free_label(d: &Drawing, record: &str, prefix: &str) -> String { (1..).map(|i| format!("{prefix}{i}")).find(|n| !used.iter().any(|u| u.eq_ignore_ascii_case(n))).unwrap_or_else(|| format!("{prefix}1")) } -fn finite(p: Vec3) -> bool { +pub(super) fn finite(p: Vec3) -> bool { p.x.is_finite() && p.y.is_finite() && p.z.is_finite() } diff --git a/crates/engine/src/blockedit.rs b/crates/engine/src/blockedit.rs index bcd8e10e90..193a2a8905 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -62,6 +62,9 @@ pub struct BlockEdit { pub current: bool, /// The visibility state the editor shows (BVSTATE Set); `None` for the block's first. pub visibility: Option, + /// The parameters and actions picked in the editor (graph ids): MOVE, ERASE and Delete act on + /// them with the selected objects, and their points have grips. + pub picked: Vec, } /// Why a block can't be opened in the Block Editor, if it can't. @@ -349,6 +352,7 @@ impl DocState { base: Vec2::ZERO, current: true, visibility: None, + picked: Vec::new(), }); return Ok(()); } @@ -377,6 +381,7 @@ impl DocState { base, current: false, visibility: None, + picked: Vec::new(), }; // The editor shows the block's first visibility state (its other objects hidden). be.show_visibility_state(&mut d, bvmode); @@ -506,4 +511,58 @@ impl crate::Session { } Ok(()) } + + /// The parameters and actions picked in the Block Editor (graph ids), those still there. + pub fn picked_elements(&self) -> Vec { + let Ok(st) = self.state() else { return Vec::new() }; + let Some(be) = &st.block_edit else { return Vec::new() }; + let Some(m) = cadcraft_doc::dynblock::dynamic_block(&st.doc, &be.name) else { return Vec::new() }; + be.picked.iter().copied().filter(|n| m.parameters.iter().any(|p| p.node == *n) || m.actions.iter().any(|a| a.node == *n)).collect() + } + + /// Pick parameters and actions `nodes` in the Block Editor (added to those picked with + /// `add`; none and not `add` picks nothing). + pub fn pick_elements(&mut self, nodes: &[i32], add: bool) -> Result<()> { + let st = self.state_mut()?; + let Some(be) = st.block_edit.as_mut() else { return Ok(()) }; + if !add { + be.picked.clear(); + } + for n in nodes { + if !be.picked.contains(n) { + be.picked.push(*n); + } + } + Ok(()) + } + + /// Move the picked parameters and actions by `d` (MOVE with them picked); they stay picked. + pub(crate) fn move_picked_elements(&mut self, d: Vec2) -> Result { + let nodes = self.picked_elements(); + if nodes.is_empty() || d == Vec2::ZERO { + return Ok(0); + } + let name = self.state()?.block_edit.as_ref().map(|b| b.name.clone()).unwrap_or_default(); + let mut doc = self.doc()?.clone(); + for n in &nodes { + cadcraft_doc::dynblock::move_element(&mut doc, &name, *n, d.to3(0.0)).map_err(EngineError::Other)?; + } + *self.doc_mut()? = doc; + Ok(nodes.len()) + } + + /// Erase the picked parameters and actions (ERASE, Delete), as AutoCAD erases them: a + /// parameter takes its actions along. Nothing is picked afterwards. + pub(crate) fn erase_picked_elements(&mut self) -> Result { + let nodes = self.picked_elements(); + self.pick_elements(&[], false)?; + if nodes.is_empty() { + return Ok(0); + } + let name = self.state()?.block_edit.as_ref().map(|b| b.name.clone()).unwrap_or_default(); + let mut doc = self.doc()?.clone(); + let erased = cadcraft_doc::dynblock::erase_elements(&mut doc, &name, &nodes).map_err(EngineError::Other)?; + *self.doc_mut()? = doc; + Ok(erased.len()) + } } diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 1079ec0b68..7b67e653e4 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -19,6 +19,7 @@ use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, St mod attedit; mod bauthor; +mod belement; mod burst; mod bvstate; mod description; @@ -90,6 +91,7 @@ pub fn specs() -> Vec { .chain(refedit::specs()) .chain(bedit::specs()) .chain(bauthor::specs()) + .chain(belement::specs()) .chain(bvstate::specs()) .collect() } diff --git a/crates/engine/src/cmd/blocks/belement.rs b/crates/engine/src/cmd/blocks/belement.rs new file mode 100644 index 0000000000..547617b71a --- /dev/null +++ b/crates/engine/src/cmd/blocks/belement.rs @@ -0,0 +1,218 @@ +//! Picking, moving and erasing a dynamic block's parameters and actions in the Block Editor, as +//! AutoCAD's editor treats them: they are picked like objects (the UI picks them on a click), +//! MOVE and ERASE (and Delete) act on the picked ones with the selected objects, and a picked +//! one's points have grips (a linear parameter's ends and label line, a point parameter's +//! location and label, a visibility or lookup parameter's location, an action's location). +//! Erasing a parameter erases its actions. Points are in the editor's coordinates (the block's +//! base point at the origin). + +use cadcraft_doc::EntityKind; +use cadcraft_doc::dynblock::{self, ElementPoint}; +use cadcraft_geom::Vec2; +use serde_json::{Value, json}; + +use crate::cmd::{CommandSpec, bad, point_param, str_param}; +use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Running, Session, Step}; + +pub(super) fn specs() -> Vec { + vec![ + CommandSpec::new("blocks.element.select", "Pick Parameters and Actions", run_select) + .params("{nodes?: [graph ids] (none: pick nothing), add?: bool (add to those picked)} → {picked}") + .enabled(editing), + CommandSpec::new("blocks.element.move", "Move Parameters and Actions", run_move) + .params("{nodes?: [graph ids] (default the picked ones), delta: [dx, dy]} → {moved}") + .enabled(editing), + CommandSpec::new("blocks.element.point", "Move a Parameter's Point", run_point) + .params("{node: graph id, point: \"base\"|\"end\"|\"at\"|\"label\", to: [x, y]} (editor coordinates)") + .enabled(editing), + CommandSpec::new("blocks.element.points", "Parameter Points", run_points) + .params("{node: graph id} → {points: [{point, at}]} (editor coordinates; read-only)") + .enabled(editing), + CommandSpec::new("blocks.element.erase", "Erase Parameters and Actions", run_erase) + .params("{nodes?: [graph ids] (default the picked ones)} → {erased: [graph ids]} (a parameter's actions go with it)") + .enabled(editing), + ] +} + +/// The Block Editor is open on a block. +fn editing(s: &Session) -> std::result::Result<(), String> { + match s.state() { + Ok(st) => match &st.block_edit { + Some(be) if be.current => Err("This editor is open on the drawing itself, which has no parameters or actions.".into()), + Some(_) => Ok(()), + None => Err("Open a block in the Block Editor first (BEDIT).".into()), + }, + Err(e) => Err(e.to_string()), + } +} + +/// The edited block and its base point (the editor's origin). +fn edited(s: &Session) -> Result<(String, Vec2)> { + editing(s).map_err(EngineError::Other)?; + let be = s.state()?.block_edit.as_ref().ok_or_else(|| EngineError::Other("The Block Editor is not open.".into()))?; + Ok((be.name.clone(), be.base())) +} + +fn nodes_param(cmd: &str, p: &Value, s: &Session) -> Result> { + match p.get("nodes") { + None | Some(Value::Null) => Ok(s.picked_elements()), + Some(Value::Array(a)) if a.len() <= dynblock::MAX_ACTION_ITEMS => { + a.iter().map(|v| v.as_i64().and_then(|n| i32::try_from(n).ok()).ok_or_else(|| bad(cmd, format!("{v} is not a graph id")))).collect() + } + Some(_) => Err(bad(cmd, "`nodes` is a list of graph ids")), + } +} + +fn node_param(cmd: &str, p: &Value) -> Result { + p.get("node").and_then(Value::as_i64).and_then(|n| i32::try_from(n).ok()).ok_or_else(|| bad(cmd, "`node`: a graph id")) +} + +fn point_name(p: ElementPoint) -> &'static str { + match p { + ElementPoint::Base => "base", + ElementPoint::End => "end", + ElementPoint::At => "at", + ElementPoint::Label => "label", + } +} + +fn run_select(s: &mut Session, p: &Value) -> Result { + let (block, _) = edited(s)?; + let nodes = match p.get("nodes") { + None | Some(Value::Null) => Vec::new(), + _ => nodes_param("blocks.element.select", p, s)?, + }; + let m = dynblock::dynamic_block(s.doc()?, &block); + let known = |n: &i32| m.as_ref().is_some_and(|m| m.parameters.iter().any(|p| p.node == *n) || m.actions.iter().any(|a| a.node == *n)); + if let Some(n) = nodes.iter().find(|n| !known(n)) { + return Err(bad("blocks.element.select", format!("no parameter or action {n} in the block"))); + } + let add = p.get("add").and_then(Value::as_bool).unwrap_or(false); + s.pick_elements(&nodes, add)?; + Ok(json!({ "picked": s.picked_elements() })) +} + +fn run_move(s: &mut Session, p: &Value) -> Result { + let (block, _) = edited(s)?; + let nodes = nodes_param("blocks.element.move", p, s)?; + let d = point_param(p, "delta").ok_or_else(|| bad("blocks.element.move", "`delta`: [dx, dy]"))?; + let mut doc = s.doc()?.clone(); + for n in &nodes { + dynblock::move_element(&mut doc, &block, *n, d.to3(0.0)).map_err(|e| bad("blocks.element.move", e))?; + } + *s.doc_mut()? = doc; + Ok(json!({ "moved": nodes.len() })) +} + +fn run_point(s: &mut Session, p: &Value) -> Result { + let (block, base) = edited(s)?; + let node = node_param("blocks.element.point", p)?; + let which = match str_param(p, "point").map(str::to_ascii_lowercase).as_deref() { + Some("base") | Some("start") => ElementPoint::Base, + Some("end") => ElementPoint::End, + Some("at") => ElementPoint::At, + Some("label") => ElementPoint::Label, + _ => return Err(bad("blocks.element.point", "`point` is \"base\", \"end\", \"at\" or \"label\"")), + }; + let to = point_param(p, "to").ok_or_else(|| bad("blocks.element.point", "`to`: [x, y]"))?; + let mut doc = s.doc()?.clone(); + dynblock::set_element_point(&mut doc, &block, node, which, (to + base).to3(0.0)).map_err(|e| bad("blocks.element.point", e))?; + *s.doc_mut()? = doc; + Ok(json!({ "node": node })) +} + +fn run_points(s: &mut Session, p: &Value) -> Result { + let (block, base) = edited(s)?; + let node = node_param("blocks.element.points", p)?; + let pts: Vec = dynblock::element_points(s.doc()?, &block, node) + .into_iter() + .map(|(w, at)| json!({ "point": point_name(w), "at": [at.x - base.x, at.y - base.y] })) + .collect(); + Ok(json!({ "points": pts })) +} + +fn run_erase(s: &mut Session, p: &Value) -> Result { + let (block, _) = edited(s)?; + let nodes = nodes_param("blocks.element.erase", p, s)?; + if nodes.is_empty() { + return Ok(json!({ "erased": [] })); + } + let mut doc = s.doc()?.clone(); + let erased = dynblock::erase_elements(&mut doc, &block, &nodes).map_err(|e| bad("blocks.element.erase", e))?; + *s.doc_mut()? = doc; + let left: Vec = s.picked_elements().into_iter().filter(|n| !erased.contains(n)).collect(); + s.pick_elements(&left, false)?; + Ok(json!({ "erased": erased })) +} + +/// A picked parameter's or action's grip being dragged (click it, then click where it goes). +struct ElementGrip { + node: i32, + which: ElementPoint, + /// Where the grip is, in the editor (the rubber band's start). + from: Vec2, +} + +impl Interactive for ElementGrip { + fn name(&self) -> &'static str { + "GRIP" + } + + fn prompt(&self, _s: &Session) -> Prompt { + Prompt::new("** STRETCH ** Specify stretch point", Accept::POINT).kw(&["eXit"]).base(self.from) + } + + fn input(&mut self, s: &mut Session, i: Input) -> Result { + let to = match i { + Input::Point(p) => p, + Input::Deferred(d) => d.at, + Input::Keyword(k) if k == "eXit" => return Ok(Step::Done), + Input::Enter | Input::Cancel => return Ok(Step::Done), + _ => return Err(EngineError::Other("Requires a point.".into())), + }; + let (block, base) = edited(s)?; + let mut doc = s.doc()?.clone(); + dynblock::set_element_point(&mut doc, &block, self.node, self.which, (to + base).to3(0.0)).map_err(EngineError::Other)?; + *s.doc_mut()? = doc; + Ok(Step::Done) + } + + fn preview(&self, _s: &Session, c: Vec2) -> Vec { + vec![crate::cmd::helpers::line(self.from, c)] + } +} + +impl Session { + /// The grips of the parameters and actions picked in the Block Editor: (graph id, point, + /// where it is in the editor). + pub fn element_grips(&self) -> Vec<(i32, ElementPoint, Vec2)> { + let Ok((block, base)) = edited(self) else { return Vec::new() }; + let Ok(d) = self.doc() else { return Vec::new() }; + self.picked_elements() + .into_iter() + .flat_map(|n| dynblock::element_points(d, &block, n).into_iter().map(move |(w, at)| (n, w, at.xy() - base))) + .collect() + } + + /// Start dragging point `which` of picked parameter or action `node` (the UI's click on its + /// grip in the Block Editor): the next point puts it there. + pub fn start_element_grip(&mut self, node: i32, which: ElementPoint) -> Result<()> { + if self.running.is_some() { + self.cancel(); + } + let from = self + .element_grips() + .into_iter() + .find(|(n, w, _)| *n == node && *w == which) + .map(|(_, _, at)| at) + .ok_or_else(|| EngineError::Other("no such grip".into()))?; + let machine = crate::guard::Guarded::wrap(Box::new(ElementGrip { node, which, from })); + let st = self.state()?; + let (before, selection_before) = (st.doc.clone(), st.selection.clone()); + self.running = Some(Running { id: "grip".into(), machine, before, selection_before }); + self.pending_window = None; + self.point_mods.clear(); + self.echo("** STRETCH **"); + Ok(()) + } +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 3a4c43e738..53bf8bc97c 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -60,7 +60,7 @@ pub fn specs() -> Vec { .params("{} (only into a drawing other than the one copied from)") .enabled(clipboard::can_paste_orig) .interactive(|_| Ok(Box::new(PasteM { mode: PasteMode::Orig }))), - CommandSpec::new("erase.selection", "Clear", run_clear).menu(&["Edit", "Clear"]).key("Delete").enabled(has_selection).params("{}"), + CommandSpec::new("erase.selection", "Clear", run_clear).menu(&["Edit", "Clear"]).key("Delete").enabled(clearable).params("{}"), CommandSpec::new("selectall", "Select All", run_selectall).menu(&["Edit", "Select All"]).key("Cmd+A").alias(&["ai_selall"]).noundo(), CommandSpec::new("ai_deselect", "Deselect All", run_deselect).params("{}").noundo(), CommandSpec::new("select", "Select", run_select) @@ -546,11 +546,17 @@ fn run_pasteorig(s: &mut Session, _p: &Value) -> Result { Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::>() })) } +/// Something to clear: selected objects, or parameters and actions picked in the Block Editor. +fn clearable(s: &Session) -> std::result::Result<(), String> { + if !s.picked_elements().is_empty() { Ok(()) } else { has_selection(s) } +} + fn run_clear(s: &mut Session, _p: &Value) -> Result { let mut hs = s.selection(); hs.retain(|h| !super::curves::is_locked(s, *h)); + // The Block Editor's picked parameters and actions go too. + let mut n = s.erase_picked_elements()?; let d = s.doc_mut()?; - let mut n = 0; for h in hs { if d.remove_entity(h).is_some() { n += 1; diff --git a/crates/engine/src/cmd/modify/select_then.rs b/crates/engine/src/cmd/modify/select_then.rs index 10bf08399e..66966e98f5 100644 --- a/crates/engine/src/cmd/modify/select_then.rs +++ b/crates/engine/src/cmd/modify/select_then.rs @@ -293,6 +293,11 @@ impl Interactive for SelectThen { } fn begin(&mut self, s: &mut Session) -> Result { self.sel = SelectPhase::begin(s); + // Parameters or actions picked in the Block Editor are a selection for MOVE and ERASE. + if !self.sel.done && matches!(self.op, Op::Move | Op::Erase) && !s.picked_elements().is_empty() { + self.sel.picked = s.selection(); + self.sel.done = true; + } if self.sel.done { self.objs = self.sel.picked.clone(); return self.apply(s); @@ -396,12 +401,14 @@ impl Interactive for SelectThen { (Op::Move, 1, Input::Point(p)) => { let d = p - self.pts[0]; transform_entities(s, &self.objs, &Mat3::translate(d), false)?; + s.move_picked_elements(d)?; s.set_selection(Vec::new()); Ok(Step::Done) } (Op::Move, 1, Input::Enter) => { let d = self.pts[0]; transform_entities(s, &self.objs, &Mat3::translate(d), false)?; + s.move_picked_elements(d)?; s.set_selection(Vec::new()); Ok(Step::Done) } @@ -570,6 +577,9 @@ impl Interactive for DisplaceM { }; if d != Vec2::ZERO { transform_entities(s, &self.inner.objs, &Mat3::translate(d), self.inner.op == Op::Copy)?; + if self.inner.op == Op::Move { + s.move_picked_elements(d)?; + } } s.set_selection(Vec::new()); return Ok(Step::Done); diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index 5a86d9e077..8c446052b5 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -29,8 +29,9 @@ pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: } pub(super) fn erase(s: &mut Session, hs: &[Handle]) -> Result { + // The Block Editor's picked parameters and actions go too. + let mut n = s.erase_picked_elements()?; let d = s.doc_mut()?; - let mut n = 0; for h in hs { let locked = d.entity(*h).and_then(|e| d.layer(&e.common.layer)).is_some_and(|l| l.locked); if !locked && d.remove_entity(*h).is_some() { @@ -60,7 +61,8 @@ pub(super) fn run_move(s: &mut Session, p: &Value) -> Result { let hs = targets(s, p)?; let d = delta_of("move", p)?; let moved = transform_entities(s, &hs, &Mat3::translate(d), false)?; - Ok(json!({ "moved": moved.len() })) + let marks = s.move_picked_elements(d)?; + Ok(json!({ "moved": moved.len() + marks })) } pub(super) fn run_copy(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index e7cb074504..93fe2633d5 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -426,6 +426,8 @@ impl Session { } else { self.pending_window = None; self.set_selection(Vec::new()); + // The Block Editor's picked parameters and actions too. + let _ = self.pick_elements(&[], false); } } diff --git a/crates/engine/tests/block_elements.rs b/crates/engine/tests/block_elements.rs new file mode 100644 index 0000000000..f4b84d25bd --- /dev/null +++ b/crates/engine/tests/block_elements.rs @@ -0,0 +1,162 @@ +//! Picking, moving and erasing parameters and actions in the Block Editor, as AutoCAD's editor +//! does (recorded in AutoCAD: erasing a parameter erases its actions; moving one moves its +//! points, grips and label; moving an action moves only where it shows). + +use cadcraft_engine::doc::dynblock::{ActionKind, ElementPoint, ParameterKind, dynamic_block}; +use cadcraft_engine::doc::{EntityKind, Handle}; +use cadcraft_engine::geom::{Vec2, Vec3}; +use cadcraft_engine::{Input, Session}; +use serde_json::{Value, json}; + +/// Block "Box" (a 10 × 5 rectangle at the origin, a circle) in the Block Editor with a linear +/// parameter (node 1) under it, a stretch of the rectangle's right edge (node 8) and a point +/// parameter (node 9). Returns the rectangle's handle. +fn authored() -> (Session, Handle) { + let mut s = Session::new(); + let made = |v: Value| if v["handle"].is_null() { v["handles"][0].clone() } else { v["handle"].clone() }; + let r = made(s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 5] })).unwrap()); + let c = made(s.execute("circle", &json!({ "center": [5, 2.5], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "Box", "base": [0, 0], "handles": [r, c], "keep": "delete" })).unwrap(); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + let rect = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::LwPolyline(_))).unwrap().handle; + s.execute("bparameter", &json!({ "type": "linear", "start": [0, -1], "end": [10, -1], "labelAt": [5, -3] })).unwrap(); + let a = s + .execute("baction", &json!({ "parameter": 1, "type": "stretch", "frame": [[8, -2], [12, 6]], "handles": [rect.hex()], "at": [12, -3] })) + .unwrap(); + assert_eq!(a["node"], 8); + let p = s.execute("bparameter", &json!({ "type": "point", "at": [2, 2], "labelAt": [3, 3] })).unwrap(); + assert_eq!(p["node"], 9); + (s, rect) +} + +fn names(s: &Session) -> Vec { + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + m.parameters.iter().map(|p| p.element.clone()).chain(m.actions.iter().map(|a| a.name.clone())).collect() +} + +/// The graph's nodes (index, id) as written. +fn graph_nodes(s: &Session) -> Vec<(i32, i32)> { + let d = s.doc().unwrap(); + let g = d.foreign.objects.iter().find(|o| o.kind == "ACAD_EVALUATION_GRAPH").unwrap(); + let at = g.tags.iter().position(|t| t.value == "AcDbEvalGraph").unwrap(); + let body = &g.tags[at + 3..]; + body.chunks(8).take_while(|c| c[0].code == 91).map(|c| (c[0].value.parse().unwrap(), c[2].value.parse().unwrap())).collect() +} + +#[test] +fn deleting_a_picked_parameter_erases_its_actions_as_autocad_does() { + let (mut s, _) = authored(); + s.execute("blocks.element.select", &json!({ "nodes": [1] })).unwrap(); + assert_eq!(s.picked_elements(), [1]); + let objects = s.doc().unwrap().foreign.objects.len(); + s.execute("erase.selection", &json!({})).unwrap(); + assert_eq!(names(&s), ["Point"], "the stretch went with its parameter"); + assert_eq!(objects - s.doc().unwrap().foreign.objects.len(), 8, "parameter, 2 grips, 4 components, action"); + // As in AutoCAD's file: indices close up, graph ids stay. + assert_eq!(graph_nodes(&s), [(0, 9), (1, 10), (2, 11), (3, 12)]); + // The graph's id counter (96, 97) keeps the highest id given out, as AutoCAD's does; with the + // node count there AutoCAD didn't take the block as dynamic from DXF. + let d = s.doc().unwrap(); + let g = d.foreign.objects.iter().find(|o| o.kind == "ACAD_EVALUATION_GRAPH").unwrap(); + let counters: Vec<&str> = g.tags.iter().filter(|t| t.code == 96 || t.code == 97).map(|t| t.value.as_str()).collect(); + assert_eq!(counters, ["12", "12"]); + assert!(s.picked_elements().is_empty()); + // Undo brings them back. + s.execute("u", &json!({})).unwrap(); + assert_eq!(names(&s), ["Linear", "Point", "Stretch"]); + // An action alone goes alone. + s.execute("blocks.element.erase", &json!({ "nodes": [8] })).unwrap(); + assert_eq!(names(&s), ["Linear", "Point"]); + // The block saves and stays dynamic. + s.execute("bclose", &json!({})).unwrap(); + assert_eq!(dynamic_block(s.doc().unwrap(), "Box").unwrap().parameters.len(), 2); +} + +#[test] +fn moving_picked_parameters_moves_their_points_grips_and_labels() { + let (mut s, _) = authored(); + s.execute("blocks.element.select", &json!({ "nodes": [1, 8] })).unwrap(); + s.execute("move", &json!({ "delta": [0, -2] })).unwrap(); + s.execute("blocks.element.select", &json!({ "nodes": [9] })).unwrap(); + s.script("MOVE\n0,0\n1,1\n").unwrap(); + assert!(s.running.is_none(), "MOVE takes the picked parameter as its selection"); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let ParameterKind::Linear { base, end, .. } = &m.parameters[0].kind else { panic!() }; + assert_eq!((*base, *end), (Vec3::new(0.0, -3.0, 0.0), Vec3::new(10.0, -3.0, 0.0))); + let ParameterKind::Point { at, .. } = &m.parameters[1].kind else { panic!() }; + assert_eq!(*at, Vec3::new(3.0, 3.0, 0.0)); + let a = &m.actions[0]; + assert_eq!(a.at, Vec3::new(12.0, -5.0, 0.0)); + let ActionKind::Stretch { frame, .. } = &a.kind else { panic!() }; + assert_eq!(frame, &[Vec2::new(8.0, -2.0), Vec2::new(12.0, 6.0)], "the frame stays, as in AutoCAD"); + // Grips follow (in the editor's coordinates). + s.execute("blocks.element.select", &json!({ "nodes": [1, 9] })).unwrap(); + let grips = s.element_grips(); + assert!(grips.contains(&(1, ElementPoint::Base, Vec2::new(0.0, -3.0))), "{grips:?}"); + assert!(grips.contains(&(1, ElementPoint::Label, Vec2::new(5.0, -5.0))), "the label line stays 2 below: {grips:?}"); + assert!(grips.contains(&(9, ElementPoint::Label, Vec2::new(4.0, 4.0))), "{grips:?}"); +} + +#[test] +fn a_picked_parameters_grip_moves_one_point() { + let (mut s, _) = authored(); + s.execute("blocks.element.select", &json!({ "nodes": [1] })).unwrap(); + s.start_element_grip(1, ElementPoint::End).unwrap(); + s.input(Input::Point(Vec2::new(14.0, -1.0))).unwrap(); + assert!(s.running.is_none()); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let ParameterKind::Linear { end, .. } = &m.parameters[0].kind else { panic!() }; + assert_eq!(*end, Vec3::new(14.0, -1.0, 0.0)); + // The block works with the new length: a reference's Distance1 starts at 14. + s.execute("bclose", &json!({})).unwrap(); + let i = s.execute("insert", &json!({ "name": "Box", "at": [50, 0] })).unwrap()["handle"].clone(); + let props = s.execute("blocks.reference", &json!({ "handle": i })).unwrap(); + assert_eq!(props["properties"][0]["value"], "14.0000"); + // One undo step per grip edit. + let mut s = authored().0; + s.execute("blocks.element.select", &json!({ "nodes": [8] })).unwrap(); + s.execute("blocks.element.point", &json!({ "node": 8, "point": "at", "to": [20, 20] })).unwrap(); + assert_eq!(dynamic_block(s.doc().unwrap(), "Box").unwrap().actions[0].at, Vec3::new(20.0, 20.0, 0.0)); +} + +#[test] +fn escape_and_erase_work_on_picked_elements() { + let (mut s, _) = authored(); + s.execute("blocks.element.select", &json!({ "nodes": [9] })).unwrap(); + s.execute("blocks.element.select", &json!({ "nodes": [1], "add": true })).unwrap(); + assert_eq!(s.picked_elements(), [9, 1]); + s.cancel(); + assert!(s.picked_elements().is_empty(), "Escape unpicks"); + s.execute("blocks.element.select", &json!({ "nodes": [9] })).unwrap(); + s.script("ERASE\n").unwrap(); + assert!(s.running.is_none(), "ERASE takes the picked parameter"); + assert_eq!(names(&s), ["Linear", "Stretch"]); +} + +#[test] +fn hostile_element_params_never_panic() { + let (mut s, _) = authored(); + let many: Vec = (0..20_001).collect(); + for (cmd, p) in [ + ("blocks.element.select", json!({ "nodes": [99] })), + ("blocks.element.select", json!({ "nodes": "1" })), + ("blocks.element.select", json!({ "nodes": many })), + ("blocks.element.move", json!({ "nodes": [1] })), + ("blocks.element.move", json!({ "nodes": [1], "delta": "far" })), + ("blocks.element.move", json!({ "nodes": [99], "delta": [1, 0] })), + ("blocks.element.point", json!({ "node": 1, "point": "end", "to": [0, -1] })), + ("blocks.element.point", json!({ "node": 1, "point": "middle", "to": [0, 0] })), + ("blocks.element.point", json!({ "node": 8, "point": "base", "to": [0, 0] })), + ("blocks.element.point", json!({ "node": 2, "point": "at", "to": [0, 0] })), + ("blocks.element.erase", json!({ "nodes": [2] })), + ("blocks.element.erase", json!({ "nodes": [99] })), + ] { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + } + assert_eq!(names(&s), ["Linear", "Point", "Stretch"], "nothing changed"); + assert_eq!(s.execute("blocks.element.points", &json!({ "node": -5 })).unwrap(), json!({ "points": [] })); + assert!(s.start_element_grip(42, ElementPoint::At).is_err()); + // Outside the editor. + s.execute("bclose", &json!({ "save": false })).unwrap(); + assert!(s.execute("blocks.element.select", &json!({ "nodes": [1] })).is_err()); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index fcc464be3a..32e3064713 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -857,6 +857,9 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { if let Err(e) = result { app.session.echo(e.to_string()); } + } else if let Some(t) = blockedit::target(app, ui.ctx(), &xf, hover_pos) { + // The Block Editor's parameters and actions, and their grips, before objects. + blockedit::click(app, t, mods.shift); } else if let Some(g) = crate::dyngrips::at(app, &xf, hover_pos) { crate::dyngrips::click(app, g); } else if let Some(g) = grip_at(app, &xf, hover_pos) { @@ -880,6 +883,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { && rect.contains(origin) && grip_at(app, &xf, Some(origin)).is_none() && crate::dyngrips::at(app, &xf, Some(origin)).is_none() + && blockedit::target(app, ui.ctx(), &xf, Some(origin)).is_none() { app.canvas.drag_window = app.session.begin_window(xf.to_world(origin)); } diff --git a/crates/ui-egui/src/canvas/blockedit.rs b/crates/ui-egui/src/canvas/blockedit.rs index 6365d1bfe1..503b473c1d 100644 --- a/crates/ui-egui/src/canvas/blockedit.rs +++ b/crates/ui-egui/src/canvas/blockedit.rs @@ -3,17 +3,22 @@ //! parameters and actions (BPARAMETER, BACTION) drawn as the editor shows them, and a bar with //! the block's name and Save Block, Save Block As and Close Block Editor. A block with visibility //! states gets Visibility Mode (BVMODE), the state shown (picked from a list, as AutoCAD's -//! Visibility panel offers it), Visibility States, Make Visible and Make Invisible; with BVMODE 1 the objects the state hides -//! are drawn dimmed. +//! Visibility panel offers it), Visibility States, Make Visible and Make Invisible; with BVMODE 1 +//! the objects the state hides are drawn dimmed. +//! +//! Parameters and actions are picked with a click ([`target`], [`click`]; Shift+click unpicks), +//! as in AutoCAD's editor: picked ones are drawn heavier with grips at their points, and clicking +//! a grip moves that point. MOVE, ERASE and Delete act on them (the engine's +//! `blocks.element.*`). use std::sync::Arc; use cadcraft_engine::doc::Handle; -use cadcraft_engine::doc::dynblock::{Mark, ParameterKind, dynamic_block}; +use cadcraft_engine::doc::dynblock::{ElementPoint, Mark, ParameterKind, dynamic_block}; use cadcraft_engine::geom::Vec2; use cadcraft_render::DisplayList; use egui::{Align2, Color32, FontId, Painter, Pos2, Rect, RichText, Shape, Stroke, vec2}; -use serde_json::json; +use serde_json::{Value, json}; use super::Xf; use crate::CadApp; @@ -102,6 +107,7 @@ pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, p: &egui::Painter, xf p.line_segment([o - vec2(0.0, 12.0), o + vec2(0.0, 12.0)], st); } paint_marks(app, ctx, p, xf); + paint_grips(app, p, xf); let vis = states(app, ctx); if app.session.settings.bvmode && let Some(v) = &vis @@ -202,6 +208,105 @@ fn marks(app: &CadApp, ctx: &egui::Context) -> Arc<(Vec, Vec)> { m } +/// What a click in the Block Editor hits first: a picked parameter's or action's grip, or a +/// parameter or action. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Target { + Grip(i32, ElementPoint), + Mark(i32), +} + +/// How far from the cursor (screen points) a mark or grip still counts as hit. +const REACH: f32 = 6.0; + +fn segment_distance(a: Pos2, b: Pos2, p: Pos2) -> f32 { + let d = b - a; + let t = if d.length_sq() <= 1e-6 { 0.0 } else { ((p - a).dot(d) / d.length_sq()).clamp(0.0, 1.0) }; + (a + d * t).distance(p) +} + +/// About where a label of `text` drawn at `at` with `align` lies (12-point text). +fn label_rect(at: Pos2, align: Align2, text: &str) -> Rect { + let size = vec2(7.0 * text.chars().count() as f32, 14.0); + align.anchor_size(at, size) +} + +/// The graph id a mark stands for (a parameter's or an action's). +fn mark_node(m: &Mark) -> i32 { + match m { + Mark::Action { node, .. } => *node, + other => other.parameter_node().unwrap_or(0), + } +} + +/// The grip or mark under `pos`, when the Block Editor is open with no command running. +pub(super) fn target(app: &CadApp, ctx: &egui::Context, xf: &Xf, pos: Option) -> Option { + let pos = pos?; + if app.session.prompting() || editing(app).is_none() { + return None; + } + if let Some((n, w, _)) = app.session.element_grips().into_iter().find(|(_, _, at)| xf.to_screen(*at).distance(pos) <= REACH) { + return Some(Target::Grip(n, w)); + } + let to = |v: cadcraft_engine::geom::Vec3| xf.to_screen(v.xy()); + let marks = marks(app, ctx); + marks + .0 + .iter() + .find(|m| match m { + Mark::Linear { base, end, offset, label, .. } => { + let (a, b) = (base.xy(), end.xy()); + let dir = (b - a).normalized(); + let shift = Vec2::new(-dir.y, dir.x) * *offset; + let (da, db) = (xf.to_screen(a + shift), xf.to_screen(b + shift)); + let (sa, sb) = (to(*base), to(*end)); + [(sa, da), (sb, db), (da, db)].iter().any(|(p, q)| segment_distance(*p, *q, pos) <= REACH) + || label_rect(da + (db - da) * 0.5, Align2::CENTER_BOTTOM, label).contains(pos) + } + Mark::Point { at, label_at, label, .. } => { + let (s, l) = (to(*at), to(*label_at)); + s.distance(pos) <= REACH || segment_distance(s, l, pos) <= REACH || label_rect(l, Align2::LEFT_BOTTOM, label).contains(pos) + } + Mark::List { at, label, .. } => { + let s = to(*at); + s.distance(pos) <= REACH + 2.0 || label_rect(s + vec2(8.0, 0.0), Align2::LEFT_CENTER, label).contains(pos) + } + Mark::Parameter { at, label, .. } => label_rect(to(*at), Align2::LEFT_BOTTOM, label).contains(pos), + Mark::Action { at, name, .. } => label_rect(to(*at), Align2::CENTER_CENTER, name).expand2(vec2(4.0, 2.0)).contains(pos), + }) + .map(|m| Target::Mark(mark_node(m))) +} + +/// A click on `t`: a grip starts moving its point; a parameter or action is picked (Shift+click +/// unpicks it). +pub(super) fn click(app: &mut CadApp, t: Target, shift: bool) { + let r = match t { + Target::Grip(n, w) => app.session.start_element_grip(n, w).map(|_| Value::Null).map_err(|e| e.to_string()), + Target::Mark(n) => { + let picked = app.session.picked_elements(); + if shift && picked.contains(&n) { + let rest: Vec = picked.into_iter().filter(|p| *p != n).collect(); + app.run("blocks.element.select", json!({ "nodes": rest })) + } else { + app.run("blocks.element.select", json!({ "nodes": [n], "add": true })) + } + } + }; + if let Err(e) = r { + app.session.echo(e); + } +} + +/// The picked parameters' and actions' grips: squares at their points, as entity grips. +fn paint_grips(app: &CadApp, p: &Painter, xf: &Xf) { + let t = Tokens::get(); + for (_, _, at) in app.session.element_grips() { + let r = Rect::from_center_size(xf.to_screen(at), vec2(9.0, 9.0)); + p.rect_filled(r, 0.0, t.grip); + p.rect_stroke(r, 0.0, Stroke::new(1.0, t.canvas), egui::StrokeKind::Middle); + } +} + /// A filled arrow at `at` pointing along screen direction `u`, as a linear parameter's grip. fn arrow(p: &Painter, at: Pos2, u: egui::Vec2, color: Color32) { let n = vec2(-u.y, u.x); @@ -218,12 +323,15 @@ fn paint_marks(app: &CadApp, ctx: &egui::Context, p: &Painter, xf: &Xf) { let to = |v: cadcraft_engine::geom::Vec3| xf.to_screen(v.xy()); let marks = marks(app, ctx); let (all, inactive) = &*marks; + let picked = app.session.picked_elements(); for m in all { // A parameter the visibility state leaves out shows dimmed (BVMODE 1). let dim = m.parameter_node().is_some_and(|n| inactive.contains(&n)); let fade = |c: Color32| if dim { c.gamma_multiply(0.35) } else { c }; let (accent, grip_dyn) = (fade(t.accent), fade(t.grip_dyn)); - let line = Stroke::new(1.0, accent); + // Picked ones are drawn heavier. + let width = if picked.contains(&mark_node(m)) { 2.5 } else { 1.0 }; + let line = Stroke::new(width, accent); match m { Mark::Linear { base, end, offset, label, base_grip, end_grip, .. } => { let (a, b) = (base.xy(), end.xy()); @@ -271,7 +379,7 @@ fn paint_marks(app: &CadApp, ctx: &egui::Context, p: &Painter, xf: &Xf) { let g = p.layout_no_wrap(name.clone(), font.clone(), t.text); let r = Rect::from_center_size(c, g.size() + vec2(8.0, 4.0)); p.rect_filled(r, 3.0, t.cmd_bg); - p.rect_stroke(r, 3.0, Stroke::new(1.0, t.warn), egui::StrokeKind::Middle); + p.rect_stroke(r, 3.0, Stroke::new(width, t.warn), egui::StrokeKind::Middle); p.galley(r.min + vec2(4.0, 2.0), g, t.text); } } diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 65f57434bc..96addf529a 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -112,6 +112,10 @@ pub fn entries(app: &CadApp) -> Vec> { let mut clip: Vec = sub("Clipboard", items(app, CLIPBOARD)).into_iter().collect(); clip.extend(sub("Isolate", items(app, ISOLATE))); push(&mut groups, clip); + // Only parameters or actions picked in the Block Editor: what acts on them. + if !selected && !app.session.picked_elements().is_empty() { + push(&mut groups, items(app, &["erase", "move"])); + } if selected { let mut edit: Vec = EDIT.iter().filter_map(|(id, label)| item(app, id, *label)).collect(); edit.extend(sub("Draw Order", items(app, DRAW_ORDER))); diff --git a/docs/gaps.md b/docs/gaps.md index a40d07cbd5..34fb675cf7 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -26,7 +26,7 @@ do them first. |---|---|---|---|---| | F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | | F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | -| F3 | **[alpha blocker]** (dynamic-block authoring is beta) Dynamic-block authoring has started: in the Block Editor, BPARAMETER adds linear, point and visibility parameters and BACTION stretch and move actions; BVSTATE (the Visibility States dialog: Set current, New, Rename, Delete, Move Up, Move Down; -BVSTATE: New, Set, Delete), BVHIDE and BVSHOW (also Object Visibility on the editor's right-click menu) edit visibility states, the editor shows the state picked on its bar and hides (BVMODE 0) or dims (BVMODE 1) what it hides (AutoCAD's prompts, JSON forms), all written so AutoCAD opens the block as a dynamic block (DXF and DWG), and the editor draws them. Missing: the other parameters (polar, XY, rotation, flip, alignment, base point, lookup) and actions (scale, rotate, flip, array, polar stretch, lookup), lookup tables (BLOOKUPTABLE), selecting and editing parameters and actions in the editor, the Name/Chain/Value set options, Authoring Palettes, BTESTBLOCK. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips); BEDIT (which, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS, BCLOSE and REFEDIT edit block definitions | issue #185 offers help | High: standard libraries are dynamic | 30–50 | +| F3 | **[alpha blocker]** (dynamic-block authoring is beta) Dynamic-block authoring has started: in the Block Editor, BPARAMETER adds linear, point and visibility parameters and BACTION stretch and move actions; BVSTATE (the Visibility States dialog: Set current, New, Rename, Delete, Move Up, Move Down; -BVSTATE: New, Set, Delete), BVHIDE and BVSHOW (also Object Visibility on the editor's right-click menu) edit visibility states, the editor shows the state picked on its bar and hides (BVMODE 0) or dims (BVMODE 1) what it hides (AutoCAD's prompts, JSON forms), all written so AutoCAD opens the block as a dynamic block (DXF and DWG), and the editor draws them. Missing: the other parameters (polar, XY, rotation, flip, alignment, base point, lookup) and actions (scale, rotate, flip, array, polar stretch, lookup), lookup tables (BLOOKUPTABLE), grip-editing points beyond a linear parameter's ends and label, a point parameter's location and label, a list grip's and an action's location, window selection of parameters and actions, Properties for them, BACTIONSET, the Name/Chain/Value set options, Authoring Palettes, BTESTBLOCK. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips); BEDIT (which, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS, BCLOSE and REFEDIT edit block definitions | issue #185 offers help | High: standard libraries are dynamic | 30–50 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | | F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 | @@ -156,6 +156,7 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | | 2026-10-22 | minor | APPLOAD typed or from Tools ▸ Load Application opens a `.lsp` file browser starting in the last-used folder (kept in the preferences); a picked file loads interactively like a typed name (routines that ask for input wait), the web says to drop the file (no file system), and the JSON form `{path}` reads the path as given and returns the commands the file defined, never opening a dialog (#1820): E1 narrowed | +| 2026-10-25 | minor | F3: parameters and actions are picked with a click in the Block Editor (Shift+click unpicks, Escape clears), drawn heavier with grips; a grip moves that point; MOVE, ERASE and Delete act on them, a parameter's actions erased with it, as AutoCAD does; the graph keeps its id counter (AutoCAD read no erased block from DXF without it) | | 2026-10-25 | minor | F3: visibility authoring. BPARAMETER adds a visibility parameter; BVSTATE (the Visibility States dialog, or -BVSTATE's New with Hide all / Show all / Current visibility, Set, Delete), BVHIDE and BVSHOW (current or all states; also the right-click menu's Object Visibility) edit its states with AutoCAD's prompts; objects drawn and parameters added show in the state shown, as AutoCAD keeps them; BVMODE; AutoCAD reads the states from DXF and DWG. A grip's location components now name their own parameter (AutoCAD evaluated no parameter of a block with a second one) | | 2026-10-21 | minor | F3: dynamic-block authoring started. In the Block Editor BPARAMETER adds linear and point parameters, BACTION stretch and move actions, with AutoCAD's prompts and JSON forms; AutoCAD opens the result as a dynamic block from DXF and DWG; the editor draws them (40–65 → 30–50 h) | | 2026-10-16 | minor | ALIASEDIT typed or from Tools ▸ Customize opens the Command Aliases dialog (user aliases next to the built-in ones; Add, Edit, Remove; OK, Cancel, Apply), #1381: U12 and E5 narrowed | From f1bb35e5f3522b2ac7227e5fe471b65b066c6ead Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:28:44 -0600 Subject: [PATCH 16/47] Visibility States dialogs: window ids use egui 0.37's Id::unique Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/bvstate.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/bvstate.rs b/crates/ui-egui/src/bvstate.rs index 204a560693..05f80e42a6 100644 --- a/crates/ui-egui/src/bvstate.rs +++ b/crates/ui-egui/src/bvstate.rs @@ -174,7 +174,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { let mut st = std::mem::take(&mut app.bvstate); let modal = st.new.is_some(); egui::Window::new(crate::tl!("Visibility States")) - .id(egui::Id::new("Visibility States")) + .id(egui::Id::unique("Visibility States")) .open(open) .collapsible(false) .resizable(false) @@ -300,7 +300,7 @@ fn new_dialog(ctx: &egui::Context, st: &mut State) { let (mut ok, mut cancel) = (false, false); let mut open = true; egui::Window::new(crate::tl!("New Visibility State")) - .id(egui::Id::new("New Visibility State")) + .id(egui::Id::unique("New Visibility State")) .open(&mut open) .collapsible(false) .resizable(false) From 3c344a455de034de2f2791d7400ec0674f4aaa85 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:03:40 -0600 Subject: [PATCH 17/47] Dynamic blocks: erasing keeps edge flags; MOVE leaves an unmovable parameter; BVMODE without a drawing Review fixes: - Erasing parameters or actions links the remaining edges again with their own flags (a graph read from a file may set them), not 0. - MOVE with a picked parameter of a kind that can't be moved yet (a polar parameter from AutoCAD) leaves it where it is and says so; the objects and other picked ones move once and the command ends, instead of stopping after the objects had moved. - Setting BVMODE with no drawing open (saved settings at startup) succeeds like the other session variables. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/edit.rs | 40 +++++++++++++++++++++++++-- crates/engine/src/blockedit.rs | 25 ++++++++++++++--- crates/engine/tests/block_elements.rs | 34 +++++++++++++++++++++++ 3 files changed, 93 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/dynblock/edit.rs b/crates/doc/src/dynblock/edit.rs index d621567977..7f82fc735f 100644 --- a/crates/doc/src/dynblock/edit.rs +++ b/crates/doc/src/dynblock/edit.rs @@ -270,15 +270,19 @@ pub fn erase_elements(d: &mut Drawing, block: &str, nodes: &[i32]) -> Result = g.nodes.iter().filter(|n| !gone.contains(&n.index)).cloned().collect(); let renumber: Vec<(i32, i32)> = kept.iter().zip(0..).map(|(n, i)| (n.index, i)).collect(); let new_index = |old: i32| renumber.iter().find(|(o, _)| *o == old).map(|(_, n)| *n); - let edges: Vec<(i32, i32, i32)> = g.edges.iter().filter_map(|e| Some((new_index(e.from)?, new_index(e.to)?, e.kind))).collect(); + let edges: Vec<(i32, i32, i32, i32)> = g.edges.iter().filter_map(|e| Some((new_index(e.from)?, new_index(e.to)?, e.kind, e.flags))).collect(); g.nodes = kept; for (n, i) in g.nodes.iter_mut().zip(0..) { n.index = i; n.links = [-1; 4]; } g.edges.clear(); - for (from, to, kind) in edges { + for (from, to, kind, flags) in edges { g.link(from, to, kind); + // An edge keeps its flags (a graph read from a file may have set some). + if let Some(e) = g.edges.last_mut() { + e.flags = flags; + } } let erased_handles: Vec = handles.clone(); let f = std::sync::Arc::make_mut(&mut d.foreign); @@ -335,3 +339,35 @@ pub fn element_points(d: &Drawing, block: &str, node: i32) -> Vec<(ElementPoint, _ => Vec::new(), } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::dynblock::{ActionSpec, ParamPoint, ParameterSpec, add_action, add_parameter}; + + fn v(x: f64, y: f64) -> Vec3 { + Vec3::new(x, y, 0.0) + } + + /// Erasing keeps the flags of the edges that stay (a graph from a file may set them). + #[test] + fn erasing_keeps_the_remaining_edges_flags() { + let mut d = Drawing::default(); + let p = add_parameter(&mut d, "B", &ParameterSpec::Linear { base: v(0.0, 0.0), end: v(10.0, 0.0), label: None, label_offset: 0.0, grips: 2 }) + .unwrap(); + let a = + add_action(&mut d, "B", &ActionSpec::Move { parameter: p, point: ParamPoint::End, selection: vec![Handle(1)], at: v(1.0, 1.0) }).unwrap(); + let mut g = graph(&d, "B").unwrap(); + for e in &mut g.edges { + e.flags = 4; + } + let tags = g.tags(); + if let Some(o) = object_mut(&mut d, g.handle) { + o.tags = tags; + } + assert_eq!(erase_elements(&mut d, "B", &[a]).unwrap(), [a]); + let g = graph(&d, "B").unwrap(); + assert_eq!(g.edges.len(), 6, "the parameter's components and grips"); + assert!(g.edges.iter().all(|e| e.flags == 4), "{:?}", g.edges); + } +} diff --git a/crates/engine/src/blockedit.rs b/crates/engine/src/blockedit.rs index 193a2a8905..391c32a645 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -502,7 +502,8 @@ impl crate::Session { /// objects hidden, or with BVMODE 1 left for the canvas to dim. Nothing outside the editor. pub(crate) fn refresh_block_visibility(&mut self) -> Result<()> { let bvmode = self.settings.bvmode; - let st = self.state()?; + // Without a drawing there is no Block Editor (SETVAR BVMODE from the Start tab). + let Ok(st) = self.state() else { return Ok(()) }; let Some(be) = &st.block_edit else { return Ok(()) }; let hidden = if bvmode { Vec::new() } else { be.visibility_state(&st.doc).map(|(_, h)| h).unwrap_or_default() }; let hidden: std::collections::BTreeSet<_> = hidden.into_iter().filter(|h| st.doc.model.get(*h).is_some()).collect(); @@ -537,6 +538,8 @@ impl crate::Session { } /// Move the picked parameters and actions by `d` (MOVE with them picked); they stay picked. + /// One that can't be moved yet (a kind from another file, such as a polar parameter) stays + /// where it is and is reported, so MOVE never stops after the objects have moved. pub(crate) fn move_picked_elements(&mut self, d: Vec2) -> Result { let nodes = self.picked_elements(); if nodes.is_empty() || d == Vec2::ZERO { @@ -544,11 +547,25 @@ impl crate::Session { } let name = self.state()?.block_edit.as_ref().map(|b| b.name.clone()).unwrap_or_default(); let mut doc = self.doc()?.clone(); + let (mut moved, mut stayed) = (0, 0); for n in &nodes { - cadcraft_doc::dynblock::move_element(&mut doc, &name, *n, d.to3(0.0)).map_err(EngineError::Other)?; + // Each on a copy: a refused one leaves the others' moves alone. + let mut trial = doc.clone(); + match cadcraft_doc::dynblock::move_element(&mut trial, &name, *n, d.to3(0.0)) { + Ok(()) => { + doc = trial; + moved += 1; + } + Err(_) => stayed += 1, + } } - *self.doc_mut()? = doc; - Ok(nodes.len()) + if stayed > 0 { + self.echo(format!("{stayed} parameter(s) of a kind that can't be moved yet stayed where they were.")); + } + if moved > 0 { + *self.doc_mut()? = doc; + } + Ok(moved) } /// Erase the picked parameters and actions (ERASE, Delete), as AutoCAD erases them: a diff --git a/crates/engine/tests/block_elements.rs b/crates/engine/tests/block_elements.rs index f4b84d25bd..f4c16f315b 100644 --- a/crates/engine/tests/block_elements.rs +++ b/crates/engine/tests/block_elements.rs @@ -160,3 +160,37 @@ fn hostile_element_params_never_panic() { s.execute("bclose", &json!({ "save": false })).unwrap(); assert!(s.execute("blocks.element.select", &json!({ "nodes": [1] })).is_err()); } + +/// A picked parameter of a kind that can't be moved yet (here a polar parameter, as AutoCAD's +/// blocks have) stays put; MOVE still moves the objects and the other picked ones, once. +#[test] +fn move_leaves_a_parameter_it_cannot_move_and_finishes() { + let (mut s, rect) = authored(); + { + let d = s.doc_mut().unwrap(); + let f = std::sync::Arc::make_mut(&mut d.foreign); + let o = f.objects.iter_mut().find(|o| o.kind == "BLOCKLINEARPARAMETER").unwrap(); + o.kind = "BLOCKPOLARPARAMETER".into(); + } + s.execute("blocks.element.select", &json!({ "nodes": [1, 9] })).unwrap(); + s.execute("select", &json!({ "handles": [rect.hex()] })).unwrap(); + s.script("MOVE\n0,0\n1,0\n").unwrap(); + assert!(s.running.is_none(), "MOVE finished"); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let ParameterKind::Polar { base, .. } = &m.parameters[0].kind else { panic!("{:?}", m.parameters[0].kind) }; + assert_eq!(*base, Vec3::new(0.0, -1.0, 0.0), "the polar parameter stayed"); + let ParameterKind::Point { at, .. } = &m.parameters[1].kind else { panic!() }; + assert_eq!(*at, Vec3::new(3.0, 2.0, 0.0), "the point parameter moved"); + let EntityKind::LwPolyline(pl) = &s.doc().unwrap().entity(rect).unwrap().kind else { panic!() }; + assert_eq!(pl.vertices[0].p, Vec2::new(1.0, 0.0), "the rectangle moved once"); +} + +/// BVMODE can be set before any drawing is open (saved settings load at startup), like the +/// other session variables. +#[test] +fn bvmode_is_set_without_a_drawing() { + let mut s = Session::empty(); + cadcraft_engine::sysvars::set(&mut s, "BVMODE", &json!(1)).unwrap(); + assert!(s.settings.bvmode); + cadcraft_engine::sysvars::set(&mut s, "OSMODE", &json!(3)).unwrap(); +} From 69eaaadb460146315f105d74f097e1ded4ab582a Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:12:18 -0600 Subject: [PATCH 18/47] Dynamic blocks: a linear parameter's lone end grip moves with it; nothing picked skips the graph A linear parameter's grips are kept by position, so one with only its end grip (BPARAMETER accepts 0, 1 or 2 grips) moves that grip on MOVE and on an endpoint drag instead of leaving it behind. picked_elements returns at once when nothing is picked. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/edit.rs | 44 +++++++++++++++++++++++++-------- crates/engine/src/blockedit.rs | 3 +++ 2 files changed, 37 insertions(+), 10 deletions(-) diff --git a/crates/doc/src/dynblock/edit.rs b/crates/doc/src/dynblock/edit.rs index 7f82fc735f..877f9a2799 100644 --- a/crates/doc/src/dynblock/edit.rs +++ b/crates/doc/src/dynblock/edit.rs @@ -84,12 +84,12 @@ fn set_real(tags: &mut [RawTag], marker: &str, code: i32, v: f64) { } /// Element graph id `node` of `block`: its object's kind and handle, and its grips' handles by -/// grip id (a linear parameter's base grip first). +/// position (a linear parameter's base grip first; `None` where it has no grip there). struct Element { kind: String, handle: Handle, param: Option, - grips: Vec, + grips: Vec>, } fn element(d: &Drawing, block: &str, node: i32) -> Result { @@ -99,7 +99,7 @@ fn element(d: &Drawing, block: &str, node: i32) -> Result { let m = dynamic_block(d, block); let p = m.as_ref().and_then(|m| m.parameters.iter().find(|p| p.node == node)); let grips = match (&m, p) { - (Some(m), Some(p)) => p.grips.iter().filter_map(|id| m.grip_objects.iter().find(|(g, _)| g == id).map(|(_, h)| *h)).collect(), + (Some(m), Some(p)) => p.grips.iter().map(|id| m.grip_objects.iter().find(|(g, _)| g == id).map(|(_, h)| *h)).collect(), _ => Vec::new(), }; Ok(Element { kind: o.kind.clone(), handle: o.handle, param: p.map(|p| p.kind.clone()), grips }) @@ -142,9 +142,10 @@ pub fn move_element(d: &mut Drawing, block: &str, node: i32, delta: Vec3) -> Res set_point(&mut o.tags, "AcDbBlock2PtParameter", 1010, b); set_point(&mut o.tags, "AcDbBlock2PtParameter", 1011, n); } - if let [bg, eg] = e.grips[..] { - move_grip(d, bg, b, None); - move_grip(d, eg, n, None); + for (grip, at) in e.grips.iter().zip([b, n]) { + if let Some(g) = grip { + move_grip(d, *g, at, None); + } } Ok(()) } @@ -183,9 +184,10 @@ pub fn set_element_point(d: &mut Drawing, block: &str, node: i32, which: Element if let Some(o) = object_mut(d, e.handle) { set_point(&mut o.tags, "AcDbBlock2PtParameter", if which == ElementPoint::Base { 1010 } else { 1011 }, to); } - if let [bg, eg] = e.grips[..] { - move_grip(d, bg, b, Some(-dir)); - move_grip(d, eg, n, Some(dir)); + for (grip, (at, dir)) in e.grips.iter().zip([(b, -dir), (n, dir)]) { + if let Some(g) = grip { + move_grip(d, *g, at, Some(dir)); + } } Ok(()) } @@ -202,7 +204,7 @@ pub fn set_element_point(d: &mut Drawing, block: &str, node: i32, which: Element if let Some(o) = object_mut(d, e.handle) { set_point(&mut o.tags, "AcDbBlock1PtParameter", 1010, to); } - if let Some(g) = e.grips.first() { + if let Some(Some(g)) = e.grips.first() { move_grip(d, *g, to, None); } Ok(()) @@ -370,4 +372,26 @@ mod tests { assert_eq!(g.edges.len(), 6, "the parameter's components and grips"); assert!(g.edges.iter().all(|e| e.flags == 4), "{:?}", g.edges); } + + /// A linear parameter with only its end grip: moving it, or its endpoint, takes that grip along. + #[test] + fn a_lone_end_grip_follows_its_linear_parameter() { + let mut d = Drawing::default(); + let p = add_parameter(&mut d, "B", &ParameterSpec::Linear { base: v(0.0, 0.0), end: v(10.0, 0.0), label: None, label_offset: 0.0, grips: 1 }) + .unwrap(); + let grip = |d: &Drawing| { + let m = dynamic_block(d, "B").unwrap(); + let id = m.parameters.iter().find(|x| x.node == p).unwrap().grips.iter().copied().find(|g| *g != 0).unwrap(); + let h = m.grip_objects.iter().find(|(g, _)| *g == id).unwrap().1; + let tags = &d.foreign.objects.iter().find(|o| o.handle == h).unwrap().tags; + let dir_x = find(tags, "AcDbBlockLinearGrip", 140).and_then(|i| tags[i].value.trim().parse::().ok()); + (point_at(tags, "AcDbBlockGrip", 1010).unwrap(), dir_x) + }; + move_element(&mut d, "B", p, v(5.0, 1.0)).unwrap(); + assert_eq!(grip(&d).0, v(15.0, 1.0)); + set_element_point(&mut d, "B", p, ElementPoint::End, v(5.0, 11.0)).unwrap(); + let (at, dir_x) = grip(&d); + assert_eq!(at, v(5.0, 11.0)); + assert!(dir_x.is_some_and(|x| x.abs() < 1e-9), "the grip points along the new direction (0, 10): {dir_x:?}"); + } } diff --git a/crates/engine/src/blockedit.rs b/crates/engine/src/blockedit.rs index 391c32a645..061aea5ead 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -517,6 +517,9 @@ impl crate::Session { pub fn picked_elements(&self) -> Vec { let Ok(st) = self.state() else { return Vec::new() }; let Some(be) = &st.block_edit else { return Vec::new() }; + if be.picked.is_empty() { + return Vec::new(); + } let Some(m) = cadcraft_doc::dynblock::dynamic_block(&st.doc, &be.name) else { return Vec::new() }; be.picked.iter().copied().filter(|n| m.parameters.iter().any(|p| p.node == *n) || m.actions.iter().any(|a| a.node == *n)).collect() } From c049412dd81822faca967c0bcc12faf6e6b8d31c Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:27:04 -0600 Subject: [PATCH 19/47] Dynamic blocks: picked elements follow PICKFIRST, JSON handles and win over selection cycling Review fixes: - MOVE/ERASE with parameters or actions picked in the Block Editor take the object selection along only when PICKFIRST lets a selection count. - JSON MOVE/ERASE given `handles` (or `handle`) act on those objects only; picked parameters and actions come along only when the command uses the selection. - A click on a parameter, action or their grip in the Block Editor is theirs, not the start of selection cycling over the objects under it. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/modify/select_then.rs | 5 +-- crates/engine/src/cmd/modify/transform.rs | 16 +++++++--- crates/engine/tests/block_elements.rs | 34 +++++++++++++++++++++ crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/canvas/cycle.rs | 5 +-- 5 files changed, 52 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/modify/select_then.rs b/crates/engine/src/cmd/modify/select_then.rs index 66966e98f5..292c7f06b6 100644 --- a/crates/engine/src/cmd/modify/select_then.rs +++ b/crates/engine/src/cmd/modify/select_then.rs @@ -62,7 +62,7 @@ impl SelectThen { // Immediate operations once selection is done. match self.op { Op::Erase => { - let n = erase(s, &self.objs)?; + let n = erase(s, &self.objs, true)?; let _ = n; Ok(Step::Done) } @@ -295,7 +295,8 @@ impl Interactive for SelectThen { self.sel = SelectPhase::begin(s); // Parameters or actions picked in the Block Editor are a selection for MOVE and ERASE. if !self.sel.done && matches!(self.op, Op::Move | Op::Erase) && !s.picked_elements().is_empty() { - self.sel.picked = s.selection(); + // Selected objects come along only where PICKFIRST lets a selection count. + self.sel.picked = if s.settings.pickfirst { s.selection() } else { Vec::new() }; self.sel.done = true; } if self.sel.done { diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index 8c446052b5..7e6f17a40c 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -28,9 +28,15 @@ pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: Ok(out) } -pub(super) fn erase(s: &mut Session, hs: &[Handle]) -> Result { - // The Block Editor's picked parameters and actions go too. - let mut n = s.erase_picked_elements()?; +/// Whether a JSON call acts on the selection (no `handles` or `handle` given): only then do the +/// Block Editor's picked parameters and actions come along. +fn default_selection(p: &Value) -> bool { + p.get("handles").is_none_or(Value::is_null) && p.get("handle").is_none_or(Value::is_null) +} + +/// Erase `hs`, and with `picked` the Block Editor's picked parameters and actions too. +pub(super) fn erase(s: &mut Session, hs: &[Handle], picked: bool) -> Result { + let mut n = if picked { s.erase_picked_elements()? } else { 0 }; let d = s.doc_mut()?; for h in hs { let locked = d.entity(*h).and_then(|e| d.layer(&e.common.layer)).is_some_and(|l| l.locked); @@ -44,7 +50,7 @@ pub(super) fn erase(s: &mut Session, hs: &[Handle]) -> Result { pub(super) fn run_erase(s: &mut Session, p: &Value) -> Result { let hs = targets(s, p)?; - let n = erase(s, &hs)?; + let n = erase(s, &hs, default_selection(p))?; Ok(json!({ "erased": n })) } @@ -61,7 +67,7 @@ pub(super) fn run_move(s: &mut Session, p: &Value) -> Result { let hs = targets(s, p)?; let d = delta_of("move", p)?; let moved = transform_entities(s, &hs, &Mat3::translate(d), false)?; - let marks = s.move_picked_elements(d)?; + let marks = if default_selection(p) { s.move_picked_elements(d)? } else { 0 }; Ok(json!({ "moved": moved.len() + marks })) } diff --git a/crates/engine/tests/block_elements.rs b/crates/engine/tests/block_elements.rs index f4c16f315b..dc54629588 100644 --- a/crates/engine/tests/block_elements.rs +++ b/crates/engine/tests/block_elements.rs @@ -194,3 +194,37 @@ fn bvmode_is_set_without_a_drawing() { assert!(s.settings.bvmode); cadcraft_engine::sysvars::set(&mut s, "OSMODE", &json!(3)).unwrap(); } + +/// A JSON MOVE or ERASE given `handles` acts on those objects only; picked parameters and +/// actions come along only when the command uses the selection. +#[test] +fn json_handles_leave_picked_elements_alone() { + let (mut s, rect) = authored(); + s.execute("blocks.element.select", &json!({ "nodes": [9] })).unwrap(); + s.execute("erase", &json!({ "handles": [] })).unwrap(); + assert_eq!(names(&s), ["Linear", "Point", "Stretch"], "an empty list erases nothing"); + s.execute("move", &json!({ "handles": [rect.hex()], "delta": [1, 0] })).unwrap(); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let ParameterKind::Point { at, .. } = &m.parameters[1].kind else { panic!() }; + assert_eq!(*at, Vec3::new(2.0, 2.0, 0.0), "the picked point parameter stayed"); + s.execute("move", &json!({ "delta": [1, 0] })).unwrap(); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let ParameterKind::Point { at, .. } = &m.parameters[1].kind else { panic!() }; + assert_eq!(*at, Vec3::new(3.0, 2.0, 0.0), "with the selection, it moves"); +} + +/// With PICKFIRST off a selection made before MOVE doesn't count; picked parameters still do. +#[test] +fn pickfirst_off_moves_picked_elements_without_the_selection() { + let (mut s, rect) = authored(); + s.settings.pickfirst = false; + s.execute("select", &json!({ "handles": [rect.hex()] })).unwrap(); + s.execute("blocks.element.select", &json!({ "nodes": [9] })).unwrap(); + s.script("MOVE\n0,0\n1,0\n").unwrap(); + assert!(s.running.is_none()); + let EntityKind::LwPolyline(pl) = &s.doc().unwrap().entity(rect).unwrap().kind else { panic!() }; + assert_eq!(pl.vertices[0].p, Vec2::new(0.0, 0.0), "the selected rectangle stayed"); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let ParameterKind::Point { at, .. } = &m.parameters[1].kind else { panic!() }; + assert_eq!(*at, Vec3::new(3.0, 2.0, 0.0)); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 32e3064713..fd20011219 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -830,7 +830,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { app.canvas.hover_cycle = None; app.canvas.cycle_key = Some(key); } - let cycled = pressed_primary && !middle_down && cycle_click(app, &xf, hover_pos, raw_world.filter(|_| inside), mods.shift); + let cycled = pressed_primary && !middle_down && cycle_click(app, ui.ctx(), &xf, hover_pos, raw_world.filter(|_| inside), mods.shift); // Clicks. if inside && pressed_primary diff --git a/crates/ui-egui/src/canvas/cycle.rs b/crates/ui-egui/src/canvas/cycle.rs index e7dae44bc7..d5b1872cb4 100644 --- a/crates/ui-egui/src/canvas/cycle.rs +++ b/crates/ui-egui/src/canvas/cycle.rs @@ -20,7 +20,7 @@ impl CycleList { /// A click while selection cycling's list is open picks the row under it (anywhere else just /// closes the list); otherwise a click over overlapping objects that a pick would choose between /// opens the list (SELECTIONCYCLING 2). True when the click was used up here. -pub(super) fn cycle_click(app: &mut CadApp, xf: &Xf, hover: Option, world: Option, shift: bool) -> bool { +pub(super) fn cycle_click(app: &mut CadApp, ctx: &egui::Context, xf: &Xf, hover: Option, world: Option, shift: bool) -> bool { // Only where a click picks objects; a click that places a point goes through. let picks = app.session.click_picks(); if let Some((_, hs, i)) = app.canvas.hover_cycle.take() @@ -40,7 +40,8 @@ pub(super) fn cycle_click(app: &mut CadApp, xf: &Xf, hover: Option, world: return true; } let (Some(hp), Some(w)) = (hover, world) else { return false }; - if crate::dyngrips::at(app, xf, hover).is_some() || grip_at(app, xf, hover).is_some() { + // Grips, and the Block Editor's parameters, actions and their grips, take the click first. + if crate::dyngrips::at(app, xf, hover).is_some() || grip_at(app, xf, hover).is_some() || super::blockedit::target(app, ctx, xf, hover).is_some() { return false; } let hs = app.session.cycling_candidates(w); From 513d0245558cc62b974a7fffebffea649b513ae7 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 28 Oct 2026 09:37:13 -0600 Subject: [PATCH 20/47] Block Editor: the visibility state list uses craft-ui's ComboBox main bans egui::ComboBox (clippy.toml): its menu can't grow back while open. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/canvas/blockedit.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/blockedit.rs b/crates/ui-egui/src/canvas/blockedit.rs index 503b473c1d..da7c76d662 100644 --- a/crates/ui-egui/src/canvas/blockedit.rs +++ b/crates/ui-egui/src/canvas/blockedit.rs @@ -151,7 +151,7 @@ pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, p: &egui::Painter, xf { toggle_mode = true; } - egui::ComboBox::from_id_salt("cadcraft-block-editor-state").selected_text(v.current.as_str()).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt("cadcraft-block-editor-state").selected_text(v.current.as_str()).show_ui(ui, |ui| { for n in &v.names { if ui.selectable_label(*n == v.current, n.as_str()).clicked() && *n != v.current { pick = Some(n.clone()); From 9884b5c06a565b6fa914b3ae4447760cf0ae63c3 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 25 Oct 2026 18:33:20 -0600 Subject: [PATCH 21/47] Dynamic blocks: author lookup parameters, lookup actions and lookup tables (BPARAMETER Lookup, BACTION, BLOOKUPTABLE) In the Block Editor, BPARAMETER Lookup adds a lookup parameter with AutoCAD's prompts (Name, Label, Description, Palette, 0 or 1 grip), and BACTION on it adds its lookup action, which asks only where it goes; a second one is refused ("Lookup parameter already associated with a lookup table."). BLOOKUPTABLE fills the table: input columns for a distance, a position's X or Y and a visibility state, lookup columns for lookup parameters, unmatched values and reverse lookup. AutoCAD's dialog rules apply: two rows with the same inputs are refused ("Duplicate row of input values found."), a lookup column whose values repeat is read only, and the action's own lookup column stays. JSON calls fill the table directly; on the command line BLOOKUPTABLE asks "Select lookup action" and lists the table. The objects are written as AutoCAD writes its own: the parameter names its action (94), cells in block units, each column's value type and unit, and an edge each way between the action and each parameter it reads (kind = that parameter's column count), each pair flagged 4 and naming the other. Without the flag AutoCAD reads the block as static. Erasing a parameter takes its columns out of lookup tables (rows stay, as in AutoCAD); erasing a lookup parameter takes its table; edges keep their pairs. References: lookup tables now read and set positions (UpdatedX/Y, from the block's base point), and a lookup that doesn't allow reverse lookup is read only. Visibility states list the actions active in them, as AutoCAD's do: an action added shows in the state the editor shows. Checked in AutoCAD from DXF and DWG: CADCraft-authored lookups are dynamic, setting Size or Distance1 gives the same distances, positions, visibility and Custom values as CADCraft, and AutoCAD's BEDIT and BSAVE keep the tables. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock.rs | 12 +- crates/doc/src/dynblock/apply.rs | 20 +- crates/doc/src/dynblock/edit.rs | 34 +- crates/doc/src/dynblock/lookup.rs | 574 ++++++++++++++++++++++++ crates/doc/src/dynblock/reference.rs | 26 +- crates/doc/src/dynblock/write.rs | 167 ++++++- crates/engine/src/cmd/blocks.rs | 2 + crates/engine/src/cmd/blocks/bauthor.rs | 188 +++++++- crates/engine/src/cmd/blocks/blookup.rs | 313 +++++++++++++ crates/engine/tests/block_authoring.rs | 2 +- crates/engine/tests/block_lookup.rs | 268 +++++++++++ 11 files changed, 1535 insertions(+), 71 deletions(-) create mode 100644 crates/doc/src/dynblock/lookup.rs create mode 100644 crates/engine/src/cmd/blocks/blookup.rs create mode 100644 crates/engine/tests/block_lookup.rs diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index 367d651b54..add850c28c 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -24,6 +24,7 @@ mod apply; mod copy; mod edit; mod grips; +mod lookup; mod marks; mod reference; mod write; @@ -31,6 +32,7 @@ pub use apply::{drag_grip, set_property}; pub use copy::{copy_definition, remap_handles, restore_definition}; pub use edit::{ElementPoint, element_points, erase_elements, move_element, set_element_point}; pub use grips::{DynGrip, GripPart, GripShape, grips}; +pub use lookup::{MAX_LOOKUP_ROWS, TableColumn, column_property, input_properties, set_lookup_table}; pub use marks::{Mark, marks}; pub use reference::{CustomProperty, Reference, Value, custom_properties, reference}; pub use write::{ @@ -247,6 +249,9 @@ pub struct LookupColumn { pub lookup: bool, /// What the reference shows when no row matches ("Custom"). pub unmatched: String, + /// A lookup column whose value can be set on a reference, setting the row's inputs + /// ("Allow reverse lookup"); otherwise it is read only. + pub reverse: bool, } /// The groups of an object split at its subclass markers (100): `(marker, groups after it)`. @@ -527,8 +532,8 @@ fn stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) { } /// A lookup table: rows (92) and columns (93), the cells row by row (302, after a 301 header), -/// then each column: unmatched name (303 then 305), parameter id (94), lookup flag (282) and the -/// parameter value it stands for (304). +/// then each column: parameter id (94, after an empty 303), lookup flag (282), unmatched name +/// (305), reverse lookup (281) and the parameter value it stands for (304). fn lookup(tags: &[RawTag]) -> ActionKind { let mut c = Cursor::new(tags); let rows = c.count(92); @@ -543,8 +548,9 @@ fn lookup(tags: &[RawTag]) -> ActionKind { let node = c.int(94); let lookup = c.int(282) != 0; let unmatched = c.string(305); + let reverse = c.int(281) != 0; let property = c.string(304); - LookupColumn { node, property, lookup, unmatched } + LookupColumn { node, property, lookup, unmatched, reverse } }) .collect(); ActionKind::Lookup { columns, rows } diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index ed5281bf69..08139ffefb 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -155,6 +155,8 @@ fn linear_points(base: Vec3, end: Vec3, dist: f64, from_midpoint: bool) -> (Vec3 #[derive(Default)] struct Plan { set: BTreeMap, + /// The block's base point (table cells give positions from it). + base: Vec3, } impl Plan { @@ -176,6 +178,18 @@ impl Plan { let (b2, e2) = linear_points(b, e, dist, *from_midpoint); self.set.insert(node, Val::Points(b2, e2)); } + (ParameterKind::Point { .. }, axis @ ("updatedx" | "updatedy")) => { + // From the block's base point, as Properties shows a position. + let v = cell + .trim() + .parse::() + .ok() + .filter(|v| v.is_finite()) + .ok_or_else(|| format!("A lookup table gives \"{cell}\" for a position."))?; + let Some(Val::Point(at)) = self.set.get(&node).cloned().or_else(|| current(m, values, node)) else { return Ok(()) }; + let at = if axis == "updatedx" { Vec3::new(self.base.x + v, at.y, at.z) } else { Vec3::new(at.x, self.base.y + v, at.z) }; + self.set.insert(node, Val::Point(at)); + } (_, other) => return Err(format!("A lookup table sets {other}, which CADCraft can't change yet.")), } Ok(()) @@ -209,6 +223,8 @@ impl Plan { match (v, prop.to_ascii_lowercase().as_str()) { (Val::Text(t), "visibilitystate" | "lookupstring") => Some(t), (Val::Points(b, e), "updateddistance" | "distance") => Some(format!("{}", (e - b).len())), + (Val::Point(at), "updatedx") => Some(format!("{}", at.x - plan.base.x)), + (Val::Point(at), "updatedy") => Some(format!("{}", at.y - plan.base.y)), _ => None, } }; @@ -268,7 +284,7 @@ pub fn set_property(d: &mut Drawing, insert: Handle, name: &str, value: &str) -> p.show_properties && p.kind.label().is_some_and(|l| l.eq_ignore_ascii_case(want) || (axis.is_some() && l.eq_ignore_ascii_case(label))) }) .ok_or_else(|| format!("The reference has no property \"{name}\"."))?; - let mut plan = Plan::default(); + let mut plan = Plan { base: block_base, ..Plan::default() }; match (&p.kind, axis) { (ParameterKind::Visibility { states, label, .. }, _) => { let s = states.iter().find(|s| s.name.eq_ignore_ascii_case(value.trim())).ok_or_else(|| { @@ -324,7 +340,7 @@ pub fn drag_grip(d: &mut Drawing, insert: Handle, node: i32, part: super::GripPa let base = d.block(&r.definition).map(|b| b.base.xy()).unwrap_or_default(); let q = ins.transform(base).inverse().ok_or("The reference has a zero scale.")?.apply(to); let p = m.parameters.iter().find(|p| p.node == node).ok_or("The reference has no such parameter.")?; - let mut plan = Plan::default(); + let mut plan = Plan { base: base.to3(0.0), ..Plan::default() }; match (&p.kind, part) { (ParameterKind::Linear { values, from_midpoint, label, .. }, GripPart::Base | GripPart::End) => { let Some(Val::Points(b, e)) = current(&m, &r.values, node) else { return Err(format!("{label} has no points.")) }; diff --git a/crates/doc/src/dynblock/edit.rs b/crates/doc/src/dynblock/edit.rs index 877f9a2799..5533eed9eb 100644 --- a/crates/doc/src/dynblock/edit.rs +++ b/crates/doc/src/dynblock/edit.rs @@ -222,12 +222,28 @@ pub fn set_element_point(d: &mut Drawing, block: &str, node: i32, which: Element /// parameter takes its grips, their location components and its actions along. Returns the /// graph ids erased (the parameters' and actions'; grips and components aren't listed). pub fn erase_elements(d: &mut Drawing, block: &str, nodes: &[i32]) -> Result, String> { + // Lookup tables lose the columns of parameters erased; a lookup parameter's own table goes. + let params: Vec = + dynamic_block(d, block).map(|m| m.parameters.iter().map(|p| p.node).filter(|n| nodes.contains(n)).collect()).unwrap_or_default(); + let tables = super::lookup::drop_columns(d, block, ¶ms)?; + let nodes: Vec = nodes.iter().copied().chain(tables.into_iter().filter(|t| !nodes.contains(t))).collect(); + // A lookup parameter whose table goes (and that stays) names no table any more. + if let Some(m) = dynamic_block(d, block) { + for a in m.actions.iter().filter(|a| nodes.contains(&a.node)) { + let super::ActionKind::Lookup { columns, .. } = &a.kind else { continue }; + for c in columns.iter().filter(|c| c.lookup && !nodes.contains(&c.node)) { + if let Some(p) = m.parameters.iter().find(|p| p.node == c.node) { + super::lookup::set_action_of(d, p.handle, 0); + } + } + } + } let mut g = graph(d, block)?; let kind_of = |h: Handle| d.foreign.objects.iter().find(|o| o.handle == h).map(|o| o.kind.clone()).unwrap_or_default(); let index_of = |g: &Graph, id: i32| g.nodes.iter().find(|n| n.id == id).map(|n| n.index); let mut gone: Vec = Vec::new(); // node indices let mut erased: Vec = Vec::new(); // graph ids - for id in nodes { + for id in &nodes { let Some(i) = index_of(&g, *id) else { return Err(format!("No parameter or action {id} in the block.")) }; let kind = g.nodes.iter().find(|n| n.index == i).map(|n| kind_of(n.handle)).unwrap_or_default(); if kind.contains("GRIP") { @@ -256,7 +272,8 @@ pub fn erase_elements(d: &mut Drawing, block: &str, nodes: &[i32]) -> Result Result = g.nodes.iter().filter(|n| !gone.contains(&n.index)).cloned().collect(); let renumber: Vec<(i32, i32)> = kept.iter().zip(0..).map(|(n, i)| (n.index, i)).collect(); let new_index = |old: i32| renumber.iter().find(|(o, _)| *o == old).map(|(_, n)| *n); - let edges: Vec<(i32, i32, i32, i32)> = g.edges.iter().filter_map(|e| Some((new_index(e.from)?, new_index(e.to)?, e.kind, e.flags))).collect(); + // An edge keeps its flags (a graph read from a file may have set some) and its pair. + let edges = g.kept_edges(|_| false, new_index); g.nodes = kept; for (n, i) in g.nodes.iter_mut().zip(0..) { n.index = i; - n.links = [-1; 4]; - } - g.edges.clear(); - for (from, to, kind, flags) in edges { - g.link(from, to, kind); - // An edge keeps its flags (a graph read from a file may have set some). - if let Some(e) = g.edges.last_mut() { - e.flags = flags; - } } + g.relink(&edges); let erased_handles: Vec = handles.clone(); let f = std::sync::Arc::make_mut(&mut d.foreign); let tags = g.tags(); diff --git a/crates/doc/src/dynblock/lookup.rs b/crates/doc/src/dynblock/lookup.rs new file mode 100644 index 0000000000..842afc380e --- /dev/null +++ b/crates/doc/src/dynblock/lookup.rs @@ -0,0 +1,574 @@ +//! Lookup tables (BLOOKUPTABLE): a lookup action's rows of input values (a distance, a position, +//! a visibility state) and the lookup values each row gives, written as AutoCAD writes its own +//! (observed in files it saves, and in its Property Lookup Table dialog): +//! +//! - The table lists its input columns, then its lookup columns. Each column names its parameter +//! and the value it stands for (`UpdatedDistance`, `UpdatedX`, `UpdatedY`, `VisibilityState`, +//! `lookupString`), that value's type and unit, what a reference shows when no row matches +//! ("Custom") and, for a lookup column, whether setting it on a reference sets the row's inputs +//! ("Allow reverse lookup") or it is read only. +//! - Cells are text: numbers in block units, visibility states by name. +//! - Two rows with the same inputs are refused ("Duplicate row of input values found."); a lookup +//! column whose values repeat can't be reversed (AutoCAD sets it back to read only). +//! - The graph has an edge each way between the action and each parameter it reads (its kind is +//! how many of the parameter's values the table has), then between the action and its lookup +//! parameters, each pair flagged 4 and naming the other; a table with no inputs has only the +//! edge from the action to its lookup parameter. + +use super::write::{Graph, dict_entry, tag}; +use super::{ActionKind, DynamicBlock, ParameterKind, dynamic_block}; +use crate::{Drawing, Handle, RawTag}; + +/// Most rows one lookup table is written with. +pub const MAX_LOOKUP_ROWS: usize = 10_000; + +/// Most columns one lookup table is written with. +const MAX_COLUMNS: usize = 1_000; + +/// A lookup table column as it is written: the parameter's graph id and the value it stands for, +/// whether it is a lookup column, what references show when no row matches, and whether a lookup +/// column can be set on a reference (reverse lookup). +#[derive(Clone, Debug, PartialEq)] +pub struct TableColumn { + pub node: i32, + pub property: String, + pub lookup: bool, + pub unmatched: String, + pub reverse: bool, +} + +/// The value type (95) and unit (96) AutoCAD writes for a column standing for `property`: text, +/// an angle, a flip state or a distance. +fn value_type(property: &str) -> (i32, i32) { + match property.to_ascii_lowercase().as_str() { + "lookupstring" | "visibilitystate" => (1, 0), + "updatedangle" => (40, 1), + "updatedflip" => (70, 0), + _ => (40, 2), + } +} + +/// A lookup action's own section: rows and columns, the cells row by row, then each column. +pub(super) fn table_tags(columns: &[TableColumn], rows: &[Vec]) -> Vec { + let mut out = vec![tag(100, "AcDbBlockLookupAction"), tag(92, rows.len()), tag(93, columns.len()), tag(301, "")]; + out.extend(rows.iter().flatten().map(|c| tag(302, c))); + for c in columns { + let (ty, unit) = value_type(&c.property); + out.extend([tag(303, ""), tag(94, c.node), tag(95, ty), tag(96, unit), tag(282, i32::from(c.lookup))]); + out.extend([tag(305, &c.unmatched), tag(281, i32::from(c.lookup && c.reverse)), tag(304, &c.property)]); + } + out.push(tag(280, 1)); + out +} + +/// The lookup action whose table gives lookup parameter `node`'s value, if one does. +pub(super) fn table_of(m: &DynamicBlock, node: i32) -> Option { + m.actions + .iter() + .find(|a| matches!(&a.kind, ActionKind::Lookup { columns, .. } if columns.iter().any(|c| c.lookup && c.node == node))) + .map(|a| a.node) +} + +/// Set the lookup action a lookup parameter names (`94`): `id`, or 0 for none. +pub(super) fn set_action_of(d: &mut Drawing, param: Handle, id: i32) { + let f = std::sync::Arc::make_mut(&mut d.foreign); + let Some(o) = f.objects.iter_mut().find(|o| o.handle == param) else { return }; + let Some(at) = o.tags.iter().position(|t| t.code == 100 && t.value.eq_ignore_ascii_case("AcDbBlockLookUpParameter")) else { return }; + if let Some(t) = o.tags.iter_mut().skip(at + 1).take_while(|t| t.code != 100).find(|t| t.code == 94) { + *t = tag(94, id); + } +} + +/// The input properties block `m`'s lookup tables can read, as the Add Parameter Properties +/// dialog lists them: (name, parameter graph id, value). A distance, a position's X and Y, a +/// visibility state. +pub fn input_properties(m: &DynamicBlock) -> Vec<(String, i32, String)> { + let mut out = Vec::new(); + for p in &m.parameters { + match &p.kind { + ParameterKind::Linear { label, .. } => out.push((label.clone(), p.node, "UpdatedDistance".to_string())), + ParameterKind::Point { label, .. } => { + out.push((format!("{label} X"), p.node, "UpdatedX".to_string())); + out.push((format!("{label} Y"), p.node, "UpdatedY".to_string())); + } + ParameterKind::Visibility { label, .. } => out.push((label.clone(), p.node, "VisibilityState".to_string())), + _ => {} + } + } + out +} + +/// The name a lookup table column shows: an input property's name ("Position1 X"), a lookup +/// parameter's property name, or the property itself when the parameter is unknown. +pub fn column_property(m: &DynamicBlock, node: i32, property: &str) -> String { + if let Some((n, ..)) = input_properties(m).into_iter().find(|(_, id, prop)| *id == node && prop.eq_ignore_ascii_case(property)) { + return n; + } + match m.parameters.iter().find(|p| p.node == node).map(|p| &p.kind) { + Some(ParameterKind::Lookup { label, .. }) => label.clone(), + Some(k) => k.label().map_or_else(|| property.to_string(), |l| format!("{l} {property}")), + None => property.to_string(), + } +} + +/// Whether table cells `a` and `b` read the same (numbers compare as numbers, text in any case). +fn same(a: &str, b: &str) -> bool { + match (a.trim().parse::(), b.trim().parse::()) { + (Ok(x), Ok(y)) => (x - y).abs() <= 1e-9 * x.abs().max(y.abs()).max(1.0), + _ => a.trim().eq_ignore_ascii_case(b.trim()), + } +} + +/// Fill lookup action `action` of block `block` (any case) with `columns` and `rows` (each row +/// one cell per column), as the Property Lookup Table dialog's OK does. Input columns are written +/// before lookup columns; rows with every cell empty are left out. Refused, with AutoCAD's reason, +/// when a column can't be read or set, a cell isn't a value of its column, or two rows have the +/// same inputs. +pub fn set_lookup_table(d: &mut Drawing, block: &str, action: i32, columns: &[TableColumn], rows: &[Vec]) -> Result<(), String> { + write_table(d, block, action, columns, rows, false) +} + +/// [`set_lookup_table`]; with `dedupe`, a row whose inputs repeat an earlier row's is left out +/// instead of refused (a column was taken out from under it). +fn write_table(d: &mut Drawing, block: &str, action: i32, columns: &[TableColumn], rows: &[Vec], dedupe: bool) -> Result<(), String> { + if columns.len() > MAX_COLUMNS { + return Err(format!("A lookup table has at most {MAX_COLUMNS} columns.")); + } + if rows.len() > MAX_LOOKUP_ROWS { + return Err(format!("A lookup table has at most {MAX_LOOKUP_ROWS} rows.")); + } + let m = dynamic_block(d, block).ok_or("The block has no parameters or actions.")?; + let a = m.actions.iter().find(|a| a.node == action).ok_or_else(|| format!("No action {action} in the block."))?; + let ActionKind::Lookup { columns: old, .. } = &a.kind else { return Err(format!("{} is not a lookup action.", a.name)) }; + let own = old.iter().find(|c| c.lookup).map(|c| c.node); + let (action_handle, name) = (a.handle, a.name.clone()); + + // The columns, checked and spelled as AutoCAD spells them; inputs first. + let mut cols: Vec<(usize, TableColumn)> = Vec::new(); + for (i, c) in columns.iter().enumerate() { + let p = m.parameters.iter().find(|p| p.node == c.node).ok_or_else(|| format!("No parameter {} in the block.", c.node))?; + let property = match (&p.kind, c.property.trim().to_ascii_lowercase().as_str(), c.lookup) { + (ParameterKind::Lookup { .. }, "lookupstring" | "", true) => "lookupString", + (ParameterKind::Lookup { label, .. }, _, false) => return Err(format!("{label} is a lookup parameter; it can only be a lookup column.")), + (_, _, true) => return Err(format!("{} is not a lookup parameter.", p.element)), + (ParameterKind::Linear { .. }, "updateddistance" | "distance", _) => "UpdatedDistance", + (ParameterKind::Point { .. }, "updatedx" | "x", _) => "UpdatedX", + (ParameterKind::Point { .. }, "updatedy" | "y", _) => "UpdatedY", + (ParameterKind::Visibility { .. }, "visibilitystate" | "", _) => "VisibilityState", + (_, other, _) => return Err(format!("A lookup table can't read {other} of {}.", p.element)), + }; + if c.lookup && table_of(&m, c.node).is_some_and(|t| t != action) { + return Err(format!("{} already has a lookup table.", column_property(&m, c.node, property))); + } + if cols.iter().any(|(_, o)| o.node == c.node && o.property == property) { + return Err(format!("{} is in the table twice.", column_property(&m, c.node, property))); + } + let unmatched = if c.unmatched.trim().is_empty() { "Custom".to_string() } else { c.unmatched.trim().to_string() }; + cols.push((i, TableColumn { node: c.node, property: property.to_string(), lookup: c.lookup, unmatched, reverse: c.reverse })); + } + if let Some(own) = own + && !cols.iter().any(|(_, c)| c.lookup && c.node == own) + { + return Err(format!("{name} gives {}; its lookup column can't be removed.", column_property(&m, own, "lookupString"))); + } + cols.sort_by_key(|(_, c)| c.lookup); + + // The cells, in the columns' new order. + let states = |node: i32| match m.parameters.iter().find(|p| p.node == node).map(|p| &p.kind) { + Some(ParameterKind::Visibility { states, .. }) => states.iter().map(|s| s.name.clone()).collect(), + _ => Vec::new(), + }; + let mut table: Vec> = Vec::new(); + for (r, row) in rows.iter().enumerate() { + if row.len() != columns.len() { + return Err(format!("Row {} has {} cells; the table has {} columns.", r + 1, row.len(), columns.len())); + } + if row.iter().all(|c| c.trim().is_empty()) { + continue; + } + let mut out = Vec::with_capacity(cols.len()); + for (i, c) in &cols { + let cell = row.get(*i).map(|c| c.trim()).unwrap_or_default(); + let shown = column_property(&m, c.node, &c.property); + if cell.is_empty() { + return Err(format!("Row {}: {shown} needs a value.", r + 1)); + } + out.push(match c.property.as_str() { + "VisibilityState" => states(c.node) + .into_iter() + .find(|s| s.eq_ignore_ascii_case(cell)) + .ok_or_else(|| format!("Row {}: \"{cell}\" is not a visibility state of {shown}.", r + 1))?, + "lookupString" => cell.to_string(), + _ => { + let v = cell + .parse::() + .ok() + .filter(|v| v.is_finite()) + .ok_or_else(|| format!("Row {}: {shown} needs a number, not \"{cell}\".", r + 1))?; + if c.property == "UpdatedDistance" && v < 0.0 { + return Err(format!("Row {}: {shown} can't be negative.", r + 1)); + } + format!("{v}") + } + }); + } + table.push(out); + } + let inputs = cols.iter().filter(|(_, c)| !c.lookup).count(); + let same_inputs = |a: &[String], b: &[String]| a.iter().zip(b).take(inputs).all(|(x, y)| same(x, y)); + let mut kept: Vec> = Vec::new(); + for row in table { + if inputs > 0 && kept.iter().any(|k| same_inputs(k, &row)) { + if dedupe { + continue; + } + return Err("Duplicate row of input values found.".into()); + } + kept.push(row); + } + // A lookup column whose values repeat (or that has none) can't be reversed. + let mut cols: Vec = cols.into_iter().map(|(_, c)| c).collect(); + for (j, c) in cols.iter_mut().enumerate() { + let values: Vec<&String> = kept.iter().filter_map(|r| r.get(j)).collect(); + let repeats = values.iter().enumerate().any(|(i, v)| values.iter().take(i).any(|w| w.eq_ignore_ascii_case(v))); + c.reverse = c.lookup && c.reverse && !values.is_empty() && !repeats; + } + + // The action's object: its table, and the flag AutoCAD changes once the table has inputs. + let f = std::sync::Arc::make_mut(&mut d.foreign); + let o = f.objects.iter_mut().find(|o| o.handle == action_handle).ok_or("The lookup action is missing.")?; + let at = o + .tags + .iter() + .position(|t| t.code == 100 && t.value.eq_ignore_ascii_case("AcDbBlockLookupAction")) + .ok_or("The lookup action can't be changed.")?; + // Its section is the object's last; anything after it would be a layout this doesn't know. + if o.tags.iter().skip(at + 1).any(|t| t.code == 100) { + return Err("The lookup action can't be changed.".into()); + } + o.tags.truncate(at); + o.tags.extend(table_tags(&cols, &kept)); + if let Some(el) = o.tags.iter().position(|t| t.code == 100 && t.value.eq_ignore_ascii_case("AcDbBlockElement")) + && let Some(t) = o.tags.iter_mut().skip(el + 1).take_while(|t| t.code != 100).find(|t| t.code == 1071) + { + *t = tag(1071, if inputs > 0 { 0 } else { 8 }); + } + + // The edges: the action's own, made again for its columns. + let key = ("BLOCK_RECORD".to_string(), block.trim().to_ascii_uppercase()); + let gh = d + .foreign + .records + .get(&key) + .and_then(|x| x.xdict) + .and_then(|x| dict_entry(d, x, "ACAD_ENHANCEDBLOCK")) + .ok_or("The block's evaluation graph is missing.")?; + let mut g = d.foreign.objects.iter().find(|o| o.handle == gh).and_then(Graph::read).ok_or("The block's evaluation graph can't be changed.")?; + let index = |id: i32| g.nodes.iter().find(|n| n.id == id).map(|n| n.index); + let ai = index(action).ok_or("The lookup action is missing from the graph.")?; + let mut edges = g.kept_edges(|e| e.from == ai || e.to == ai, Some); + let pair = |edges: &mut Vec<(i32, i32, i32, i32, i32)>, from: i32, to: i32, kind: i32, both: bool| { + let at = i32::try_from(edges.len()).unwrap_or(i32::MAX); + // AutoCAD flags a pair of edges 4 (without it, it reads the block as a static one). + if both { + edges.push((from, to, kind, 4, at.saturating_add(1))); + edges.push((to, from, kind, 4, at)); + } else { + edges.push((from, to, kind, 0, -1)); + } + }; + let mut seen: Vec = Vec::new(); + for c in cols.iter().filter(|c| !c.lookup) { + if seen.contains(&c.node) { + continue; + } + seen.push(c.node); + let kind = i32::try_from(cols.iter().filter(|o| !o.lookup && o.node == c.node).count()).unwrap_or(1); + let pi = index(c.node).ok_or("A parameter of the table is missing from the graph.")?; + pair(&mut edges, pi, ai, kind, true); + } + for c in cols.iter().filter(|c| c.lookup) { + let pi = index(c.node).ok_or("A parameter of the table is missing from the graph.")?; + pair(&mut edges, ai, pi, 1, inputs > 0); + } + g.relink(&edges); + let tags = g.tags(); + if let Some(o) = std::sync::Arc::make_mut(&mut d.foreign).objects.iter_mut().find(|o| o.handle == gh) { + o.tags = tags; + } + + // Lookup parameters name the action giving their value; one left out names none. + for p in &m.parameters { + if !matches!(p.kind, ParameterKind::Lookup { .. }) { + continue; + } + if cols.iter().any(|c| c.lookup && c.node == p.node) { + set_action_of(d, p.handle, action); + } else if old.iter().any(|c| c.lookup && c.node == p.node) { + set_action_of(d, p.handle, 0); + } + } + Ok(()) +} + +/// Before parameters `erased` of block `block` go: every lookup table reading them (or giving +/// one of them that isn't its own) loses those columns, and rows that then repeat another's +/// inputs. Returns the lookup actions whose own parameter goes (they go with it). +pub(super) fn drop_columns(d: &mut Drawing, block: &str, erased: &[i32]) -> Result, String> { + let Some(m) = dynamic_block(d, block) else { return Ok(Vec::new()) }; + let mut gone = Vec::new(); + for a in &m.actions { + let ActionKind::Lookup { columns, rows } = &a.kind else { continue }; + if columns.iter().find(|c| c.lookup).is_some_and(|c| erased.contains(&c.node)) { + gone.push(a.node); + continue; + } + if !columns.iter().any(|c| erased.contains(&c.node)) { + continue; + } + let keep: Vec = (0..columns.len()).filter(|i| columns.get(*i).is_some_and(|c| !erased.contains(&c.node))).collect(); + let cols: Vec = keep + .iter() + .filter_map(|i| columns.get(*i)) + .map(|c| TableColumn { node: c.node, property: c.property.clone(), lookup: c.lookup, unmatched: c.unmatched.clone(), reverse: c.reverse }) + .collect(); + let rows: Vec> = rows.iter().map(|r| keep.iter().map(|i| r.get(*i).cloned().unwrap_or_default()).collect()).collect(); + write_table(d, block, a.node, &cols, &rows, true)?; + } + Ok(gone) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::dynblock::{ActionSpec, ParamPoint, ParameterSpec, VisibilityState, add_action, add_parameter, erase_elements, set_visibility}; + use cadcraft_geom::Vec3; + + fn v(x: f64, y: f64) -> Vec3 { + Vec3::new(x, y, 0.0) + } + + fn col(node: i32, property: &str, lookup: bool) -> TableColumn { + TableColumn { node, property: property.into(), lookup, unmatched: String::new(), reverse: lookup } + } + + fn row(cells: &[&str]) -> Vec { + cells.iter().map(|c| c.to_string()).collect() + } + + /// Block "B" as AutoCAD's sample is made: a linear parameter (Distance1) with a move, a point + /// (Position1), a visibility parameter with states VisibilityState0 and Small, a lookup + /// parameter (Size) and its lookup action. Returns (linear, point, visibility, lookup, + /// action). + fn block() -> (Drawing, [i32; 5]) { + let mut d = Drawing::default(); + let lin = + add_parameter(&mut d, "B", &ParameterSpec::Linear { base: v(0.0, 0.0), end: v(10.0, 0.0), label: None, label_offset: -1.0, grips: 1 }) + .unwrap(); + add_action(&mut d, "B", &ActionSpec::Move { parameter: lin, point: ParamPoint::End, selection: vec![Handle(0x40)], at: v(12.0, 0.0) }) + .unwrap(); + let pt = add_parameter(&mut d, "B", &ParameterSpec::Point { at: v(5.0, 2.0), label: None, label_at: v(5.0, 3.0), grips: 1 }).unwrap(); + let vis = + add_parameter(&mut d, "B", &ParameterSpec::Visibility { at: v(-2.0, 5.0), label: None, objects: vec![Handle(0x40)], grips: 1 }).unwrap(); + let states = [ + VisibilityState { name: "VisibilityState0".into(), ..Default::default() }, + VisibilityState { name: "Small".into(), ..Default::default() }, + ]; + set_visibility(&mut d, "B", &[Handle(0x40)], &states).unwrap(); + let spec = + ParameterSpec::Lookup { at: v(-2.0, 7.0), label: Some("Size".into()), name: None, description: String::new(), show: true, grips: 1 }; + let lk = add_parameter(&mut d, "B", &spec).unwrap(); + let act = add_action(&mut d, "B", &ActionSpec::Lookup { parameter: lk, at: v(-2.0, 8.0) }).unwrap(); + (d, [lin, pt, vis, lk, act]) + } + + fn graph(d: &Drawing) -> Graph { + d.foreign.objects.iter().find(|o| o.kind == "ACAD_EVALUATION_GRAPH").and_then(Graph::read).unwrap() + } + + /// The graph's edges by node ids: (from, to, kind, the pair edge's from and to). + fn edges(g: &Graph) -> Vec<(i32, i32, i32, Option<(i32, i32)>)> { + let id = |i: i32| g.nodes.iter().find(|n| n.index == i).unwrap().id; + g.edges + .iter() + .map(|e| { + let pair = (e.links[4] >= 0).then(|| g.edges.iter().find(|p| p.index == e.links[4]).map(|p| (id(p.from), id(p.to))).unwrap()); + (id(e.from), id(e.to), e.kind, pair) + }) + .collect() + } + + fn of(g: &Graph, node: i32) -> Vec<(i32, i32, i32, Option<(i32, i32)>)> { + edges(g).into_iter().filter(|(f, t, ..)| *f == node || *t == node).collect() + } + + fn object<'a>(d: &'a Drawing, kind: &str) -> &'a crate::foreign::ForeignObject { + d.foreign.objects.iter().find(|o| o.kind == kind).unwrap() + } + + fn group(o: &crate::foreign::ForeignObject, marker: &str, code: i32) -> String { + let at = o.tags.iter().position(|t| t.code == 100 && t.value == marker).unwrap(); + o.tags.iter().skip(at + 1).find(|t| t.code == code).unwrap().value.clone() + } + + fn table(d: &Drawing, act: i32) -> (Vec, Vec>) { + let m = dynamic_block(d, "B").unwrap(); + match &m.actions.iter().find(|a| a.node == act).unwrap().kind { + ActionKind::Lookup { columns, rows } => (columns.clone(), rows.clone()), + k => panic!("{k:?}"), + } + } + + #[test] + fn a_new_lookup_action_gives_its_parameter_and_reads_nothing() { + let (d, [.., lk, act]) = block(); + let m = dynamic_block(&d, "B").unwrap(); + let p = m.parameters.iter().find(|p| p.node == lk).unwrap(); + assert!(matches!(&p.kind, ParameterKind::Lookup { label, .. } if label == "Size")); + assert_eq!((p.element.as_str(), p.grips.len()), ("Lookup", 1)); + assert_eq!(m.actions.iter().find(|a| a.node == act).unwrap().name, "Lookup1"); + let (columns, rows) = table(&d, act); + assert!(rows.is_empty()); + assert_eq!(columns.len(), 1); + let c = &columns[0]; + assert_eq!((c.node, c.property.as_str(), c.lookup, c.unmatched.as_str(), c.reverse), (lk, "lookupString", true, "Custom", false)); + assert_eq!(group(object(&d, "BLOCKLOOKUPPARAMETER"), "AcDbBlockLookUpParameter", 94), act.to_string(), "the parameter names its table"); + assert_eq!(group(object(&d, "BLOCKLOOKUPACTION"), "AcDbBlockElement", 1071), "8"); + assert_eq!(object(&d, "BLOCKLOOKUPGRIP").tags.last().unwrap().value, "AcDbBlockLookUpGrip"); + // Only the edge from the action to its parameter. + let g = graph(&d); + assert_eq!(of(&g, act), [(act, lk, 1, None)]); + // The lookup grip is linked before its parameter's location components, as visibility's. + let grip = p.grips[0]; + assert_eq!(of(&g, lk).first(), Some(&(grip, lk, 1, None))); + let again = add_action(&mut d.clone(), "B", &ActionSpec::Lookup { parameter: lk, at: v(0.0, 0.0) }); + assert!(again.unwrap_err().contains("already associated")); + } + + #[test] + fn a_table_is_written_as_autocad_writes_it() { + let (mut d, [lin, pt, vis, lk, act]) = block(); + let cols = [ + col(lin, "UpdatedDistance", false), + col(pt, "UpdatedX", false), + col(pt, "UpdatedY", false), + col(vis, "VisibilityState", false), + col(lk, "lookupString", true), + ]; + let rows = [row(&["10", "5", "2", "visibilitystate0", "Big"]), row(&["6.0", "3", "2", "Small", "Small"]), row(&["", "", "", "", ""])]; + set_lookup_table(&mut d, "B", act, &cols, &rows).unwrap(); + let (columns, rows) = table(&d, act); + assert_eq!(rows, [row(&["10", "5", "2", "VisibilityState0", "Big"]), row(&["6", "3", "2", "Small", "Small"])]); + let props: Vec<(i32, &str, bool, bool)> = columns.iter().map(|c| (c.node, c.property.as_str(), c.lookup, c.reverse)).collect(); + assert_eq!( + props, + [ + (lin, "UpdatedDistance", false, false), + (pt, "UpdatedX", false, false), + (pt, "UpdatedY", false, false), + (vis, "VisibilityState", false, false), + (lk, "lookupString", true, true) + ] + ); + // Types and units as AutoCAD writes them. + let o = object(&d, "BLOCKLOOKUPACTION"); + let types: Vec<&str> = o.tags.iter().filter(|t| t.code == 95 || t.code == 96).map(|t| t.value.as_str()).collect(); + assert_eq!(types, ["40", "2", "40", "2", "40", "2", "1", "0", "1", "0"]); + assert_eq!(group(o, "AcDbBlockElement", 1071), "0"); + assert_eq!(o.tags.last().map(|t| (t.code, t.value.as_str())), Some((280, "1"))); + // An edge each way per parameter read (the point's two columns: kind 2), then the lookup. + let lk_pair = Some((lk, act)); + assert_eq!( + of(&graph(&d), act), + [ + (lin, act, 1, Some((act, lin))), + (act, lin, 1, Some((lin, act))), + (pt, act, 2, Some((act, pt))), + (act, pt, 2, Some((pt, act))), + (vis, act, 1, Some((act, vis))), + (act, vis, 1, Some((vis, act))), + (act, lk, 1, lk_pair), + (lk, act, 1, Some((act, lk))), + ] + ); + let g = graph(&d); + let ai = g.nodes.iter().find(|n| n.id == act).unwrap().index; + assert!(g.edges.iter().filter(|e| e.from == ai || e.to == ai).all(|e| e.flags == 4), "a pair is flagged 4"); + // Filled again, the same edges, not more. + set_lookup_table(&mut d, "B", act, &cols, &[row(&["10", "5", "2", "Small", "Big"])]).unwrap(); + assert_eq!(of(&graph(&d), act).len(), 8); + // Emptied, it is back to its first form. + set_lookup_table(&mut d, "B", act, &[col(lk, "lookupString", true)], &[]).unwrap(); + assert_eq!(of(&graph(&d), act), [(act, lk, 1, None)]); + assert!(graph(&d).edges.iter().all(|e| e.flags == 0), "an edge on its own isn't flagged"); + assert_eq!(group(object(&d, "BLOCKLOOKUPACTION"), "AcDbBlockElement", 1071), "8"); + } + + #[test] + fn the_dialogs_rules_refuse_what_autocad_refuses() { + let (d, [lin, pt, vis, lk, act]) = block(); + let cols = [col(lin, "UpdatedDistance", false), col(vis, "VisibilityState", false), col(lk, "", true)]; + let set = |rows: &[Vec]| set_lookup_table(&mut d.clone(), "B", act, &cols, rows); + assert_eq!(set(&[row(&["10", "Small", "A"]), row(&["10.0", "small", "B"])]).unwrap_err(), "Duplicate row of input values found."); + assert!(set(&[row(&["10", "Nope", "A"])]).unwrap_err().contains("not a visibility state")); + assert!(set(&[row(&["ten", "Small", "A"])]).unwrap_err().contains("needs a number")); + assert!(set(&[row(&["10", "Small", ""])]).unwrap_err().contains("needs a value")); + assert!(set(&[row(&["10", "Small"])]).unwrap_err().contains("cells")); + // Repeated lookup values: read only. + let mut d2 = d.clone(); + set_lookup_table(&mut d2, "B", act, &cols, &[row(&["10", "Small", "A"]), row(&["5", "Small", "a"])]).unwrap(); + assert!(!table(&d2, act).0[2].reverse); + // Columns that can't be: a lookup parameter as an input, the wrong value, twice, without + // the action's own lookup column, an input as a lookup column. + let bad = |cols: &[TableColumn]| set_lookup_table(&mut d.clone(), "B", act, cols, &[]).unwrap_err(); + assert!(bad(&[col(lk, "lookupString", false), col(lk, "lookupString", true)]).contains("only be a lookup column")); + assert!(bad(&[col(pt, "UpdatedDistance", false), col(lk, "", true)]).contains("can't read")); + assert!(bad(&[col(lin, "distance", false), col(lin, "UpdatedDistance", false), col(lk, "", true)]).contains("twice")); + assert!(bad(&[col(lin, "UpdatedDistance", false)]).contains("can't be removed")); + assert!(bad(&[col(lin, "UpdatedDistance", true), col(lk, "", true)]).contains("not a lookup parameter")); + assert!(set_lookup_table(&mut d.clone(), "B", lin, &cols, &[]).is_err(), "not an action"); + } + + #[test] + fn erasing_a_parameter_takes_its_columns_and_a_lookup_parameter_its_table() { + let (mut d, [lin, pt, vis, lk, act]) = block(); + let cols = [col(lin, "UpdatedDistance", false), col(pt, "UpdatedX", false), col(vis, "VisibilityState", false), col(lk, "", true)]; + set_lookup_table(&mut d, "B", act, &cols, &[row(&["10", "5", "Small", "Big"]), row(&["6", "5", "Small", "Small"])]).unwrap(); + erase_elements(&mut d, "B", &[lin]).unwrap(); + let (columns, rows) = table(&d, act); + assert_eq!(columns.iter().map(|c| c.node).collect::>(), [pt, vis, lk]); + assert_eq!(rows, [row(&["5", "Small", "Big"])], "the row that now repeats the first's inputs goes"); + assert!(!dynamic_block(&d, "B").unwrap().actions.iter().any(|a| a.name == "Move"), "the distance's move went with it"); + let g = graph(&d); + assert!( + g.edges.iter().all(|e| e.links[4] < 0 || g.edges.iter().any(|p| p.index == e.links[4] && p.from == e.to && p.to == e.from)), + "pairs kept" + ); + assert_eq!(erase_elements(&mut d, "B", &[lk]).unwrap(), [lk, act]); + assert!(dynamic_block(&d, "B").unwrap().actions.is_empty()); + assert!(graph(&d).edges.iter().all(|e| e.links[4] < 0)); + } + + #[test] + fn erasing_a_lookup_action_leaves_its_parameter_without_a_table() { + let (mut d, [.., lk, act]) = block(); + erase_elements(&mut d, "B", &[act]).unwrap(); + assert_eq!(group(object(&d, "BLOCKLOOKUPPARAMETER"), "AcDbBlockLookUpParameter", 94), "0"); + add_action(&mut d, "B", &ActionSpec::Lookup { parameter: lk, at: v(0.0, 0.0) }).unwrap(); + } + + #[test] + fn hostile_tables_are_refused() { + let (d, [lin, .., lk, act]) = block(); + let cols = [col(lin, "UpdatedDistance", false), col(lk, "", true)]; + let rows = vec![row(&["1", "a"]); MAX_LOOKUP_ROWS + 1]; + assert!(set_lookup_table(&mut d.clone(), "B", act, &cols, &rows).is_err()); + let many = vec![col(lk, "", true); MAX_COLUMNS + 1]; + assert!(set_lookup_table(&mut d.clone(), "B", act, &many, &[]).is_err()); + for cell in ["NaN", "inf", "-1", "1e400"] { + assert!(set_lookup_table(&mut d.clone(), "B", act, &cols, &[row(&[cell, "a"])]).is_err(), "{cell}"); + } + assert!(set_lookup_table(&mut d.clone(), "Nope", act, &cols, &[]).is_err()); + assert!(set_lookup_table(&mut d.clone(), "B", 9999, &cols, &[]).is_err()); + } +} diff --git a/crates/doc/src/dynblock/reference.rs b/crates/doc/src/dynblock/reference.rs index 3465a9f944..4fd9c31168 100644 --- a/crates/doc/src/dynblock/reference.rs +++ b/crates/doc/src/dynblock/reference.rs @@ -151,6 +151,8 @@ fn same(cell: &str, value: &str) -> bool { struct Current<'a> { m: &'a DynamicBlock, values: &'a BTreeMap, + /// The block's base point (table cells give positions from it). + base: Vec3, } impl Current<'_> { @@ -170,6 +172,13 @@ impl Current<'_> { }; Some(format!("{}", (e - b).len())) } + (ParameterKind::Point { at, .. }, axis @ ("updatedx" | "updatedy")) => { + let at = match v { + Some(Value::Point { at }) => *at, + _ => *at, + }; + Some(format!("{}", if axis == "updatedx" { at.x - self.base.x } else { at.y - self.base.y })) + } (ParameterKind::Lookup { .. }, "lookupstring") => match v { Some(Value::Text { value }) => Some(value.clone()), _ => None, @@ -226,7 +235,7 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec Option<(String, Vec bool { let mut any = false; for a in &m.actions { @@ -272,9 +282,13 @@ fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool { continue; } any = true; - if !columns - .iter() - .all(|c| matches!(c.property.to_ascii_lowercase().as_str(), "lookupstring" | "visibilitystate" | "updateddistance" | "distance")) + if !columns.iter().any(|c| c.lookup && c.node == node && c.reverse) + || !columns.iter().all(|c| { + matches!( + c.property.to_ascii_lowercase().as_str(), + "lookupstring" | "visibilitystate" | "updateddistance" | "distance" | "updatedx" | "updatedy" + ) + }) { return false; } diff --git a/crates/doc/src/dynblock/write.rs b/crates/doc/src/dynblock/write.rs index cf1ff4b3eb..cabde61bf8 100644 --- a/crates/doc/src/dynblock/write.rs +++ b/crates/doc/src/dynblock/write.rs @@ -41,15 +41,26 @@ pub enum ParameterSpec { /// Named visibility states (Visibility1) of `objects`, at `at`, with 0 or 1 grip: one state, /// `VisibilityState0`, showing them all. A block has one at most. Visibility { at: Vec3, label: Option, objects: Vec, grips: u8 }, + /// A value picked from a lookup table (Lookup1), at `at`, with 0 or 1 grip. `name` is its name + /// in the Block Editor (default Lookup), `description` the property's, and `show` whether + /// references show it in Properties. Its table comes with a lookup action (BACTION). + Lookup { at: Vec3, label: Option, name: Option, description: String, show: bool, grips: u8 }, } -/// What a grip is: a linear parameter's (pointing along `Vec3`), a point's, or a visibility -/// parameter's (a list to pick from). +/// What a grip is: a linear parameter's (pointing along `Vec3`), a point's, or a visibility or +/// lookup parameter's (a list to pick from). #[derive(Clone, Copy, Debug, PartialEq)] enum GripKind { Linear(Vec3), Xy, Visibility, + Lookup, +} + +impl GripKind { + fn is_list(self) -> bool { + matches!(self, GripKind::Visibility | GripKind::Lookup) + } } /// Which point of a two-point parameter an action follows. @@ -68,6 +79,9 @@ pub enum ActionSpec { Stretch { parameter: i32, point: ParamPoint, frame: Vec, selection: Vec, vertices: Vec<(Handle, Vec)>, at: Vec3 }, /// Moves the selected objects. Move { parameter: i32, point: ParamPoint, selection: Vec, at: Vec3 }, + /// The lookup table of lookup parameter `parameter`, empty until it is filled + /// ([`set_lookup_table`](super::set_lookup_table)). A lookup parameter has one at most. + Lookup { parameter: i32, at: Vec3 }, } /// One node of the evaluation graph: its index, flags, graph id, object and the first and last @@ -81,9 +95,11 @@ pub(super) struct Node { pub(super) links: [i32; 4], } -/// One edge: its index, flags, kind (1 from a parameter, 2 from a grip), the nodes it joins +/// One edge: its index, flags, kind (1 from a parameter, 2 from a grip; between a lookup action +/// and a parameter, how many of the parameter's values the table has), the nodes it joins /// (indices) and its neighbours in their lists: previous and next incoming of `to`, previous and -/// next outgoing of `from`, then one more link AutoCAD leaves at -1. +/// next outgoing of `from`, then the edge running the other way between the same nodes (a lookup +/// table's, which reads and sets its parameters), -1 for none. #[derive(Clone, Debug, PartialEq)] pub(super) struct Edge { pub(super) index: i32, @@ -190,6 +206,33 @@ impl Graph { index } + /// Link `edges` again, in order, after the nodes' links were cleared: (from, to, kind, flags, + /// pair), `pair` the position in `edges` of the edge running the other way (-1 for none). + pub(super) fn relink(&mut self, edges: &[(i32, i32, i32, i32, i32)]) { + self.edges.clear(); + for n in &mut self.nodes { + n.links = [-1; 4]; + } + for &(from, to, kind, flags, _) in edges { + self.link(from, to, kind); + if let Some(e) = self.edges.last_mut() { + e.flags = flags; + } + } + // Edge indices are the positions in `edges` now. + for (e, &(.., pair)) in self.edges.iter_mut().zip(edges) { + e.links[4] = if pair >= 0 && usize::try_from(pair).is_ok_and(|p| p < edges.len()) { pair } else { -1 }; + } + } + + /// The graph's edges as [`relink`](Self::relink) takes them, except those `drop` refuses, + /// with node indices mapped by `index` (an edge to a node it maps to `None` is dropped too). + pub(super) fn kept_edges(&self, drop: impl Fn(&Edge) -> bool, index: impl Fn(i32) -> Option) -> Vec<(i32, i32, i32, i32, i32)> { + let kept: Vec<(&Edge, i32, i32)> = self.edges.iter().filter(|e| !drop(e)).filter_map(|e| Some((e, index(e.from)?, index(e.to)?))).collect(); + let position = |old: i32| kept.iter().position(|(e, ..)| e.index == old).and_then(|p| i32::try_from(p).ok()).unwrap_or(-1); + kept.iter().map(|(e, from, to)| (*from, *to, e.kind, e.flags, if e.links[4] >= 0 { position(e.links[4]) } else { -1 })).collect() + } + fn node_mut(&mut self, index: i32) -> Option<&mut Node> { self.nodes.iter_mut().find(|n| n.index == index) } @@ -348,8 +391,8 @@ impl<'a> Author<'a> { let mut tags = element_head(gh, self.graph.handle, gid, name, 0); tags.extend([tag(100, "AcDbBlockGrip"), tag(91, xid), tag(92, yid)]); point(&mut tags, 1010, at); - // A visibility grip is the only one AutoCAD writes 280 0 on. - tags.extend([tag(280, i32::from(kind != GripKind::Visibility)), tag(93, -1)]); + // A visibility or lookup grip is the only one AutoCAD writes 280 0 on. + tags.extend([tag(280, i32::from(!kind.is_list())), tag(93, -1)]); let dxf = match kind { GripKind::Linear(dir) => { tags.extend([tag(100, "AcDbBlockLinearGrip"), real(140, dir.x), real(141, dir.y), real(142, dir.z)]); @@ -366,10 +409,15 @@ impl<'a> Author<'a> { self.class("BLOCKVISIBILITYGRIP", "AcDbBlockVisibilityGrip"); "BLOCKVISIBILITYGRIP" } + GripKind::Lookup => { + tags.push(tag(100, "AcDbBlockLookUpGrip")); + self.class("BLOCKLOOKUPGRIP", "AcDbBlockLookupGrip"); + "BLOCKLOOKUPGRIP" + } }; let grip = self.node(dxf, gh, gid, tags); - // AutoCAD links a visibility grip to its parameter before the location components. - if kind == GripKind::Visibility { + // AutoCAD links a list grip to its parameter before the location components. + if kind.is_list() { self.graph.link(grip, param, 1); } self.class("BLOCKGRIPLOCATIONCOMPONENT", "AcDbBlockGripExpr"); @@ -382,7 +430,7 @@ impl<'a> Author<'a> { let c = self.node("BLOCKGRIPLOCATIONCOMPONENT", h, id, tags); self.graph.link(param, c, 1); } - if kind != GripKind::Visibility { + if !kind.is_list() { self.graph.link(grip, param, 2); } gid @@ -390,14 +438,19 @@ impl<'a> Author<'a> { /// An element name not used in the block yet: `base`, else `base` and the lowest free number. fn element_name(&self, base: &str) -> String { - let used: Vec = dynamic_block(self.d, &self.record) - .map(|m| m.parameters.iter().map(|p| p.element.clone()).chain(m.actions.iter().map(|a| a.name.clone())).collect()) - .unwrap_or_default(); - let free = |n: &str| !used.iter().any(|u| u.eq_ignore_ascii_case(n)); - if free(base) { - return base.to_string(); - } - (1..).map(|i| format!("{base}{i}")).find(|n| free(n)).unwrap_or_else(|| base.to_string()) + if self.name_free(base) { base.to_string() } else { self.numbered_name(base) } + } + + /// `base` and the lowest number from 1 not used as an element name in the block yet + /// (AutoCAD numbers lookup actions from Lookup1). + fn numbered_name(&self, base: &str) -> String { + (1..).map(|i| format!("{base}{i}")).find(|n| self.name_free(n)).unwrap_or_else(|| format!("{base}1")) + } + + /// No parameter or action of the block has element name `name` (any case). + fn name_free(&self, name: &str) -> bool { + dynamic_block(self.d, &self.record) + .is_none_or(|m| !m.parameters.iter().map(|p| &p.element).chain(m.actions.iter().map(|a| &a.name)).any(|u| u.eq_ignore_ascii_case(name))) } } @@ -558,6 +611,36 @@ pub fn add_parameter(d: &mut Drawing, name: &str, spec: &ParameterSpec) -> Resul a.finish(); Ok(id) } + ParameterSpec::Lookup { at, label, name: element, description, show, grips } => { + if !finite(*at) { + return Err("Invalid point.".into()); + } + if *grips > 1 { + return Err("A lookup parameter has 0 or 1 grip.".into()); + } + let record = name.trim().to_ascii_uppercase(); + let label = label.clone().unwrap_or_else(|| free_label(d, &record, "Lookup")); + let mut a = Author::open(d, name)?; + let element = match element.as_deref().map(str::trim).filter(|e| !e.is_empty()) { + Some(e) if !a.name_free(e) => return Err(format!("A parameter or action is already named \"{e}\".")), + Some(e) => e.to_string(), + None => a.element_name("Lookup"), + }; + let (h, id) = (a.d.new_handle(), a.graph.next_id()); + let param = a.graph.add_node(id, h); + let first_grip = a.new.len(); + let grip = if *grips == 1 { a.grip(param, *at, "Grip", ["UpdatedX", "UpdatedY"], 0.0, GripKind::Lookup) } else { 0 }; + let mut tags = element_head(h, a.graph.handle, id, &element, if *grips == 1 { 0 } else { 1 }); + tags.extend([tag(100, "AcDbBlockParameter"), tag(280, i32::from(*show)), tag(281, 0), tag(100, "AcDbBlock1PtParameter")]); + point(&mut tags, 1010, *at); + tags.extend([tag(93, grip), tag(170, 0), tag(171, 0)]); + // 94: its lookup action's graph id, none yet. + tags.extend([tag(100, "AcDbBlockLookUpParameter"), tag(303, &label), tag(304, description.trim()), tag(94, 0)]); + a.new.insert(first_grip, ForeignObject { handle: h, kind: "BLOCKLOOKUPPARAMETER".into(), tags }); + a.class("BLOCKLOOKUPPARAMETER", "AcDbBlockLookupParameter"); + a.finish(); + Ok(id) + } } } @@ -580,15 +663,17 @@ fn visibility_tags(label: &str, description: &str, controlled: &[Handle], states out } -/// The objects of block `m`'s parameters other than its visibility parameter, and their grips -/// (all of them, or parameter `only`'s): what a visibility state lists as active in it. +/// The objects of block `m`'s parameters other than its visibility parameter, their grips and +/// the block's actions (all of them, or parameter or action `only`'s): what a visibility state +/// lists as active in it. pub fn parameter_objects(m: &super::DynamicBlock, only: Option) -> Vec { let grip = |id: &i32| m.grip_objects.iter().find(|(g, _)| g == id).map(|(_, h)| *h); - m.parameters + let params = m + .parameters .iter() .filter(|p| !matches!(p.kind, ParameterKind::Visibility { .. }) && only.is_none_or(|n| n == p.node)) - .flat_map(|p| std::iter::once(p.handle).chain(p.grips.iter().filter(|g| **g != 0).filter_map(grip))) - .collect() + .flat_map(|p| std::iter::once(p.handle).chain(p.grips.iter().filter(|g| **g != 0).filter_map(grip))); + params.chain(m.actions.iter().filter(|a| only.is_none_or(|n| n == a.node)).map(|a| a.handle)).collect() } /// Keep block `name`'s visibility parameter in step with `objects`, the block's objects: as @@ -675,6 +760,7 @@ pub fn add_action(d: &mut Drawing, name: &str, spec: &ActionSpec) -> Result { (*parameter, *point, selection, *at) } + ActionSpec::Lookup { parameter, at } => return add_lookup_action(d, name, *parameter, *at), }; if !finite(at) { return Err("Invalid point.".into()); @@ -698,7 +784,8 @@ pub fn add_action(d: &mut Drawing, name: &str, spec: &ActionSpec) -> Result ("BLOCKSTRETCHACTION", "AcDbBlockStretchAction", a.element_name("Stretch")), - ActionSpec::Move { .. } => ("BLOCKMOVEACTION", "AcDbBlockMoveAction", a.element_name("Move")), + // (A lookup action returned above.) + ActionSpec::Move { .. } | ActionSpec::Lookup { .. } => ("BLOCKMOVEACTION", "AcDbBlockMoveAction", a.element_name("Move")), }; let mut tags = element_head(h, a.graph.handle, id, &element, 0); tags.extend([tag(100, "AcDbBlockAction"), tag(70, 0), tag(71, selection.len())]); @@ -732,6 +819,40 @@ pub fn add_action(d: &mut Drawing, name: &str, spec: &ActionSpec) -> Result Result { + if !finite(at) { + return Err("Invalid point.".into()); + } + let m = dynamic_block(d, name).ok_or("The block has no parameters; add one first (BPARAMETER).")?; + let p = m.parameters.iter().find(|p| p.node == parameter).ok_or_else(|| format!("No parameter {parameter} in the block."))?; + if !matches!(p.kind, ParameterKind::Lookup { .. }) { + return Err(format!("A {} can't have a lookup action.", p.element)); + } + if super::lookup::table_of(&m, parameter).is_some() { + return Err("Lookup parameter already associated with a lookup table.".into()); + } + let param_handle = p.handle; + let mut a = Author::open(d, name)?; + let pindex = a.graph.index_of(parameter).ok_or_else(|| format!("No parameter {parameter} in the block."))?; + let (h, id) = (a.d.new_handle(), a.graph.next_id()); + let element = a.numbered_name("Lookup"); + let column = super::TableColumn { node: parameter, property: "lookupString".into(), lookup: true, unmatched: "Custom".into(), reverse: false }; + // 1071 is 8 on a table with no inputs yet, 0 once it has some. + let mut tags = element_head(h, a.graph.handle, id, &element, 8); + tags.extend([tag(100, "AcDbBlockAction"), tag(70, 0), tag(71, 0)]); + point(&mut tags, 1010, at); + tags.extend(super::lookup::table_tags(&[column], &[])); + let node = a.node("BLOCKLOOKUPACTION", h, id, tags); + a.graph.link(node, pindex, 1); + a.class("BLOCKLOOKUPACTION", "AcDbBlockLookupAction"); + a.finish(); + super::lookup::set_action_of(d, param_handle, id); + Ok(id) +} + /// Give every object of `store`, block `name`'s objects, an element tag (`AcDbBlockRepETag` /// xdata: `1070 1`, `1071` tag, `1005` the object itself) when it has none or has another /// object's (a copy), and keep the next free tag on the block's record, as AutoCAD does. Only for diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 7b67e653e4..ed77fa5bde 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -20,6 +20,7 @@ use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, St mod attedit; mod bauthor; mod belement; +mod blookup; mod burst; mod bvstate; mod description; @@ -93,6 +94,7 @@ pub fn specs() -> Vec { .chain(bauthor::specs()) .chain(belement::specs()) .chain(bvstate::specs()) + .chain(blookup::specs()) .collect() } diff --git a/crates/engine/src/cmd/blocks/bauthor.rs b/crates/engine/src/cmd/blocks/bauthor.rs index 73e03ae1a8..5b8121fcaf 100644 --- a/crates/engine/src/cmd/blocks/bauthor.rs +++ b/crates/engine/src/cmd/blocks/bauthor.rs @@ -1,12 +1,15 @@ //! BPARAMETER and BACTION: authoring a dynamic block in the Block Editor. A parameter is a -//! property references to the block can change (a distance, a position); an action is what -//! changing it does to the block's objects (stretch them, move them). Both are written into the +//! property references to the block can change (a distance, a position, a value from a lookup +//! table); an action is what changing it does to the block's objects (stretch them, move them) or, +//! for a lookup parameter, its lookup table (filled with BLOOKUPTABLE). Both are written into the //! block's dynamic data ([`cadcraft_doc::dynblock::add_parameter`], [`add_action`]) as AutoCAD //! writes its own, so the block works as a dynamic block here and in AutoCAD. Only while the //! Block Editor is open on a block; points are in the editor's coordinates (the block's base point //! at the origin). -use cadcraft_doc::dynblock::{ActionSpec, Mark, ParamPoint, ParameterSpec, add_action, add_parameter, marks}; +use cadcraft_doc::dynblock::{ + ActionKind, ActionSpec, Mark, ParamPoint, ParameterKind, ParameterSpec, add_action, add_parameter, dynamic_block, marks, +}; use cadcraft_doc::{Drawing, EntityKind, Handle}; use cadcraft_geom::{Vec2, Vec3}; use serde_json::{Value, json}; @@ -21,14 +24,14 @@ pub(super) fn specs() -> Vec { CommandSpec::new("bparameter", "Parameter", run_bparameter) .alias(&["-bparameter"]) .params( - "{type: \"linear\"|\"point\"|\"visibility\", linear: start: [x,y], end: [x,y], labelAt?: [x,y] (where the label goes; default on the line); point: at: [x,y], labelAt?: [x,y]; visibility: at: [x,y] (one state, VisibilityState0, showing every object; one per block); label?: property name (default Distance1/Position1/Visibility1…), grips?: 0|1|2 (linear, default 2) or 0|1 (point, visibility, default 1)} → {node, element, label} (editor coordinates)", + "{type: \"linear\"|\"point\"|\"visibility\"|\"lookup\", linear: start: [x,y], end: [x,y], labelAt?: [x,y] (where the label goes; default on the line); point: at: [x,y], labelAt?: [x,y]; visibility: at: [x,y] (one state, VisibilityState0, showing every object; one per block); lookup: at: [x,y], name?: its name in the editor (default Lookup), description?: text, palette?: bool (shown in Properties; default true); label?: property name (default Distance1/Position1/Visibility1/Lookup1…), grips?: 0|1|2 (linear, default 2) or 0|1 (point, visibility, lookup, default 1)} → {node, element, label} (editor coordinates)", ) .enabled(authoring) .interactive(|_| Ok(Box::new(BparameterM::default()))), CommandSpec::new("baction", "Action", run_baction) .alias(&["-baction"]) .params( - "{parameter: graph id or property name (\"Distance1\"), type: \"stretch\"|\"move\", point?: \"start\"|\"second\" (which end of a linear parameter it follows, default second), handles: [objects], frame?: [[x,y],[x,y]] (stretch: corners) | polygon?: [[x,y]…] (stretch: a crossing polygon), at?: [x,y] (where the action shows; default the parameter's point)} → {node, name} (editor coordinates)", + "{parameter: graph id or property name (\"Distance1\"), type: \"stretch\"|\"move\"|\"lookup\" (a lookup parameter's, and the default for one: its empty lookup table, one per parameter; fill it with BLOOKUPTABLE), point?: \"start\"|\"second\" (which end of a linear parameter it follows, default second), handles: [objects], frame?: [[x,y],[x,y]] (stretch: corners) | polygon?: [[x,y]…] (stretch: a crossing polygon), at?: [x,y] (where the action shows; default the parameter's point)} → {node, name} (editor coordinates)", ) .enabled(authoring) .interactive(|_| Ok(Box::new(BactionM::default()))), @@ -99,10 +102,25 @@ fn run_bparameter(s: &mut Session, p: &Value) -> Result { let objects = s.doc()?.model.iter().map(|e| e.handle).collect(); ParameterSpec::Visibility { at: to_block(at, base), label, objects, grips: grips_param("bparameter", p, 1, 1)? } } - Some(other) if ["alignment", "base", "polar", "xy", "rotation", "flip", "lookup"].contains(&other) => { + Some("lookup") => { + let at = point_param(p, "at").ok_or_else(|| bad("bparameter", "`at` ([x, y]) is required"))?; + let show = match p.get("palette") { + None | Some(Value::Null) => true, + Some(v) => v.as_bool().ok_or_else(|| bad("bparameter", "`palette` is true or false"))?, + }; + ParameterSpec::Lookup { + at: to_block(at, base), + label, + name: str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string), + description: str_param(p, "description").unwrap_or_default().to_string(), + show, + grips: grips_param("bparameter", p, 1, 1)?, + } + } + Some(other) if ["alignment", "base", "polar", "xy", "rotation", "flip"].contains(&other) => { return Err(bad("bparameter", format!("{other} parameters are not available yet"))); } - _ => return Err(bad("bparameter", "`type` is \"linear\", \"point\" or \"visibility\"")), + _ => return Err(bad("bparameter", "`type` is \"linear\", \"point\", \"visibility\" or \"lookup\"")), }; let visibility = matches!(spec, ParameterSpec::Visibility { .. }); let node = add_parameter(s.doc_mut()?, &block, &spec).map_err(|e| bad("bparameter", e))?; @@ -118,30 +136,53 @@ fn run_bparameter(s: &mut Session, p: &Value) -> Result { /// A parameter of the edited block as BACTION follows it, in editor coordinates. #[derive(Clone, Debug, PartialEq)] enum Followed { - Linear { node: i32, base: Vec2, end: Vec2 }, - Point { node: i32, at: Vec2 }, + Linear { + node: i32, + base: Vec2, + end: Vec2, + }, + Point { + node: i32, + at: Vec2, + }, + /// A lookup parameter (its action is its lookup table). + Lookup { + node: i32, + at: Vec2, + }, } impl Followed { fn node(&self) -> i32 { match self { - Followed::Linear { node, .. } | Followed::Point { node, .. } => *node, + Followed::Linear { node, .. } | Followed::Point { node, .. } | Followed::Lookup { node, .. } => *node, } } } /// The parameters of `block` an action can follow, in editor coordinates. fn followable(d: &Drawing, block: &str, base: Vec2) -> Vec { + let lookups: Vec = dynamic_block(d, block) + .map(|m| m.parameters.iter().filter(|p| matches!(p.kind, ParameterKind::Lookup { .. })).map(|p| p.node).collect()) + .unwrap_or_default(); marks(d, block) .into_iter() .filter_map(|m| match m { Mark::Linear { node, base: b, end, .. } => Some(Followed::Linear { node, base: b.xy() - base, end: end.xy() - base }), Mark::Point { node, at, .. } => Some(Followed::Point { node, at: at.xy() - base }), + Mark::List { node, at, .. } if lookups.contains(&node) => Some(Followed::Lookup { node, at: at.xy() - base }), _ => None, }) .collect() } +/// Whether lookup parameter `node` of `block` has its lookup table already (one per parameter). +fn has_table(d: &Drawing, block: &str, node: i32) -> bool { + dynamic_block(d, block).is_some_and(|m| { + m.actions.iter().any(|a| matches!(&a.kind, ActionKind::Lookup { columns, .. } if columns.iter().any(|c| c.lookup && c.node == node))) + }) +} + /// The parameter named by `v`: its graph id, or its property name ("Distance1"). fn parameter_named(d: &Drawing, block: &str, base: Vec2, v: &Value) -> Result { let list = followable(d, block, base); @@ -160,9 +201,7 @@ fn parameter_named(d: &Drawing, block: &str, base: Vec2, v: &Value) -> Result Ok(f), - None if m.is_some_and(|m| m.parameters.iter().any(|p| p.node == node)) => { - Err(bad("baction", "that parameter can't have stretch or move actions yet")) - } + None if m.is_some_and(|m| m.parameters.iter().any(|p| p.node == node)) => Err(bad("baction", "that parameter can't have actions yet")), None => Err(bad("baction", format!("no parameter {v} in the block"))), } } @@ -242,9 +281,15 @@ fn add( *end } } - Followed::Point { at, .. } => *at, + Followed::Point { at, .. } | Followed::Lookup { at, .. } => *at, }; let at = to_block(at.unwrap_or(shown), base); + match (param, kind) { + (Followed::Lookup { .. }, "lookup") => {} + (Followed::Lookup { .. }, _) => return Err(bad("baction", "a lookup parameter's action is its lookup table (`type`: \"lookup\")")), + (_, "lookup") => return Err(bad("baction", "a lookup action needs a lookup parameter")), + _ => {} + } let spec = match kind { "stretch" => { let frame = frame.ok_or_else(|| bad("baction", "a stretch needs `frame` (two corners) or `polygon`"))?; @@ -259,12 +304,15 @@ fn add( ActionSpec::Stretch { parameter: param.node(), point, frame, selection, vertices, at } } "move" => ActionSpec::Move { parameter: param.node(), point, selection: handles.to_vec(), at }, - "array" | "scale" | "rotate" | "flip" | "polarstretch" | "lookup" => { + "lookup" => ActionSpec::Lookup { parameter: param.node(), at }, + "array" | "scale" | "rotate" | "flip" | "polarstretch" => { return Err(bad("baction", format!("{kind} actions are not available yet"))); } - _ => return Err(bad("baction", "`type` is \"stretch\" or \"move\"")), + _ => return Err(bad("baction", "`type` is \"stretch\", \"move\" or \"lookup\"")), }; let node = add_action(s.doc_mut()?, &block, &spec).map_err(|e| bad("baction", e))?; + // Active in the visibility state the editor shows, as a parameter added there is. + super::bvstate::parameter_added(s, node)?; let name = cadcraft_doc::dynblock::dynamic_block(s.doc()?, &block).and_then(|m| m.actions.into_iter().find(|a| a.node == node)).map(|a| a.name); Ok(json!({ "node": node, "name": name })) } @@ -273,7 +321,15 @@ fn run_baction(s: &mut Session, p: &Value) -> Result { let (block, base) = editing(s)?; let which = p.get("parameter").ok_or_else(|| bad("baction", "`parameter` (graph id or property name) is required"))?; let param = parameter_named(s.doc()?, &block, base, which)?; - let kind = str_param(p, "type").map(|t| t.trim().to_ascii_lowercase().replace(' ', "")).ok_or_else(|| bad("baction", "`type` is required"))?; + let kind = match (str_param(p, "type"), ¶m) { + (Some(t), _) => t.trim().to_ascii_lowercase().replace(' ', ""), + // A lookup parameter has one kind of action, and it acts on no objects. + (None, Followed::Lookup { .. }) => "lookup".to_string(), + (None, _) => return Err(bad("baction", "`type` is required")), + }; + if kind == "lookup" { + return add(s, ¶m, &kind, ParamPoint::End, &[], None, point_param(p, "at")); + } let point = match str_param(p, "point").map(str::to_ascii_lowercase).as_deref() { None | Some("second") | Some("end") => ParamPoint::End, Some("start") | Some("base") => ParamPoint::Base, @@ -314,6 +370,29 @@ fn text_of(i: &Input) -> Option<&str> { } } +/// The name a new parameter gets by default: `prefix` alone when free (element names only, as +/// for the element "Lookup"), else `prefix` and the lowest free number; property labels +/// (`labels`) always take a number (Lookup1). +fn next_name(s: &Session, prefix: &str, labels: bool) -> String { + let used: Vec = s + .state() + .ok() + .and_then(|st| dynamic_block(&st.doc, &st.block_edit.as_ref()?.name)) + .map(|m| { + if labels { + m.parameters.iter().filter_map(|p| p.kind.label().map(str::to_string)).collect() + } else { + m.parameters.iter().map(|p| p.element.clone()).chain(m.actions.iter().map(|a| a.name.clone())).collect() + } + }) + .unwrap_or_default(); + let free = |n: &str| !used.iter().any(|u| u.eq_ignore_ascii_case(n)); + if !labels && free(prefix) { + return prefix.to_string(); + } + (1..).map(|i| format!("{prefix}{i}")).find(|n| free(n)).unwrap_or_else(|| format!("{prefix}1")) +} + /// Options AutoCAD offers that are not available yet: answered with a message. fn not_yet(s: &mut Session, what: &str) -> Result { s.echo(format!("{what} is not available yet.")); @@ -334,6 +413,10 @@ enum PStage { VisibilityGrips, /// Typing the property name, then back to the stage it was asked at. Label(&'static str), + /// A lookup parameter's name in the editor, its description, and whether Properties shows it. + Name, + Description, + Palette, } /// BPARAMETER's prompts, as AutoCAD asks them on the command line. @@ -342,6 +425,11 @@ struct BparameterM { stage: PStage, linear: bool, visibility: bool, + lookup: bool, + /// A lookup parameter's name, description and "not in Properties" (Palette No). + name: Option, + description: String, + hidden: bool, start: Vec2, end: Vec2, label_at: Vec2, @@ -364,7 +452,9 @@ const TYPES: &[(&str, &str)] = &[ impl BparameterM { fn make(&self, s: &mut Session, grips: u8) -> Result { let label = self.label.clone(); - let p = if self.visibility { + let p = if self.lookup { + json!({ "type": "lookup", "at": [self.start.x, self.start.y], "label": label, "name": self.name, "description": self.description, "palette": !self.hidden, "grips": grips }) + } else if self.visibility { json!({ "type": "visibility", "at": [self.start.x, self.start.y], "label": label, "grips": grips }) } else if self.linear { json!({ "type": "linear", "start": [self.start.x, self.start.y], "end": [self.end.x, self.end.y], "labelAt": [self.label_at.x, self.label_at.y], "label": label, "grips": grips }) @@ -378,7 +468,7 @@ impl BparameterM { fn options(&self, i: &Input) -> Option<&'static str> { let opts: &[(&str, &str)] = if self.linear { &[("Name", "N"), ("Label", "L"), ("Chain", "C"), ("Description", "D"), ("Base", "B"), ("Palette", "P"), ("Value set", "V")] - } else if self.visibility { + } else if self.visibility || self.lookup { &[("Name", "N"), ("Label", "L"), ("Description", "D"), ("Palette", "P")] } else { &[("Name", "N"), ("Label", "L"), ("Chain", "C"), ("Description", "D"), ("Palette", "P")] @@ -391,7 +481,7 @@ impl Interactive for BparameterM { fn name(&self) -> &'static str { "BPARAMETER" } - fn prompt(&self, _s: &Session) -> Prompt { + fn prompt(&self, s: &Session) -> Prompt { match self.stage { PStage::Type => Prompt::new("Enter parameter type", KW).kw(&TYPES.iter().map(|(k, _)| *k).collect::>()), PStage::Start => Prompt::new("Specify start point", Accept::POINT) @@ -400,12 +490,22 @@ impl Interactive for BparameterM { PStage::End => Prompt::new("Specify endpoint", Accept::POINT).base(self.start), PStage::LinearLabel | PStage::PointLabel => Prompt::new("Specify label location", Accept::POINT), PStage::LinearGrips => Prompt::new("Enter number of grips", KW).kw(&["0", "1", "2"]).default("2"), - PStage::Location if self.visibility => { + PStage::Location if self.visibility || self.lookup => { Prompt::new("Specify parameter location", Accept::POINT).kw(&["Name", "Label", "Description", "Palette"]) } PStage::Location => Prompt::new("Specify parameter location", Accept::POINT).kw(&["Name", "Label", "Chain", "Description", "Palette"]), PStage::PointGrips | PStage::VisibilityGrips => Prompt::new("Enter number of grips", KW).kw(&["0", "1"]).default("1"), + PStage::Label("lookup") => { + Prompt::new("Enter lookup property label", Accept::TEXT).default(self.label.clone().unwrap_or_else(|| next_name(s, "Lookup", true))) + } PStage::Label(what) => Prompt::new(format!("Enter {what} property label"), Accept::TEXT), + PStage::Name => { + Prompt::new("Enter parameter name", Accept::TEXT).default(self.name.clone().unwrap_or_else(|| next_name(s, "Lookup", false))) + } + PStage::Description => Prompt::new("Enter property description", Accept::TEXT), + PStage::Palette => { + Prompt::new("Display property in Properties palette", KW).kw(&["Yes", "No"]).default(if self.hidden { "No" } else { "Yes" }) + } } } fn input(&mut self, s: &mut Session, i: Input) -> Result { @@ -419,6 +519,7 @@ impl Interactive for BparameterM { Some("Linear") => (self.linear, self.stage) = (true, PStage::Start), Some("pOint") => (self.linear, self.stage) = (false, PStage::Location), Some("Visibility") => (self.visibility, self.stage) = (true, PStage::Location), + Some("looKup") => (self.lookup, self.stage) = (true, PStage::Location), Some(other) => return Err(EngineError::Other(format!("{other} parameters are not available yet."))), None => s.echo("Invalid option keyword."), } @@ -428,7 +529,7 @@ impl Interactive for BparameterM { self.start = *p; self.stage = if self.linear { PStage::End - } else if self.visibility { + } else if self.visibility || self.lookup { PStage::VisibilityGrips } else { PStage::PointLabel @@ -437,12 +538,17 @@ impl Interactive for BparameterM { (_, Some("Label")) => { self.stage = PStage::Label(if self.linear { "distance" + } else if self.lookup { + "lookup" } else if self.visibility { "visibility" } else { "position" }) } + (_, Some("Name")) if self.lookup => self.stage = PStage::Name, + (_, Some("Description")) if self.lookup => self.stage = PStage::Description, + (_, Some("Palette")) if self.lookup => self.stage = PStage::Palette, (_, Some(other)) => return not_yet(s, other), _ => {} }, @@ -480,6 +586,30 @@ impl Interactive for BparameterM { } self.stage = if self.linear { PStage::Start } else { PStage::Location }; } + PStage::Name => { + match &i { + Input::Text(t) | Input::Keyword(t) if !t.trim().is_empty() => self.name = Some(t.trim().to_string()), + _ => {} + } + self.stage = PStage::Location; + } + PStage::Description => { + if let Some(t) = text_of(&i) { + self.description = t.trim().to_string(); + } + self.stage = PStage::Location; + } + PStage::Palette => { + match (&i, text_of(&i).and_then(|t| keyword(t, &[("Yes", "Y"), ("No", "N")]))) { + (Input::Enter, _) => {} + (_, Some(k)) => self.hidden = k == "No", + _ => { + s.echo("Invalid option keyword."); + return Ok(Step::Continue); + } + } + self.stage = PStage::Location; + } } Ok(Step::Continue) } @@ -559,6 +689,7 @@ impl Interactive for BactionM { .base_opt(self.frame.last().copied()) } AStage::Objects => self.select.prompt(), + AStage::Location if self.kind == "lookup" => Prompt::new("Specify action location", Accept::POINT), AStage::Location => Prompt::new("Specify action location", Accept::POINT).kw(&["Multiplier", "Offset"]), } } @@ -574,7 +705,7 @@ impl Interactive for BactionM { let reach = (s.pixel_size() * s.settings.pickbox.max(1.0) * 3.0).max(1e-9); let near = |f: &Followed| match f { Followed::Linear { base, end, .. } => segment_distance(*base, *end, *p), - Followed::Point { at, .. } => (*at - *p).len(), + Followed::Point { at, .. } | Followed::Lookup { at, .. } => (*at - *p).len(), }; let list = followable(s.doc()?, &block, base); list.into_iter().map(|f| (near(&f), f)).filter(|(d, _)| *d <= reach).min_by(|a, b| a.0.total_cmp(&b.0)).map(|(_, f)| f) @@ -584,11 +715,20 @@ impl Interactive for BactionM { _ => return Ok(Step::Continue), }; match found { + // A lookup parameter's action is its table, asked for no type or objects. + Some(Followed::Lookup { node, .. }) if has_table(s.doc()?, &block, node) => { + s.echo("Lookup parameter already associated with a lookup table."); + } + Some(f @ Followed::Lookup { .. }) => { + self.param = Some(f); + self.kind = "lookup"; + self.stage = AStage::Location; + } Some(f) => { self.param = Some(f); self.stage = AStage::Type; } - None => s.echo("No linear or point parameter there."), + None => s.echo("No linear, point or lookup parameter there."), } } AStage::Type => { diff --git a/crates/engine/src/cmd/blocks/blookup.rs b/crates/engine/src/cmd/blocks/blookup.rs new file mode 100644 index 0000000000..fe39ecb846 --- /dev/null +++ b/crates/engine/src/cmd/blocks/blookup.rs @@ -0,0 +1,313 @@ +//! BLOOKUPTABLE: the lookup table of a dynamic block's lookup action, in the Block Editor. A +//! lookup action (BACTION on a lookup parameter) starts empty; its table lists input properties +//! (a distance, a position's X or Y, a visibility state) and lookup properties (lookup +//! parameters), and each row gives the lookup values for one set of inputs. A reference then shows +//! the lookup value its inputs match ("Custom" when none does) and, when the lookup property +//! allows reverse lookup, setting it sets the row's inputs. The rules are AutoCAD's Property +//! Lookup Table dialog's ([`cadcraft_doc::dynblock::set_lookup_table`]); the UI opens that dialog +//! for BLOOKUPTABLE typed, and JSON calls fill the table directly. + +use cadcraft_doc::dynblock::{ + ActionKind, DynamicBlock, MAX_LOOKUP_ROWS, ParameterKind, TableColumn, column_property, dynamic_block, input_properties, marks, set_lookup_table, +}; +use serde_json::{Value, json}; + +use crate::cmd::{CommandSpec, bad}; +use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; + +pub(super) fn specs() -> Vec { + vec![ + CommandSpec::new("blookuptable", "Lookup Table", run) + .params( + "{action?: graph id, action name (\"Lookup1\") or its lookup parameter's property name (default the block's only lookup action); to fill it: inputs?: [input property names: \"Distance1\", \"Position1 X\", \"Position1 Y\", \"Visibility1\"] (default the table's), lookups?: [lookup parameter property names] (default the table's; its own first), rows?: [[a cell per input, then per lookup]] (numbers in block units, visibility states by name), unmatched?: text (shown when no row matches; default Custom) | {property: text}, reverse?: bool | [lookup property names] (allow reverse lookup; default as it was)} → {action, name, columns: [{name, parameter, property, lookup, unmatched, reverse}], rows} (no fill: just the table)", + ) + .enabled(editing) + .interactive(|_| Ok(Box::new(BlookupM))), + ] +} + +/// The Block Editor is open on a block (lookup tables belong to a block). +fn editing(s: &Session) -> std::result::Result<(), String> { + match s.state() { + Ok(st) => match &st.block_edit { + Some(be) if be.current => Err("Lookup tables belong to a block; this editor is open on the drawing itself.".into()), + Some(_) => Ok(()), + None => Err("Open a block in the Block Editor first (BEDIT).".into()), + }, + Err(e) => Err(e.to_string()), + } +} + +/// The edited block's name and its dynamic data. +fn block(s: &Session) -> Result<(String, DynamicBlock)> { + editing(s).map_err(EngineError::Other)?; + let st = s.state()?; + let be = st.block_edit.as_ref().ok_or_else(|| EngineError::Other("The Block Editor is not open.".into()))?; + let m = dynamic_block(&st.doc, &be.name).ok_or_else(none_yet)?; + Ok((be.name.clone(), m)) +} + +fn none_yet() -> EngineError { + bad("blookuptable", "the block has no lookup action; add a lookup parameter (BPARAMETER Lookup) and its action (BACTION)") +} + +/// The block's lookup actions: (graph id, name). +pub fn lookup_actions(m: &DynamicBlock) -> Vec<(i32, String)> { + m.actions.iter().filter(|a| matches!(a.kind, ActionKind::Lookup { .. })).map(|a| (a.node, a.name.clone())).collect() +} + +/// The lookup action `v` names: its graph id, its name, or the property name of the lookup +/// parameter it gives; none: the block's only one. +fn action_named(m: &DynamicBlock, v: Option<&Value>) -> Result { + let actions = lookup_actions(m); + let by_text = |t: &str| { + let t = t.trim(); + actions.iter().find(|(_, n)| n.eq_ignore_ascii_case(t)).map(|(id, _)| *id).or_else(|| { + let p = m.parameters.iter().find(|p| matches!(&p.kind, ParameterKind::Lookup { label, .. } if label.eq_ignore_ascii_case(t)))?; + m.actions + .iter() + .find(|a| matches!(&a.kind, ActionKind::Lookup { columns, .. } if columns.iter().any(|c| c.lookup && c.node == p.node))) + .map(|a| a.node) + }) + }; + let found = match v { + None | Some(Value::Null) => match actions.as_slice() { + [] => return Err(none_yet()), + [(id, _)] => Some(*id), + many => { + let names: Vec<&str> = many.iter().map(|(_, n)| n.as_str()).collect(); + return Err(bad("blookuptable", format!("the block has {} lookup actions; name one (`action`): {}", many.len(), names.join(", ")))); + } + }, + Some(Value::Number(n)) => n.as_i64().and_then(|n| i32::try_from(n).ok()).filter(|n| actions.iter().any(|(id, _)| id == n)), + Some(Value::String(t)) => t.trim().parse::().ok().filter(|n| actions.iter().any(|(id, _)| id == n)).or_else(|| by_text(t)), + Some(_) => None, + }; + found.ok_or_else(|| bad("blookuptable", format!("no lookup action {}", v.map(Value::to_string).unwrap_or_default()))) +} + +/// Lookup action `action`'s table as BLOOKUPTABLE reports it. +pub fn describe(m: &DynamicBlock, action: i32) -> Value { + let Some(a) = m.actions.iter().find(|a| a.node == action) else { return Value::Null }; + let ActionKind::Lookup { columns, rows } = &a.kind else { return Value::Null }; + let columns: Vec = columns + .iter() + .map(|c| { + json!({ + "name": column_property(m, c.node, &c.property), + "parameter": c.node, + "property": c.property, + "lookup": c.lookup, + "unmatched": c.unmatched, + "reverse": c.lookup && c.reverse, + }) + }) + .collect(); + json!({ "action": action, "name": a.name, "columns": columns, "rows": rows }) +} + +/// A cell given in JSON: text, or a number written as text. +fn cell(v: &Value) -> Option { + match v { + Value::String(t) => Some(t.clone()), + Value::Number(n) => Some(n.to_string()), + Value::Null => Some(String::new()), + _ => None, + } +} + +fn names(p: &Value, key: &str) -> Result>> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Array(a)) if a.len() <= 1_000 => a + .iter() + .map(|v| v.as_str().map(str::to_string).ok_or_else(|| bad("blookuptable", format!("`{key}` lists property names")))) + .collect::>() + .map(Some), + Some(_) => Err(bad("blookuptable", format!("`{key}` is a list of property names"))), + } +} + +fn run(s: &mut Session, p: &Value) -> Result { + let (name, m) = block(s)?; + let action = action_named(&m, p.get("action"))?; + let fill = ["inputs", "lookups", "rows", "unmatched", "reverse"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); + if !fill { + return Ok(describe(&m, action)); + } + let Some(ActionKind::Lookup { columns: old, rows: old_rows }) = m.actions.iter().find(|a| a.node == action).map(|a| &a.kind) else { + return Err(none_yet()); + }; + let inputs = input_properties(&m); + // A column of the table as it is, kept by name. + let kept = |node: i32, property: &str, lookup: bool| { + old.iter().find(|c| c.node == node && c.lookup == lookup && c.property.eq_ignore_ascii_case(property)) + }; + let mut columns: Vec = Vec::new(); + match names(p, "inputs")? { + Some(list) => { + for n in list { + let (_, node, property) = inputs.iter().find(|(shown, ..)| shown.eq_ignore_ascii_case(n.trim())).ok_or_else(|| { + bad( + "blookuptable", + format!( + "no input property \"{}\"; the block has: {}", + n.trim(), + inputs.iter().map(|(n, ..)| n.as_str()).collect::>().join(", ") + ), + ) + })?; + let unmatched = kept(*node, property, false).map(|c| c.unmatched.clone()).unwrap_or_default(); + columns.push(TableColumn { node: *node, property: property.clone(), lookup: false, unmatched, reverse: false }); + } + } + None => columns.extend(old.iter().filter(|c| !c.lookup).map(|c| TableColumn { + node: c.node, + property: c.property.clone(), + lookup: false, + unmatched: c.unmatched.clone(), + reverse: false, + })), + } + match names(p, "lookups")? { + Some(list) => { + for n in list { + let node = m + .parameters + .iter() + .find(|q| matches!(&q.kind, ParameterKind::Lookup { label, .. } if label.eq_ignore_ascii_case(n.trim()))) + .map(|q| q.node) + .ok_or_else(|| bad("blookuptable", format!("no lookup property \"{}\"", n.trim())))?; + let k = kept(node, "lookupString", true); + columns.push(TableColumn { + node, + property: "lookupString".into(), + lookup: true, + unmatched: k.map(|c| c.unmatched.clone()).unwrap_or_default(), + reverse: k.is_some_and(|c| c.reverse), + }); + } + } + None => columns.extend(old.iter().filter(|c| c.lookup).map(|c| TableColumn { + node: c.node, + property: c.property.clone(), + lookup: true, + unmatched: c.unmatched.clone(), + reverse: c.reverse, + })), + } + // What references show when no row matches. + match p.get("unmatched") { + None | Some(Value::Null) => {} + Some(Value::String(t)) => columns.iter_mut().for_each(|c| c.unmatched = t.clone()), + Some(Value::Object(o)) => { + for (k, v) in o { + let t = v.as_str().ok_or_else(|| bad("blookuptable", "`unmatched` values are text"))?; + let c = columns + .iter_mut() + .find(|c| column_property(&m, c.node, &c.property).eq_ignore_ascii_case(k.trim())) + .ok_or_else(|| bad("blookuptable", format!("no column \"{k}\" in the table")))?; + c.unmatched = t.to_string(); + } + } + Some(_) => Err(bad("blookuptable", "`unmatched` is text or {property: text}"))?, + } + match p.get("reverse") { + None | Some(Value::Null) => {} + Some(Value::Bool(b)) => columns.iter_mut().filter(|c| c.lookup).for_each(|c| c.reverse = *b), + Some(Value::Array(list)) => { + for c in columns.iter_mut().filter(|c| c.lookup) { + let shown = column_property(&m, c.node, &c.property); + c.reverse = list.iter().any(|v| v.as_str().is_some_and(|n| n.trim().eq_ignore_ascii_case(&shown))); + } + } + Some(_) => Err(bad("blookuptable", "`reverse` is true, false or a list of lookup property names"))?, + } + let rows: Vec> = match p.get("rows") { + None | Some(Value::Null) => { + // The table's rows, when its columns stay as they were. + let same = + columns.len() == old.len() && columns.iter().zip(old).all(|(a, b)| a.node == b.node && a.property.eq_ignore_ascii_case(&b.property)); + if same || old_rows.is_empty() { + old_rows.clone() + } else { + return Err(bad("blookuptable", "the columns changed; give `rows` for them")); + } + } + Some(Value::Array(rows)) if rows.len() <= MAX_LOOKUP_ROWS => rows + .iter() + .map(|r| match r { + Value::Array(cells) if cells.len() <= 1_000 => { + cells.iter().map(|c| cell(c).ok_or_else(|| bad("blookuptable", "a cell is text or a number"))).collect::>>() + } + _ => Err(bad("blookuptable", "each of `rows` is a list of cells")), + }) + .collect::>()?, + Some(_) => return Err(bad("blookuptable", format!("`rows` is a list of at most {MAX_LOOKUP_ROWS} rows"))), + }; + set_lookup_table(s.doc_mut()?, &name, action, &columns, &rows).map_err(|e| bad("blookuptable", e))?; + let m = dynamic_block(s.doc()?, &name).ok_or_else(none_yet)?; + Ok(describe(&m, action)) +} + +/// BLOOKUPTABLE on the command line (the UI opens the dialog instead): pick a lookup action, and +/// its table is listed. +struct BlookupM; + +impl Interactive for BlookupM { + fn name(&self) -> &'static str { + "BLOOKUPTABLE" + } + fn prompt(&self, _s: &Session) -> Prompt { + Prompt::new("Select lookup action", Accept::POINT) + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + let at = match i { + Input::Cancel | Input::Enter => return Ok(Step::Cancel), + Input::Point(p) => p, + Input::Text(t) | Input::Keyword(t) => { + let (_, m) = block(s)?; + let action = action_named(&m, Some(&Value::String(t)))?; + list(s, &m, action); + return Ok(Step::Done); + } + _ => return Ok(Step::Continue), + }; + let (name, m) = block(s)?; + let base = s.state()?.block_edit.as_ref().map(|b| b.base()).unwrap_or_default(); + let reach = (s.pixel_size() * s.settings.pickbox.max(1.0) * 3.0).max(1e-9); + let actions = lookup_actions(&m); + let hit = marks(s.doc()?, &name) + .into_iter() + .filter_map(|k| match k { + cadcraft_doc::dynblock::Mark::Action { node, at: a, .. } if actions.iter().any(|(id, _)| *id == node) => { + Some((node, (a.xy() - base - at).len())) + } + _ => None, + }) + .filter(|(_, d)| *d <= reach) + .min_by(|a, b| a.1.total_cmp(&b.1)); + match hit { + Some((action, _)) => { + list(s, &m, action); + Ok(Step::Done) + } + None => { + s.echo("Nothing Selected."); + Ok(Step::Continue) + } + } + } +} + +/// Echo action `action`'s table: its columns, then each row. +fn list(s: &mut Session, m: &DynamicBlock, action: i32) { + let t = describe(m, action); + let heads: Vec = + t["columns"].as_array().map(|c| c.iter().map(|c| c["name"].as_str().unwrap_or_default().to_string()).collect()).unwrap_or_default(); + s.echo(format!("{}: {}", t["name"].as_str().unwrap_or_default(), heads.join(" | "))); + for r in t["rows"].as_array().into_iter().flatten() { + let cells: Vec<&str> = r.as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + s.echo(format!(" {}", cells.join(" | "))); + } +} diff --git a/crates/engine/tests/block_authoring.rs b/crates/engine/tests/block_authoring.rs index 388c222f1a..e85f1928b2 100644 --- a/crates/engine/tests/block_authoring.rs +++ b/crates/engine/tests/block_authoring.rs @@ -194,7 +194,7 @@ fn types_not_available_yet_say_so() { let mut s = Session::new(); boxed(&mut s); s.execute("bedit", &json!({ "name": "Box" })).unwrap(); - for t in ["polar", "xy", "rotation", "flip", "lookup", "base", "alignment"] { + for t in ["polar", "xy", "rotation", "flip", "base", "alignment"] { let e = s.execute("bparameter", &json!({ "type": t, "start": [0, 0], "end": [1, 0] })).unwrap_err().to_string(); assert!(e.contains("not available yet"), "{t}: {e}"); } diff --git a/crates/engine/tests/block_lookup.rs b/crates/engine/tests/block_lookup.rs new file mode 100644 index 0000000000..d403400660 --- /dev/null +++ b/crates/engine/tests/block_lookup.rs @@ -0,0 +1,268 @@ +//! Lookup parameters and tables in the Block Editor (BPARAMETER Lookup, BACTION Lookup, +//! BLOOKUPTABLE): a table authored here sets a reference's distances, positions and visibility +//! state from the lookup value picked, and shows the lookup value its inputs match. + +use cadcraft_engine::doc::dynblock::{ActionKind, ParameterKind, custom_properties, dynamic_block, parameter_objects}; +use cadcraft_engine::doc::{EntityKind, Handle}; +use cadcraft_engine::{Input, Session}; +use serde_json::{Value, json}; + +fn h(v: &Value) -> Handle { + cadcraft_engine::cmd::curves::handle_value(v).unwrap() +} + +/// Block "Box": a 10 × 5 rectangle from (5,5) and a circle on its right edge, base point (5,5), +/// and a reference at (100,0). Returns the reference. +fn boxed(s: &mut Session) -> Value { + let made = |v: Value| if v["handle"].is_null() { v["handles"][0].clone() } else { v["handle"].clone() }; + let r = made(s.execute("rectang", &json!({ "p1": [5, 5], "p2": [15, 10] })).unwrap()); + let c = made(s.execute("circle", &json!({ "center": [15, 7.5], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "Box", "base": [5, 5], "handles": [r, c], "keep": "delete" })).unwrap(); + s.execute("insert", &json!({ "name": "Box", "at": [100, 0] })).unwrap()["handle"].clone() +} + +/// In the Block Editor on "Box" (editor coordinates: the rectangle from (0,0) to (10,5), the +/// circle at (10,2.5)): Distance1 stretching the right edge, Position1 moving the circle, states +/// VisibilityState0 (both) and Small (the rectangle only), and lookup parameter Size with its +/// table. Returns the lookup action's graph id. +fn authored(s: &mut Session) -> i32 { + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + let d = s.doc().unwrap(); + let of = |rect: bool| d.model.iter().find(|e| matches!(e.kind, EntityKind::LwPolyline(_)) == rect).unwrap().handle.hex(); + let (r, c) = (of(true), of(false)); + s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0], "grips": 1 })).unwrap(); + s.execute("baction", &json!({ "parameter": "Distance1", "type": "stretch", "frame": [[9, -1], [11, 6]], "handles": [r] })).unwrap(); + s.execute("bparameter", &json!({ "type": "point", "at": [10, 2.5] })).unwrap(); + s.execute("baction", &json!({ "parameter": "Position1", "type": "move", "handles": [c] })).unwrap(); + s.execute("bparameter", &json!({ "type": "visibility", "at": [-2, 5] })).unwrap(); + s.execute("bvstate", &json!({ "new": "Small", "visibility": "show" })).unwrap(); + s.execute("bvhide", &json!({ "handles": [c] })).unwrap(); + let p = s.execute("bparameter", &json!({ "type": "lookup", "at": [-2, 7], "label": "Size" })).unwrap(); + assert_eq!((p["element"].as_str(), p["label"].as_str()), (Some("Lookup"), Some("Size"))); + let a = s.execute("baction", &json!({ "parameter": "Size", "at": [-2, 8] })).unwrap(); + assert_eq!(a["name"], "Lookup1"); + a["node"].as_i64().unwrap() as i32 +} + +/// Reference `i`'s rectangle corners, circle centre and which of them show. +fn shape(s: &Session, i: &Value) -> (Vec<(f64, f64)>, (f64, f64), Vec) { + let d = s.doc().unwrap(); + let EntityKind::Insert(ins) = &d.entity(h(i)).unwrap().kind else { panic!() }; + let b = d.block(&ins.block).unwrap(); + let rect = b + .entities + .iter() + .find_map(|e| if let EntityKind::LwPolyline(p) = &e.kind { Some(p.vertices.iter().map(|v| (v.p.x, v.p.y)).collect()) } else { None }); + let circle = b.entities.iter().find_map(|e| if let EntityKind::Circle(c) = &e.kind { Some((c.center.x, c.center.y)) } else { None }); + (rect.unwrap(), circle.unwrap(), b.entities.iter().map(|e| e.common.visible).collect()) +} + +fn custom(s: &Session, i: &Value) -> Vec<(String, String, bool)> { + custom_properties(s.doc().unwrap(), h(i)).unwrap().1.into_iter().map(|p| (p.name, p.value, p.editable)).collect() +} + +#[test] +fn a_lookup_table_authored_in_json_drives_references() { + let mut s = Session::new(); + let i = boxed(&mut s); + let act = authored(&mut s); + // Empty, as BACTION makes it. + let t = s.execute("blookuptable", &json!({})).unwrap(); + assert_eq!(t["name"], "Lookup1"); + assert_eq!( + t["columns"], + json!([{ "name": "Size", "parameter": t["columns"][0]["parameter"], "property": "lookupString", "lookup": true, "unmatched": "Custom", "reverse": false }]) + ); + let undo = s.state().unwrap().undo.len(); + let t = s + .execute( + "blookuptable", + &json!({ + "inputs": ["Distance1", "Position1 X", "Visibility1"], + "rows": [[10, 10, "VisibilityState0", "Big"], ["6", "6", "small", "Small"]], + "reverse": true, + }), + ) + .unwrap(); + assert_eq!(s.state().unwrap().undo.len(), undo + 1, "one undo step"); + assert_eq!(t["action"], act); + let names: Vec<&str> = t["columns"].as_array().unwrap().iter().map(|c| c["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Distance1", "Position1 X", "Visibility1", "Size"]); + assert_eq!(t["rows"], json!([["10", "10", "VisibilityState0", "Big"], ["6", "6", "Small", "Small"]])); + assert_eq!(t["columns"][3]["reverse"], true); + s.execute("bclose", &json!({})).unwrap(); + + // The block's own values match the first row. + assert!(custom(&s, &i).contains(&("Size".to_string(), "Big".to_string(), true)), "{:?}", custom(&s, &i)); + // Size → Small sets the row's distance, position and state. + s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Size", "value": "Small" })).unwrap(); + let (rect, circle, shown) = shape(&s, &i); + assert_eq!(rect, [(5.0, 5.0), (11.0, 5.0), (11.0, 10.0), (5.0, 10.0)]); + assert_eq!(circle, (11.0, 7.5)); + assert_eq!(shown, [true, false], "Small hides the circle"); + // Inputs matching no row show Custom; matching one again, its value. + s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Distance1", "value": "8" })).unwrap(); + assert!(custom(&s, &i).contains(&("Size".to_string(), "Custom".to_string(), true))); + s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Distance1", "value": "6" })).unwrap(); + assert!(custom(&s, &i).contains(&("Size".to_string(), "Small".to_string(), true))); +} + +#[test] +fn a_read_only_lookup_cannot_be_set() { + let mut s = Session::new(); + let i = boxed(&mut s); + authored(&mut s); + s.execute("blookuptable", &json!({ "inputs": ["Distance1"], "rows": [[10, "Big"], [6, "Small"]] })).unwrap(); + s.execute("bclose", &json!({})).unwrap(); + assert!(custom(&s, &i).contains(&("Size".to_string(), "Big".to_string(), false)), "read only unless reverse lookup is allowed"); + assert!(s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Distance1", "value": "6" })).is_ok()); + assert!(custom(&s, &i).contains(&("Size".to_string(), "Small".to_string(), false))); +} + +#[test] +fn lookup_prompts_ask_as_autocad_does() { + let mut s = Session::new(); + boxed(&mut s); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + s.execute("bparameter", &json!({ "type": "lookup", "at": [-2, 9] })).unwrap(); + s.script("BPARAMETER K\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Specify parameter location"); + s.script("N\n").unwrap(); + let p = s.current_prompt().unwrap(); + assert_eq!((p.message.as_str(), p.default.as_deref()), ("Enter parameter name", Some("Lookup1"))); + s.script("Look2\nL\n").unwrap(); + let p = s.current_prompt().unwrap(); + assert_eq!((p.message.as_str(), p.default.as_deref()), ("Enter lookup property label", Some("Lookup2"))); + s.script("Size\nD\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Enter property description"); + s.script("desc\nP\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Display property in Properties palette"); + s.script("N\n-2,7\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Enter number of grips"); + s.script("0\n").unwrap(); + assert!(s.running.is_none()); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let p = m.parameters.iter().find(|p| p.element == "Look2").unwrap(); + assert!(matches!(&p.kind, ParameterKind::Lookup { label, description, .. } if label == "Size" && description == "desc")); + assert!(!p.show_properties && p.grips.iter().all(|g| *g == 0)); + + // BACTION on it asks only where the action goes; a second one is refused. + s.script("BACTION -2,7\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Specify action location"); + s.script("-2,8\n").unwrap(); + assert!(s.running.is_none()); + s.script("BACTION -2,7\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Select parameter", "already has its table"); + s.input(Input::Cancel).unwrap(); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + assert_eq!(m.actions.iter().filter(|a| matches!(a.kind, ActionKind::Lookup { .. })).count(), 1); + + // BLOOKUPTABLE on the command line: pick the action; its table is listed. + s.script("BLOOKUPTABLE\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Select lookup action"); + s.script("-2,8\n").unwrap(); + assert!(s.running.is_none()); +} + +#[test] +fn the_lookup_action_is_active_in_the_state_shown() { + let mut s = Session::new(); + boxed(&mut s); + let act = authored(&mut s); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let action = m.actions.iter().find(|a| a.node == act).unwrap().handle; + let Some(ParameterKind::Visibility { states, .. }) = + m.parameters.iter().map(|p| p.kind.clone()).find(|k| matches!(k, ParameterKind::Visibility { .. })) + else { + panic!() + }; + let small = states.iter().find(|st| st.name == "Small").unwrap(); + assert!(small.active.contains(&action), "added while Small is shown"); + assert!(!states[0].active.contains(&action)); + // A visibility state made to show everything lists the actions too, as AutoCAD's does. + s.execute("bvstate", &json!({ "new": "All", "visibility": "show" })).unwrap(); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let all = parameter_objects(&m, None); + let Some(ParameterKind::Visibility { states, .. }) = + m.parameters.iter().map(|p| p.kind.clone()).find(|k| matches!(k, ParameterKind::Visibility { .. })) + else { + panic!() + }; + assert_eq!(states.last().unwrap().active, all); + assert!(all.contains(&action)); +} + +#[test] +fn erasing_the_lookup_parameter_erases_its_table() { + let mut s = Session::new(); + boxed(&mut s); + authored(&mut s); + s.execute("blookuptable", &json!({ "inputs": ["Distance1", "Visibility1"], "rows": [[10, "VisibilityState0", "Big"], [6, "Small", "Small"]] })) + .unwrap(); + // Erasing an input takes its column. + let lin = dynamic_block(s.doc().unwrap(), "Box").unwrap().parameters.iter().find(|p| p.kind.label() == Some("Distance1")).unwrap().node; + s.execute("blocks.element.erase", &json!({ "nodes": [lin] })).unwrap(); + let t = s.execute("blookuptable", &json!({})).unwrap(); + assert_eq!(t["rows"], json!([["VisibilityState0", "Big"], ["Small", "Small"]])); + let size = dynamic_block(s.doc().unwrap(), "Box").unwrap().parameters.iter().find(|p| p.kind.label() == Some("Size")).unwrap().node; + s.execute("blocks.element.erase", &json!({ "nodes": [size] })).unwrap(); + assert!(s.execute("blookuptable", &json!({})).is_err(), "no lookup action left"); +} + +#[test] +fn hostile_lookup_params_never_panic() { + let mut s = Session::new(); + boxed(&mut s); + assert!(s.execute("blookuptable", &json!({})).is_err(), "only in the Block Editor"); + authored(&mut s); + let many: Vec = (0..20_001).map(|_| json!(["1", "a"])).collect(); + for p in [ + json!(null), + json!([]), + json!({ "action": "Nope" }), + json!({ "action": 9999 }), + json!({ "action": [1] }), + json!({ "inputs": "Distance1" }), + json!({ "inputs": [5] }), + json!({ "inputs": ["Nope"], "rows": [] }), + json!({ "inputs": ["Distance1"], "rows": 5 }), + json!({ "inputs": ["Distance1"], "rows": [5] }), + json!({ "inputs": ["Distance1"], "rows": [[{}, "a"]] }), + json!({ "inputs": ["Distance1"], "rows": [["1"]] }), + json!({ "inputs": ["Distance1"], "rows": [["NaN", "a"]] }), + json!({ "inputs": ["Distance1"], "rows": [["1e999", "a"]] }), + json!({ "inputs": ["Distance1"], "rows": many }), + json!({ "inputs": ["Distance1", "Distance1"], "rows": [] }), + json!({ "inputs": ["Distance1"], "lookups": ["Nope"], "rows": [] }), + json!({ "inputs": ["Distance1"], "lookups": [], "rows": [] }), + json!({ "unmatched": 5 }), + json!({ "unmatched": { "Nope": "x" } }), + json!({ "reverse": "yes" }), + json!({ "inputs": ["Distance1"] }), + ] { + let _ = s.execute("blookuptable", &p); + } + let before = s.doc().unwrap().foreign.clone(); + assert!(s.execute("blookuptable", &json!({ "inputs": ["Distance1"], "rows": [["1", "a"], ["1.0", "b"]] })).is_err()); + assert_eq!(s.doc().unwrap().foreign, before, "a refused table changes nothing"); + for p in [ + json!({ "type": "lookup" }), + json!({ "type": "lookup", "at": [0, 0], "grips": 2 }), + json!({ "type": "lookup", "at": [0, 0], "palette": "no" }), + json!({ "type": "lookup", "at": [0, 0], "name": "Lookup" }), + ] { + assert!(s.execute("bparameter", &p).is_err(), "{p}"); + } + let _ = s.execute("bparameter", &json!({ "type": "lookup", "at": [1e308, f64::MAX] })); + for p in [ + json!({ "parameter": "Size" }), + json!({ "parameter": "Size", "type": "move", "handles": [] }), + json!({ "parameter": "Distance1", "type": "lookup" }), + ] { + assert!(s.execute("baction", &p).is_err(), "{p}"); + } + s.script("BLOOKUPTABLE\n1000,1000\n").unwrap(); + s.input(Input::Cancel).unwrap(); + s.script("BPARAMETER K N\n\nP\nmaybe\n").unwrap(); + s.input(Input::Cancel).unwrap(); +} From db3e5acb7ed880fd3c0248516f7807fa3cdde17d Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 25 Oct 2026 19:24:30 -0600 Subject: [PATCH 22/47] Dynamic blocks: the Property Lookup Table dialog (BLOOKUPTABLE, or double-click a lookup action) BLOOKUPTABLE typed, or a double-click on a lookup action in the Block Editor (as in AutoCAD), opens a Property Lookup Table dialog like AutoCAD's: Input Properties and Lookup Properties side by side, each a bordered grid with a header row and numbered rows, a row per set of inputs with a blank row at the end to add one, visibility states picked from a list, the row with each lookup property's value for no match, and Allow reverse lookup / Read only (greyed while its values repeat). Add Properties... lists the input properties (Name, Type) or the lookup parameters no table gives yet; Audit checks the table with AutoCAD's rules and messages; right-click removes a column or deletes a row. OK writes the table as one undo step; Cancel changes nothing. The double-click opens the table even when the first click's pick put the action's grip under the cursor. Typed BLOOKUPTABLE opens the action picked in the editor (else the first) and offers the others at the top. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/blookup.rs | 713 +++++++++++++++++++++++++ crates/ui-egui/src/canvas.rs | 14 +- crates/ui-egui/src/canvas/blockedit.rs | 17 +- crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/src/menus.rs | 3 + 6 files changed, 746 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/blookup.rs diff --git a/crates/ui-egui/src/blookup.rs b/crates/ui-egui/src/blookup.rs new file mode 100644 index 0000000000..3c74812bfc --- /dev/null +++ b/crates/ui-egui/src/blookup.rs @@ -0,0 +1,713 @@ +//! The Property Lookup Table dialog: BLOOKUPTABLE typed, or a double-click on a lookup action in +//! the Block Editor (as in AutoCAD), while the Block Editor is open on a block with one. As AutoCAD's dialog: the +//! action's input properties (left) and lookup properties (right) as columns, one row per set of +//! inputs, a blank row at the end to add one, then the `` row (what a reference shows +//! when no row matches, editable for each lookup property) and whether each lookup property can be +//! set on a reference ("Allow reverse lookup", only while its values don't repeat) or is "Read +//! only". Add Properties... adds columns, Audit checks the table, OK writes it as one step +//! (`blookuptable {inputs, lookups, rows, unmatched, reverse}`); Cancel changes nothing. A block +//! with several lookup actions picks one at the top (the one picked in the editor first). JSON +//! calls skip the dialog. + +use cadcraft_engine::doc::dynblock::{ActionKind, DynamicBlock, ParameterKind, column_property, dynamic_block, input_properties, set_lookup_table}; +use egui::{RichText, Stroke, vec2}; +use serde_json::{Map, Value, json}; + +use crate::CadApp; +use crate::theme::Tokens; + +/// One column as the dialog edits it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Column { + /// The property name shown ("Distance1", "Position1 X", "Size"). + pub name: String, + pub parameter: i32, + pub property: String, + pub lookup: bool, + pub unmatched: String, + pub reverse: bool, + /// A visibility state column's states (its cells are picked from them). + pub states: Vec, +} + +/// The Add Parameter Properties dialog's fields: which list, and the properties ticked in it. +#[derive(Clone, Debug, Default)] +pub struct Adding { + pub lookup: bool, + pub ticked: Vec, +} + +/// The dialog's state while it is open: the table as it will be written on OK. +#[derive(Clone, Debug, Default)] +pub struct State { + /// The block's lookup actions (graph id, name) and the one shown. + pub actions: Vec<(i32, String)>, + pub action: i32, + /// Input columns first, then lookup columns. + pub columns: Vec, + /// One cell per column; the blank row at the end isn't kept here. + pub rows: Vec>, + /// The Add Parameter Properties dialog, while open. + pub adding: Option, + /// Audit's verdict or why OK was refused (`true`: a problem). + pub message: Option<(String, bool)>, +} + +impl State { + /// Load action `action` of block `m` into the dialog. + fn load(m: &DynamicBlock, action: i32) -> State { + let actions: Vec<(i32, String)> = + m.actions.iter().filter(|a| matches!(a.kind, ActionKind::Lookup { .. })).map(|a| (a.node, a.name.clone())).collect(); + let Some(ActionKind::Lookup { columns, rows }) = m.actions.iter().find(|a| a.node == action).map(|a| &a.kind) else { + return State { actions, action, ..State::default() }; + }; + let columns = columns + .iter() + .map(|c| Column { + name: column_property(m, c.node, &c.property), + parameter: c.node, + property: c.property.clone(), + lookup: c.lookup, + unmatched: c.unmatched.clone(), + reverse: c.lookup && c.reverse, + states: states_of(m, c.node, &c.property), + }) + .collect(); + State { actions, action, columns, rows: rows.clone(), ..State::default() } + } + + fn inputs(&self) -> usize { + self.columns.iter().filter(|c| !c.lookup).count() + } + + /// Whether lookup column `j`'s values repeat (or it has none): it can't be reversed then. + fn repeats(&self, j: usize) -> bool { + let values: Vec = self.rows.iter().filter_map(|r| r.get(j)).map(|v| v.trim().to_lowercase()).filter(|v| !v.is_empty()).collect(); + values.is_empty() || values.iter().enumerate().any(|(i, v)| values.iter().take(i).any(|w| w == v)) + } + + /// Add `column` with an empty cell in every row: an input after the other inputs, a lookup + /// column last. + fn add_column(&mut self, column: Column) { + let at = if column.lookup { self.columns.len() } else { self.inputs() }; + self.columns.insert(at, column); + for r in &mut self.rows { + r.insert(at.min(r.len()), String::new()); + } + } + + /// Remove column `j` (not the action's own lookup column, the first lookup column). + fn remove_column(&mut self, j: usize) { + if !self.removable(j) { + return; + } + self.columns.remove(j); + for r in &mut self.rows { + if j < r.len() { + r.remove(j); + } + } + } + + fn removable(&self, j: usize) -> bool { + j != self.inputs() && j < self.columns.len() + } + + /// The `blookuptable` parameters writing this table. + fn params(&self) -> Value { + let names = |lookup: bool| self.columns.iter().filter(|c| c.lookup == lookup).map(|c| c.name.clone()).collect::>(); + let mut unmatched = Map::new(); + for c in &self.columns { + unmatched.insert(c.name.clone(), json!(c.unmatched)); + } + let reverse: Vec = + self.columns.iter().enumerate().filter(|(j, c)| c.lookup && c.reverse && !self.repeats(*j)).map(|(_, c)| c.name.clone()).collect(); + let rows: Vec<&Vec> = self.rows.iter().filter(|r| r.iter().any(|c| !c.trim().is_empty())).collect(); + json!({ "action": self.action, "inputs": names(false), "lookups": names(true), "rows": rows, "unmatched": unmatched, "reverse": reverse }) + } + + /// The table written into a copy of drawing `d`'s block `block`: `Err` with AutoCAD's reason + /// when it would be refused (Audit, and OK before writing). + fn audit(&self, d: &cadcraft_engine::doc::Drawing, block: &str) -> Result<(), String> { + let mut d = d.clone(); + let columns: Vec = self + .columns + .iter() + .enumerate() + .map(|(j, c)| cadcraft_engine::doc::dynblock::TableColumn { + node: c.parameter, + property: c.property.clone(), + lookup: c.lookup, + unmatched: c.unmatched.clone(), + reverse: c.reverse && !self.repeats(j), + }) + .collect(); + set_lookup_table(&mut d, block, self.action, &columns, &self.rows) + } +} + +/// A visibility column's states (empty for other columns). +fn states_of(m: &DynamicBlock, node: i32, property: &str) -> Vec { + if !property.eq_ignore_ascii_case("VisibilityState") { + return Vec::new(); + } + m.parameters + .iter() + .find(|p| p.node == node) + .and_then(|p| match &p.kind { + ParameterKind::Visibility { states, .. } => Some(states.iter().map(|s| s.name.clone()).collect()), + _ => None, + }) + .unwrap_or_default() +} + +/// The edited block's name and dynamic data, when the Block Editor is open on a block. +fn edited(app: &CadApp) -> Option<(String, DynamicBlock, Vec)> { + let st = app.session.state().ok()?; + let be = st.block_edit.as_ref()?; + if be.current { + return None; + } + Some((be.name.clone(), dynamic_block(&st.doc, &be.name)?, be.picked.clone())) +} + +/// BLOOKUPTABLE typed or from the Block Editor's bar without parameters opens the dialog when the +/// edited block has a lookup action (the one picked in the editor, else its first); otherwise +/// BLOOKUPTABLE runs and says why it can't. +pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option> { + if id != "blookuptable" || !params.is_null() { + return None; + } + let (_, m, picked) = edited(app)?; + let lookups: Vec = m.actions.iter().filter(|a| matches!(a.kind, ActionKind::Lookup { .. })).map(|a| a.node).collect(); + let action = lookups.iter().copied().find(|a| picked.contains(a)).or_else(|| lookups.first().copied())?; + open(app, action).then_some(Ok(Value::Null)) +} + +/// Open the dialog on action `node` of the edited block when it is a lookup action (a +/// double-click on its mark); whether it opened. +pub fn open(app: &mut CadApp, node: i32) -> bool { + let Some((_, m, _)) = edited(app) else { return false }; + if !m.actions.iter().any(|a| a.node == node && matches!(a.kind, ActionKind::Lookup { .. })) { + return false; + } + app.blookup = State::load(&m, node); + app.ui.dialog = Some("blookuptable".into()); + true +} + +/// The Property Lookup Table window (and Add Parameter Properties over it). +pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { + let t = Tokens::get(); + let Some((block, m, _)) = edited(app) else { + *open = false; + return; + }; + let (mut ok, mut cancel, mut audit) = (false, false, false); + let mut st = std::mem::take(&mut app.blookup); + let modal = st.adding.is_some(); + let mut switch: Option = None; + egui::Window::new(crate::tl!("Property Lookup Table")) + .id(egui::Id::unique("Property Lookup Table")) + .open(open) + .collapsible(false) + .resizable(true) + .default_width(760.0) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.add_enabled_ui(!modal, |ui| { + ui.horizontal(|ui| { + ui.label(crate::tl!("Action name:")); + let current = st.actions.iter().find(|(id, _)| *id == st.action).map(|(_, n)| n.clone()).unwrap_or_default(); + if st.actions.len() > 1 { + craft_ui::ComboBox::from_id_salt("blookup-action").selected_text(current).show_ui(ui, |ui| { + for (id, n) in &st.actions { + if ui.selectable_label(*id == st.action, n.as_str()).clicked() && *id != st.action { + switch = Some(*id); + } + } + }); + } else { + ui.label(RichText::new(current).color(t.text)); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(crate::tl!("Audit")).clicked() { + audit = true; + } + if ui.button(crate::tl!("Add Properties...")).clicked() { + st.adding = Some(Adding::default()); + st.message = None; + } + }); + }); + ui.add_space(6.0); + egui::ScrollArea::both().id_salt("blookup-table").auto_shrink([false, true]).max_height(420.0).show(ui, |ui| { + table(ui, &mut st); + }); + ui.add_space(6.0); + if let Some((msg, problem)) = &st.message { + let color = if *problem { t.warn } else { t.accent }; + egui::Frame::new().stroke(Stroke::new(1.0, color)).corner_radius(3.0).inner_margin(vec2(8.0, 4.0)).show(ui, |ui| { + ui.colored_label(color, msg); + }); + } + ui.separator(); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(crate::tl!("Cancel")).clicked() { + cancel = true; + } + if ui.button(crate::tl!("OK")).clicked() { + ok = true; + } + }); + }); + }); + }); + if st.adding.is_some() { + add_dialog(ctx, &mut st, &m); + } + if let Some(id) = switch { + st = State::load(&m, id); + } + if audit { + st.message = Some(match st.audit(&app.session.state().map(|s| s.doc.clone()).unwrap_or_default(), &block) { + Ok(()) => (crate::i18n::t("No errors have been found in the Property Lookup Table.").to_string(), false), + Err(e) => (e, true), + }); + } + if ok { + match app.run("blookuptable", st.params()) { + Ok(_) => *open = false, + Err(e) => { + st.message = Some((e, true)); + app.blookup = st; + return; + } + } + } + if cancel { + *open = false; + } + app.blookup = st; +} + +/// The grid's row height, header height and row-number column width. +const ROW_H: f32 = 26.0; +const HEAD_H: f32 = 28.0; +const NUM_W: f32 = 34.0; + +/// A column's width: wider for a list (a visibility state, a lookup's reverse-lookup choice). +fn col_width(c: &Column) -> f32 { + if c.states.is_empty() && !c.lookup { 120.0 } else { 180.0 } +} + +/// What the grid asks for once drawn: a column to remove, a row to delete. +#[derive(Default)] +struct Edits { + remove: Option, + delete_row: Option, +} + +/// The table, as AutoCAD lays it out: Input Properties and Lookup Properties side by side, each +/// a grid with its header, a row per set of inputs, a blank row that adds one when filled in, +/// then the `` row and (lookups) the reverse-lookup row. Right-click a header to +/// remove the property, a row number to delete the row. +fn table(ui: &mut egui::Ui, st: &mut State) { + let inputs = st.inputs(); + let len = st.columns.len(); + let mut edits = Edits::default(); + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = 12.0; + pane(ui, st, crate::tl!("Input Properties"), 0..inputs, true, &mut edits); + pane(ui, st, crate::tl!("Lookup Properties"), inputs..len, false, &mut edits); + }); + if let Some(j) = edits.remove { + st.remove_column(j); + } + if let Some(r) = edits.delete_row + && r < st.rows.len() + { + st.rows.remove(r); + } +} + +/// One side of the table: columns `cols` (with row numbers when `numbers`). +fn pane(ui: &mut egui::Ui, st: &mut State, title: &str, cols: std::ops::Range, numbers: bool, edits: &mut Edits) { + let t = Tokens::get(); + let n = st.rows.len(); + // The data rows, the blank row, and reverse lookup: both sides line up. + let rows = n + 3; + let num_w = if numbers { NUM_W } else { 0.0 }; + let widths: Vec = cols.clone().filter_map(|j| st.columns.get(j)).map(col_width).collect(); + let w = num_w + if widths.is_empty() { 240.0 } else { widths.iter().sum() }; + let font = egui::FontId::proportional(13.0); + ui.vertical(|ui| { + ui.label(RichText::new(title).strong().color(t.text)); + ui.add_space(2.0); + let (rect, _) = ui.allocate_exact_size(vec2(w, HEAD_H + ROW_H * rows as f32), egui::Sense::hover()); + let p = ui.painter_at(rect.expand(1.0)); + let top = rect.top() + HEAD_H; + let row_y = |r: usize| top + ROW_H * r as f32; + // Backgrounds: the cells, the header, the row numbers, and the rows after the data. + p.rect_filled(rect, 3.0, t.field); + p.rect_filled(egui::Rect::from_min_size(rect.min, vec2(w, HEAD_H)), egui::CornerRadius { nw: 3, ne: 3, sw: 0, se: 0 }, t.panel); + if numbers { + p.rect_filled(egui::Rect::from_min_max(egui::pos2(rect.left(), top), egui::pos2(rect.left() + num_w, rect.bottom())), 0.0, t.panel); + } + p.rect_filled(egui::Rect::from_min_max(egui::pos2(rect.left() + num_w, row_y(n + 1)), rect.max), 0.0, t.panel.gamma_multiply(0.55)); + let line = Stroke::new(1.0, t.border); + for r in 0..rows { + p.hline(rect.x_range(), row_y(r), line); + } + let mut x = rect.left() + num_w; + if numbers { + p.vline(x, rect.y_range(), line); + } + for cw in &widths { + x += cw; + if x < rect.right() - 1.0 { + p.vline(x, rect.y_range(), line); + } + } + p.rect_stroke(rect, 3.0, line, egui::StrokeKind::Inside); + if widths.is_empty() { + let hint = crate::tl!("Add Properties... adds input properties"); + p.text(rect.center(), egui::Align2::CENTER_CENTER, hint, font.clone(), t.text_dim); + return; + } + + // Headers: right-click one to remove its property (not the action's own lookup). + let mut x = rect.left() + num_w; + for (k, j) in cols.clone().enumerate() { + let (Some(c), Some(cw)) = (st.columns.get(j), widths.get(k)) else { continue }; + let hr = egui::Rect::from_min_size(egui::pos2(x, rect.top()), vec2(*cw, HEAD_H)); + let color = if c.lookup { t.accent } else { t.text }; + p.text(hr.left_center() + vec2(8.0, 0.0), egui::Align2::LEFT_CENTER, &c.name, egui::FontId::proportional(13.0), color); + let removable = st.removable(j); + ui.interact(hr, ui.scope_id().with(("blookup-head", j)), egui::Sense::click()).context_menu(|ui| { + if ui.add_enabled(removable, egui::Button::new(crate::tl!("Remove Property"))).clicked() { + edits.remove = Some(j); + ui.close(); + } + }); + x += cw; + } + + // Row numbers: right-click one to delete its row; `*` marks the row that adds one. + if numbers { + for r in 0..=n { + let nr = egui::Rect::from_min_size(egui::pos2(rect.left(), row_y(r)), vec2(num_w, ROW_H)); + let label = if r < n { format!("{}", r + 1) } else { "*".to_string() }; + p.text(nr.center(), egui::Align2::CENTER_CENTER, label, font.clone(), t.text_dim); + if r < n { + ui.interact(nr, ui.scope_id().with(("blookup-row", r)), egui::Sense::click()).context_menu(|ui| { + if ui.button(crate::tl!("Delete Row")).clicked() { + edits.delete_row = Some(r); + ui.close(); + } + }); + } + } + } + + // The cells: text, or a visibility state picked from its list. + let cell_rect = |k: usize, r: usize| { + let x = rect.left() + num_w + widths.iter().take(k).sum::(); + egui::Rect::from_min_size(egui::pos2(x, row_y(r)), vec2(widths.get(k).copied().unwrap_or(0.0), ROW_H)).shrink(1.0) + }; + let blank = vec![String::new(); st.columns.len()]; + for r in 0..=n { + let mut row = st.rows.get(r).cloned().unwrap_or_else(|| blank.clone()); + for (k, j) in cols.clone().enumerate() { + let (Some(c), Some(cell)) = (st.columns.get(j), row.get_mut(j)) else { continue }; + let cr = cell_rect(k, r); + if c.states.is_empty() { + let edit = egui::TextEdit::singleline(cell) + .frame(egui::Frame::NONE) + .margin(vec2(8.0, 0.0)) + .align(egui::Align2::LEFT_CENTER) + .id_salt(("blookup-cell", r, j)); + ui.put(cr.with_min_x(cr.min.x + 6.0), edit); + } else { + ui.scope_builder(egui::UiBuilder::new().max_rect(cr.shrink2(vec2(4.0, 1.0))), |ui| { + flat(ui); + craft_ui::ComboBox::from_id_salt(("blookup-state", r, j)).width(cr.width() - 8.0).selected_text(cell.as_str()).show_ui( + ui, + |ui| { + for s in &c.states { + if ui.selectable_label(cell == s, s.as_str()).clicked() { + *cell = s.clone(); + } + } + }, + ); + }); + } + } + if r < n { + if let Some(old) = st.rows.get_mut(r) { + *old = row; + } + } else if row.iter().any(|c| !c.trim().is_empty()) { + st.rows.push(row); + } + } + + // What references show when no row matches: under the inputs, each lookup's + // value (editable) under the lookups; then whether each lookup can be set backwards. + if numbers { + let ur = egui::Rect::from_min_max(egui::pos2(rect.left() + num_w, row_y(n + 1)), egui::pos2(rect.right(), row_y(n + 2))); + let italic = egui::FontId::new(13.0, egui::FontFamily::Proportional); + p.text(ur.left_center() + vec2(8.0, 0.0), egui::Align2::LEFT_CENTER, "", italic, t.text_dim); + return; + } + let repeats: Vec = cols.clone().map(|j| st.repeats(j)).collect(); + for (k, j) in cols.clone().enumerate() { + let Some(c) = st.columns.get_mut(j) else { continue }; + let edit = egui::TextEdit::singleline(&mut c.unmatched) + .frame(egui::Frame::NONE) + .margin(vec2(8.0, 0.0)) + .align(egui::Align2::LEFT_CENTER) + .id_salt(("blookup-unmatched", j)); + let ur = cell_rect(k, n + 1); + ui.put(ur.with_min_x(ur.min.x + 6.0), edit); + let can = !repeats.get(k).copied().unwrap_or(true); + let shown = if c.reverse && can { crate::tl!("Allow reverse lookup") } else { crate::tl!("Read only") }; + let rr = cell_rect(k, n + 2); + ui.scope_builder(egui::UiBuilder::new().max_rect(rr.shrink2(vec2(4.0, 1.0))), |ui| { + flat(ui); + ui.add_enabled_ui(can, |ui| { + craft_ui::ComboBox::from_id_salt(("blookup-reverse", j)).width(rr.width() - 8.0).selected_text(shown).show_ui(ui, |ui| { + if ui.selectable_label(c.reverse, crate::tl!("Allow reverse lookup")).clicked() { + c.reverse = true; + } + if ui.selectable_label(!c.reverse, crate::tl!("Read only")).clicked() { + c.reverse = false; + } + }); + }) + .response + .on_disabled_hover_text(crate::tl!("Read only while lookup values repeat")); + }); + } + }); +} + +/// A list inside a grid cell: no button background until hovered, so it reads as the cell. +fn flat(ui: &mut egui::Ui) { + let w = &mut ui.style_mut().visuals.widgets; + w.inactive.weak_bg_fill = egui::Color32::TRANSPARENT; + w.inactive.bg_stroke = Stroke::NONE; +} + +/// The properties the Add Parameter Properties dialog lists: (name, type shown, column). +fn addable(st: &State, m: &DynamicBlock, lookup: bool) -> Vec<(String, String, Column)> { + let has = |node: i32, property: &str| st.columns.iter().any(|c| c.parameter == node && c.property.eq_ignore_ascii_case(property)); + if lookup { + // Lookup parameters no table gives yet. + let taken = |node: i32| { + m.actions.iter().any(|a| matches!(&a.kind, ActionKind::Lookup { columns, .. } if columns.iter().any(|c| c.lookup && c.node == node))) + }; + return m + .parameters + .iter() + .filter_map(|p| match &p.kind { + ParameterKind::Lookup { label, .. } if !has(p.node, "lookupString") && !taken(p.node) => Some(( + label.clone(), + p.element.clone(), + Column { name: label.clone(), parameter: p.node, property: "lookupString".into(), lookup: true, ..Column::default() }, + )), + _ => None, + }) + .collect(); + } + input_properties(m) + .into_iter() + .filter(|(_, node, prop)| !has(*node, prop)) + .map(|(name, node, property)| { + let kind = match m.parameters.iter().find(|p| p.node == node).map(|p| &p.kind) { + Some(ParameterKind::Linear { .. }) => crate::i18n::t("Linear"), + Some(ParameterKind::Point { .. }) => crate::i18n::t("Point"), + _ => crate::i18n::t("Visibility State"), + }; + let states = states_of(m, node, &property); + (name.clone(), kind.to_string(), Column { name, parameter: node, property, states, ..Column::default() }) + }) + .collect() +} + +/// The Add Parameter Properties dialog: input or lookup properties to tick and add. +fn add_dialog(ctx: &egui::Context, st: &mut State, m: &DynamicBlock) { + let Some(mut adding) = st.adding.take() else { return }; + let (mut ok, mut cancel) = (false, false); + let mut open = true; + let list = addable(st, m, adding.lookup); + egui::Window::new(crate::tl!("Add Parameter Properties")) + .id(egui::Id::unique("Add Parameter Properties")) + .open(&mut open) + .collapsible(false) + .resizable(false) + .order(egui::Order::Foreground) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.set_min_width(340.0); + ui.label(crate::tl!("Parameter properties:")); + egui::Frame::new().stroke(Stroke::new(1.0, Tokens::get().border)).inner_margin(4.0).show(ui, |ui| { + ui.set_min_height(160.0); + egui::Grid::new("blookup-add").striped(true).show(ui, |ui| { + ui.label(RichText::new(crate::tl!("Name")).strong()); + ui.label(RichText::new(crate::tl!("Type")).strong()); + ui.end_row(); + for (name, kind, _) in &list { + let mut on = adding.ticked.contains(name); + if ui.checkbox(&mut on, name.as_str()).changed() { + if on { + adding.ticked.push(name.clone()); + } else { + adding.ticked.retain(|n| n != name); + } + } + ui.label(kind.as_str()); + ui.end_row(); + } + }); + }); + ui.group(|ui| { + ui.label(crate::tl!("Property type")); + let before = adding.lookup; + ui.radio_value(&mut adding.lookup, false, crate::tl!("Add input properties")); + ui.radio_value(&mut adding.lookup, true, crate::tl!("Add lookup properties")); + if adding.lookup != before { + adding.ticked.clear(); + } + }); + ui.separator(); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(crate::tl!("Cancel")).clicked() { + cancel = true; + } + if ui.button(crate::tl!("OK")).clicked() { + ok = true; + } + }); + }); + }); + if ok { + for (name, _, column) in list { + if adding.ticked.contains(&name) { + st.add_column(column); + } + } + return; + } + if cancel || !open { + return; + } + st.adding = Some(adding); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// An app in the Block Editor on block "B" (a rectangle and a circle) with Distance1, + /// Position1, Visibility1 (VisibilityState0, Small), lookup parameter Size and its action. + fn editing() -> CadApp { + let mut app = CadApp::new(cadcraft_engine::Session::empty(), crate::Services::default()); + let s = &mut app.session; + s.execute("new", &Value::Null).unwrap(); + let made = |v: Value| if v["handle"].is_null() { v["handles"][0].clone() } else { v["handle"].clone() }; + let r = made(s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 5] })).unwrap()); + let c = made(s.execute("circle", &json!({ "center": [10, 2.5], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [r, c], "keep": "delete" })).unwrap(); + s.execute("bedit", &json!({ "name": "B" })).unwrap(); + s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0] })).unwrap(); + s.execute("bparameter", &json!({ "type": "point", "at": [10, 2.5] })).unwrap(); + s.execute("bparameter", &json!({ "type": "visibility", "at": [-2, 5] })).unwrap(); + s.execute("bvstate", &json!({ "new": "Small", "visibility": "show" })).unwrap(); + s.execute("bparameter", &json!({ "type": "lookup", "at": [-2, 7], "label": "Size" })).unwrap(); + app + } + + #[test] + fn blookuptable_opens_the_dialog_and_ok_writes_the_table_in_one_step() { + let mut app = editing(); + assert!(route(&mut app, "blookuptable", &Value::Null).is_none(), "no lookup action: BLOOKUPTABLE says why"); + let act = app.session.execute("baction", &json!({ "parameter": "Size" })).unwrap()["node"].as_i64().unwrap() as i32; + assert!(!open(&mut app, 1), "a parameter isn't a lookup action"); + assert!(open(&mut app, act), "a double-click on the lookup action opens its table"); + app.ui.dialog = None; + assert!(route(&mut app, "blookuptable", &json!({})).is_none(), "JSON calls skip the dialog"); + assert!(route(&mut app, "blookuptable", &Value::Null).is_some()); + assert_eq!(app.ui.dialog.as_deref(), Some("blookuptable")); + let mut st = app.blookup.clone(); + assert_eq!(st.columns.iter().map(|c| c.name.as_str()).collect::>(), ["Size"]); + let st_m = dynamic_block(&app.session.state().unwrap().doc, "B").unwrap(); + let inputs = addable(&st, &st_m, false); + assert_eq!( + inputs.iter().map(|(n, k, _)| (n.as_str(), k.as_str())).collect::>(), + [("Distance1", "Linear"), ("Position1 X", "Point"), ("Position1 Y", "Point"), ("Visibility1", "Visibility State")] + ); + for (_, _, c) in inputs.into_iter().filter(|(n, ..)| n != "Position1 Y") { + st.add_column(c); + } + assert_eq!(st.columns.iter().map(|c| c.name.as_str()).collect::>(), ["Distance1", "Position1 X", "Visibility1", "Size"]); + assert_eq!(st.columns[2].states, ["VisibilityState0", "Small"]); + st.rows = vec![ + ["10", "10", "VisibilityState0", "Big"].map(String::from).to_vec(), + ["6", "6", "Small", "Small"].map(String::from).to_vec(), + ["", "", "", ""].map(String::from).to_vec(), + ]; + st.columns[3].reverse = true; + st.columns[3].unmatched = "Other".into(); + let block = "B"; + st.audit(&app.session.state().unwrap().doc, block).unwrap(); + let before = app.session.state().unwrap().undo.len(); + app.run("blookuptable", st.params()).unwrap(); + assert_eq!(app.session.state().unwrap().undo.len(), before + 1, "one undo step"); + let t = app.session.execute("blookuptable", &json!({})).unwrap(); + assert_eq!(t["rows"], json!([["10", "10", "VisibilityState0", "Big"], ["6", "6", "Small", "Small"]])); + assert_eq!((t["columns"][3]["unmatched"].clone(), t["columns"][3]["reverse"].clone()), (json!("Other"), json!(true))); + // Opened again, the dialog shows what was written. + route(&mut app, "blookuptable", &Value::Null).unwrap().unwrap(); + assert_eq!(app.blookup.rows.len(), 2); + assert!(app.blookup.columns[3].reverse); + } + + #[test] + fn audit_and_reverse_lookup_follow_autocads_rules() { + let mut app = editing(); + app.session.execute("baction", &json!({ "parameter": "Size" })).unwrap(); + route(&mut app, "blookuptable", &Value::Null).unwrap().unwrap(); + let mut st = app.blookup.clone(); + let m = dynamic_block(&app.session.state().unwrap().doc, "B").unwrap(); + let d1 = addable(&st, &m, false).into_iter().next().unwrap().2; + st.add_column(d1); + st.rows = vec![vec!["10".into(), "Big".into()], vec!["10.0".into(), "Small".into()]]; + let doc = app.session.state().unwrap().doc.clone(); + assert_eq!(st.audit(&doc, "B").unwrap_err(), "Duplicate row of input values found."); + st.rows = vec![vec!["10".into(), "Big".into()], vec!["6".into(), "big".into()]]; + assert!(st.repeats(1), "repeated lookup values: read only"); + st.columns[1].reverse = true; + assert_eq!(st.params()["reverse"], json!([])); + // The action's own lookup column stays; an input can go, its cells with it. + assert!(!st.removable(1)); + st.remove_column(1); + assert_eq!(st.columns.len(), 2); + st.remove_column(0); + assert_eq!(st.columns.iter().map(|c| c.name.as_str()).collect::>(), ["Size"]); + assert_eq!(st.rows, [vec!["Big".to_string()], vec!["big".to_string()]]); + // Lookup parameters another table gives aren't offered as lookup columns. + app.session.execute("bparameter", &json!({ "type": "lookup", "at": [-2, 9] })).unwrap(); + let m = dynamic_block(&app.session.state().unwrap().doc, "B").unwrap(); + assert_eq!( + addable(&st, &m, true).iter().map(|(n, k, _)| (n.as_str(), k.as_str())).collect::>(), + [("Lookup1", "Lookup2")], + "label, then its name in the editor" + ); + } +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index fd20011219..fb9080d7ed 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -528,6 +528,7 @@ fn paint_pointer_overlay( // spin the CPU with the low-latency present mode (`gpu::surface_config`). } struct DoubleClickContext<'a> { + ctx: &'a egui::Context, inside: bool, double: bool, hover: Option, @@ -538,8 +539,8 @@ struct DoubleClickContext<'a> { active_clip: &'a Option, } -fn handle_double_click(app: &mut CadApp, ctx: DoubleClickContext<'_>) -> Option { - let DoubleClickContext { inside, double, hover, xf, xf_paper, scale, active_viewport, active_clip } = ctx; +fn handle_double_click(app: &mut CadApp, context: DoubleClickContext<'_>) -> Option { + let DoubleClickContext { ctx, inside, double, hover, xf, xf_paper, scale, active_viewport, active_clip } = context; if inside && double && !app.session.prompting() @@ -572,10 +573,12 @@ fn handle_double_click(app: &mut CadApp, ctx: DoubleClickContext<'_>) -> Option< return None; } - let mut hatch_dialog = false; // Double-click a hatch (no command running) to edit it in the Hatch Edit dialog. The click is - // used up: it must not also start a grip edit on the hatch's centre grip below. - if inside + // used up: it must not also start a grip edit on the hatch's centre grip below. In the Block + // Editor, double-clicking a lookup action opens its lookup table, as in AutoCAD. + let mut hatch_dialog = inside && double && blockedit::double_click(app, ctx, &xf, hover); + if !hatch_dialog + && inside && double && app.session.running.is_none() && let Some(hp) = hover @@ -780,6 +783,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { let Some(hatch_dialog) = handle_double_click( app, DoubleClickContext { + ctx: ui.ctx(), inside, double: dbl_primary, hover: hover_pos, diff --git a/crates/ui-egui/src/canvas/blockedit.rs b/crates/ui-egui/src/canvas/blockedit.rs index da7c76d662..e32e73ad3f 100644 --- a/crates/ui-egui/src/canvas/blockedit.rs +++ b/crates/ui-egui/src/canvas/blockedit.rs @@ -248,6 +248,11 @@ pub(super) fn target(app: &CadApp, ctx: &egui::Context, xf: &Xf, pos: Option Option { let to = |v: cadcraft_engine::geom::Vec3| xf.to_screen(v.xy()); let marks = marks(app, ctx); marks @@ -274,7 +279,17 @@ pub(super) fn target(app: &CadApp, ctx: &egui::Context, xf: &Xf, pos: Option label_rect(to(*at), Align2::LEFT_BOTTOM, label).contains(pos), Mark::Action { at, name, .. } => label_rect(to(*at), Align2::CENTER_CENTER, name).expand2(vec2(4.0, 2.0)).contains(pos), }) - .map(|m| Target::Mark(mark_node(m))) + .map(mark_node) +} + +/// A double-click on a lookup action's mark opens its Property Lookup Table; whether it did. +/// The first click picked it, so its grip may be under the cursor too: the mark wins. +pub(super) fn double_click(app: &mut CadApp, ctx: &egui::Context, xf: &Xf, pos: Option) -> bool { + let Some(pos) = pos else { return false }; + if app.session.prompting() || editing(app).is_none() { + return false; + } + mark_at(app, ctx, xf, pos).is_some_and(|n| crate::blookup::open(app, n)) } /// A click on `t`: a grip starts moving its point; a parameter or action is picked (Shift+click diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 46ec8a09f6..d15992c7ef 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -29,6 +29,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "blocks" => blocks(app, ctx, &mut open), "bedit" => crate::bedit::dialog(app, ctx, &mut open), "bvstate" => crate::bvstate::dialog(app, ctx, &mut open), + "blookuptable" => crate::blookup::dialog(app, ctx, &mut open), "authoring" => crate::bedit::authoring_dialog(app, ctx, &mut open), "stylesmanager" => crate::plotstyles::dialog(app, ctx, &mut open), o if o == "options" || o.starts_with("options:") => crate::options::dialog(app, ctx, o, &mut open), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 53cf2b0605..5be03f4775 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -12,6 +12,7 @@ pub mod aliasdlg; pub mod animation; pub mod autosave; pub mod bedit; +pub mod blookup; pub mod bvstate; pub mod canvas; pub mod capture; @@ -295,6 +296,8 @@ pub struct CadApp { pub updates_rt: updates_ui::Runtime, /// The Visibility States dialog ([`bvstate`]). pub bvstate: bvstate::State, + /// The Property Lookup Table dialog ([`blookup`]). + pub blookup: blookup::State, } impl CadApp { @@ -348,6 +351,7 @@ impl CadApp { #[cfg(not(target_arch = "wasm32"))] updates_rt: updates_ui::Runtime::default(), bvstate: bvstate::State::default(), + blookup: blookup::State::default(), } } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 8ea08db1b3..efe74e2c67 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -98,6 +98,9 @@ fn route_ui_subsystems(app: &mut CadApp, id: &str, params: &Value) -> Option Date: Sun, 25 Oct 2026 19:24:30 -0600 Subject: [PATCH 23/47] Docs: F3 and the blocks row list lookup authoring Co-Authored-By: Claude Opus 5.5 --- docs/gaps.md | 5 +++-- docs/target-app-parity.md | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index 34fb675cf7..7a7550ccdf 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where CADCraft falls short of AutoCAD -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (BEDIT in the Block Editor switches blocks; dynamic-block authoring started: BPARAMETER linear/point, BACTION stretch/move; visibility parameters and states, BVSTATE, BVHIDE, BVSHOW, BVMODE; F3 updated) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (BEDIT in the Block Editor switches blocks; dynamic-block authoring: lookup parameters, lookup actions and the Property Lookup Table dialog, BLOOKUPTABLE; F3 narrowed) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first), and remove or update a row in the same PR @@ -26,7 +26,7 @@ do them first. |---|---|---|---|---| | F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | | F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | -| F3 | **[alpha blocker]** (dynamic-block authoring is beta) Dynamic-block authoring has started: in the Block Editor, BPARAMETER adds linear, point and visibility parameters and BACTION stretch and move actions; BVSTATE (the Visibility States dialog: Set current, New, Rename, Delete, Move Up, Move Down; -BVSTATE: New, Set, Delete), BVHIDE and BVSHOW (also Object Visibility on the editor's right-click menu) edit visibility states, the editor shows the state picked on its bar and hides (BVMODE 0) or dims (BVMODE 1) what it hides (AutoCAD's prompts, JSON forms), all written so AutoCAD opens the block as a dynamic block (DXF and DWG), and the editor draws them. Missing: the other parameters (polar, XY, rotation, flip, alignment, base point, lookup) and actions (scale, rotate, flip, array, polar stretch, lookup), lookup tables (BLOOKUPTABLE), grip-editing points beyond a linear parameter's ends and label, a point parameter's location and label, a list grip's and an action's location, window selection of parameters and actions, Properties for them, BACTIONSET, the Name/Chain/Value set options, Authoring Palettes, BTESTBLOCK. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips); BEDIT (which, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS, BCLOSE and REFEDIT edit block definitions | issue #185 offers help | High: standard libraries are dynamic | 30–50 | +| F3 | **[alpha blocker]** (dynamic-block authoring is beta) Dynamic-block authoring has started: in the Block Editor, BPARAMETER adds linear, point, visibility and lookup parameters and BACTION stretch, move and lookup actions; BLOOKUPTABLE fills a lookup table (the Property Lookup Table dialog: input and lookup properties for distances, positions and visibility states, unmatched values, reverse lookup or read only, Audit); BVSTATE (the Visibility States dialog: Set current, New, Rename, Delete, Move Up, Move Down; -BVSTATE: New, Set, Delete), BVHIDE and BVSHOW (also Object Visibility on the editor's right-click menu) edit visibility states, the editor shows the state picked on its bar and hides (BVMODE 0) or dims (BVMODE 1) what it hides (AutoCAD's prompts, JSON forms), all written so AutoCAD opens the block as a dynamic block (DXF and DWG), and the editor draws them. Missing: the other parameters (polar, XY, rotation, flip, alignment, base point) and actions (scale, rotate, flip, array, polar stretch), lookup columns for angles, flips and XY distances, grip-editing points beyond a linear parameter's ends and label, a point parameter's location and label, a list grip's and an action's location, window selection of parameters and actions, Properties for them, BACTIONSET, the Name/Chain/Value set options, Authoring Palettes, BTESTBLOCK. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips); BEDIT (which, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS, BCLOSE and REFEDIT edit block definitions | issue #185 offers help | High: standard libraries are dynamic | 30–50 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | | F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 | @@ -157,6 +157,7 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | | 2026-10-22 | minor | APPLOAD typed or from Tools ▸ Load Application opens a `.lsp` file browser starting in the last-used folder (kept in the preferences); a picked file loads interactively like a typed name (routines that ask for input wait), the web says to drop the file (no file system), and the JSON form `{path}` reads the path as given and returns the commands the file defined, never opening a dialog (#1820): E1 narrowed | | 2026-10-25 | minor | F3: parameters and actions are picked with a click in the Block Editor (Shift+click unpicks, Escape clears), drawn heavier with grips; a grip moves that point; MOVE, ERASE and Delete act on them, a parameter's actions erased with it, as AutoCAD does; the graph keeps its id counter (AutoCAD read no erased block from DXF without it) | +| 2026-10-25 | minor | F3: lookup authoring. BPARAMETER adds a lookup parameter (Name, Label, Description, Palette), BACTION its lookup action, BLOOKUPTABLE (the Property Lookup Table dialog, or JSON) fills its table with AutoCAD's rules (duplicate inputs refused, repeated lookup values read only); AutoCAD evaluates the tables from DXF and DWG as CADCraft does. Visibility states list the actions active in them, as AutoCAD's do | | 2026-10-25 | minor | F3: visibility authoring. BPARAMETER adds a visibility parameter; BVSTATE (the Visibility States dialog, or -BVSTATE's New with Hide all / Show all / Current visibility, Set, Delete), BVHIDE and BVSHOW (current or all states; also the right-click menu's Object Visibility) edit its states with AutoCAD's prompts; objects drawn and parameters added show in the state shown, as AutoCAD keeps them; BVMODE; AutoCAD reads the states from DXF and DWG. A grip's location components now name their own parameter (AutoCAD evaluated no parameter of a block with a second one) | | 2026-10-21 | minor | F3: dynamic-block authoring started. In the Block Editor BPARAMETER adds linear and point parameters, BACTION stretch and move actions, with AutoCAD's prompts and JSON forms; AutoCAD opens the result as a dynamic block from DXF and DWG; the editor draws them (40–65 → 30–50 h) | | 2026-10-16 | minor | ALIASEDIT typed or from Tools ▸ Customize opens the Command Aliases dialog (user aliases next to the built-in ones; Add, Edit, Remove; OK, Cancel, Apply), #1381: U12 and E5 narrowed | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cf38018857..cb510ad6c5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -154,7 +154,7 @@ presence: an option that prints "not available yet" doesn't count. | Text and MTEXT | 6% | 35% | 30–45 | TrueType, formatting codes, stacking; MTEXT prompt options (#408), indents, tabs, bullets, numbering and columns (#547), annotative scaling (#468); editor is a dialog, not in place; no fields or SPELL (open PR #551), no SHX | [gaps](gaps.md#features) | | Leaders, tables, fields | 4% | 25% | 25–35 | MLEADER options and block content (#408), native MULTILEADER in DXF (#459); tables with cell styles, formulas, breaking and CSV data links (#534); no MLEADEREDIT/ALIGN/COLLECT, no FIELD | [gaps](gaps.md#features) | | Hatch and gradients | 5% | 35% | 15–25 | pick points with islands; 23 patterns of ~85; gradients render flat; origin, gap tolerance, separate hatches, island styles and HATCHEDIT options (#451); Hatch and Gradient / Hatch Edit dialogs (no Preview or Inherit Properties) | [gaps](gaps.md#features) | -| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT; dynamic block references read and edited; dynamic-block authoring started (linear, point and visibility parameters, visibility states, stretch and move actions); no XCLIP, DesignCenter | [gaps](gaps.md#features) | +| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT; dynamic block references read and edited; dynamic-block authoring started (linear, point, visibility and lookup parameters, visibility states, lookup tables, stretch, move and lookup actions); no XCLIP, DesignCenter | [gaps](gaps.md#features) | | Layouts, viewports, plotting | 9% | 35% | 35–50 | layouts, per-VP layers, page setups, plot styles (CTB/STB), Plot dialog (#160), Plot Preview and PUBLISH (#186), plotter devices (#564), PDF with text, layers and sheets (#567, #571), polygonal/object/clipped viewports (#453), annotative scales (#468); no MVIEW Restore, no system printers | [gaps](gaps.md#features) | | Inquiry and utilities | 4% | 30% | 30–45 | DIST, AREA, ID, LIST, MEASUREGEOM, CAL, FIND, COUNT across layouts, QuickCalc, COMPARE (#563) and COMPAREEXPORT, MASSPROP on regions (#510), autosave/recovery, AUDIT, RECOVER (#406), OPTIONS (#23); no SPELL (open PR #551), ETRANSMIT | [gaps](gaps.md#features) | | Parametric constraints | 2% | 50% | 20–30 | all 12 geometric and the dimensional constraints, own solver; DOF report, G2 Smooth, ellipse/spline/block geometry and CONSTRAINTINFER landed (#546) | [geometry-parity](geometry-parity.md#constraint-solver--50) | @@ -225,6 +225,7 @@ DWG/DXF corpus (files from people who own them); black-box checks in AutoCAD of |---|---|---| | 2026-10-24 | minor | Inquiry and utilities row: COMPAREEXPORT exports a comparison to a new drawing; parity percentages and hours not re-measured | | 2026-10-22 | minor | Draw row: RECTANG gained a centre construction mode (`Center` keyword, `center: true`) beside its corner mode (#1127); parity percentages and hours not re-measured | +| 2026-10-25 | minor | Blocks row evidence: lookup parameters and tables authored (BLOOKUPTABLE); percentages and hours not re-measured | | 2026-10-25 | minor | Blocks row evidence: visibility parameters and states authored (BVSTATE, BVHIDE, BVSHOW); percentages and hours not re-measured | | 2026-10-21 | minor | Blocks row evidence: dynamic-block authoring started (BPARAMETER linear/point, BACTION stretch/move); percentages and hours not re-measured | | 2026-10-12 | minor | Hatch row evidence: Hatch and Gradient / Hatch Edit dialogs; percentages and hours not re-measured | From 36856fa2aff80879e96e73eba990ed6c44036609 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:29:23 -0600 Subject: [PATCH 24/47] Dynamic blocks: a lookup on a position follows its point; BEDIT names lookup authoring Typing Position X/Y in Properties or dragging a point parameter's grip now runs the lookup chain, as distances and visibility states already did, so a lookup table reading a position gives its lookup value, written to the reference. BEDIT's dynamic-block notice lists lookup parameters, lookup actions and BLOOKUPTABLE. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/apply.rs | 3 +++ crates/engine/src/cmd/blocks/bedit.rs | 2 +- crates/engine/tests/block_lookup.rs | 33 +++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index 08139ffefb..464aead8c6 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -318,6 +318,7 @@ pub fn set_property(d: &mut Drawing, insert: Handle, name: &str, value: &str) -> let v = number(value)?; let at = if is_x { Vec3::new(block_base.x + v / sx, at.y, at.z) } else { Vec3::new(at.x, block_base.y + v / sy, at.z) }; plan.set.insert(p.node, Val::Point(at)); + plan.chain(&m, &r.values, p.node, if is_x { "UpdatedX" } else { "UpdatedY" })?; } _ => return Err(format!("CADCraft can't change {name} yet.")), } @@ -372,6 +373,8 @@ pub fn drag_grip(d: &mut Drawing, insert: Handle, node: i32, part: super::GripPa (ParameterKind::Point { label, .. }, GripPart::At) => { let Some(Val::Point(at)) = current(&m, &r.values, node) else { return Err(format!("{label} has no position.")) }; plan.set.insert(node, Val::Point(Vec3::new(q.x, q.y, at.z))); + plan.chain(&m, &r.values, node, "UpdatedX")?; + plan.chain(&m, &r.values, node, "UpdatedY")?; } _ => return Err("That grip can't be dragged.".into()), } diff --git a/crates/engine/src/cmd/blocks/bedit.rs b/crates/engine/src/cmd/blocks/bedit.rs index 1557cc8e30..eae69b27f0 100644 --- a/crates/engine/src/cmd/blocks/bedit.rs +++ b/crates/engine/src/cmd/blocks/bedit.rs @@ -160,7 +160,7 @@ fn open_closed(s: &mut Session, name: &str, create: bool) -> Result { let dynamic = |be: &crate::blockedit::BlockEdit| crate::blockedit::has_dynamic_data(&be.host.doc, if be.current { "*Model_Space" } else { &be.name }); if s.state().is_ok_and(|st| st.block_edit.as_ref().is_some_and(dynamic)) { - s.echo("This is a dynamic block: BPARAMETER and BACTION add linear, point and visibility parameters with stretch and move actions, BVSTATE, BVHIDE and BVSHOW edit visibility states; its other parameters and actions are kept as they are."); + s.echo("This is a dynamic block: BPARAMETER and BACTION add linear, point, visibility and lookup parameters with stretch, move and lookup actions, BVSTATE, BVHIDE and BVSHOW edit visibility states, BLOOKUPTABLE fills lookup tables; its other parameters and actions are kept as they are."); } Ok(json!({ "block": name, "new": new })) } diff --git a/crates/engine/tests/block_lookup.rs b/crates/engine/tests/block_lookup.rs index d403400660..87fb6ed475 100644 --- a/crates/engine/tests/block_lookup.rs +++ b/crates/engine/tests/block_lookup.rs @@ -266,3 +266,36 @@ fn hostile_lookup_params_never_panic() { s.script("BPARAMETER K N\n\nP\nmaybe\n").unwrap(); s.input(Input::Cancel).unwrap(); } + +#[test] +fn a_lookup_on_a_position_follows_its_point() { + let mut s = Session::new(); + let i = boxed(&mut s); + authored(&mut s); + s.execute("blookuptable", &json!({ "inputs": ["Position1 X"], "rows": [[10, "Big"], [6, "Small"]], "reverse": true })).unwrap(); + s.execute("bclose", &json!({})).unwrap(); + assert!(custom(&s, &i).contains(&("Size".to_string(), "Big".to_string(), true))); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let size = m.parameters.iter().find(|p| matches!(p.kind, ParameterKind::Lookup { .. })).unwrap().node; + // The lookup value the reference keeps (written to its data, as AutoCAD writes it). + let kept = |s: &Session| match cadcraft_engine::doc::dynblock::reference(s.doc().unwrap(), h(&i)).unwrap().values.get(&size) { + Some(cadcraft_engine::doc::dynblock::Value::Text { value }) => value.clone(), + v => format!("{v:?}"), + }; + // Typed in Properties. + s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Position1 X", "value": "6" })).unwrap(); + assert!(custom(&s, &i).contains(&("Size".to_string(), "Small".to_string(), true)), "{:?}", custom(&s, &i)); + assert_eq!(kept(&s), "Small"); + // Dragged by its grip (the reference is at (100,0), so the block's x = 10 is at 110). + let node = m.parameters.iter().find(|p| matches!(p.kind, ParameterKind::Point { .. })).unwrap().node; + cadcraft_engine::doc::dynblock::drag_grip( + s.doc_mut().unwrap(), + h(&i), + node, + cadcraft_engine::doc::dynblock::GripPart::At, + cadcraft_engine::geom::Vec2::new(110.0, 2.5), + ) + .unwrap(); + assert!(custom(&s, &i).contains(&("Size".to_string(), "Big".to_string(), true)), "{:?}", custom(&s, &i)); + assert_eq!(kept(&s), "Big"); +} From 1f4aba9c02077b55c0fe2078196d35ab718b0bee Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:19:51 -0600 Subject: [PATCH 25/47] i18n: Chinese for the Block Editor's visibility and parameter labels Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/zh.tsv | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 21c86d1fe7..8e9e14f257 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1381,3 +1381,33 @@ Save Layout as Template 将布局另存为样板 Set Dynamic Property 设置动态特性 Units 单位 + Parameter 参数 + Action 动作 + Visibility States 可见性状态 + Make Visible 使可见 + Make Invisible 使不可见 + Visibility states: 可见性状态: + Set current 置为当前 + New... 新建... + Rename 重命名 + Move Up 上移 + Move Down 下移 + New Visibility State 新建可见性状态 + Visibility state name: 可见性状态名称: + Visibility options for new states 新状态的可见性选项 + Hide all existing objects in new state 在新状态中隐藏所有现有对象 + Show all existing objects in new state 在新状态中显示所有现有对象 + Leave visibility of existing objects unchanged in new state 在新状态中保持现有对象的可见性不变 + Visibility Mode 可见性模式 + Object Visibility 对象可见性 + Hide for Current State 在当前状态中隐藏 + Show for Current State 在当前状态中显示 + Hide for All States 在所有状态中隐藏 + Show for All States 在所有状态中显示 + A visibility state needs a name. 可见性状态需要名称。 + A visibility state already has the name 已有可见性状态使用名称 + Pick Parameters and Actions 拾取参数和动作 + Erase Parameters and Actions 擦除参数和动作 + Move Parameters and Actions 移动参数和动作 + Move a Parameter's Point 移动参数的点 + Parameter Points 参数点 From fc0cb7a3a15c68cb0917ef576762c07e7158b721 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:18:52 -0600 Subject: [PATCH 26/47] Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them) Co-Authored-By: Claude Sonnet 5.5 --- docs/gaps.md | 21 +++++++++------------ docs/target-app-parity.md | 12 ++++-------- 2 files changed, 13 insertions(+), 20 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index 7a7550ccdf..f8ddac9410 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,10 +1,10 @@ # Where CADCraft falls short of AutoCAD -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (BEDIT in the Block Editor switches blocks; dynamic-block authoring: lookup parameters, lookup actions and the Property Lookup Table dialog, BLOOKUPTABLE; F3 narrowed) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (QSAVE asks before losing content and keeps a `.bak`: rows 1, FF1 and F20 updated) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work -list: agents pick from here (top of a section first), and remove or update a row in the same PR -that closes it. Numbers and weights live in [target-app-parity.md](target-app-parity.md); hours +list: agents pick from here (top of a section first). A PR names the rows it closes in its +description, and maintainers update them in batches. Numbers and weights live in [target-app-parity.md](target-app-parity.md); hours are Opus 5.5 agent-hours, calibrated as explained there. "Est." means a judgement from the cited evidence. Rows marked **[alpha blocker]** are what fails the [alpha gate](roadmap.md#alpha-gate); do them first. @@ -13,7 +13,7 @@ do them first. | # | Gap | Why it ranks here | Est. | Doc | |---|---|---|---|---| -| 1 | **[alpha blocker]** **Saving DWG drops what we don't model** (DXF now writes back unknown entities and objects, foreign xdata, extension dictionaries, reactors, layer states and colour books, #528, and native MULTILEADERs, #459 (not yet tested through DWG); through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour books and reactors) | Opening a colleague's DWG and saving it still deletes some content: the one thing a CAD user can't forgive | 6–10 | [file formats](file-format-parity.md) | +| 1 | **[alpha blocker]** **Saving DWG drops what we don't model** (DXF now writes back unknown entities and objects, foreign xdata, extension dictionaries, reactors, layer states and colour books, #528, and native MULTILEADERs, #459 (not yet tested through DWG); through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour books and reactors; a user's QSAVE now asks before replacing the file and keeps the previous one as `.bak`, which reduces the harm but does not close this row) | Opening a colleague's DWG and saving it still deletes some content: the one thing a CAD user can't forgive | 6–10 | [file formats](file-format-parity.md) | | 2 | **[alpha blocker]** **No real-file test corpus and no check in AutoCAD** | All 36 file tests are synthetic; nobody has verified a CADCraft DWG/DXF opens cleanly in AutoCAD | 10–15 + human | [file formats](file-format-parity.md#tests) | | 3 | **Ellipse and spline geometry is tessellated** (intersections, offsets, closest points; polyline offset ignores bulges) | Coordinates are subtly wrong; offsets of ellipses come out as polylines | 30–50 | [geometry](geometry-parity.md) | | 4 | **[alpha blocker]** **No dynamic blocks or REFEDIT; xrefs can't be edited in place or clipped** (xrefs, #525, groups, #417, and the Block Editor for static blocks landed) | Most production drawings use them | 55–90 | [features](#features) | @@ -26,7 +26,7 @@ do them first. |---|---|---|---|---| | F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | | F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | -| F3 | **[alpha blocker]** (dynamic-block authoring is beta) Dynamic-block authoring has started: in the Block Editor, BPARAMETER adds linear, point, visibility and lookup parameters and BACTION stretch, move and lookup actions; BLOOKUPTABLE fills a lookup table (the Property Lookup Table dialog: input and lookup properties for distances, positions and visibility states, unmatched values, reverse lookup or read only, Audit); BVSTATE (the Visibility States dialog: Set current, New, Rename, Delete, Move Up, Move Down; -BVSTATE: New, Set, Delete), BVHIDE and BVSHOW (also Object Visibility on the editor's right-click menu) edit visibility states, the editor shows the state picked on its bar and hides (BVMODE 0) or dims (BVMODE 1) what it hides (AutoCAD's prompts, JSON forms), all written so AutoCAD opens the block as a dynamic block (DXF and DWG), and the editor draws them. Missing: the other parameters (polar, XY, rotation, flip, alignment, base point) and actions (scale, rotate, flip, array, polar stretch), lookup columns for angles, flips and XY distances, grip-editing points beyond a linear parameter's ends and label, a point parameter's location and label, a list grip's and an action's location, window selection of parameters and actions, Properties for them, BACTIONSET, the Name/Chain/Value set options, Authoring Palettes, BTESTBLOCK. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips); BEDIT (which, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS, BCLOSE and REFEDIT edit block definitions | issue #185 offers help | High: standard libraries are dynamic | 30–50 | +| F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | | F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 | @@ -41,7 +41,7 @@ do them first. | F16 | Groups: no group bounding box or single grip when a group is selected (GROUPDISPLAYMODE), copying a whole group does not make a new group, no Object Grouping dialog (GROUP, GROUPEDIT, UNGROUP, -GROUP, PICKSTYLE group selection and the DXF/DWG round trip landed, #417); PICKSTYLE's associative-hatch bit is stored but unused | `cmd/groups.rs` | Low | 2–4 | | F17 | Attributes (ATTSYNC, global -ATTEDIT, BATTMAN editing and DATAEXTRACTION/EATTEXT landed, #433): no verify, preset or lock-position modes, and multiline attributes (read, drawn and saved since 2026-10-12) can't be created or switched in BATTMAN; data extraction covers block references and attribute values (CSV or a table) only — no wizard, nested blocks, other objects' properties, `.dxe` templates or spreadsheet output | `cmd/blocks/battman.rs`, `cmd/blocks/extract.rs` | Low | 4–6 | | F19 | MATCHPROP Settings is a keyword prompt (no dialog) and has no material, shadow or centre-object settings; TEXTTOFRONT and HATCHTOBACK act on the current space only; OVERKILL doesn't compare polyline segments with other objects (picker and Settings, DRAWORDER Above/Under, TEXTTOFRONT, HATCHTOBACK, OVERKILL tolerance/ignore/overlap/end-to-end options landed, #439) | `props/matchprop.rs`, `draworder.rs`, `overkill.rs` | Low | 2–4 | -| F20 | OPTIONS dialog done (#23): Display, Open and Save, Drafting, Selection, User Preferences and Profiles tabs, and the user profile (object snap modes, drafting toggles, Dynamic Input, PICKBOX, APERTURE, GRIPSIZE, CURSORSIZE, PICKFIRST, PICKADD, QPMODE, model and paper background, snap marker size, system cursor) survives restarts. Left: right-click customization, the autosave interval and default save version on Open and Save (the features themselves landed, #406, #421), AutoSnap magnet and tooltip toggles, colours of the other drawing-area elements, named profiles with import and export | `ui-egui/src/options/` | Low | 2–4 | +| F20 | OPTIONS dialog done (#23): Display, Open and Save, Drafting, Selection, User Preferences and Profiles tabs, and the user profile (object snap modes, drafting toggles, Dynamic Input, PICKBOX, APERTURE, GRIPSIZE, CURSORSIZE, PICKFIRST, PICKADD, QPMODE, model and paper background, snap marker size, system cursor) survives restarts. Left: right-click customization, the autosave interval and default save version on Open and Save (the features themselves landed, #406, #421), AutoSnap magnet and tooltip toggles, colours of the other drawing-area elements, named profiles with import and export Open and Save has the backup copy checkbox (ISAVEBAK). | `ui-egui/src/options/` | Low | 2–4 | | F21 | MLINE, REGION and HELIX are objects since #510, with gaps: MLEDIT tees trim square; UNION/SUBTRACT/INTERSECT only combine regions whose boundaries don't meet; regions are saved as closed polylines (no ACIS data) | `draw2/mline.rs`, `inquiry/regions.rs`, `dxf_region.rs` | Low | 6–10 | | F22 | Inquiry leftovers (COUNT across spaces and nested blocks, the QuickCalc palette and COMPARE landed, #563; MASSPROP on regions, #510): COMPARE compares the tab shown, not every layout at once (COMPAREEXPORT, the comparison as a new drawing, landed); COMPAREEXPORT puts the two sets of objects in model-space groups, where AutoCAD puts them in blocks; QuickCalc keeps its history and variables for the session only | `file/compare.rs`, `palettes/quickcalc.rs` | Low | 3–5 | | F23 | No Sheet Set Manager, eTransmit, Share, Traces, Markup Import, Activity Insights | menu items uncovered | Low-medium (team workflows) | 40–70 | @@ -73,7 +73,7 @@ Detail: [file-format-parity.md](file-format-parity.md). | # | Gap | User impact | Est. | |---|---|---|---| -| FF1 | **[alpha blocker]** Round-trip what we don't model. DXF done (#528): unknown entities and objects (with their CLASS records), foreign xdata (hyperlinks included), extension dictionaries, persistent reactors, DICTIONARYVAR and XRECORDs, layer states, colour book colours, references remapped on save; IMAGE, VIEW/UCS, groups, block descriptions, true colours, transparency (#201, #204, #208, #209, #213, #223); WIPEOUT and gradients (#147, #162). Left: through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour book names and reactors; UCS elevation; MTEXT background colours; unknown entities follow only layer edits, and renamed layers and blocks lose their foreign data | High | 6–10 | +| FF1 | **[alpha blocker]** Round-trip what we don't model. DXF done (#528): unknown entities and objects (with their CLASS records), foreign xdata (hyperlinks included), extension dictionaries, persistent reactors, DICTIONARYVAR and XRECORDs, layer states, colour book colours, references remapped on save; IMAGE, VIEW/UCS, groups, block descriptions, true colours, transparency (#201, #204, #208, #209, #213, #223); WIPEOUT and gradients (#147, #162). Left: through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour book names and reactors; UCS elevation; MTEXT background colours; unknown entities follow only layer edits, and renamed layers and blocks lose their foreign data A user's QSAVE now asks before such a loss and keeps the previous file as `.bak`; the loss itself remains. | High | 6–10 | | FF2 | Multileader leftovers (native MULTILEADER read/write landed, #459): several landings per multileader (extra leader roots are folded into the lines), per-object overrides (leader colour and linetype, arrowhead symbol, text frame), annotative scale contexts; check the text placement of our MULTILEADER output in AutoCAD | Medium | 3–5 | | FF3 | Save-version leftovers (DXF/DWG 2000–2018, binary DXF, SAVEAS `version`/`binary` and the default save version landed, #421): no R14 DWG or R12 DXF output; the Save dialog can't pick the version per file (the file picker doesn't report the chosen type; File > Default Save Format sets it); no command-line SAVEAS format prompt | Low | 2–4 | | FF4 | Code-page leftovers (pre-2007 DXF read in their `$DWGCODEPAGE` landed, #505): Johab (ANSI_1361) and DOS 855/857/860–865/869 read as ANSI_1252; saving declares `ANSI_1252` instead of the file's code page (the text is pure ASCII, so still correct); acadrust approximates DOS code pages in pre-2007 DWG (DOS437 as 866, DOS850 as 1252) | Low | 1–2 | @@ -107,7 +107,7 @@ Detail: [localization-parity.md](localization-parity.md). | # | Gap | Est. | |---|---|---| | L1 | Catalog covers the UI (989 rows, #36) but not engine diagnostics, CLI/MCP replies or command history | 4–6 | -| L2 | AutoCAD for Mac's other languages (zh-Hans, es, fr, ja, ko, it; de landed 2026-10-11) plus pt, hi, ar, id, vi from the standard's list | 35–55 + native review | +| L2 | AutoCAD for Mac's other languages (zh-Hans, es, fr, ja, ko, it; de landed 2026-10-11) plus pt, hi, ar, id, vi | 35–55 + native review | | L3 | Complex-script shaping for Devanagari and other Indic scripts in drawing text; RTL (mirrored) UI. Arabic-script shaping and bidi in drawing text landed (#287) | 20–30 | | L4 | IME fixes on every platform (PRs #110–#119); vertical text styles | 6–10 | @@ -150,16 +150,13 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | QSAVE asks before replacing a file with content the DWG writer can't keep, and ISAVEBAK keeps the previous file as `.bak`: row 1 narrowed, FF1 and F20 updated | | 2026-10-25 | minor | Named Viewports (View ▸ Viewports ▸ Named Viewports..., `vports.named`) lists the saved viewport configurations with a preview and the current one's name, and restores or deletes one; in a layout Restore places it as MVIEW Restore does: U11 narrowed. F15 and U11 no longer list MVIEW Restore (#633), and F21 no longer says PURGE skips multiline styles | | 2026-10-25 | minor | DIMTFILL limits: with DIMTFILL 1 (the drawing's background color) the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI: F7 updated | | 2026-10-26 | minor | BEDIT in the Block Editor (typed, Edit Block, or the Edit Block Definition dialog) switches to another block as AutoCAD's does, asking whether to save the changes not saved yet; the JSON form takes `save`: F3 evidence | | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | | 2026-10-22 | minor | APPLOAD typed or from Tools ▸ Load Application opens a `.lsp` file browser starting in the last-used folder (kept in the preferences); a picked file loads interactively like a typed name (routines that ask for input wait), the web says to drop the file (no file system), and the JSON form `{path}` reads the path as given and returns the commands the file defined, never opening a dialog (#1820): E1 narrowed | -| 2026-10-25 | minor | F3: parameters and actions are picked with a click in the Block Editor (Shift+click unpicks, Escape clears), drawn heavier with grips; a grip moves that point; MOVE, ERASE and Delete act on them, a parameter's actions erased with it, as AutoCAD does; the graph keeps its id counter (AutoCAD read no erased block from DXF without it) | -| 2026-10-25 | minor | F3: lookup authoring. BPARAMETER adds a lookup parameter (Name, Label, Description, Palette), BACTION its lookup action, BLOOKUPTABLE (the Property Lookup Table dialog, or JSON) fills its table with AutoCAD's rules (duplicate inputs refused, repeated lookup values read only); AutoCAD evaluates the tables from DXF and DWG as CADCraft does. Visibility states list the actions active in them, as AutoCAD's do | -| 2026-10-25 | minor | F3: visibility authoring. BPARAMETER adds a visibility parameter; BVSTATE (the Visibility States dialog, or -BVSTATE's New with Hide all / Show all / Current visibility, Set, Delete), BVHIDE and BVSHOW (current or all states; also the right-click menu's Object Visibility) edit its states with AutoCAD's prompts; objects drawn and parameters added show in the state shown, as AutoCAD keeps them; BVMODE; AutoCAD reads the states from DXF and DWG. A grip's location components now name their own parameter (AutoCAD evaluated no parameter of a block with a second one) | -| 2026-10-21 | minor | F3: dynamic-block authoring started. In the Block Editor BPARAMETER adds linear and point parameters, BACTION stretch and move actions, with AutoCAD's prompts and JSON forms; AutoCAD opens the result as a dynamic block from DXF and DWG; the editor draws them (40–65 → 30–50 h) | | 2026-10-16 | minor | ALIASEDIT typed or from Tools ▸ Customize opens the Command Aliases dialog (user aliases next to the built-in ones; Add, Edit, Remove; OK, Cancel, Apply), #1381: U12 and E5 narrowed | | 2026-10-16 | minor | MOCORO (Tools ▸ Express Tools ▸ Move/Copy/Rotate): select objects and a base point once, then Move, Copy, Rotate, Scale, Base and Undo until eXit, one undo step; JSON form `{base, ops}`: E3 narrowed | | 2026-10-16 | minor | MLEDIT Merged Tee (MT): the first multiline's outer elements stop at the second one's near side, which opens, and its inner elements run on to the second one's inner element: F21 narrowed, hours unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cb510ad6c5..fc36dea7d8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity: CADCraft vs AutoCAD 2027 -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (dynamic-block authoring started; blocks evidence updated, numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (COMPAREEXPORT; numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 The authoritative assessment of how close CADCraft is to AutoCAD, and how much Opus 5.5 work remains. [ROADMAP.md](../ROADMAP.md) summarises it, [gaps.md](gaps.md) lists every shortfall, @@ -65,8 +65,7 @@ mainstream and essentials numbers use multiplicative discounts. ## Mainstream practitioner The typical AutoCAD professional is a 2D drafter or detailer: draw, modify, dimension, use -blocks, manage layers, plot sheets, and exchange DWGs with colleagues, every week. Excluded per -the standard: 3D, AutoLISP and plug-ins, cloud/AI (Autodesk Assistant, Smart Blocks, Traces, +blocks, manage layers, plot sheets, and exchange DWGs with colleagues, every week. Excluded: 3D, AutoLISP and plug-ins, cloud/AI (Autodesk Assistant, Smart Blocks, Traces, Share), Sheet Set Manager administration, specialist hardware, languages other than English. | Area (weekly use) | Weight | Depth | Weighted | @@ -154,7 +153,7 @@ presence: an option that prints "not available yet" doesn't count. | Text and MTEXT | 6% | 35% | 30–45 | TrueType, formatting codes, stacking; MTEXT prompt options (#408), indents, tabs, bullets, numbering and columns (#547), annotative scaling (#468); editor is a dialog, not in place; no fields or SPELL (open PR #551), no SHX | [gaps](gaps.md#features) | | Leaders, tables, fields | 4% | 25% | 25–35 | MLEADER options and block content (#408), native MULTILEADER in DXF (#459); tables with cell styles, formulas, breaking and CSV data links (#534); no MLEADEREDIT/ALIGN/COLLECT, no FIELD | [gaps](gaps.md#features) | | Hatch and gradients | 5% | 35% | 15–25 | pick points with islands; 23 patterns of ~85; gradients render flat; origin, gap tolerance, separate hatches, island styles and HATCHEDIT options (#451); Hatch and Gradient / Hatch Edit dialogs (no Preview or Inherit Properties) | [gaps](gaps.md#features) | -| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT; dynamic block references read and edited; dynamic-block authoring started (linear, point, visibility and lookup parameters, visibility states, lookup tables, stretch, move and lookup actions); no XCLIP, DesignCenter | [gaps](gaps.md#features) | +| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT; dynamic block references read and edited; no dynamic-block authoring, XCLIP, DesignCenter | [gaps](gaps.md#features) | | Layouts, viewports, plotting | 9% | 35% | 35–50 | layouts, per-VP layers, page setups, plot styles (CTB/STB), Plot dialog (#160), Plot Preview and PUBLISH (#186), plotter devices (#564), PDF with text, layers and sheets (#567, #571), polygonal/object/clipped viewports (#453), annotative scales (#468); no MVIEW Restore, no system printers | [gaps](gaps.md#features) | | Inquiry and utilities | 4% | 30% | 30–45 | DIST, AREA, ID, LIST, MEASUREGEOM, CAL, FIND, COUNT across layouts, QuickCalc, COMPARE (#563) and COMPAREEXPORT, MASSPROP on regions (#510), autosave/recovery, AUDIT, RECOVER (#406), OPTIONS (#23); no SPELL (open PR #551), ETRANSMIT | [gaps](gaps.md#features) | | Parametric constraints | 2% | 50% | 20–30 | all 12 geometric and the dimensional constraints, own solver; DOF report, G2 Smooth, ellipse/spline/block geometry and CONSTRAINTINFER landed (#546) | [geometry-parity](geometry-parity.md#constraint-solver--50) | @@ -215,7 +214,7 @@ DWG/DXF corpus (files from people who own them); black-box checks in AutoCAD of | Date | Feature breadth | Weighted parity | Remaining | Note | |---|---|---|---|---| | 2026-10-10 (merge) | unchanged (233/491 re-scanned) | ready ≈ 38% (37.7%), mainstream ≈ 28%, essentials ≈ 46% | unchanged within rounding | main landed dynamic input pointer boxes (#60), the Ukrainian catalog (#36), WIPEOUT/gradient DXF fixes (#147, #162): UI/UX 40% → 43%, localization 3% → 5% | -| 2026-10-10 (later) | unchanged | ready for real work ≈ 37% (unchanged: already built from the written dimension weights, no hidden judgement); mainstream practitioner ≈ 27%; essentials user ≈ 45% | unchanged | mainstream and essentials numbers added (craftrules standard) | +| 2026-10-10 (later) | unchanged | ready for real work ≈ 37% (unchanged: already built from the written dimension weights, no hidden judgement); mainstream practitioner ≈ 27%; essentials user ≈ 45% | unchanged | mainstream and essentials numbers added | | 2026-10-10 | 245/491 (50%), engine-only 233/491 | features ≈ 41%, ready for real work ≈ 37% | 1,300–2,100 h | full re-measure in this format (this file) | | 2026-10-07 | 233/491 (47%) | ≈ 29% overall, 2D ≈ 55% | ≈ 570 h | old ROADMAP: milestone percentages reported by the building agents | @@ -225,9 +224,6 @@ DWG/DXF corpus (files from people who own them); black-box checks in AutoCAD of |---|---|---| | 2026-10-24 | minor | Inquiry and utilities row: COMPAREEXPORT exports a comparison to a new drawing; parity percentages and hours not re-measured | | 2026-10-22 | minor | Draw row: RECTANG gained a centre construction mode (`Center` keyword, `center: true`) beside its corner mode (#1127); parity percentages and hours not re-measured | -| 2026-10-25 | minor | Blocks row evidence: lookup parameters and tables authored (BLOOKUPTABLE); percentages and hours not re-measured | -| 2026-10-25 | minor | Blocks row evidence: visibility parameters and states authored (BVSTATE, BVHIDE, BVSHOW); percentages and hours not re-measured | -| 2026-10-21 | minor | Blocks row evidence: dynamic-block authoring started (BPARAMETER linear/point, BACTION stretch/move); percentages and hours not re-measured | | 2026-10-12 | minor | Hatch row evidence: Hatch and Gradient / Hatch Edit dialogs; percentages and hours not re-measured | | 2026-10-12 | minor | Blocks row evidence: Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); percentages and hours not re-measured | | 2026-10-11 | minor | Evidence text of the feature-area rows refreshed for merged work (#397, #406, #408, #417, #420, #433, #448, #451, #453, #459, #468, #507, #510, #525, #534, #546, #547, #558, #563, #564, #567, #571); parity percentages and hours not re-measured | From ebfd8f2473fd3b2816c64a3760d3845397b2f1a7 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:18:56 -0600 Subject: [PATCH 27/47] Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them) Co-Authored-By: Claude Sonnet 5.5 --- docs/gaps.md | 7 ++----- docs/target-app-parity.md | 6 ++---- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index a3ba1bea81..f8ddac9410 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where CADCraft falls short of AutoCAD -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (QSAVE asks before losing content and keeps a `.bak`: rows 1, FF1 and F20 updated; BEDIT in the Block Editor switches blocks; dynamic-block authoring started: BPARAMETER linear/point, BACTION stretch/move; visibility parameters and states, BVSTATE, BVHIDE, BVSHOW, BVMODE; F3 updated) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (QSAVE asks before losing content and keeps a `.bak`: rows 1, FF1 and F20 updated) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first). A PR names the rows it closes in its @@ -26,7 +26,7 @@ do them first. |---|---|---|---|---| | F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | | F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | -| F3 | **[alpha blocker]** (dynamic-block authoring is beta) Dynamic-block authoring has started: in the Block Editor, BPARAMETER adds linear, point and visibility parameters and BACTION stretch and move actions; BVSTATE (the Visibility States dialog: Set current, New, Rename, Delete, Move Up, Move Down; -BVSTATE: New, Set, Delete), BVHIDE and BVSHOW (also Object Visibility on the editor's right-click menu) edit visibility states, the editor shows the state picked on its bar and hides (BVMODE 0) or dims (BVMODE 1) what it hides (AutoCAD's prompts, JSON forms), all written so AutoCAD opens the block as a dynamic block (DXF and DWG), and the editor draws them. Missing: the other parameters (polar, XY, rotation, flip, alignment, base point, lookup) and actions (scale, rotate, flip, array, polar stretch, lookup), lookup tables (BLOOKUPTABLE), grip-editing points beyond a linear parameter's ends and label, a point parameter's location and label, a list grip's and an action's location, window selection of parameters and actions, Properties for them, BACTIONSET, the Name/Chain/Value set options, Authoring Palettes, BTESTBLOCK. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips); BEDIT (which, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS, BCLOSE and REFEDIT edit block definitions | issue #185 offers help | High: standard libraries are dynamic | 30–50 | +| F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | | F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 | @@ -157,9 +157,6 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | | 2026-10-22 | minor | APPLOAD typed or from Tools ▸ Load Application opens a `.lsp` file browser starting in the last-used folder (kept in the preferences); a picked file loads interactively like a typed name (routines that ask for input wait), the web says to drop the file (no file system), and the JSON form `{path}` reads the path as given and returns the commands the file defined, never opening a dialog (#1820): E1 narrowed | -| 2026-10-25 | minor | F3: parameters and actions are picked with a click in the Block Editor (Shift+click unpicks, Escape clears), drawn heavier with grips; a grip moves that point; MOVE, ERASE and Delete act on them, a parameter's actions erased with it, as AutoCAD does; the graph keeps its id counter (AutoCAD read no erased block from DXF without it) | -| 2026-10-25 | minor | F3: visibility authoring. BPARAMETER adds a visibility parameter; BVSTATE (the Visibility States dialog, or -BVSTATE's New with Hide all / Show all / Current visibility, Set, Delete), BVHIDE and BVSHOW (current or all states; also the right-click menu's Object Visibility) edit its states with AutoCAD's prompts; objects drawn and parameters added show in the state shown, as AutoCAD keeps them; BVMODE; AutoCAD reads the states from DXF and DWG. A grip's location components now name their own parameter (AutoCAD evaluated no parameter of a block with a second one) | -| 2026-10-21 | minor | F3: dynamic-block authoring started. In the Block Editor BPARAMETER adds linear and point parameters, BACTION stretch and move actions, with AutoCAD's prompts and JSON forms; AutoCAD opens the result as a dynamic block from DXF and DWG; the editor draws them (40–65 → 30–50 h) | | 2026-10-16 | minor | ALIASEDIT typed or from Tools ▸ Customize opens the Command Aliases dialog (user aliases next to the built-in ones; Add, Edit, Remove; OK, Cancel, Apply), #1381: U12 and E5 narrowed | | 2026-10-16 | minor | MOCORO (Tools ▸ Express Tools ▸ Move/Copy/Rotate): select objects and a base point once, then Move, Copy, Rotate, Scale, Base and Undo until eXit, one undo step; JSON form `{base, ops}`: E3 narrowed | | 2026-10-16 | minor | MLEDIT Merged Tee (MT): the first multiline's outer elements stop at the second one's near side, which opens, and its inner elements run on to the second one's inner element: F21 narrowed, hours unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fd5017f6ac..fc36dea7d8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity: CADCraft vs AutoCAD 2027 -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (dynamic-block authoring started; blocks evidence updated, numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (COMPAREEXPORT; numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 The authoritative assessment of how close CADCraft is to AutoCAD, and how much Opus 5.5 work remains. [ROADMAP.md](../ROADMAP.md) summarises it, [gaps.md](gaps.md) lists every shortfall, @@ -153,7 +153,7 @@ presence: an option that prints "not available yet" doesn't count. | Text and MTEXT | 6% | 35% | 30–45 | TrueType, formatting codes, stacking; MTEXT prompt options (#408), indents, tabs, bullets, numbering and columns (#547), annotative scaling (#468); editor is a dialog, not in place; no fields or SPELL (open PR #551), no SHX | [gaps](gaps.md#features) | | Leaders, tables, fields | 4% | 25% | 25–35 | MLEADER options and block content (#408), native MULTILEADER in DXF (#459); tables with cell styles, formulas, breaking and CSV data links (#534); no MLEADEREDIT/ALIGN/COLLECT, no FIELD | [gaps](gaps.md#features) | | Hatch and gradients | 5% | 35% | 15–25 | pick points with islands; 23 patterns of ~85; gradients render flat; origin, gap tolerance, separate hatches, island styles and HATCHEDIT options (#451); Hatch and Gradient / Hatch Edit dialogs (no Preview or Inherit Properties) | [gaps](gaps.md#features) | -| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT; dynamic block references read and edited; dynamic-block authoring started (linear, point and visibility parameters, visibility states, stretch and move actions); no XCLIP, DesignCenter | [gaps](gaps.md#features) | +| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT; dynamic block references read and edited; no dynamic-block authoring, XCLIP, DesignCenter | [gaps](gaps.md#features) | | Layouts, viewports, plotting | 9% | 35% | 35–50 | layouts, per-VP layers, page setups, plot styles (CTB/STB), Plot dialog (#160), Plot Preview and PUBLISH (#186), plotter devices (#564), PDF with text, layers and sheets (#567, #571), polygonal/object/clipped viewports (#453), annotative scales (#468); no MVIEW Restore, no system printers | [gaps](gaps.md#features) | | Inquiry and utilities | 4% | 30% | 30–45 | DIST, AREA, ID, LIST, MEASUREGEOM, CAL, FIND, COUNT across layouts, QuickCalc, COMPARE (#563) and COMPAREEXPORT, MASSPROP on regions (#510), autosave/recovery, AUDIT, RECOVER (#406), OPTIONS (#23); no SPELL (open PR #551), ETRANSMIT | [gaps](gaps.md#features) | | Parametric constraints | 2% | 50% | 20–30 | all 12 geometric and the dimensional constraints, own solver; DOF report, G2 Smooth, ellipse/spline/block geometry and CONSTRAINTINFER landed (#546) | [geometry-parity](geometry-parity.md#constraint-solver--50) | @@ -224,8 +224,6 @@ DWG/DXF corpus (files from people who own them); black-box checks in AutoCAD of |---|---|---| | 2026-10-24 | minor | Inquiry and utilities row: COMPAREEXPORT exports a comparison to a new drawing; parity percentages and hours not re-measured | | 2026-10-22 | minor | Draw row: RECTANG gained a centre construction mode (`Center` keyword, `center: true`) beside its corner mode (#1127); parity percentages and hours not re-measured | -| 2026-10-25 | minor | Blocks row evidence: visibility parameters and states authored (BVSTATE, BVHIDE, BVSHOW); percentages and hours not re-measured | -| 2026-10-21 | minor | Blocks row evidence: dynamic-block authoring started (BPARAMETER linear/point, BACTION stretch/move); percentages and hours not re-measured | | 2026-10-12 | minor | Hatch row evidence: Hatch and Gradient / Hatch Edit dialogs; percentages and hours not re-measured | | 2026-10-12 | minor | Blocks row evidence: Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); percentages and hours not re-measured | | 2026-10-11 | minor | Evidence text of the feature-area rows refreshed for merged work (#397, #406, #408, #417, #420, #433, #448, #451, #453, #459, #468, #507, #510, #525, #534, #546, #547, #558, #563, #564, #567, #571); parity percentages and hours not re-measured | From 913105380110447a272cc4bc4a6ab918486ad5f4 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:19:00 -0600 Subject: [PATCH 28/47] Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them) Co-Authored-By: Claude Sonnet 5.5 --- docs/gaps.md | 18 +++++++++--------- docs/target-app-parity.md | 10 ++++------ 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index f700a6f785..f8ddac9410 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,10 +1,10 @@ # Where CADCraft falls short of AutoCAD -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (BEDIT in the Block Editor switches blocks; dynamic-block authoring started: BPARAMETER linear/point, BACTION stretch/move; F3 updated) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (QSAVE asks before losing content and keeps a `.bak`: rows 1, FF1 and F20 updated) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work -list: agents pick from here (top of a section first), and remove or update a row in the same PR -that closes it. Numbers and weights live in [target-app-parity.md](target-app-parity.md); hours +list: agents pick from here (top of a section first). A PR names the rows it closes in its +description, and maintainers update them in batches. Numbers and weights live in [target-app-parity.md](target-app-parity.md); hours are Opus 5.5 agent-hours, calibrated as explained there. "Est." means a judgement from the cited evidence. Rows marked **[alpha blocker]** are what fails the [alpha gate](roadmap.md#alpha-gate); do them first. @@ -13,7 +13,7 @@ do them first. | # | Gap | Why it ranks here | Est. | Doc | |---|---|---|---|---| -| 1 | **[alpha blocker]** **Saving DWG drops what we don't model** (DXF now writes back unknown entities and objects, foreign xdata, extension dictionaries, reactors, layer states and colour books, #528, and native MULTILEADERs, #459 (not yet tested through DWG); through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour books and reactors) | Opening a colleague's DWG and saving it still deletes some content: the one thing a CAD user can't forgive | 6–10 | [file formats](file-format-parity.md) | +| 1 | **[alpha blocker]** **Saving DWG drops what we don't model** (DXF now writes back unknown entities and objects, foreign xdata, extension dictionaries, reactors, layer states and colour books, #528, and native MULTILEADERs, #459 (not yet tested through DWG); through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour books and reactors; a user's QSAVE now asks before replacing the file and keeps the previous one as `.bak`, which reduces the harm but does not close this row) | Opening a colleague's DWG and saving it still deletes some content: the one thing a CAD user can't forgive | 6–10 | [file formats](file-format-parity.md) | | 2 | **[alpha blocker]** **No real-file test corpus and no check in AutoCAD** | All 36 file tests are synthetic; nobody has verified a CADCraft DWG/DXF opens cleanly in AutoCAD | 10–15 + human | [file formats](file-format-parity.md#tests) | | 3 | **Ellipse and spline geometry is tessellated** (intersections, offsets, closest points; polyline offset ignores bulges) | Coordinates are subtly wrong; offsets of ellipses come out as polylines | 30–50 | [geometry](geometry-parity.md) | | 4 | **[alpha blocker]** **No dynamic blocks or REFEDIT; xrefs can't be edited in place or clipped** (xrefs, #525, groups, #417, and the Block Editor for static blocks landed) | Most production drawings use them | 55–90 | [features](#features) | @@ -26,7 +26,7 @@ do them first. |---|---|---|---|---| | F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | | F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | -| F3 | **[alpha blocker]** (dynamic-block authoring is beta) Dynamic-block authoring has started: in the Block Editor, BPARAMETER adds linear and point parameters and BACTION stretch and move actions (AutoCAD's prompts, JSON forms), written so AutoCAD opens the block as a dynamic block (DXF and DWG), and the editor draws them. Missing: the other parameters (polar, XY, rotation, flip, alignment, base point, visibility, lookup) and actions (scale, rotate, flip, array, polar stretch, lookup), visibility states and lookup tables (BVSTATE, BLOOKUPTABLE), selecting and editing parameters and actions in the editor, the Name/Chain/Value set options, Authoring Palettes, BTESTBLOCK. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips); BEDIT (which, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS, BCLOSE and REFEDIT edit block definitions | issue #185 offers help | High: standard libraries are dynamic | 30–50 | +| F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | | F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 | @@ -41,7 +41,7 @@ do them first. | F16 | Groups: no group bounding box or single grip when a group is selected (GROUPDISPLAYMODE), copying a whole group does not make a new group, no Object Grouping dialog (GROUP, GROUPEDIT, UNGROUP, -GROUP, PICKSTYLE group selection and the DXF/DWG round trip landed, #417); PICKSTYLE's associative-hatch bit is stored but unused | `cmd/groups.rs` | Low | 2–4 | | F17 | Attributes (ATTSYNC, global -ATTEDIT, BATTMAN editing and DATAEXTRACTION/EATTEXT landed, #433): no verify, preset or lock-position modes, and multiline attributes (read, drawn and saved since 2026-10-12) can't be created or switched in BATTMAN; data extraction covers block references and attribute values (CSV or a table) only — no wizard, nested blocks, other objects' properties, `.dxe` templates or spreadsheet output | `cmd/blocks/battman.rs`, `cmd/blocks/extract.rs` | Low | 4–6 | | F19 | MATCHPROP Settings is a keyword prompt (no dialog) and has no material, shadow or centre-object settings; TEXTTOFRONT and HATCHTOBACK act on the current space only; OVERKILL doesn't compare polyline segments with other objects (picker and Settings, DRAWORDER Above/Under, TEXTTOFRONT, HATCHTOBACK, OVERKILL tolerance/ignore/overlap/end-to-end options landed, #439) | `props/matchprop.rs`, `draworder.rs`, `overkill.rs` | Low | 2–4 | -| F20 | OPTIONS dialog done (#23): Display, Open and Save, Drafting, Selection, User Preferences and Profiles tabs, and the user profile (object snap modes, drafting toggles, Dynamic Input, PICKBOX, APERTURE, GRIPSIZE, CURSORSIZE, PICKFIRST, PICKADD, QPMODE, model and paper background, snap marker size, system cursor) survives restarts. Left: right-click customization, the autosave interval and default save version on Open and Save (the features themselves landed, #406, #421), AutoSnap magnet and tooltip toggles, colours of the other drawing-area elements, named profiles with import and export | `ui-egui/src/options/` | Low | 2–4 | +| F20 | OPTIONS dialog done (#23): Display, Open and Save, Drafting, Selection, User Preferences and Profiles tabs, and the user profile (object snap modes, drafting toggles, Dynamic Input, PICKBOX, APERTURE, GRIPSIZE, CURSORSIZE, PICKFIRST, PICKADD, QPMODE, model and paper background, snap marker size, system cursor) survives restarts. Left: right-click customization, the autosave interval and default save version on Open and Save (the features themselves landed, #406, #421), AutoSnap magnet and tooltip toggles, colours of the other drawing-area elements, named profiles with import and export Open and Save has the backup copy checkbox (ISAVEBAK). | `ui-egui/src/options/` | Low | 2–4 | | F21 | MLINE, REGION and HELIX are objects since #510, with gaps: MLEDIT tees trim square; UNION/SUBTRACT/INTERSECT only combine regions whose boundaries don't meet; regions are saved as closed polylines (no ACIS data) | `draw2/mline.rs`, `inquiry/regions.rs`, `dxf_region.rs` | Low | 6–10 | | F22 | Inquiry leftovers (COUNT across spaces and nested blocks, the QuickCalc palette and COMPARE landed, #563; MASSPROP on regions, #510): COMPARE compares the tab shown, not every layout at once (COMPAREEXPORT, the comparison as a new drawing, landed); COMPAREEXPORT puts the two sets of objects in model-space groups, where AutoCAD puts them in blocks; QuickCalc keeps its history and variables for the session only | `file/compare.rs`, `palettes/quickcalc.rs` | Low | 3–5 | | F23 | No Sheet Set Manager, eTransmit, Share, Traces, Markup Import, Activity Insights | menu items uncovered | Low-medium (team workflows) | 40–70 | @@ -73,7 +73,7 @@ Detail: [file-format-parity.md](file-format-parity.md). | # | Gap | User impact | Est. | |---|---|---|---| -| FF1 | **[alpha blocker]** Round-trip what we don't model. DXF done (#528): unknown entities and objects (with their CLASS records), foreign xdata (hyperlinks included), extension dictionaries, persistent reactors, DICTIONARYVAR and XRECORDs, layer states, colour book colours, references remapped on save; IMAGE, VIEW/UCS, groups, block descriptions, true colours, transparency (#201, #204, #208, #209, #213, #223); WIPEOUT and gradients (#147, #162). Left: through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour book names and reactors; UCS elevation; MTEXT background colours; unknown entities follow only layer edits, and renamed layers and blocks lose their foreign data | High | 6–10 | +| FF1 | **[alpha blocker]** Round-trip what we don't model. DXF done (#528): unknown entities and objects (with their CLASS records), foreign xdata (hyperlinks included), extension dictionaries, persistent reactors, DICTIONARYVAR and XRECORDs, layer states, colour book colours, references remapped on save; IMAGE, VIEW/UCS, groups, block descriptions, true colours, transparency (#201, #204, #208, #209, #213, #223); WIPEOUT and gradients (#147, #162). Left: through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour book names and reactors; UCS elevation; MTEXT background colours; unknown entities follow only layer edits, and renamed layers and blocks lose their foreign data A user's QSAVE now asks before such a loss and keeps the previous file as `.bak`; the loss itself remains. | High | 6–10 | | FF2 | Multileader leftovers (native MULTILEADER read/write landed, #459): several landings per multileader (extra leader roots are folded into the lines), per-object overrides (leader colour and linetype, arrowhead symbol, text frame), annotative scale contexts; check the text placement of our MULTILEADER output in AutoCAD | Medium | 3–5 | | FF3 | Save-version leftovers (DXF/DWG 2000–2018, binary DXF, SAVEAS `version`/`binary` and the default save version landed, #421): no R14 DWG or R12 DXF output; the Save dialog can't pick the version per file (the file picker doesn't report the chosen type; File > Default Save Format sets it); no command-line SAVEAS format prompt | Low | 2–4 | | FF4 | Code-page leftovers (pre-2007 DXF read in their `$DWGCODEPAGE` landed, #505): Johab (ANSI_1361) and DOS 855/857/860–865/869 read as ANSI_1252; saving declares `ANSI_1252` instead of the file's code page (the text is pure ASCII, so still correct); acadrust approximates DOS code pages in pre-2007 DWG (DOS437 as 866, DOS850 as 1252) | Low | 1–2 | @@ -107,7 +107,7 @@ Detail: [localization-parity.md](localization-parity.md). | # | Gap | Est. | |---|---|---| | L1 | Catalog covers the UI (989 rows, #36) but not engine diagnostics, CLI/MCP replies or command history | 4–6 | -| L2 | AutoCAD for Mac's other languages (zh-Hans, es, fr, ja, ko, it; de landed 2026-10-11) plus pt, hi, ar, id, vi from the standard's list | 35–55 + native review | +| L2 | AutoCAD for Mac's other languages (zh-Hans, es, fr, ja, ko, it; de landed 2026-10-11) plus pt, hi, ar, id, vi | 35–55 + native review | | L3 | Complex-script shaping for Devanagari and other Indic scripts in drawing text; RTL (mirrored) UI. Arabic-script shaping and bidi in drawing text landed (#287) | 20–30 | | L4 | IME fixes on every platform (PRs #110–#119); vertical text styles | 6–10 | @@ -150,13 +150,13 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | QSAVE asks before replacing a file with content the DWG writer can't keep, and ISAVEBAK keeps the previous file as `.bak`: row 1 narrowed, FF1 and F20 updated | | 2026-10-25 | minor | Named Viewports (View ▸ Viewports ▸ Named Viewports..., `vports.named`) lists the saved viewport configurations with a preview and the current one's name, and restores or deletes one; in a layout Restore places it as MVIEW Restore does: U11 narrowed. F15 and U11 no longer list MVIEW Restore (#633), and F21 no longer says PURGE skips multiline styles | | 2026-10-25 | minor | DIMTFILL limits: with DIMTFILL 1 (the drawing's background color) the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI: F7 updated | | 2026-10-26 | minor | BEDIT in the Block Editor (typed, Edit Block, or the Edit Block Definition dialog) switches to another block as AutoCAD's does, asking whether to save the changes not saved yet; the JSON form takes `save`: F3 evidence | | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | | 2026-10-22 | minor | APPLOAD typed or from Tools ▸ Load Application opens a `.lsp` file browser starting in the last-used folder (kept in the preferences); a picked file loads interactively like a typed name (routines that ask for input wait), the web says to drop the file (no file system), and the JSON form `{path}` reads the path as given and returns the commands the file defined, never opening a dialog (#1820): E1 narrowed | -| 2026-10-21 | minor | F3: dynamic-block authoring started. In the Block Editor BPARAMETER adds linear and point parameters, BACTION stretch and move actions, with AutoCAD's prompts and JSON forms; AutoCAD opens the result as a dynamic block from DXF and DWG; the editor draws them (40–65 → 30–50 h) | | 2026-10-16 | minor | ALIASEDIT typed or from Tools ▸ Customize opens the Command Aliases dialog (user aliases next to the built-in ones; Add, Edit, Remove; OK, Cancel, Apply), #1381: U12 and E5 narrowed | | 2026-10-16 | minor | MOCORO (Tools ▸ Express Tools ▸ Move/Copy/Rotate): select objects and a base point once, then Move, Copy, Rotate, Scale, Base and Undo until eXit, one undo step; JSON form `{base, ops}`: E3 narrowed | | 2026-10-16 | minor | MLEDIT Merged Tee (MT): the first multiline's outer elements stop at the second one's near side, which opens, and its inner elements run on to the second one's inner element: F21 narrowed, hours unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 22b85689cf..fc36dea7d8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity: CADCraft vs AutoCAD 2027 -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (dynamic-block authoring started; blocks evidence updated, numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (COMPAREEXPORT; numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 The authoritative assessment of how close CADCraft is to AutoCAD, and how much Opus 5.5 work remains. [ROADMAP.md](../ROADMAP.md) summarises it, [gaps.md](gaps.md) lists every shortfall, @@ -65,8 +65,7 @@ mainstream and essentials numbers use multiplicative discounts. ## Mainstream practitioner The typical AutoCAD professional is a 2D drafter or detailer: draw, modify, dimension, use -blocks, manage layers, plot sheets, and exchange DWGs with colleagues, every week. Excluded per -the standard: 3D, AutoLISP and plug-ins, cloud/AI (Autodesk Assistant, Smart Blocks, Traces, +blocks, manage layers, plot sheets, and exchange DWGs with colleagues, every week. Excluded: 3D, AutoLISP and plug-ins, cloud/AI (Autodesk Assistant, Smart Blocks, Traces, Share), Sheet Set Manager administration, specialist hardware, languages other than English. | Area (weekly use) | Weight | Depth | Weighted | @@ -154,7 +153,7 @@ presence: an option that prints "not available yet" doesn't count. | Text and MTEXT | 6% | 35% | 30–45 | TrueType, formatting codes, stacking; MTEXT prompt options (#408), indents, tabs, bullets, numbering and columns (#547), annotative scaling (#468); editor is a dialog, not in place; no fields or SPELL (open PR #551), no SHX | [gaps](gaps.md#features) | | Leaders, tables, fields | 4% | 25% | 25–35 | MLEADER options and block content (#408), native MULTILEADER in DXF (#459); tables with cell styles, formulas, breaking and CSV data links (#534); no MLEADEREDIT/ALIGN/COLLECT, no FIELD | [gaps](gaps.md#features) | | Hatch and gradients | 5% | 35% | 15–25 | pick points with islands; 23 patterns of ~85; gradients render flat; origin, gap tolerance, separate hatches, island styles and HATCHEDIT options (#451); Hatch and Gradient / Hatch Edit dialogs (no Preview or Inherit Properties) | [gaps](gaps.md#features) | -| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT; dynamic block references read and edited; dynamic-block authoring started (linear and point parameters, stretch and move actions); no XCLIP, DesignCenter | [gaps](gaps.md#features) | +| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT; dynamic block references read and edited; no dynamic-block authoring, XCLIP, DesignCenter | [gaps](gaps.md#features) | | Layouts, viewports, plotting | 9% | 35% | 35–50 | layouts, per-VP layers, page setups, plot styles (CTB/STB), Plot dialog (#160), Plot Preview and PUBLISH (#186), plotter devices (#564), PDF with text, layers and sheets (#567, #571), polygonal/object/clipped viewports (#453), annotative scales (#468); no MVIEW Restore, no system printers | [gaps](gaps.md#features) | | Inquiry and utilities | 4% | 30% | 30–45 | DIST, AREA, ID, LIST, MEASUREGEOM, CAL, FIND, COUNT across layouts, QuickCalc, COMPARE (#563) and COMPAREEXPORT, MASSPROP on regions (#510), autosave/recovery, AUDIT, RECOVER (#406), OPTIONS (#23); no SPELL (open PR #551), ETRANSMIT | [gaps](gaps.md#features) | | Parametric constraints | 2% | 50% | 20–30 | all 12 geometric and the dimensional constraints, own solver; DOF report, G2 Smooth, ellipse/spline/block geometry and CONSTRAINTINFER landed (#546) | [geometry-parity](geometry-parity.md#constraint-solver--50) | @@ -215,7 +214,7 @@ DWG/DXF corpus (files from people who own them); black-box checks in AutoCAD of | Date | Feature breadth | Weighted parity | Remaining | Note | |---|---|---|---|---| | 2026-10-10 (merge) | unchanged (233/491 re-scanned) | ready ≈ 38% (37.7%), mainstream ≈ 28%, essentials ≈ 46% | unchanged within rounding | main landed dynamic input pointer boxes (#60), the Ukrainian catalog (#36), WIPEOUT/gradient DXF fixes (#147, #162): UI/UX 40% → 43%, localization 3% → 5% | -| 2026-10-10 (later) | unchanged | ready for real work ≈ 37% (unchanged: already built from the written dimension weights, no hidden judgement); mainstream practitioner ≈ 27%; essentials user ≈ 45% | unchanged | mainstream and essentials numbers added (craftrules standard) | +| 2026-10-10 (later) | unchanged | ready for real work ≈ 37% (unchanged: already built from the written dimension weights, no hidden judgement); mainstream practitioner ≈ 27%; essentials user ≈ 45% | unchanged | mainstream and essentials numbers added | | 2026-10-10 | 245/491 (50%), engine-only 233/491 | features ≈ 41%, ready for real work ≈ 37% | 1,300–2,100 h | full re-measure in this format (this file) | | 2026-10-07 | 233/491 (47%) | ≈ 29% overall, 2D ≈ 55% | ≈ 570 h | old ROADMAP: milestone percentages reported by the building agents | @@ -225,7 +224,6 @@ DWG/DXF corpus (files from people who own them); black-box checks in AutoCAD of |---|---|---| | 2026-10-24 | minor | Inquiry and utilities row: COMPAREEXPORT exports a comparison to a new drawing; parity percentages and hours not re-measured | | 2026-10-22 | minor | Draw row: RECTANG gained a centre construction mode (`Center` keyword, `center: true`) beside its corner mode (#1127); parity percentages and hours not re-measured | -| 2026-10-21 | minor | Blocks row evidence: dynamic-block authoring started (BPARAMETER linear/point, BACTION stretch/move); percentages and hours not re-measured | | 2026-10-12 | minor | Hatch row evidence: Hatch and Gradient / Hatch Edit dialogs; percentages and hours not re-measured | | 2026-10-12 | minor | Blocks row evidence: Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); percentages and hours not re-measured | | 2026-10-11 | minor | Evidence text of the feature-area rows refreshed for merged work (#397, #406, #408, #417, #420, #433, #448, #451, #453, #459, #468, #507, #510, #525, #534, #546, #547, #558, #563, #564, #567, #571); parity percentages and hours not re-measured | From 49cac9e67dd9b81d6551cbf3426488595231ad7b Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:25:36 -0600 Subject: [PATCH 29/47] Dynamic blocks: lookup tables are written all or nothing, compared by key, own column first Review (eliets2) on #2184: - write_table, drop_columns and erase_elements run all or nothing: refused partway (a graph that can't be read, an unknown id after a column was dropped), the drawing's dynamic block data is put back as it was. - Duplicate inputs and repeated lookup values are found through hash sets of cell keys (a number to nine significant digits, text in any case) instead of nested scans; a table has at most 1,000,000 cells; column names are worked out once per column, not once per cell. - The action's own lookup column is written first of its lookup columns, so it is the one protected however the caller orders them. A lookup parameter's 94 names the action for every lookup column of the table, so it can't tell the own one apart. - The Property Lookup Table dialog's repeat check uses the same cell key. - BSAVEAS refuses a dynamic block with too many objects to copy whole instead of making a copy that points at the original's objects. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock.rs | 2 +- crates/doc/src/dynblock/copy.rs | 30 +++++-- crates/doc/src/dynblock/edit.rs | 7 +- crates/doc/src/dynblock/lookup.rs | 139 ++++++++++++++++++++++++++---- crates/engine/src/blockedit.rs | 2 +- crates/ui-egui/src/blookup.rs | 18 +++- 6 files changed, 166 insertions(+), 32 deletions(-) diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index d5e62a68bf..6a336a6c41 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -32,7 +32,7 @@ pub use apply::{drag_grip, set_property}; pub use copy::{copy_definition, remap_handles, restore_definition}; pub use edit::{ElementPoint, element_points, erase_elements, move_element, set_element_point}; pub use grips::{DynGrip, GripPart, GripShape, grips}; -pub use lookup::{MAX_LOOKUP_ROWS, TableColumn, column_property, input_properties, set_lookup_table}; +pub use lookup::{MAX_LOOKUP_ROWS, TableColumn, cell_key, column_property, input_properties, set_lookup_table}; pub use marks::{Mark, marks}; pub use reference::{CustomProperty, Reference, Value, custom_properties, reference}; pub use write::{ diff --git a/crates/doc/src/dynblock/copy.rs b/crates/doc/src/dynblock/copy.rs index a394810dd3..6742c6f888 100644 --- a/crates/doc/src/dynblock/copy.rs +++ b/crates/doc/src/dynblock/copy.rs @@ -54,6 +54,16 @@ fn owned_subtree(d: &Drawing, root: Handle) -> Vec { out } +/// [`owned_subtree`], refused when it reaches [`MAX_COPIED`]: a copy of only part of it would keep +/// pointing at the original's objects. +fn whole_subtree(d: &Drawing, root: Handle) -> Result, String> { + let out = owned_subtree(d, root); + if out.len() >= MAX_COPIED { + return Err(format!("The dynamic block has {MAX_COPIED} or more objects; it can't be copied.")); + } + Ok(out) +} + /// The handle `h` names, as `map` has it. fn mapped(map: &HashMap, value: &str) -> Option { Handle::parse_hex(value).and_then(|h| map.get(&h)).copied() @@ -166,20 +176,22 @@ fn rename_in_xdata(xdata: &mut [RawTag], name: &str, guid: &str) { /// original's with new handles, and its own true name and GUID. What `to` had of dynamic data goes /// first (a block replaced by one that isn't dynamic keeps none). Returns the handles the objects /// of `store` got, by their old ones; nothing changes when `from` has no dynamic data or is `to`. -pub fn copy_definition(d: &mut Drawing, from: &str, to: &str, store: &mut EntityStore) -> HashMap { +/// Refused, changing nothing, when `from` has too many objects to copy whole. +pub fn copy_definition(d: &mut Drawing, from: &str, to: &str, store: &mut EntityStore) -> Result, String> { let (from_name, to_name) = (from.trim().to_ascii_uppercase(), to.trim().to_ascii_uppercase()); let key = |n: &str| ("BLOCK_RECORD".to_string(), n.to_string()); if from_name == to_name { - return HashMap::new(); + return Ok(HashMap::new()); } + let source = d.foreign.records.get(&key(&from_name)).cloned(); + let owned = match source.as_ref().and_then(|s| s.xdict) { + Some(xdict) if dynamic_block(d, from).is_some() => Some(whole_subtree(d, xdict)?), + _ => None, + }; remove_definition(d, &to_name); - if dynamic_block(d, from).is_none() { - return HashMap::new(); - } - let Some(source) = d.foreign.records.get(&key(&from_name)).cloned() else { return HashMap::new() }; - let Some(xdict) = source.xdict else { return HashMap::new() }; + let (Some(source), Some(owned)) = (source, owned) else { return Ok(HashMap::new()) }; + let Some(xdict) = source.xdict else { return Ok(HashMap::new()) }; let graph = dict_entry(d, xdict, "ACAD_ENHANCEDBLOCK"); - let owned = owned_subtree(d, xdict); let owned_set: HashSet = owned.iter().copied().collect(); let mut map: HashMap = owned.iter().map(|h| (*h, d.new_handle())).collect(); let old_record = d.foreign.targets.iter().find(|(_, (k, n))| k == "BLOCK_RECORD" && *n == from_name).map(|(h, _)| *h); @@ -209,5 +221,5 @@ pub fn copy_definition(d: &mut Drawing, from: &str, to: &str, store: &mut Entity f.entities.extend(extras); let made = store.iter().filter_map(|e| Some((e.handle, *map.get(&e.handle)?))).collect(); *store = entities; - made + Ok(made) } diff --git a/crates/doc/src/dynblock/edit.rs b/crates/doc/src/dynblock/edit.rs index 5533eed9eb..26e7fa8da7 100644 --- a/crates/doc/src/dynblock/edit.rs +++ b/crates/doc/src/dynblock/edit.rs @@ -220,8 +220,13 @@ pub fn set_element_point(d: &mut Drawing, block: &str, node: i32, which: Element /// Erase parameters and actions `nodes` of block `block` (any case), as AutoCAD erases them: a /// parameter takes its grips, their location components and its actions along. Returns the -/// graph ids erased (the parameters' and actions'; grips and components aren't listed). +/// graph ids erased (the parameters' and actions'; grips and components aren't listed). All or +/// nothing: refused partway, the drawing is left as it was. pub fn erase_elements(d: &mut Drawing, block: &str, nodes: &[i32]) -> Result, String> { + super::lookup::all_or_nothing(d, |d| erase_elements_in(d, block, nodes)) +} + +fn erase_elements_in(d: &mut Drawing, block: &str, nodes: &[i32]) -> Result, String> { // Lookup tables lose the columns of parameters erased; a lookup parameter's own table goes. let params: Vec = dynamic_block(d, block).map(|m| m.parameters.iter().map(|p| p.node).filter(|n| nodes.contains(n)).collect()).unwrap_or_default(); diff --git a/crates/doc/src/dynblock/lookup.rs b/crates/doc/src/dynblock/lookup.rs index 842afc380e..dfc6153baf 100644 --- a/crates/doc/src/dynblock/lookup.rs +++ b/crates/doc/src/dynblock/lookup.rs @@ -18,6 +18,7 @@ use super::write::{Graph, dict_entry, tag}; use super::{ActionKind, DynamicBlock, ParameterKind, dynamic_block}; use crate::{Drawing, Handle, RawTag}; +use std::collections::HashSet; /// Most rows one lookup table is written with. pub const MAX_LOOKUP_ROWS: usize = 10_000; @@ -25,6 +26,9 @@ pub const MAX_LOOKUP_ROWS: usize = 10_000; /// Most columns one lookup table is written with. const MAX_COLUMNS: usize = 1_000; +/// Most cells (rows times columns) one lookup table is written with. +const MAX_CELLS: usize = 1_000_000; + /// A lookup table column as it is written: the parameter's graph id and the value it stands for, /// whether it is a lookup column, what references show when no row matches, and whether a lookup /// column can be set on a reference (reverse lookup). @@ -101,8 +105,13 @@ pub fn input_properties(m: &DynamicBlock) -> Vec<(String, i32, String)> { /// The name a lookup table column shows: an input property's name ("Position1 X"), a lookup /// parameter's property name, or the property itself when the parameter is unknown. pub fn column_property(m: &DynamicBlock, node: i32, property: &str) -> String { - if let Some((n, ..)) = input_properties(m).into_iter().find(|(_, id, prop)| *id == node && prop.eq_ignore_ascii_case(property)) { - return n; + column_named(m, &input_properties(m), node, property) +} + +/// [`column_property`] with block `m`'s [`input_properties`] already listed. +fn column_named(m: &DynamicBlock, inputs: &[(String, i32, String)], node: i32, property: &str) -> String { + if let Some((n, ..)) = inputs.iter().find(|(_, id, prop)| *id == node && prop.eq_ignore_ascii_case(property)) { + return n.clone(); } match m.parameters.iter().find(|p| p.node == node).map(|p| &p.kind) { Some(ParameterKind::Lookup { label, .. }) => label.clone(), @@ -111,12 +120,26 @@ pub fn column_property(m: &DynamicBlock, node: i32, property: &str) -> String { } } -/// Whether table cells `a` and `b` read the same (numbers compare as numbers, text in any case). -fn same(a: &str, b: &str) -> bool { - match (a.trim().parse::(), b.trim().parse::()) { - (Ok(x), Ok(y)) => (x - y).abs() <= 1e-9 * x.abs().max(y.abs()).max(1.0), - _ => a.trim().eq_ignore_ascii_case(b.trim()), +/// A table cell as two cells are compared by: a number by its value to nine significant digits +/// (`10` and `10.0` are the same), text in any case. Cells with the same key read the same. +pub fn cell_key(cell: &str) -> String { + let cell = cell.trim(); + match cell.parse::() { + // Adding 0 turns -0 into 0. + Ok(v) if v.is_finite() => format!("{:.8e}", v + 0.0), + _ => cell.to_lowercase(), + } +} + +/// Run `change` on `d` all or nothing: when it fails, the drawing's dynamic block data (its foreign +/// objects, all that lookup tables and element edits change) is put back as it was. +pub(super) fn all_or_nothing(d: &mut Drawing, change: impl FnOnce(&mut Drawing) -> Result) -> Result { + let kept = std::sync::Arc::clone(&d.foreign); + let out = change(d); + if out.is_err() { + d.foreign = kept; } + out } /// Fill lookup action `action` of block `block` (any case) with `columns` and `rows` (each row @@ -129,17 +152,27 @@ pub fn set_lookup_table(d: &mut Drawing, block: &str, action: i32, columns: &[Ta } /// [`set_lookup_table`]; with `dedupe`, a row whose inputs repeat an earlier row's is left out -/// instead of refused (a column was taken out from under it). +/// instead of refused (a column was taken out from under it). All or nothing: a table refused +/// partway leaves the drawing as it was. fn write_table(d: &mut Drawing, block: &str, action: i32, columns: &[TableColumn], rows: &[Vec], dedupe: bool) -> Result<(), String> { + all_or_nothing(d, |d| write_table_in(d, block, action, columns, rows, dedupe)) +} + +fn write_table_in(d: &mut Drawing, block: &str, action: i32, columns: &[TableColumn], rows: &[Vec], dedupe: bool) -> Result<(), String> { if columns.len() > MAX_COLUMNS { return Err(format!("A lookup table has at most {MAX_COLUMNS} columns.")); } if rows.len() > MAX_LOOKUP_ROWS { return Err(format!("A lookup table has at most {MAX_LOOKUP_ROWS} rows.")); } + if rows.len().saturating_mul(columns.len()) > MAX_CELLS { + return Err(format!("A lookup table has at most {MAX_CELLS} cells.")); + } let m = dynamic_block(d, block).ok_or("The block has no parameters or actions.")?; let a = m.actions.iter().find(|a| a.node == action).ok_or_else(|| format!("No action {action} in the block."))?; let ActionKind::Lookup { columns: old, .. } = &a.kind else { return Err(format!("{} is not a lookup action.", a.name)) }; + // The action's own lookup column is written first of its lookup columns (below), so it is the + // first one read back. let own = old.iter().find(|c| c.lookup).map(|c| c.node); let (action_handle, name) = (a.handle, a.name.clone()); @@ -171,7 +204,13 @@ fn write_table(d: &mut Drawing, block: &str, action: i32, columns: &[TableColumn { return Err(format!("{name} gives {}; its lookup column can't be removed.", column_property(&m, own, "lookupString"))); } - cols.sort_by_key(|(_, c)| c.lookup); + // Inputs first, then the action's own lookup column, then the other lookup columns, each in the + // caller's order. + cols.sort_by_key(|(_, c)| (c.lookup, !(c.lookup && Some(c.node) == own))); + let shown: Vec = { + let inputs = input_properties(&m); + cols.iter().map(|(_, c)| column_named(&m, &inputs, c.node, &c.property)).collect() + }; // The cells, in the columns' new order. let states = |node: i32| match m.parameters.iter().find(|p| p.node == node).map(|p| &p.kind) { @@ -187,9 +226,8 @@ fn write_table(d: &mut Drawing, block: &str, action: i32, columns: &[TableColumn continue; } let mut out = Vec::with_capacity(cols.len()); - for (i, c) in &cols { + for ((i, c), shown) in cols.iter().zip(&shown) { let cell = row.get(*i).map(|c| c.trim()).unwrap_or_default(); - let shown = column_property(&m, c.node, &c.property); if cell.is_empty() { return Err(format!("Row {}: {shown} needs a value.", r + 1)); } @@ -215,10 +253,10 @@ fn write_table(d: &mut Drawing, block: &str, action: i32, columns: &[TableColumn table.push(out); } let inputs = cols.iter().filter(|(_, c)| !c.lookup).count(); - let same_inputs = |a: &[String], b: &[String]| a.iter().zip(b).take(inputs).all(|(x, y)| same(x, y)); + let mut seen: HashSet> = HashSet::new(); let mut kept: Vec> = Vec::new(); for row in table { - if inputs > 0 && kept.iter().any(|k| same_inputs(k, &row)) { + if inputs > 0 && !seen.insert(row.iter().take(inputs).map(|c| cell_key(c)).collect()) { if dedupe { continue; } @@ -229,9 +267,13 @@ fn write_table(d: &mut Drawing, block: &str, action: i32, columns: &[TableColumn // A lookup column whose values repeat (or that has none) can't be reversed. let mut cols: Vec = cols.into_iter().map(|(_, c)| c).collect(); for (j, c) in cols.iter_mut().enumerate() { - let values: Vec<&String> = kept.iter().filter_map(|r| r.get(j)).collect(); - let repeats = values.iter().enumerate().any(|(i, v)| values.iter().take(i).any(|w| w.eq_ignore_ascii_case(v))); - c.reverse = c.lookup && c.reverse && !values.is_empty() && !repeats; + if !(c.lookup && c.reverse) { + c.reverse = false; + continue; + } + let mut values: HashSet = HashSet::new(); + let repeats = kept.iter().filter_map(|r| r.get(j)).any(|v| !values.insert(cell_key(v))); + c.reverse = !values.is_empty() && !repeats; } // The action's object: its table, and the flag AutoCAD changes once the table has inputs. @@ -315,6 +357,10 @@ fn write_table(d: &mut Drawing, block: &str, action: i32, columns: &[TableColumn /// one of them that isn't its own) loses those columns, and rows that then repeat another's /// inputs. Returns the lookup actions whose own parameter goes (they go with it). pub(super) fn drop_columns(d: &mut Drawing, block: &str, erased: &[i32]) -> Result, String> { + all_or_nothing(d, |d| drop_columns_in(d, block, erased)) +} + +fn drop_columns_in(d: &mut Drawing, block: &str, erased: &[i32]) -> Result, String> { let Some(m) = dynamic_block(d, block) else { return Ok(Vec::new()) }; let mut gone = Vec::new(); for a in &m.actions { @@ -557,6 +603,67 @@ mod tests { add_action(&mut d, "B", &ActionSpec::Lookup { parameter: lk, at: v(0.0, 0.0) }).unwrap(); } + #[test] + fn the_actions_own_lookup_column_stays_first_whatever_order_it_is_given_in() { + let (mut d, [lin, .., lk, act]) = block(); + let spec = + ParameterSpec::Lookup { at: v(-4.0, 7.0), label: Some("Other".into()), name: None, description: String::new(), show: true, grips: 1 }; + let other = add_parameter(&mut d, "B", &spec).unwrap(); + let rows = [row(&["1", "x", "a"]), row(&["2", "y", "b"])]; + set_lookup_table(&mut d, "B", act, &[col(lin, "UpdatedDistance", false), col(other, "", true), col(lk, "", true)], &rows).unwrap(); + let (cols, cells) = table(&d, act); + assert_eq!(cols.iter().map(|c| c.node).collect::>(), [lin, lk, other]); + assert_eq!(cells, [row(&["1", "a", "x"]), row(&["2", "b", "y"])]); + // The other lookup column can go; the action's own can't, whichever comes first. + let without = |keep: i32| [col(lin, "UpdatedDistance", false), col(keep, "", true)]; + assert!(set_lookup_table(&mut d.clone(), "B", act, &without(other), &[]).unwrap_err().contains("can't be removed")); + set_lookup_table(&mut d, "B", act, &without(lk), &[]).unwrap(); + } + + #[test] + fn lookup_values_that_read_the_same_number_repeat() { + let (mut d, [lin, .., lk, act]) = block(); + let cols = [col(lin, "UpdatedDistance", false), col(lk, "", true)]; + set_lookup_table(&mut d, "B", act, &cols, &[row(&["1", "10"]), row(&["2", "10.0"])]).unwrap(); + assert!(!table(&d, act).0[1].reverse, "10 and 10.0 repeat"); + assert_eq!(cell_key(" 10 "), cell_key("1e1")); + assert_eq!(cell_key("-0"), cell_key("0")); + assert_eq!(cell_key("Small"), cell_key("SMALL")); + assert_ne!(cell_key("10"), cell_key("10.5")); + } + + #[test] + fn a_table_at_its_row_limit_is_written_and_too_many_cells_are_refused() { + let (mut d, [lin, .., lk, act]) = block(); + let cols = [col(lin, "UpdatedDistance", false), col(lk, "", true)]; + let rows: Vec> = (0..MAX_LOOKUP_ROWS).map(|i| vec![i.to_string(), format!("v{i}")]).collect(); + set_lookup_table(&mut d, "B", act, &cols, &rows).unwrap(); + assert_eq!(table(&d, act).1.len(), MAX_LOOKUP_ROWS); + assert!(table(&d, act).0[1].reverse, "every lookup value differs"); + let wide = vec![col(lk, "", true); MAX_CELLS / MAX_LOOKUP_ROWS + 1]; + let err = set_lookup_table(&mut d.clone(), "B", act, &wide, &vec![Vec::new(); MAX_LOOKUP_ROWS]).unwrap_err(); + assert!(err.contains("cells"), "{err}"); + } + + #[test] + fn an_erase_refused_partway_leaves_the_tables_as_they_were() { + let (mut d, [lin, .., lk, act]) = block(); + let cols = [col(lin, "UpdatedDistance", false), col(lk, "", true)]; + set_lookup_table(&mut d, "B", act, &cols, &[row(&["1", "a"])]).unwrap(); + let before = (*d.foreign).clone(); + // The distance's column goes first; the unknown id is refused after that. + assert!(erase_elements(&mut d, "B", &[lin, 9999]).is_err()); + assert!(*d.foreign == before, "nothing changed"); + assert_eq!(table(&d, act).0.len(), 2); + // A change that fails is undone whatever it did before failing. + let r: Result<(), String> = all_or_nothing(&mut d, |d| { + std::sync::Arc::make_mut(&mut d.foreign).objects.clear(); + Err("refused".into()) + }); + assert!(r.is_err()); + assert!(*d.foreign == before); + } + #[test] fn hostile_tables_are_refused() { let (d, [lin, .., lk, act]) = block(); diff --git a/crates/engine/src/blockedit.rs b/crates/engine/src/blockedit.rs index 470cb4b034..c5ddfab443 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -265,7 +265,7 @@ impl BlockEdit { // copy's). let mut remap = std::collections::HashMap::new(); if !name.eq_ignore_ascii_case(&self.name) { - remap = cadcraft_doc::dynblock::copy_definition(&mut d, &self.name, name, &mut entities); + remap = cadcraft_doc::dynblock::copy_definition(&mut d, &self.name, name, &mut entities).map_err(EngineError::Other)?; cadcraft_doc::dynblock::restore_definition(&mut d, host, &self.name); } // Objects drawn in the editor show in the visibility state it shows only, as in AutoCAD. diff --git a/crates/ui-egui/src/blookup.rs b/crates/ui-egui/src/blookup.rs index 3c74812bfc..ffdae55562 100644 --- a/crates/ui-egui/src/blookup.rs +++ b/crates/ui-egui/src/blookup.rs @@ -9,7 +9,9 @@ //! with several lookup actions picks one at the top (the one picked in the editor first). JSON //! calls skip the dialog. -use cadcraft_engine::doc::dynblock::{ActionKind, DynamicBlock, ParameterKind, column_property, dynamic_block, input_properties, set_lookup_table}; +use cadcraft_engine::doc::dynblock::{ + ActionKind, DynamicBlock, ParameterKind, cell_key, column_property, dynamic_block, input_properties, set_lookup_table, +}; use egui::{RichText, Stroke, vec2}; use serde_json::{Map, Value, json}; @@ -80,10 +82,18 @@ impl State { self.columns.iter().filter(|c| !c.lookup).count() } - /// Whether lookup column `j`'s values repeat (or it has none): it can't be reversed then. + /// Whether lookup column `j`'s values repeat (or it has none): it can't be reversed then. Cells + /// compare as the table compares them when it is written ([`cell_key`]: `10` and `10.0` repeat). fn repeats(&self, j: usize) -> bool { - let values: Vec = self.rows.iter().filter_map(|r| r.get(j)).map(|v| v.trim().to_lowercase()).filter(|v| !v.is_empty()).collect(); - values.is_empty() || values.iter().enumerate().any(|(i, v)| values.iter().take(i).any(|w| w == v)) + let mut seen = std::collections::HashSet::new(); + let mut any = false; + for v in self.rows.iter().filter_map(|r| r.get(j)).filter(|v| !v.trim().is_empty()) { + any = true; + if !seen.insert(cell_key(v)) { + return true; + } + } + !any } /// Add `column` with an empty cell in every row: an input after the other inputs, a lookup From 850eeb14874b596cf6ccc984b3fb13d0ad0735e9 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:13:33 -0600 Subject: [PATCH 30/47] Dynamic blocks: BSAVEAS refuses a block too big to copy whole owned_subtree stops at MAX_COPIED objects; a copy of only part of a dynamic block's objects would keep pointing at the original's. copy_definition now refuses, changing nothing, and BSAVEAS reports it (review on #2184). Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/copy.rs | 30 +++++++++++++++++++++--------- crates/engine/src/blockedit.rs | 2 +- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/crates/doc/src/dynblock/copy.rs b/crates/doc/src/dynblock/copy.rs index a394810dd3..6742c6f888 100644 --- a/crates/doc/src/dynblock/copy.rs +++ b/crates/doc/src/dynblock/copy.rs @@ -54,6 +54,16 @@ fn owned_subtree(d: &Drawing, root: Handle) -> Vec { out } +/// [`owned_subtree`], refused when it reaches [`MAX_COPIED`]: a copy of only part of it would keep +/// pointing at the original's objects. +fn whole_subtree(d: &Drawing, root: Handle) -> Result, String> { + let out = owned_subtree(d, root); + if out.len() >= MAX_COPIED { + return Err(format!("The dynamic block has {MAX_COPIED} or more objects; it can't be copied.")); + } + Ok(out) +} + /// The handle `h` names, as `map` has it. fn mapped(map: &HashMap, value: &str) -> Option { Handle::parse_hex(value).and_then(|h| map.get(&h)).copied() @@ -166,20 +176,22 @@ fn rename_in_xdata(xdata: &mut [RawTag], name: &str, guid: &str) { /// original's with new handles, and its own true name and GUID. What `to` had of dynamic data goes /// first (a block replaced by one that isn't dynamic keeps none). Returns the handles the objects /// of `store` got, by their old ones; nothing changes when `from` has no dynamic data or is `to`. -pub fn copy_definition(d: &mut Drawing, from: &str, to: &str, store: &mut EntityStore) -> HashMap { +/// Refused, changing nothing, when `from` has too many objects to copy whole. +pub fn copy_definition(d: &mut Drawing, from: &str, to: &str, store: &mut EntityStore) -> Result, String> { let (from_name, to_name) = (from.trim().to_ascii_uppercase(), to.trim().to_ascii_uppercase()); let key = |n: &str| ("BLOCK_RECORD".to_string(), n.to_string()); if from_name == to_name { - return HashMap::new(); + return Ok(HashMap::new()); } + let source = d.foreign.records.get(&key(&from_name)).cloned(); + let owned = match source.as_ref().and_then(|s| s.xdict) { + Some(xdict) if dynamic_block(d, from).is_some() => Some(whole_subtree(d, xdict)?), + _ => None, + }; remove_definition(d, &to_name); - if dynamic_block(d, from).is_none() { - return HashMap::new(); - } - let Some(source) = d.foreign.records.get(&key(&from_name)).cloned() else { return HashMap::new() }; - let Some(xdict) = source.xdict else { return HashMap::new() }; + let (Some(source), Some(owned)) = (source, owned) else { return Ok(HashMap::new()) }; + let Some(xdict) = source.xdict else { return Ok(HashMap::new()) }; let graph = dict_entry(d, xdict, "ACAD_ENHANCEDBLOCK"); - let owned = owned_subtree(d, xdict); let owned_set: HashSet = owned.iter().copied().collect(); let mut map: HashMap = owned.iter().map(|h| (*h, d.new_handle())).collect(); let old_record = d.foreign.targets.iter().find(|(_, (k, n))| k == "BLOCK_RECORD" && *n == from_name).map(|(h, _)| *h); @@ -209,5 +221,5 @@ pub fn copy_definition(d: &mut Drawing, from: &str, to: &str, store: &mut Entity f.entities.extend(extras); let made = store.iter().filter_map(|e| Some((e.handle, *map.get(&e.handle)?))).collect(); *store = entities; - made + Ok(made) } diff --git a/crates/engine/src/blockedit.rs b/crates/engine/src/blockedit.rs index ea20dff475..4f7e16da36 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -207,7 +207,7 @@ impl BlockEdit { // copy's). let mut remap = std::collections::HashMap::new(); if !name.eq_ignore_ascii_case(&self.name) { - remap = cadcraft_doc::dynblock::copy_definition(&mut d, &self.name, name, &mut entities); + remap = cadcraft_doc::dynblock::copy_definition(&mut d, &self.name, name, &mut entities).map_err(EngineError::Other)?; cadcraft_doc::dynblock::restore_definition(&mut d, host, &self.name); } // A dynamic block's objects carry element tags, which its references' copies are paired From dbf8a7303a79b72f8700593b3b94c08afae28fb8 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:15:07 -0600 Subject: [PATCH 31/47] Dynamic blocks: BSAVEAS refuses a block too big to copy whole owned_subtree stops at MAX_COPIED objects; a copy of only part of a dynamic block's objects would keep pointing at the original's. copy_definition now refuses, changing nothing, and BSAVEAS reports it (review on #2184). Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/copy.rs | 30 +++++++++++++++++++++--------- crates/engine/src/blockedit.rs | 2 +- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/crates/doc/src/dynblock/copy.rs b/crates/doc/src/dynblock/copy.rs index a394810dd3..6742c6f888 100644 --- a/crates/doc/src/dynblock/copy.rs +++ b/crates/doc/src/dynblock/copy.rs @@ -54,6 +54,16 @@ fn owned_subtree(d: &Drawing, root: Handle) -> Vec { out } +/// [`owned_subtree`], refused when it reaches [`MAX_COPIED`]: a copy of only part of it would keep +/// pointing at the original's objects. +fn whole_subtree(d: &Drawing, root: Handle) -> Result, String> { + let out = owned_subtree(d, root); + if out.len() >= MAX_COPIED { + return Err(format!("The dynamic block has {MAX_COPIED} or more objects; it can't be copied.")); + } + Ok(out) +} + /// The handle `h` names, as `map` has it. fn mapped(map: &HashMap, value: &str) -> Option { Handle::parse_hex(value).and_then(|h| map.get(&h)).copied() @@ -166,20 +176,22 @@ fn rename_in_xdata(xdata: &mut [RawTag], name: &str, guid: &str) { /// original's with new handles, and its own true name and GUID. What `to` had of dynamic data goes /// first (a block replaced by one that isn't dynamic keeps none). Returns the handles the objects /// of `store` got, by their old ones; nothing changes when `from` has no dynamic data or is `to`. -pub fn copy_definition(d: &mut Drawing, from: &str, to: &str, store: &mut EntityStore) -> HashMap { +/// Refused, changing nothing, when `from` has too many objects to copy whole. +pub fn copy_definition(d: &mut Drawing, from: &str, to: &str, store: &mut EntityStore) -> Result, String> { let (from_name, to_name) = (from.trim().to_ascii_uppercase(), to.trim().to_ascii_uppercase()); let key = |n: &str| ("BLOCK_RECORD".to_string(), n.to_string()); if from_name == to_name { - return HashMap::new(); + return Ok(HashMap::new()); } + let source = d.foreign.records.get(&key(&from_name)).cloned(); + let owned = match source.as_ref().and_then(|s| s.xdict) { + Some(xdict) if dynamic_block(d, from).is_some() => Some(whole_subtree(d, xdict)?), + _ => None, + }; remove_definition(d, &to_name); - if dynamic_block(d, from).is_none() { - return HashMap::new(); - } - let Some(source) = d.foreign.records.get(&key(&from_name)).cloned() else { return HashMap::new() }; - let Some(xdict) = source.xdict else { return HashMap::new() }; + let (Some(source), Some(owned)) = (source, owned) else { return Ok(HashMap::new()) }; + let Some(xdict) = source.xdict else { return Ok(HashMap::new()) }; let graph = dict_entry(d, xdict, "ACAD_ENHANCEDBLOCK"); - let owned = owned_subtree(d, xdict); let owned_set: HashSet = owned.iter().copied().collect(); let mut map: HashMap = owned.iter().map(|h| (*h, d.new_handle())).collect(); let old_record = d.foreign.targets.iter().find(|(_, (k, n))| k == "BLOCK_RECORD" && *n == from_name).map(|(h, _)| *h); @@ -209,5 +221,5 @@ pub fn copy_definition(d: &mut Drawing, from: &str, to: &str, store: &mut Entity f.entities.extend(extras); let made = store.iter().filter_map(|e| Some((e.handle, *map.get(&e.handle)?))).collect(); *store = entities; - made + Ok(made) } diff --git a/crates/engine/src/blockedit.rs b/crates/engine/src/blockedit.rs index 470cb4b034..c5ddfab443 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -265,7 +265,7 @@ impl BlockEdit { // copy's). let mut remap = std::collections::HashMap::new(); if !name.eq_ignore_ascii_case(&self.name) { - remap = cadcraft_doc::dynblock::copy_definition(&mut d, &self.name, name, &mut entities); + remap = cadcraft_doc::dynblock::copy_definition(&mut d, &self.name, name, &mut entities).map_err(EngineError::Other)?; cadcraft_doc::dynblock::restore_definition(&mut d, host, &self.name); } // Objects drawn in the editor show in the visibility state it shows only, as in AutoCAD. From 5895689196f360cb968aa8ee237b1f3090835db5 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:38:42 -0600 Subject: [PATCH 32/47] i18n: Chinese for the Lookup Table command Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/zh.tsv | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 2ff4fd2538..6f75034435 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1506,3 +1506,4 @@ menu View 视图 Move Parameters and Actions 移动参数和动作 Move a Parameter's Point 移动参数的点 Parameter Points 参数点 + Lookup Table 查寻表 From c6b4e4c68e5e9264d2d0bd3f2a5a61070d07cf8f Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:09:07 -0600 Subject: [PATCH 33/47] i18n: Chinese for the Parameter and Action commands Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/zh.tsv | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 0e6409b522..3cc3e71489 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1476,6 +1476,8 @@ menu View 视图 Ctrl+Enter to apply Ctrl+Enter 应用 Edit Text 编辑文字 The drawing changed. Close the window and open it again. 图纸已切换。请关闭窗口后重新打开。 + Parameter 参数 + Action 动作 # ArtCraft feature naming Additional Tools 其他工具 From 918af228e1f451469241b69cae072e045f7a4437 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:57:13 -0600 Subject: [PATCH 34/47] File access: BPARAMETER and BACTION touch no file Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/file_access/commands.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/engine/src/file_access/commands.rs b/crates/engine/src/file_access/commands.rs index 7b26f14f8b..4ba9f1b0cc 100644 --- a/crates/engine/src/file_access/commands.rs +++ b/crates/engine/src/file_access/commands.rs @@ -267,6 +267,8 @@ pub const NO_FILES: &[&str] = &[ "bsave", "bsaveas", "bclose", + "bparameter", + "baction", "erase", "oops", "move", From 681ee73943e1a57b309645ac19fe5edaabaefae5 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:58:40 -0600 Subject: [PATCH 35/47] File access: BLOOKUPTABLE touches no file Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/file_access/commands.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/file_access/commands.rs b/crates/engine/src/file_access/commands.rs index 9f5dc6920a..852a1c390f 100644 --- a/crates/engine/src/file_access/commands.rs +++ b/crates/engine/src/file_access/commands.rs @@ -272,6 +272,7 @@ pub const NO_FILES: &[&str] = &[ "bvstate", "bvhide", "bvshow", + "blookuptable", "blocks.element.select", "blocks.element.point", "blocks.element.points", From 351e9a8effb8010d29513d86646667a1ebfff53e Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:57:32 -0600 Subject: [PATCH 36/47] fmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index cf28730aef..51b14bd1a3 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -934,7 +934,8 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { app.canvas.press = None; } let pressed_primary = pressed_primary && !picked && !hatch_dialog && !idle_dbl; - let cycled = pressed_primary && !click_used && !middle_down && cycle_click(app, ui.ctx(), &xf, hover_pos, raw_world.filter(|_| inside), mods.shift); + let cycled = + pressed_primary && !click_used && !middle_down && cycle_click(app, ui.ctx(), &xf, hover_pos, raw_world.filter(|_| inside), mods.shift); // Clicks the presses above left alone: on grips, and during ZOOM Realtime. if inside && pressed_primary From 0bbb7f5002534784d9712951d2933fcaacb98f5d Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:06:38 -0600 Subject: [PATCH 37/47] Dynamic blocks: lookups follow main's evaluation (drop this branch's position chaining and base field) Main now evaluates and sets positions in lookup tables itself and chains the lookups once after any grip drag; this branch's own versions are removed. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/apply.rs | 2 -- crates/doc/src/dynblock/reference.rs | 4 +--- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index 50b55a9ac1..239a27acb6 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -594,8 +594,6 @@ pub fn drag_grip(d: &mut Drawing, insert: Handle, node: i32, part: super::GripPa (ParameterKind::Point { label, .. }, GripPart::At) => { let Some(Val::Point(at)) = current(&m, &r.values, node) else { return Err(format!("{label} has no position.")) }; plan.set.insert(node, Val::Point(Vec3::new(q.x, q.y, at.z))); - plan.chain(&m, &r.values, node, "UpdatedX")?; - plan.chain(&m, &r.values, node, "UpdatedY")?; } // The end grip goes where it is dragged (its distance snapped to the value set); the base // grip moves the base, keeping the end. diff --git a/crates/doc/src/dynblock/reference.rs b/crates/doc/src/dynblock/reference.rs index 505ca9fb2c..a14e5a064a 100644 --- a/crates/doc/src/dynblock/reference.rs +++ b/crates/doc/src/dynblock/reference.rs @@ -193,8 +193,6 @@ fn same(cell: &str, value: &str) -> bool { struct Current<'a> { m: &'a DynamicBlock, values: &'a BTreeMap, - /// The block's base point (table cells give positions from it). - base: Vec3, } impl Current<'_> { @@ -251,7 +249,7 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec Date: Sun, 29 Nov 2026 08:42:45 -0600 Subject: [PATCH 38/47] Block Editor: egui's ComboBox, as main's craft-ui port uses Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/blockedit.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/blockedit.rs b/crates/ui-egui/src/canvas/blockedit.rs index da7c76d662..503b473c1d 100644 --- a/crates/ui-egui/src/canvas/blockedit.rs +++ b/crates/ui-egui/src/canvas/blockedit.rs @@ -151,7 +151,7 @@ pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, p: &egui::Painter, xf { toggle_mode = true; } - craft_ui::ComboBox::from_id_salt("cadcraft-block-editor-state").selected_text(v.current.as_str()).show_ui(ui, |ui| { + egui::ComboBox::from_id_salt("cadcraft-block-editor-state").selected_text(v.current.as_str()).show_ui(ui, |ui| { for n in &v.names { if ui.selectable_label(*n == v.current, n.as_str()).clicked() && *n != v.current { pick = Some(n.clone()); From 349e3b69bd464f43b862f7b69a78b4f8146dced3 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:42:47 -0600 Subject: [PATCH 39/47] Lookup tables: egui's ComboBox, as main's craft-ui port uses Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/blookup.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/blookup.rs b/crates/ui-egui/src/blookup.rs index ffdae55562..bb48851b7e 100644 --- a/crates/ui-egui/src/blookup.rs +++ b/crates/ui-egui/src/blookup.rs @@ -231,7 +231,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { ui.label(crate::tl!("Action name:")); let current = st.actions.iter().find(|(id, _)| *id == st.action).map(|(_, n)| n.clone()).unwrap_or_default(); if st.actions.len() > 1 { - craft_ui::ComboBox::from_id_salt("blookup-action").selected_text(current).show_ui(ui, |ui| { + egui::ComboBox::from_id_salt("blookup-action").selected_text(current).show_ui(ui, |ui| { for (id, n) in &st.actions { if ui.selectable_label(*id == st.action, n.as_str()).clicked() && *id != st.action { switch = Some(*id); @@ -443,7 +443,7 @@ fn pane(ui: &mut egui::Ui, st: &mut State, title: &str, cols: std::ops::Range Date: Mon, 30 Nov 2026 08:45:55 -0600 Subject: [PATCH 40/47] Translations to craft-i18n, tests into the crates' it binaries (AGENTS.md rules 16 and 30) The Ukrainian and Chinese rows this PR added to the app catalogs are removed; the English keys stay, and show until craft-i18n has them. The authoring tests join the engine's and io's tests/it binaries. Co-Authored-By: Claude Opus 5.5 --- crates/engine/tests/{ => it}/block_authoring.rs | 0 crates/engine/tests/it/main.rs | 1 + crates/io/tests/{ => it}/dynblock_author.rs | 0 crates/io/tests/it/main.rs | 1 + crates/ui-egui/src/i18n/uk.tsv | 2 -- crates/ui-egui/src/i18n/zh.tsv | 2 -- 6 files changed, 2 insertions(+), 4 deletions(-) rename crates/engine/tests/{ => it}/block_authoring.rs (100%) rename crates/io/tests/{ => it}/dynblock_author.rs (100%) diff --git a/crates/engine/tests/block_authoring.rs b/crates/engine/tests/it/block_authoring.rs similarity index 100% rename from crates/engine/tests/block_authoring.rs rename to crates/engine/tests/it/block_authoring.rs diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index f3c29674b8..eee8ab21ef 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -16,6 +16,7 @@ mod attrib_props; mod attribute_tag_matching; mod attribute_tools; mod attribute_value_baseline; +mod block_authoring; mod block_description; mod block_keep; mod block_redefine; diff --git a/crates/io/tests/dynblock_author.rs b/crates/io/tests/it/dynblock_author.rs similarity index 100% rename from crates/io/tests/dynblock_author.rs rename to crates/io/tests/it/dynblock_author.rs diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index c45a576587..6b2a66d91e 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -28,6 +28,7 @@ mod dwg_roundtrip_losses; mod dwt_template; mod dxf_versions; mod dynblock_array; +mod dynblock_author; mod dynblock_params; mod dynblock_read; mod dynblock_rotate_flip; diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d6123eedef..6e85ae7b00 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -96,8 +96,6 @@ Block Attribute Manager... Диспетчер атрибутів блоків... Block Description... Опис блока... Block Editor Редактор блоків - Parameter Параметр - Action Дія Block Reference Посилання на блок Block... Блок... Blocks Блоки diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index e4403c60ca..bd89cb65f5 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1524,8 +1524,6 @@ menu View 视图 Ctrl+Enter to apply Ctrl+Enter 应用 Edit Text 编辑文字 The drawing changed. Close the window and open it again. 图纸已切换。请关闭窗口后重新打开。 - Parameter 参数 - Action 动作 # ArtCraft feature naming Additional Tools 其他工具 From 6ee02e972665df579b6e82503188947150e70566 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 08:46:18 -0600 Subject: [PATCH 41/47] Translations to craft-i18n, tests into the engine's it binary (AGENTS.md rules 16 and 30) The Chinese and Ukrainian rows this PR added to the app catalogs are removed; the English keys stay. The block element tests join crates/engine/tests/it. Co-Authored-By: Claude Opus 5.5 --- crates/engine/tests/{ => it}/block_elements.rs | 0 crates/engine/tests/it/main.rs | 1 + 2 files changed, 1 insertion(+) rename crates/engine/tests/{ => it}/block_elements.rs (100%) diff --git a/crates/engine/tests/block_elements.rs b/crates/engine/tests/it/block_elements.rs similarity index 100% rename from crates/engine/tests/block_elements.rs rename to crates/engine/tests/it/block_elements.rs diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index eee8ab21ef..e998c53c17 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -18,6 +18,7 @@ mod attribute_tools; mod attribute_value_baseline; mod block_authoring; mod block_description; +mod block_elements; mod block_keep; mod block_redefine; mod blockreplace; From adc0848b27df453d95cc41e78649b7de0f55f333 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 08:47:08 -0600 Subject: [PATCH 42/47] Translations to craft-i18n, tests into the engine's it binary (AGENTS.md rules 16 and 30) Co-Authored-By: Claude Opus 5.5 --- crates/engine/tests/{ => it}/block_lookup.rs | 0 crates/engine/tests/it/main.rs | 1 + 2 files changed, 1 insertion(+) rename crates/engine/tests/{ => it}/block_lookup.rs (100%) diff --git a/crates/engine/tests/block_lookup.rs b/crates/engine/tests/it/block_lookup.rs similarity index 100% rename from crates/engine/tests/block_lookup.rs rename to crates/engine/tests/it/block_lookup.rs diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index e998c53c17..542ea1d3cd 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -20,6 +20,7 @@ mod block_authoring; mod block_description; mod block_elements; mod block_keep; +mod block_lookup; mod block_redefine; mod blockreplace; mod break_closed_polyline; From 8906452162deb3d8e8aa2067fcb6a3d94f113d78 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:53:04 -0600 Subject: [PATCH 43/47] Lookup tables: switching actions keeps each table's edits, and OK writes every changed one Choosing another action in the Property Lookup Table dialog reloaded the dialog from the block, dropping what had been typed into the table shown, with no warning and no Apply button to save it first. Each action's table is now kept as a draft while the dialog is open: switching back shows it as it was left, and OK audits every changed table before writing any, then writes them all; a table that fails the audit is shown with the reason. FredApps on #2184. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/blookup.rs | 80 +++++++++++++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/blookup.rs b/crates/ui-egui/src/blookup.rs index bb48851b7e..b19049eb5b 100644 --- a/crates/ui-egui/src/blookup.rs +++ b/crates/ui-egui/src/blookup.rs @@ -53,6 +53,10 @@ pub struct State { pub adding: Option, /// Audit's verdict or why OK was refused (`true`: a problem). pub message: Option<(String, bool)>, + /// The tables of the other lookup actions shown since the dialog opened, as last edited: the + /// Action name list switches between them without losing what was typed, and OK writes every + /// one that changed. + drafts: std::collections::BTreeMap, } impl State { @@ -123,6 +127,31 @@ impl State { j != self.inputs() && j < self.columns.len() } + /// Show action `id`: the current table is kept as a draft, and `id`'s draft, if it has one, + /// comes back as it was left; otherwise its table is loaded from block `m`. + fn switch_to(&mut self, m: &DynamicBlock, id: i32) { + if id == self.action { + return; + } + let mut drafts = std::mem::take(&mut self.drafts); + let mut next = drafts.remove(&id).unwrap_or_else(|| State::load(m, id)); + let mut current = std::mem::take(self); + (current.adding, current.message) = (None, None); + drafts.insert(current.action, current); + next.drafts = drafts; + *self = next; + } + + /// The tables OK writes: each other action's draft that differs from block `m`'s table, then + /// the one shown (always, as before there were drafts). + fn to_write(&self, m: &DynamicBlock) -> Vec<&State> { + let saved = |st: &State| { + let s = State::load(m, st.action); + s.columns == st.columns && s.rows == st.rows + }; + self.drafts.values().filter(|d| !saved(d)).chain(std::iter::once(self)).collect() + } + /// The `blookuptable` parameters writing this table. fn params(&self) -> Value { let names = |lookup: bool| self.columns.iter().filter(|c| c.lookup == lookup).map(|c| c.name.clone()).collect::>(); @@ -279,7 +308,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { add_dialog(ctx, &mut st, &m); } if let Some(id) = switch { - st = State::load(&m, id); + st.switch_to(&m, id); } if audit { st.message = Some(match st.audit(&app.session.state().map(|s| s.doc.clone()).unwrap_or_default(), &block) { @@ -288,9 +317,11 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { }); } if ok { - match app.run("blookuptable", st.params()) { - Ok(_) => *open = false, - Err(e) => { + match write_tables(app, &st, &m, &block) { + Ok(()) => *open = false, + Err((action, e)) => { + // The table that was refused is shown with the reason. + st.switch_to(&m, action); st.message = Some((e, true)); app.blookup = st; return; @@ -303,6 +334,21 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { app.blookup = st; } +/// OK: write the changed tables of `st` (every edited action's, then the one shown). Each is +/// audited first, so a table AutoCAD would refuse stops OK before anything is written; `Err` +/// names its action and the reason. +fn write_tables(app: &mut CadApp, st: &State, m: &DynamicBlock, block: &str) -> Result<(), (i32, String)> { + let tables = st.to_write(m); + let doc = app.session.state().map(|s| s.doc.clone()).unwrap_or_default(); + for t in &tables { + t.audit(&doc, block).map_err(|e| (t.action, e))?; + } + for t in tables { + app.run("blookuptable", t.params()).map_err(|e| (t.action, e))?; + } + Ok(()) +} + /// The grid's row height, header height and row-number column width. const ROW_H: f32 = 26.0; const HEAD_H: f32 = 28.0; @@ -688,6 +734,32 @@ mod tests { assert!(app.blookup.columns[3].reverse); } + #[test] + fn switching_actions_keeps_each_tables_edits_and_ok_writes_them_all() { + let mut app = editing(); + let size = app.session.execute("baction", &json!({ "parameter": "Size" })).unwrap()["node"].as_i64().unwrap() as i32; + app.session.execute("bparameter", &json!({ "type": "lookup", "at": [-2, 9], "label": "Finish" })).unwrap(); + let finish = app.session.execute("baction", &json!({ "parameter": "Finish" })).unwrap()["node"].as_i64().unwrap() as i32; + assert!(open(&mut app, size)); + let m = dynamic_block(&app.session.state().unwrap().doc, "B").unwrap(); + // A row typed into Size's table, then Finish shown and edited too. + app.blookup.rows = vec![vec!["Big".into()]]; + app.blookup.switch_to(&m, finish); + assert!(app.blookup.rows.is_empty(), "Finish's own table"); + app.blookup.rows = vec![vec!["Matt".into()]]; + // Back to Size: its row is still there; and Finish's too, when it is shown again. + app.blookup.switch_to(&m, size); + assert_eq!(app.blookup.rows, [vec!["Big".to_string()]]); + app.blookup.switch_to(&m, finish); + assert_eq!(app.blookup.rows, [vec!["Matt".to_string()]]); + // OK writes both tables. + let st = app.blookup.clone(); + write_tables(&mut app, &st, &m, "B").unwrap(); + let rows = |app: &mut CadApp, action: i32| app.session.execute("blookuptable", &json!({ "action": action })).unwrap()["rows"].clone(); + assert_eq!(rows(&mut app, size), json!([["Big"]])); + assert_eq!(rows(&mut app, finish), json!([["Matt"]])); + } + #[test] fn audit_and_reverse_lookup_follow_autocads_rules() { let mut app = editing(); From 218faa71bfa60334464e89ad75746f40d0c18d25 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:18:38 -0600 Subject: [PATCH 44/47] Translations: the Chinese labels of BPARAMETER and BACTION stay, as the #1129 coverage test requires The app's Chinese menu and command coverage test reads the in-repo catalog, so the rows for these two command labels come back; the other translation rows stay out (craft-i18n). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/zh.tsv | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index bd89cb65f5..8b5183f8e4 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1527,3 +1527,5 @@ menu View 视图 # ArtCraft feature naming Additional Tools 其他工具 + Parameter 参数 + Action 动作 From 0917bbf541c59963835b84928e3acc68da9f3b1e Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:18:52 -0600 Subject: [PATCH 45/47] Translations: the Chinese labels the #1129 coverage test requires stay The Chinese menu and command coverage test reads the in-repo catalog, so the rows for this PR's command and menu labels come back; the other translation rows stay out (craft-i18n). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/zh.tsv | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 8b5183f8e4..ac8ba12122 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1529,3 +1529,11 @@ menu View 视图 Additional Tools 其他工具 Parameter 参数 Action 动作 + Visibility States 可见性状态 + Make Visible 使可见 + Make Invisible 使不可见 + Pick Parameters and Actions 拾取参数和动作 + Erase Parameters and Actions 擦除参数和动作 + Move Parameters and Actions 移动参数和动作 + Move a Parameter's Point 移动参数的点 + Parameter Points 参数点 From 5d38e19c908072b0898a2bc83c0726d1a117bcb8 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:18:53 -0600 Subject: [PATCH 46/47] Translations: the Chinese label of BLOOKUPTABLE stays, as the #1129 coverage test requires Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/zh.tsv | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index ac8ba12122..7452d092f9 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1537,3 +1537,4 @@ menu View 视图 Move Parameters and Actions 移动参数和动作 Move a Parameter's Point 移动参数的点 Parameter Points 参数点 + Lookup Table 查寻表 From 947764e8c35227c2070ac0bd0780349321516ae3 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 1 Dec 2026 09:34:03 -0600 Subject: [PATCH 47/47] Lookup tables: OK writes every edited table as one undo step BLOOKUPTABLE takes `tables`, several tables' fills written as one command: the session records one undo step, and a table that is refused puts the drawing back, so no table is half written. The Property Lookup Table dialog's OK audits every changed table and then sends them in one such call. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/blocks/blookup.rs | 48 ++++++++++++++++++++++++- crates/engine/tests/it/block_lookup.rs | 36 +++++++++++++++++++ crates/ui-egui/src/blookup.rs | 26 +++++++++----- 3 files changed, 100 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/blocks/blookup.rs b/crates/engine/src/cmd/blocks/blookup.rs index fe39ecb846..103ae24ce5 100644 --- a/crates/engine/src/cmd/blocks/blookup.rs +++ b/crates/engine/src/cmd/blocks/blookup.rs @@ -19,7 +19,7 @@ pub(super) fn specs() -> Vec { vec![ CommandSpec::new("blookuptable", "Lookup Table", run) .params( - "{action?: graph id, action name (\"Lookup1\") or its lookup parameter's property name (default the block's only lookup action); to fill it: inputs?: [input property names: \"Distance1\", \"Position1 X\", \"Position1 Y\", \"Visibility1\"] (default the table's), lookups?: [lookup parameter property names] (default the table's; its own first), rows?: [[a cell per input, then per lookup]] (numbers in block units, visibility states by name), unmatched?: text (shown when no row matches; default Custom) | {property: text}, reverse?: bool | [lookup property names] (allow reverse lookup; default as it was)} → {action, name, columns: [{name, parameter, property, lookup, unmatched, reverse}], rows} (no fill: just the table)", + "{action?: graph id, action name (\"Lookup1\") or its lookup parameter's property name (default the block's only lookup action); to fill it: inputs?: [input property names: \"Distance1\", \"Position1 X\", \"Position1 Y\", \"Visibility1\"] (default the table's), lookups?: [lookup parameter property names] (default the table's; its own first), rows?: [[a cell per input, then per lookup]] (numbers in block units, visibility states by name), unmatched?: text (shown when no row matches; default Custom) | {property: text}, reverse?: bool | [lookup property names] (allow reverse lookup; default as it was)} → {action, name, columns: [{name, parameter, property, lookup, unmatched, reverse}], rows} (no fill: just the table); or {tables: [those fills, each naming its action]} → {tables: [...]}: several tables as one change (one undo step; a table refused leaves every table as it was)", ) .enabled(editing) .interactive(|_| Ok(Box::new(BlookupM))), @@ -128,7 +128,53 @@ fn names(p: &Value, key: &str) -> Result>> { } } +/// The most tables one `tables` call fills. +const MAX_TABLES: usize = 1_000; + fn run(s: &mut Session, p: &Value) -> Result { + match p.get("tables") { + None | Some(Value::Null) => fill(s, p), + Some(tables) => fill_all(s, tables), + } +} + +/// `tables`: several lookup tables filled as one change, as the Property Lookup Table dialog's OK +/// writes every table edited in it. The session records one undo step for the command, and a +/// table that is refused puts the drawing back as it was, so no table is half written. +fn fill_all(s: &mut Session, tables: &Value) -> Result { + let list = match tables { + Value::Array(list) if list.len() <= MAX_TABLES => list, + _ => return Err(bad("blookuptable", format!("`tables` is a list of at most {MAX_TABLES} tables"))), + }; + let before = s.state()?.doc.clone(); + let mut filled = Vec::with_capacity(list.len()); + for t in list { + let one = match t { + Value::Object(o) if !o.contains_key("tables") => fill(s, t), + _ => Err(bad("blookuptable", "each of `tables` is one table's fill: {action, inputs?, lookups?, rows?, unmatched?, reverse?}")), + }; + match one { + Ok(v) => filled.push(v), + Err(e) => { + s.state_mut()?.doc = before; + let action = t.get("action").map(Value::to_string).unwrap_or_default(); + return Err(bad("blookuptable", format!("lookup table {action} was refused, so no table was changed: {}", reason(e)))); + } + } + } + Ok(json!({ "tables": filled })) +} + +/// An error's message without the command name it already carries. +fn reason(e: EngineError) -> String { + match e { + EngineError::BadParams { msg, .. } => msg, + e => e.to_string(), + } +} + +/// One lookup table: listed, or filled from `p`. +fn fill(s: &mut Session, p: &Value) -> Result { let (name, m) = block(s)?; let action = action_named(&m, p.get("action"))?; let fill = ["inputs", "lookups", "rows", "unmatched", "reverse"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); diff --git a/crates/engine/tests/it/block_lookup.rs b/crates/engine/tests/it/block_lookup.rs index 87fb6ed475..dca2700c98 100644 --- a/crates/engine/tests/it/block_lookup.rs +++ b/crates/engine/tests/it/block_lookup.rs @@ -239,6 +239,11 @@ fn hostile_lookup_params_never_panic() { json!({ "unmatched": { "Nope": "x" } }), json!({ "reverse": "yes" }), json!({ "inputs": ["Distance1"] }), + json!({ "tables": 5 }), + json!({ "tables": [5] }), + json!({ "tables": [{ "tables": [] }] }), + json!({ "tables": (0..1_001).map(|_| json!({})).collect::>() }), + json!({ "tables": [{ "action": "Nope", "rows": [] }] }), ] { let _ = s.execute("blookuptable", &p); } @@ -299,3 +304,34 @@ fn a_lookup_on_a_position_follows_its_point() { assert!(custom(&s, &i).contains(&("Size".to_string(), "Big".to_string(), true)), "{:?}", custom(&s, &i)); assert_eq!(kept(&s), "Big"); } + +/// The Property Lookup Table dialog's OK writes every table edited in it as one `tables` call: +/// one undo step takes them all back, and a table that is refused leaves every table as it was. +#[test] +fn several_tables_are_written_as_one_step_or_not_at_all() { + let mut s = Session::new(); + boxed(&mut s); + let size = authored(&mut s); + s.execute("bparameter", &json!({ "type": "lookup", "at": [-2, 9], "label": "Finish" })).unwrap(); + let finish = s.execute("baction", &json!({ "parameter": "Finish" })).unwrap()["node"].as_i64().unwrap() as i32; + let rows = |s: &mut Session, action: i32| s.execute("blookuptable", &json!({ "action": action })).unwrap()["rows"].clone(); + let steps = |s: &Session| s.state().unwrap().undo.len(); + let original = (rows(&mut s, size), rows(&mut s, finish)); + let before = steps(&s); + // The second table repeats a row of inputs: refused, and the first isn't written either. + let good = json!({ "action": size, "inputs": ["Distance1"], "rows": [[10, "Big"], [6, "Small"]] }); + let refused = json!({ "action": finish, "inputs": ["Distance1"], "rows": [[1, "Matt"], ["1.0", "Gloss"]] }); + let e = s.execute("blookuptable", &json!({ "tables": [good, refused] })).unwrap_err().to_string(); + assert!(e.contains("no table was changed"), "{e}"); + assert_eq!((rows(&mut s, size), rows(&mut s, finish)), original); + assert_eq!(steps(&s), before, "nothing written, no undo step"); + // Both accepted: written together, as one undo step. + let finish_rows = json!({ "action": finish, "inputs": ["Distance1"], "rows": [[1, "Matt"], [2, "Gloss"]] }); + let r = s.execute("blookuptable", &json!({ "tables": [good, finish_rows] })).unwrap(); + assert_eq!(r["tables"].as_array().map(Vec::len), Some(2)); + assert_eq!(rows(&mut s, size), json!([["10", "Big"], ["6", "Small"]])); + assert_eq!(rows(&mut s, finish), json!([["1", "Matt"], ["2", "Gloss"]])); + assert_eq!(steps(&s), before + 1, "one undo step for both tables"); + s.undo().unwrap(); + assert_eq!((rows(&mut s, size), rows(&mut s, finish)), original, "one Undo restores both tables"); +} diff --git a/crates/ui-egui/src/blookup.rs b/crates/ui-egui/src/blookup.rs index b19049eb5b..71b35baffc 100644 --- a/crates/ui-egui/src/blookup.rs +++ b/crates/ui-egui/src/blookup.rs @@ -334,19 +334,19 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { app.blookup = st; } -/// OK: write the changed tables of `st` (every edited action's, then the one shown). Each is -/// audited first, so a table AutoCAD would refuse stops OK before anything is written; `Err` -/// names its action and the reason. +/// OK: write the changed tables of `st` (every edited action's, then the one shown) as one +/// `blookuptable` command, so one Undo takes them all back and a table the engine refuses leaves +/// every table as it was. Each is audited first, so a table AutoCAD would refuse stops OK before +/// anything is written; `Err` names its action (the one shown when the engine refuses) and the +/// reason. fn write_tables(app: &mut CadApp, st: &State, m: &DynamicBlock, block: &str) -> Result<(), (i32, String)> { let tables = st.to_write(m); let doc = app.session.state().map(|s| s.doc.clone()).unwrap_or_default(); for t in &tables { t.audit(&doc, block).map_err(|e| (t.action, e))?; } - for t in tables { - app.run("blookuptable", t.params()).map_err(|e| (t.action, e))?; - } - Ok(()) + let params: Vec = tables.iter().map(|t| t.params()).collect(); + app.run("blookuptable", json!({ "tables": params })).map(|_| ()).map_err(|e| (st.action, e)) } /// The grid's row height, header height and row-number column width. @@ -752,10 +752,18 @@ mod tests { assert_eq!(app.blookup.rows, [vec!["Big".to_string()]]); app.blookup.switch_to(&m, finish); assert_eq!(app.blookup.rows, [vec!["Matt".to_string()]]); - // OK writes both tables. + // OK writes both tables, as one step: one Undo restores both, Redo writes both again. + let rows = |app: &mut CadApp, action: i32| app.session.execute("blookuptable", &json!({ "action": action })).unwrap()["rows"].clone(); + let original = (rows(&mut app, size), rows(&mut app, finish)); + let undo_steps = app.session.state().unwrap().undo.len(); let st = app.blookup.clone(); write_tables(&mut app, &st, &m, "B").unwrap(); - let rows = |app: &mut CadApp, action: i32| app.session.execute("blookuptable", &json!({ "action": action })).unwrap()["rows"].clone(); + assert_eq!(rows(&mut app, size), json!([["Big"]])); + assert_eq!(rows(&mut app, finish), json!([["Matt"]])); + assert_eq!(app.session.state().unwrap().undo.len(), undo_steps + 1, "one OK, one undo step"); + app.session.undo().unwrap(); + assert_eq!((rows(&mut app, size), rows(&mut app, finish)), original, "one Undo restores both tables"); + app.session.redo().unwrap(); assert_eq!(rows(&mut app, size), json!([["Big"]])); assert_eq!(rows(&mut app, finish), json!([["Matt"]])); }