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/15] 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/15] 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/15] 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/15] 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/15] 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/15] 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/15] 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/15] 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/15] 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 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 10/15] 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 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 11/15] 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 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 12/15] 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 13/15] 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 fc42c330c54cdfaeda8949adaace07b8ab9ab5a5 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 08:45:55 -0600 Subject: [PATCH 14/15] 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 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 15/15] 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 动作