diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index 5d0a1d4564..d5ae22ef60 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 @@ -20,11 +21,24 @@ use crate::foreign::ForeignObject; use crate::{Drawing, Handle, RawTag}; mod apply; +mod copy; +mod edit; mod grips; +mod lookup; +mod marks; mod reference; +mod write; pub use apply::{align_grip, drag_grip, grip_stops, set_property}; +pub use copy::{copy_definition, remap_handles, restore_definition}; +pub use edit::{ElementPoint, element_points, erase_elements, move_element, set_element_point}; pub use grips::{DynGrip, GripPart, GripShape, grips}; +pub use lookup::{MAX_LOOKUP_ROWS, TableColumn, cell_key, column_property, input_properties, set_lookup_table}; +pub use marks::{Mark, marks}; pub use reference::{CustomProperty, Reference, Value, custom_properties, reference}; +pub use write::{ + ActionSpec, MAX_ACTION_ITEMS, MAX_VISIBILITY_STATES, ParamPoint, ParameterSpec, add_action, add_parameter, adopt_objects, parameter_objects, + set_visibility, tag_elements, +}; /// Most objects one evaluation graph is read with. const MAX_NODES: usize = 10_000; @@ -305,6 +319,9 @@ pub struct LookupColumn { pub lookup: bool, /// What the reference shows when no row matches ("Custom"). pub unmatched: String, + /// A lookup column whose value can be set on a reference, setting the row's inputs + /// ("Allow reverse lookup"); otherwise it is read only. + pub reverse: bool, } /// The groups of an object split at its subclass markers (100): `(marker, groups after it)`. @@ -743,8 +760,8 @@ fn polar_stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) { } /// A lookup table: rows (92) and columns (93), the cells row by row (302, after a 301 header), -/// then each column: unmatched name (303 then 305), parameter id (94), lookup flag (282) and the -/// parameter value it stands for (304). +/// then each column: parameter id (94, after an empty 303), lookup flag (282), unmatched name +/// (305), reverse lookup (281) and the parameter value it stands for (304). fn lookup(tags: &[RawTag]) -> ActionKind { let mut c = Cursor::new(tags); let rows = c.count(92); @@ -759,8 +776,9 @@ fn lookup(tags: &[RawTag]) -> ActionKind { let node = c.int(94); let lookup = c.int(282) != 0; let unmatched = c.string(305); + let reverse = c.int(281) != 0; let property = c.string(304); - LookupColumn { node, property, lookup, unmatched } + LookupColumn { node, property, lookup, unmatched, reverse } }) .collect(); ActionKind::Lookup { columns, rows } diff --git a/crates/doc/src/dynblock/copy.rs b/crates/doc/src/dynblock/copy.rs new file mode 100644 index 0000000000..6742c6f888 --- /dev/null +++ b/crates/doc/src/dynblock/copy.rs @@ -0,0 +1,225 @@ +//! 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::{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. +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 +} + +/// [`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() +} + +/// 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`). +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(); + 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() +} + +/// 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(); + 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. 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`. +/// 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 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); + 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_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); + let made = store.iter().filter_map(|e| Some((e.handle, *map.get(&e.handle)?))).collect(); + *store = entities; + Ok(made) +} diff --git a/crates/doc/src/dynblock/edit.rs b/crates/doc/src/dynblock/edit.rs new file mode 100644 index 0000000000..26e7fa8da7 --- /dev/null +++ b/crates/doc/src/dynblock/edit.rs @@ -0,0 +1,412 @@ +//! Editing a dynamic block's parameters and actions in the Block Editor: moving them, dragging +//! one of their points, erasing them. As AutoCAD does it (observed in files it saves): +//! +//! - Moving a parameter moves its points, its grips and its label; moving an action moves only +//! where it shows (its frame and selection stay). +//! - Erasing a parameter erases its grips, their location components and the actions that follow +//! it; erasing an action erases only it. The graph keeps every other node's id; node and edge +//! indices close up and the edges are linked again in their order. + +use cadcraft_geom::{Vec2, Vec3}; + +use super::write::{Graph, dict_entry, finite, real}; +use super::{ParameterKind, dynamic_block}; +use crate::foreign::ForeignObject; +use crate::{Drawing, Handle, RawTag}; + +/// A point of a parameter or action that can be dragged on its own. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ElementPoint { + /// A linear parameter's start point. + Base, + /// A linear parameter's endpoint. + End, + /// Where a one-point parameter is (a point, visibility or lookup parameter), or where an + /// action shows. + At, + /// A point parameter's label, or the line of a linear parameter's label (its offset). + Label, +} + +/// The block's graph object and its graph. +fn graph(d: &Drawing, block: &str) -> Result { + let key = ("BLOCK_RECORD".to_string(), block.trim().to_ascii_uppercase()); + let xdict = d.foreign.records.get(&key).and_then(|x| x.xdict).ok_or("The block has no parameters or actions.")?; + let g = dict_entry(d, xdict, "ACAD_ENHANCEDBLOCK").ok_or("The block has no parameters or actions.")?; + let o = d.foreign.objects.iter().find(|o| o.handle == g).ok_or("The block's evaluation graph is missing.")?; + Graph::read(o).ok_or_else(|| "The block's evaluation graph can't be changed.".to_string()) +} + +fn object_mut(d: &mut Drawing, h: Handle) -> Option<&mut ForeignObject> { + std::sync::Arc::make_mut(&mut d.foreign).objects.iter_mut().find(|o| o.handle == h) +} + +/// The groups of section `marker` (from its `100` marker to the next one) of `tags`. +fn section_range(tags: &[RawTag], marker: &str) -> Option> { + let start = tags.iter().position(|t| t.code == 100 && t.value.eq_ignore_ascii_case(marker))? + 1; + let end = tags.iter().skip(start).position(|t| t.code == 100).map_or(tags.len(), |n| start + n); + Some(start..end) +} + +/// The index of the first group `code` in section `marker`. +fn find(tags: &[RawTag], marker: &str, code: i32) -> Option { + let r = section_range(tags, marker)?; + let start = r.start; + tags.get(r)?.iter().position(|t| t.code == code).map(|i| start + i) +} + +/// The point at group `code` (x; y and z follow) in section `marker`. +fn point_at(tags: &[RawTag], marker: &str, code: i32) -> Option { + let i = find(tags, marker, code)?; + let v = |k: usize| tags.get(i + k).filter(|t| t.code == code + 10 * k as i32).and_then(|t| t.value.trim().parse::().ok()); + Some(Vec3::new(v(0)?, v(1)?, v(2).unwrap_or(0.0))) +} + +/// Set the point at group `code` in section `marker`; whether it was there. +fn set_point(tags: &mut [RawTag], marker: &str, code: i32, p: Vec3) -> bool { + let Some(i) = find(tags, marker, code) else { return false }; + for (k, v) in [p.x, p.y, p.z].into_iter().enumerate() { + let c = code + 10 * k as i32; + if let Some(t) = tags.get_mut(i + k).filter(|t| t.code == c) { + *t = real(c, v); + } + } + true +} + +/// Set the real at group `code` in section `marker`. +fn set_real(tags: &mut [RawTag], marker: &str, code: i32, v: f64) { + if let Some(i) = find(tags, marker, code) + && let Some(t) = tags.get_mut(i) + { + *t = real(code, v); + } +} + +/// Element graph id `node` of `block`: its object's kind and handle, and its grips' handles by +/// position (a linear parameter's base grip first; `None` where it has no grip there). +struct Element { + kind: String, + handle: Handle, + param: Option, + grips: Vec>, +} + +fn element(d: &Drawing, block: &str, node: i32) -> Result { + let g = graph(d, block)?; + let n = g.nodes.iter().find(|n| n.id == node).ok_or_else(|| format!("No parameter or action {node} in the block."))?; + let o = d.foreign.objects.iter().find(|o| o.handle == n.handle).ok_or("The block's parameter is missing.")?; + let m = dynamic_block(d, block); + let p = m.as_ref().and_then(|m| m.parameters.iter().find(|p| p.node == node)); + let grips = match (&m, p) { + (Some(m), Some(p)) => p.grips.iter().map(|id| m.grip_objects.iter().find(|(g, _)| g == id).map(|(_, h)| *h)).collect(), + _ => Vec::new(), + }; + Ok(Element { kind: o.kind.clone(), handle: o.handle, param: p.map(|p| p.kind.clone()), grips }) +} + +fn is_action(kind: &str) -> bool { + kind.starts_with("BLOCK") && kind.ends_with("ACTION") +} + +/// Move a grip object to `at`, and point a linear grip along `dir`. +fn move_grip(d: &mut Drawing, grip: Handle, at: Vec3, dir: Option) { + if let Some(o) = object_mut(d, grip) { + set_point(&mut o.tags, "AcDbBlockGrip", 1010, at); + if let Some(dir) = dir { + for (code, v) in [(140, dir.x), (141, dir.y), (142, dir.z)] { + set_real(&mut o.tags, "AcDbBlockLinearGrip", code, v); + } + } + } +} + +/// Move parameter or action `node` of block `block` (any case) by `delta`. +pub fn move_element(d: &mut Drawing, block: &str, node: i32, delta: Vec3) -> Result<(), String> { + if !finite(delta) { + return Err("Invalid displacement.".into()); + } + let e = element(d, block, node)?; + let shifted = |tags: &[RawTag], marker: &str, code: i32| point_at(tags, marker, code).map(|p| p + delta).filter(|p| finite(*p)); + let tags = d.foreign.objects.iter().find(|o| o.handle == e.handle).map(|o| o.tags.clone()).unwrap_or_default(); + match (&e.param, e.kind.as_str()) { + (_, k) if is_action(k) => { + set_element_point(d, block, node, ElementPoint::At, shifted(&tags, "AcDbBlockAction", 1010).ok_or("Invalid point.")?) + } + (Some(ParameterKind::Linear { base, end, .. }), _) => { + let (b, n) = (*base + delta, *end + delta); + if !finite(b) || !finite(n) { + return Err("Invalid point.".into()); + } + if let Some(o) = object_mut(d, e.handle) { + set_point(&mut o.tags, "AcDbBlock2PtParameter", 1010, b); + set_point(&mut o.tags, "AcDbBlock2PtParameter", 1011, n); + } + for (grip, at) in e.grips.iter().zip([b, n]) { + if let Some(g) = grip { + move_grip(d, *g, at, None); + } + } + Ok(()) + } + (Some(ParameterKind::Point { .. }), _) => { + let label = shifted(&tags, "AcDbBlockPointParameter", 1011).ok_or("Invalid point.")?; + set_element_point(d, block, node, ElementPoint::At, shifted(&tags, "AcDbBlock1PtParameter", 1010).ok_or("Invalid point.")?)?; + set_element_point(d, block, node, ElementPoint::Label, label) + } + (Some(ParameterKind::Visibility { .. } | ParameterKind::Lookup { .. }), _) => { + set_element_point(d, block, node, ElementPoint::At, shifted(&tags, "AcDbBlock1PtParameter", 1010).ok_or("Invalid point.")?) + } + _ => Err("This parameter can't be moved yet.".into()), + } +} + +/// Put point `which` of parameter or action `node` of block `block` (any case) at `to` (block +/// coordinates). A linear parameter's grips turn with it; its label stays as far from its line. +pub fn set_element_point(d: &mut Drawing, block: &str, node: i32, which: ElementPoint, to: Vec3) -> Result<(), String> { + if !finite(to) { + return Err("Invalid point.".into()); + } + let e = element(d, block, node)?; + let none = || format!("That point of the {} can't be moved.", e.kind.to_ascii_lowercase()); + match (&e.param, which) { + (None, ElementPoint::At) if is_action(&e.kind) => { + let o = object_mut(d, e.handle).ok_or("The block's action is missing.")?; + set_point(&mut o.tags, "AcDbBlockAction", 1010, to); + Ok(()) + } + (Some(ParameterKind::Linear { base, end, .. }), ElementPoint::Base | ElementPoint::End) => { + let (b, n) = if which == ElementPoint::Base { (to, *end) } else { (*base, to) }; + let dir = n - b; + if !finite(dir) || dir.len() <= 1e-9 { + return Err("The endpoint must differ from the start point.".into()); + } + if let Some(o) = object_mut(d, e.handle) { + set_point(&mut o.tags, "AcDbBlock2PtParameter", if which == ElementPoint::Base { 1010 } else { 1011 }, to); + } + for (grip, (at, dir)) in e.grips.iter().zip([(b, -dir), (n, dir)]) { + if let Some(g) = grip { + move_grip(d, *g, at, Some(dir)); + } + } + Ok(()) + } + (Some(ParameterKind::Linear { base, end, .. }), ElementPoint::Label) => { + let (a, b, p) = (base.xy(), end.xy(), to.xy()); + let u = b - a; + let len = u.len(); + let offset = if len <= 1e-12 { 0.0 } else { (u.x * (p.y - a.y) - u.y * (p.x - a.x)) / len }; + let o = object_mut(d, e.handle).ok_or("The block's parameter is missing.")?; + set_real(&mut o.tags, "AcDbBlockLinearParameter", 140, offset); + Ok(()) + } + (Some(ParameterKind::Point { .. } | ParameterKind::Visibility { .. } | ParameterKind::Lookup { .. }), ElementPoint::At) => { + if let Some(o) = object_mut(d, e.handle) { + set_point(&mut o.tags, "AcDbBlock1PtParameter", 1010, to); + } + if let Some(Some(g)) = e.grips.first() { + move_grip(d, *g, to, None); + } + Ok(()) + } + (Some(ParameterKind::Point { .. }), ElementPoint::Label) => { + let o = object_mut(d, e.handle).ok_or("The block's parameter is missing.")?; + set_point(&mut o.tags, "AcDbBlockPointParameter", 1011, to); + Ok(()) + } + _ => Err(none()), + } +} + +/// Erase parameters and actions `nodes` of block `block` (any case), as AutoCAD erases them: a +/// parameter takes its grips, their location components and its actions along. Returns the +/// graph ids erased (the parameters' and actions'; grips and components aren't listed). All or +/// nothing: refused partway, the drawing is left as it was. +pub fn erase_elements(d: &mut Drawing, block: &str, nodes: &[i32]) -> Result, String> { + super::lookup::all_or_nothing(d, |d| erase_elements_in(d, block, nodes)) +} + +fn erase_elements_in(d: &mut Drawing, block: &str, nodes: &[i32]) -> Result, String> { + // Lookup tables lose the columns of parameters erased; a lookup parameter's own table goes. + let params: Vec = + dynamic_block(d, block).map(|m| m.parameters.iter().map(|p| p.node).filter(|n| nodes.contains(n)).collect()).unwrap_or_default(); + let tables = super::lookup::drop_columns(d, block, ¶ms)?; + let nodes: Vec = nodes.iter().copied().chain(tables.into_iter().filter(|t| !nodes.contains(t))).collect(); + // A lookup parameter whose table goes (and that stays) names no table any more. + if let Some(m) = dynamic_block(d, block) { + for a in m.actions.iter().filter(|a| nodes.contains(&a.node)) { + let super::ActionKind::Lookup { columns, .. } = &a.kind else { continue }; + for c in columns.iter().filter(|c| c.lookup && !nodes.contains(&c.node)) { + if let Some(p) = m.parameters.iter().find(|p| p.node == c.node) { + super::lookup::set_action_of(d, p.handle, 0); + } + } + } + } + let mut g = graph(d, block)?; + let kind_of = |h: Handle| d.foreign.objects.iter().find(|o| o.handle == h).map(|o| o.kind.clone()).unwrap_or_default(); + let index_of = |g: &Graph, id: i32| g.nodes.iter().find(|n| n.id == id).map(|n| n.index); + let mut gone: Vec = Vec::new(); // node indices + let mut erased: Vec = Vec::new(); // graph ids + for id in &nodes { + let Some(i) = index_of(&g, *id) else { return Err(format!("No parameter or action {id} in the block.")) }; + let kind = g.nodes.iter().find(|n| n.index == i).map(|n| kind_of(n.handle)).unwrap_or_default(); + if kind.contains("GRIP") { + return Err(format!("{id} is a grip; erase its parameter.")); + } + let take = |i: i32, gone: &mut Vec| { + if !gone.contains(&i) { + gone.push(i); + } + }; + take(i, &mut gone); + if !erased.contains(id) { + erased.push(*id); + } + if is_action(&kind) { + continue; + } + // A parameter: what it feeds (components, actions) and the grips that feed it. + for e in &g.edges { + let (other, outgoing) = if e.from == i { + (e.to, true) + } else if e.to == i { + (e.from, false) + } else { + continue; + }; + let Some(n) = g.nodes.iter().find(|n| n.index == other) else { continue }; + let k = kind_of(n.handle); + // A lookup table reading the parameter lost its column above. + let follows = outgoing && (k == "BLOCKGRIPLOCATIONCOMPONENT" || (is_action(&k) && k != "BLOCKLOOKUPACTION")); + let grip = !outgoing && k.contains("GRIP") && k != "BLOCKGRIPLOCATIONCOMPONENT"; + if follows || grip { + take(other, &mut gone); + if is_action(&k) && !erased.contains(&n.id) { + erased.push(n.id); + } + } + // A grip's components hang off the parameter, so they are caught above. + } + } + let handles: Vec = g.nodes.iter().filter(|n| gone.contains(&n.index)).map(|n| n.handle).collect(); + // What stays, its indices closed up and its edges linked again in their order. + let kept: Vec<_> = g.nodes.iter().filter(|n| !gone.contains(&n.index)).cloned().collect(); + let renumber: Vec<(i32, i32)> = kept.iter().zip(0..).map(|(n, i)| (n.index, i)).collect(); + let new_index = |old: i32| renumber.iter().find(|(o, _)| *o == old).map(|(_, n)| *n); + // An edge keeps its flags (a graph read from a file may have set some) and its pair. + let edges = g.kept_edges(|_| false, new_index); + g.nodes = kept; + for (n, i) in g.nodes.iter_mut().zip(0..) { + n.index = i; + } + g.relink(&edges); + let erased_handles: Vec = handles.clone(); + let f = std::sync::Arc::make_mut(&mut d.foreign); + let tags = g.tags(); + if let Some(o) = f.objects.iter_mut().find(|o| o.handle == g.handle) { + o.tags = tags; + } + f.objects.retain(|o| !handles.contains(&o.handle)); + // Visibility states no longer list what was erased. + drop_from_states(d, block, &erased_handles)?; + Ok(erased) +} + +/// Remove `handles` from the visibility parameter's state lists (parameters and grips shown). +fn drop_from_states(d: &mut Drawing, block: &str, handles: &[Handle]) -> Result<(), String> { + let Some(m) = dynamic_block(d, block) else { return Ok(()) }; + let Some(ParameterKind::Visibility { controlled, states, .. }) = + m.parameters.into_iter().map(|p| p.kind).find(|k| matches!(k, ParameterKind::Visibility { .. })) + else { + return Ok(()); + }; + if !states.iter().any(|s| s.active.iter().any(|h| handles.contains(h))) { + return Ok(()); + } + let mut states = states; + for s in &mut states { + s.active.retain(|h| !handles.contains(h)); + } + super::set_visibility(d, block, &controlled, &states) +} + +/// A parameter or action's points the Block Editor can drag, in block coordinates. +pub fn element_points(d: &Drawing, block: &str, node: i32) -> Vec<(ElementPoint, Vec3)> { + let Ok(e) = element(d, block, node) else { return Vec::new() }; + let Some(tags) = d.foreign.objects.iter().find(|o| o.handle == e.handle).map(|o| &o.tags) else { return Vec::new() }; + match &e.param { + None if is_action(&e.kind) => point_at(tags, "AcDbBlockAction", 1010).map(|p| vec![(ElementPoint::At, p)]).unwrap_or_default(), + Some(ParameterKind::Linear { base, end, .. }) => { + // The label's grip: the middle of its line, `offset` to the left of base → end. + let offset = + find(tags, "AcDbBlockLinearParameter", 140).and_then(|i| tags.get(i)).and_then(|t| t.value.trim().parse::().ok()).unwrap_or(0.0); + let (a, b) = (base.xy(), end.xy()); + let u = b - a; + let n = if u.len() > 1e-12 { Vec2::new(-u.y, u.x) * (1.0 / u.len()) } else { Vec2::ZERO }; + let mid = (a + b) * 0.5 + n * offset; + vec![(ElementPoint::Base, *base), (ElementPoint::End, *end), (ElementPoint::Label, mid.to3(base.z))] + } + Some(ParameterKind::Point { at, .. }) => { + let mut v = vec![(ElementPoint::At, *at)]; + v.extend(point_at(tags, "AcDbBlockPointParameter", 1011).map(|p| (ElementPoint::Label, p))); + v + } + Some(ParameterKind::Visibility { at, .. } | ParameterKind::Lookup { at, .. }) => vec![(ElementPoint::At, *at)], + _ => Vec::new(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::dynblock::{ActionSpec, ParamPoint, ParameterSpec, add_action, add_parameter}; + + fn v(x: f64, y: f64) -> Vec3 { + Vec3::new(x, y, 0.0) + } + + /// Erasing keeps the flags of the edges that stay (a graph from a file may set them). + #[test] + fn erasing_keeps_the_remaining_edges_flags() { + let mut d = Drawing::default(); + let p = add_parameter(&mut d, "B", &ParameterSpec::Linear { base: v(0.0, 0.0), end: v(10.0, 0.0), label: None, label_offset: 0.0, grips: 2 }) + .unwrap(); + let a = + add_action(&mut d, "B", &ActionSpec::Move { parameter: p, point: ParamPoint::End, selection: vec![Handle(1)], at: v(1.0, 1.0) }).unwrap(); + let mut g = graph(&d, "B").unwrap(); + for e in &mut g.edges { + e.flags = 4; + } + let tags = g.tags(); + if let Some(o) = object_mut(&mut d, g.handle) { + o.tags = tags; + } + assert_eq!(erase_elements(&mut d, "B", &[a]).unwrap(), [a]); + let g = graph(&d, "B").unwrap(); + assert_eq!(g.edges.len(), 6, "the parameter's components and grips"); + assert!(g.edges.iter().all(|e| e.flags == 4), "{:?}", g.edges); + } + + /// A linear parameter with only its end grip: moving it, or its endpoint, takes that grip along. + #[test] + fn a_lone_end_grip_follows_its_linear_parameter() { + let mut d = Drawing::default(); + let p = add_parameter(&mut d, "B", &ParameterSpec::Linear { base: v(0.0, 0.0), end: v(10.0, 0.0), label: None, label_offset: 0.0, grips: 1 }) + .unwrap(); + let grip = |d: &Drawing| { + let m = dynamic_block(d, "B").unwrap(); + let id = m.parameters.iter().find(|x| x.node == p).unwrap().grips.iter().copied().find(|g| *g != 0).unwrap(); + let h = m.grip_objects.iter().find(|(g, _)| *g == id).unwrap().1; + let tags = &d.foreign.objects.iter().find(|o| o.handle == h).unwrap().tags; + let dir_x = find(tags, "AcDbBlockLinearGrip", 140).and_then(|i| tags[i].value.trim().parse::().ok()); + (point_at(tags, "AcDbBlockGrip", 1010).unwrap(), dir_x) + }; + move_element(&mut d, "B", p, v(5.0, 1.0)).unwrap(); + assert_eq!(grip(&d).0, v(15.0, 1.0)); + set_element_point(&mut d, "B", p, ElementPoint::End, v(5.0, 11.0)).unwrap(); + let (at, dir_x) = grip(&d); + assert_eq!(at, v(5.0, 11.0)); + assert!(dir_x.is_some_and(|x| x.abs() < 1e-9), "the grip points along the new direction (0, 10): {dir_x:?}"); + } +} diff --git a/crates/doc/src/dynblock/lookup.rs b/crates/doc/src/dynblock/lookup.rs new file mode 100644 index 0000000000..dfc6153baf --- /dev/null +++ b/crates/doc/src/dynblock/lookup.rs @@ -0,0 +1,681 @@ +//! Lookup tables (BLOOKUPTABLE): a lookup action's rows of input values (a distance, a position, +//! a visibility state) and the lookup values each row gives, written as AutoCAD writes its own +//! (observed in files it saves, and in its Property Lookup Table dialog): +//! +//! - The table lists its input columns, then its lookup columns. Each column names its parameter +//! and the value it stands for (`UpdatedDistance`, `UpdatedX`, `UpdatedY`, `VisibilityState`, +//! `lookupString`), that value's type and unit, what a reference shows when no row matches +//! ("Custom") and, for a lookup column, whether setting it on a reference sets the row's inputs +//! ("Allow reverse lookup") or it is read only. +//! - Cells are text: numbers in block units, visibility states by name. +//! - Two rows with the same inputs are refused ("Duplicate row of input values found."); a lookup +//! column whose values repeat can't be reversed (AutoCAD sets it back to read only). +//! - The graph has an edge each way between the action and each parameter it reads (its kind is +//! how many of the parameter's values the table has), then between the action and its lookup +//! parameters, each pair flagged 4 and naming the other; a table with no inputs has only the +//! edge from the action to its lookup parameter. + +use super::write::{Graph, dict_entry, tag}; +use super::{ActionKind, DynamicBlock, ParameterKind, dynamic_block}; +use crate::{Drawing, Handle, RawTag}; +use std::collections::HashSet; + +/// Most rows one lookup table is written with. +pub const MAX_LOOKUP_ROWS: usize = 10_000; + +/// Most columns one lookup table is written with. +const MAX_COLUMNS: usize = 1_000; + +/// Most cells (rows times columns) one lookup table is written with. +const MAX_CELLS: usize = 1_000_000; + +/// A lookup table column as it is written: the parameter's graph id and the value it stands for, +/// whether it is a lookup column, what references show when no row matches, and whether a lookup +/// column can be set on a reference (reverse lookup). +#[derive(Clone, Debug, PartialEq)] +pub struct TableColumn { + pub node: i32, + pub property: String, + pub lookup: bool, + pub unmatched: String, + pub reverse: bool, +} + +/// The value type (95) and unit (96) AutoCAD writes for a column standing for `property`: text, +/// an angle, a flip state or a distance. +fn value_type(property: &str) -> (i32, i32) { + match property.to_ascii_lowercase().as_str() { + "lookupstring" | "visibilitystate" => (1, 0), + "updatedangle" => (40, 1), + "updatedflip" => (70, 0), + _ => (40, 2), + } +} + +/// A lookup action's own section: rows and columns, the cells row by row, then each column. +pub(super) fn table_tags(columns: &[TableColumn], rows: &[Vec]) -> Vec { + let mut out = vec![tag(100, "AcDbBlockLookupAction"), tag(92, rows.len()), tag(93, columns.len()), tag(301, "")]; + out.extend(rows.iter().flatten().map(|c| tag(302, c))); + for c in columns { + let (ty, unit) = value_type(&c.property); + out.extend([tag(303, ""), tag(94, c.node), tag(95, ty), tag(96, unit), tag(282, i32::from(c.lookup))]); + out.extend([tag(305, &c.unmatched), tag(281, i32::from(c.lookup && c.reverse)), tag(304, &c.property)]); + } + out.push(tag(280, 1)); + out +} + +/// The lookup action whose table gives lookup parameter `node`'s value, if one does. +pub(super) fn table_of(m: &DynamicBlock, node: i32) -> Option { + m.actions + .iter() + .find(|a| matches!(&a.kind, ActionKind::Lookup { columns, .. } if columns.iter().any(|c| c.lookup && c.node == node))) + .map(|a| a.node) +} + +/// Set the lookup action a lookup parameter names (`94`): `id`, or 0 for none. +pub(super) fn set_action_of(d: &mut Drawing, param: Handle, id: i32) { + let f = std::sync::Arc::make_mut(&mut d.foreign); + let Some(o) = f.objects.iter_mut().find(|o| o.handle == param) else { return }; + let Some(at) = o.tags.iter().position(|t| t.code == 100 && t.value.eq_ignore_ascii_case("AcDbBlockLookUpParameter")) else { return }; + if let Some(t) = o.tags.iter_mut().skip(at + 1).take_while(|t| t.code != 100).find(|t| t.code == 94) { + *t = tag(94, id); + } +} + +/// The input properties block `m`'s lookup tables can read, as the Add Parameter Properties +/// dialog lists them: (name, parameter graph id, value). A distance, a position's X and Y, a +/// visibility state. +pub fn input_properties(m: &DynamicBlock) -> Vec<(String, i32, String)> { + let mut out = Vec::new(); + for p in &m.parameters { + match &p.kind { + ParameterKind::Linear { label, .. } => out.push((label.clone(), p.node, "UpdatedDistance".to_string())), + ParameterKind::Point { label, .. } => { + out.push((format!("{label} X"), p.node, "UpdatedX".to_string())); + out.push((format!("{label} Y"), p.node, "UpdatedY".to_string())); + } + ParameterKind::Visibility { label, .. } => out.push((label.clone(), p.node, "VisibilityState".to_string())), + _ => {} + } + } + out +} + +/// The name a lookup table column shows: an input property's name ("Position1 X"), a lookup +/// parameter's property name, or the property itself when the parameter is unknown. +pub fn column_property(m: &DynamicBlock, node: i32, property: &str) -> String { + column_named(m, &input_properties(m), node, property) +} + +/// [`column_property`] with block `m`'s [`input_properties`] already listed. +fn column_named(m: &DynamicBlock, inputs: &[(String, i32, String)], node: i32, property: &str) -> String { + if let Some((n, ..)) = inputs.iter().find(|(_, id, prop)| *id == node && prop.eq_ignore_ascii_case(property)) { + return n.clone(); + } + match m.parameters.iter().find(|p| p.node == node).map(|p| &p.kind) { + Some(ParameterKind::Lookup { label, .. }) => label.clone(), + Some(k) => k.label().map_or_else(|| property.to_string(), |l| format!("{l} {property}")), + None => property.to_string(), + } +} + +/// A table cell as two cells are compared by: a number by its value to nine significant digits +/// (`10` and `10.0` are the same), text in any case. Cells with the same key read the same. +pub fn cell_key(cell: &str) -> String { + let cell = cell.trim(); + match cell.parse::() { + // Adding 0 turns -0 into 0. + Ok(v) if v.is_finite() => format!("{:.8e}", v + 0.0), + _ => cell.to_lowercase(), + } +} + +/// Run `change` on `d` all or nothing: when it fails, the drawing's dynamic block data (its foreign +/// objects, all that lookup tables and element edits change) is put back as it was. +pub(super) fn all_or_nothing(d: &mut Drawing, change: impl FnOnce(&mut Drawing) -> Result) -> Result { + let kept = std::sync::Arc::clone(&d.foreign); + let out = change(d); + if out.is_err() { + d.foreign = kept; + } + out +} + +/// Fill lookup action `action` of block `block` (any case) with `columns` and `rows` (each row +/// one cell per column), as the Property Lookup Table dialog's OK does. Input columns are written +/// before lookup columns; rows with every cell empty are left out. Refused, with AutoCAD's reason, +/// when a column can't be read or set, a cell isn't a value of its column, or two rows have the +/// same inputs. +pub fn set_lookup_table(d: &mut Drawing, block: &str, action: i32, columns: &[TableColumn], rows: &[Vec]) -> Result<(), String> { + write_table(d, block, action, columns, rows, false) +} + +/// [`set_lookup_table`]; with `dedupe`, a row whose inputs repeat an earlier row's is left out +/// instead of refused (a column was taken out from under it). All or nothing: a table refused +/// partway leaves the drawing as it was. +fn write_table(d: &mut Drawing, block: &str, action: i32, columns: &[TableColumn], rows: &[Vec], dedupe: bool) -> Result<(), String> { + all_or_nothing(d, |d| write_table_in(d, block, action, columns, rows, dedupe)) +} + +fn write_table_in(d: &mut Drawing, block: &str, action: i32, columns: &[TableColumn], rows: &[Vec], dedupe: bool) -> Result<(), String> { + if columns.len() > MAX_COLUMNS { + return Err(format!("A lookup table has at most {MAX_COLUMNS} columns.")); + } + if rows.len() > MAX_LOOKUP_ROWS { + return Err(format!("A lookup table has at most {MAX_LOOKUP_ROWS} rows.")); + } + if rows.len().saturating_mul(columns.len()) > MAX_CELLS { + return Err(format!("A lookup table has at most {MAX_CELLS} cells.")); + } + let m = dynamic_block(d, block).ok_or("The block has no parameters or actions.")?; + let a = m.actions.iter().find(|a| a.node == action).ok_or_else(|| format!("No action {action} in the block."))?; + let ActionKind::Lookup { columns: old, .. } = &a.kind else { return Err(format!("{} is not a lookup action.", a.name)) }; + // The action's own lookup column is written first of its lookup columns (below), so it is the + // first one read back. + let own = old.iter().find(|c| c.lookup).map(|c| c.node); + let (action_handle, name) = (a.handle, a.name.clone()); + + // The columns, checked and spelled as AutoCAD spells them; inputs first. + let mut cols: Vec<(usize, TableColumn)> = Vec::new(); + for (i, c) in columns.iter().enumerate() { + let p = m.parameters.iter().find(|p| p.node == c.node).ok_or_else(|| format!("No parameter {} in the block.", c.node))?; + let property = match (&p.kind, c.property.trim().to_ascii_lowercase().as_str(), c.lookup) { + (ParameterKind::Lookup { .. }, "lookupstring" | "", true) => "lookupString", + (ParameterKind::Lookup { label, .. }, _, false) => return Err(format!("{label} is a lookup parameter; it can only be a lookup column.")), + (_, _, true) => return Err(format!("{} is not a lookup parameter.", p.element)), + (ParameterKind::Linear { .. }, "updateddistance" | "distance", _) => "UpdatedDistance", + (ParameterKind::Point { .. }, "updatedx" | "x", _) => "UpdatedX", + (ParameterKind::Point { .. }, "updatedy" | "y", _) => "UpdatedY", + (ParameterKind::Visibility { .. }, "visibilitystate" | "", _) => "VisibilityState", + (_, other, _) => return Err(format!("A lookup table can't read {other} of {}.", p.element)), + }; + if c.lookup && table_of(&m, c.node).is_some_and(|t| t != action) { + return Err(format!("{} already has a lookup table.", column_property(&m, c.node, property))); + } + if cols.iter().any(|(_, o)| o.node == c.node && o.property == property) { + return Err(format!("{} is in the table twice.", column_property(&m, c.node, property))); + } + let unmatched = if c.unmatched.trim().is_empty() { "Custom".to_string() } else { c.unmatched.trim().to_string() }; + cols.push((i, TableColumn { node: c.node, property: property.to_string(), lookup: c.lookup, unmatched, reverse: c.reverse })); + } + if let Some(own) = own + && !cols.iter().any(|(_, c)| c.lookup && c.node == own) + { + return Err(format!("{name} gives {}; its lookup column can't be removed.", column_property(&m, own, "lookupString"))); + } + // Inputs first, then the action's own lookup column, then the other lookup columns, each in the + // caller's order. + cols.sort_by_key(|(_, c)| (c.lookup, !(c.lookup && Some(c.node) == own))); + let shown: Vec = { + let inputs = input_properties(&m); + cols.iter().map(|(_, c)| column_named(&m, &inputs, c.node, &c.property)).collect() + }; + + // The cells, in the columns' new order. + let states = |node: i32| match m.parameters.iter().find(|p| p.node == node).map(|p| &p.kind) { + Some(ParameterKind::Visibility { states, .. }) => states.iter().map(|s| s.name.clone()).collect(), + _ => Vec::new(), + }; + let mut table: Vec> = Vec::new(); + for (r, row) in rows.iter().enumerate() { + if row.len() != columns.len() { + return Err(format!("Row {} has {} cells; the table has {} columns.", r + 1, row.len(), columns.len())); + } + if row.iter().all(|c| c.trim().is_empty()) { + continue; + } + let mut out = Vec::with_capacity(cols.len()); + for ((i, c), shown) in cols.iter().zip(&shown) { + let cell = row.get(*i).map(|c| c.trim()).unwrap_or_default(); + if cell.is_empty() { + return Err(format!("Row {}: {shown} needs a value.", r + 1)); + } + out.push(match c.property.as_str() { + "VisibilityState" => states(c.node) + .into_iter() + .find(|s| s.eq_ignore_ascii_case(cell)) + .ok_or_else(|| format!("Row {}: \"{cell}\" is not a visibility state of {shown}.", r + 1))?, + "lookupString" => cell.to_string(), + _ => { + let v = cell + .parse::() + .ok() + .filter(|v| v.is_finite()) + .ok_or_else(|| format!("Row {}: {shown} needs a number, not \"{cell}\".", r + 1))?; + if c.property == "UpdatedDistance" && v < 0.0 { + return Err(format!("Row {}: {shown} can't be negative.", r + 1)); + } + format!("{v}") + } + }); + } + table.push(out); + } + let inputs = cols.iter().filter(|(_, c)| !c.lookup).count(); + let mut seen: HashSet> = HashSet::new(); + let mut kept: Vec> = Vec::new(); + for row in table { + if inputs > 0 && !seen.insert(row.iter().take(inputs).map(|c| cell_key(c)).collect()) { + if dedupe { + continue; + } + return Err("Duplicate row of input values found.".into()); + } + kept.push(row); + } + // A lookup column whose values repeat (or that has none) can't be reversed. + let mut cols: Vec = cols.into_iter().map(|(_, c)| c).collect(); + for (j, c) in cols.iter_mut().enumerate() { + if !(c.lookup && c.reverse) { + c.reverse = false; + continue; + } + let mut values: HashSet = HashSet::new(); + let repeats = kept.iter().filter_map(|r| r.get(j)).any(|v| !values.insert(cell_key(v))); + c.reverse = !values.is_empty() && !repeats; + } + + // The action's object: its table, and the flag AutoCAD changes once the table has inputs. + let f = std::sync::Arc::make_mut(&mut d.foreign); + let o = f.objects.iter_mut().find(|o| o.handle == action_handle).ok_or("The lookup action is missing.")?; + let at = o + .tags + .iter() + .position(|t| t.code == 100 && t.value.eq_ignore_ascii_case("AcDbBlockLookupAction")) + .ok_or("The lookup action can't be changed.")?; + // Its section is the object's last; anything after it would be a layout this doesn't know. + if o.tags.iter().skip(at + 1).any(|t| t.code == 100) { + return Err("The lookup action can't be changed.".into()); + } + o.tags.truncate(at); + o.tags.extend(table_tags(&cols, &kept)); + if let Some(el) = o.tags.iter().position(|t| t.code == 100 && t.value.eq_ignore_ascii_case("AcDbBlockElement")) + && let Some(t) = o.tags.iter_mut().skip(el + 1).take_while(|t| t.code != 100).find(|t| t.code == 1071) + { + *t = tag(1071, if inputs > 0 { 0 } else { 8 }); + } + + // The edges: the action's own, made again for its columns. + let key = ("BLOCK_RECORD".to_string(), block.trim().to_ascii_uppercase()); + let gh = d + .foreign + .records + .get(&key) + .and_then(|x| x.xdict) + .and_then(|x| dict_entry(d, x, "ACAD_ENHANCEDBLOCK")) + .ok_or("The block's evaluation graph is missing.")?; + let mut g = d.foreign.objects.iter().find(|o| o.handle == gh).and_then(Graph::read).ok_or("The block's evaluation graph can't be changed.")?; + let index = |id: i32| g.nodes.iter().find(|n| n.id == id).map(|n| n.index); + let ai = index(action).ok_or("The lookup action is missing from the graph.")?; + let mut edges = g.kept_edges(|e| e.from == ai || e.to == ai, Some); + let pair = |edges: &mut Vec<(i32, i32, i32, i32, i32)>, from: i32, to: i32, kind: i32, both: bool| { + let at = i32::try_from(edges.len()).unwrap_or(i32::MAX); + // AutoCAD flags a pair of edges 4 (without it, it reads the block as a static one). + if both { + edges.push((from, to, kind, 4, at.saturating_add(1))); + edges.push((to, from, kind, 4, at)); + } else { + edges.push((from, to, kind, 0, -1)); + } + }; + let mut seen: Vec = Vec::new(); + for c in cols.iter().filter(|c| !c.lookup) { + if seen.contains(&c.node) { + continue; + } + seen.push(c.node); + let kind = i32::try_from(cols.iter().filter(|o| !o.lookup && o.node == c.node).count()).unwrap_or(1); + let pi = index(c.node).ok_or("A parameter of the table is missing from the graph.")?; + pair(&mut edges, pi, ai, kind, true); + } + for c in cols.iter().filter(|c| c.lookup) { + let pi = index(c.node).ok_or("A parameter of the table is missing from the graph.")?; + pair(&mut edges, ai, pi, 1, inputs > 0); + } + g.relink(&edges); + let tags = g.tags(); + if let Some(o) = std::sync::Arc::make_mut(&mut d.foreign).objects.iter_mut().find(|o| o.handle == gh) { + o.tags = tags; + } + + // Lookup parameters name the action giving their value; one left out names none. + for p in &m.parameters { + if !matches!(p.kind, ParameterKind::Lookup { .. }) { + continue; + } + if cols.iter().any(|c| c.lookup && c.node == p.node) { + set_action_of(d, p.handle, action); + } else if old.iter().any(|c| c.lookup && c.node == p.node) { + set_action_of(d, p.handle, 0); + } + } + Ok(()) +} + +/// Before parameters `erased` of block `block` go: every lookup table reading them (or giving +/// one of them that isn't its own) loses those columns, and rows that then repeat another's +/// inputs. Returns the lookup actions whose own parameter goes (they go with it). +pub(super) fn drop_columns(d: &mut Drawing, block: &str, erased: &[i32]) -> Result, String> { + all_or_nothing(d, |d| drop_columns_in(d, block, erased)) +} + +fn drop_columns_in(d: &mut Drawing, block: &str, erased: &[i32]) -> Result, String> { + let Some(m) = dynamic_block(d, block) else { return Ok(Vec::new()) }; + let mut gone = Vec::new(); + for a in &m.actions { + let ActionKind::Lookup { columns, rows } = &a.kind else { continue }; + if columns.iter().find(|c| c.lookup).is_some_and(|c| erased.contains(&c.node)) { + gone.push(a.node); + continue; + } + if !columns.iter().any(|c| erased.contains(&c.node)) { + continue; + } + let keep: Vec = (0..columns.len()).filter(|i| columns.get(*i).is_some_and(|c| !erased.contains(&c.node))).collect(); + let cols: Vec = keep + .iter() + .filter_map(|i| columns.get(*i)) + .map(|c| TableColumn { node: c.node, property: c.property.clone(), lookup: c.lookup, unmatched: c.unmatched.clone(), reverse: c.reverse }) + .collect(); + let rows: Vec> = rows.iter().map(|r| keep.iter().map(|i| r.get(*i).cloned().unwrap_or_default()).collect()).collect(); + write_table(d, block, a.node, &cols, &rows, true)?; + } + Ok(gone) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::dynblock::{ActionSpec, ParamPoint, ParameterSpec, VisibilityState, add_action, add_parameter, erase_elements, set_visibility}; + use cadcraft_geom::Vec3; + + fn v(x: f64, y: f64) -> Vec3 { + Vec3::new(x, y, 0.0) + } + + fn col(node: i32, property: &str, lookup: bool) -> TableColumn { + TableColumn { node, property: property.into(), lookup, unmatched: String::new(), reverse: lookup } + } + + fn row(cells: &[&str]) -> Vec { + cells.iter().map(|c| c.to_string()).collect() + } + + /// Block "B" as AutoCAD's sample is made: a linear parameter (Distance1) with a move, a point + /// (Position1), a visibility parameter with states VisibilityState0 and Small, a lookup + /// parameter (Size) and its lookup action. Returns (linear, point, visibility, lookup, + /// action). + fn block() -> (Drawing, [i32; 5]) { + let mut d = Drawing::default(); + let lin = + add_parameter(&mut d, "B", &ParameterSpec::Linear { base: v(0.0, 0.0), end: v(10.0, 0.0), label: None, label_offset: -1.0, grips: 1 }) + .unwrap(); + add_action(&mut d, "B", &ActionSpec::Move { parameter: lin, point: ParamPoint::End, selection: vec![Handle(0x40)], at: v(12.0, 0.0) }) + .unwrap(); + let pt = add_parameter(&mut d, "B", &ParameterSpec::Point { at: v(5.0, 2.0), label: None, label_at: v(5.0, 3.0), grips: 1 }).unwrap(); + let vis = + add_parameter(&mut d, "B", &ParameterSpec::Visibility { at: v(-2.0, 5.0), label: None, objects: vec![Handle(0x40)], grips: 1 }).unwrap(); + let states = [ + VisibilityState { name: "VisibilityState0".into(), ..Default::default() }, + VisibilityState { name: "Small".into(), ..Default::default() }, + ]; + set_visibility(&mut d, "B", &[Handle(0x40)], &states).unwrap(); + let spec = + ParameterSpec::Lookup { at: v(-2.0, 7.0), label: Some("Size".into()), name: None, description: String::new(), show: true, grips: 1 }; + let lk = add_parameter(&mut d, "B", &spec).unwrap(); + let act = add_action(&mut d, "B", &ActionSpec::Lookup { parameter: lk, at: v(-2.0, 8.0) }).unwrap(); + (d, [lin, pt, vis, lk, act]) + } + + fn graph(d: &Drawing) -> Graph { + d.foreign.objects.iter().find(|o| o.kind == "ACAD_EVALUATION_GRAPH").and_then(Graph::read).unwrap() + } + + /// The graph's edges by node ids: (from, to, kind, the pair edge's from and to). + fn edges(g: &Graph) -> Vec<(i32, i32, i32, Option<(i32, i32)>)> { + let id = |i: i32| g.nodes.iter().find(|n| n.index == i).unwrap().id; + g.edges + .iter() + .map(|e| { + let pair = (e.links[4] >= 0).then(|| g.edges.iter().find(|p| p.index == e.links[4]).map(|p| (id(p.from), id(p.to))).unwrap()); + (id(e.from), id(e.to), e.kind, pair) + }) + .collect() + } + + fn of(g: &Graph, node: i32) -> Vec<(i32, i32, i32, Option<(i32, i32)>)> { + edges(g).into_iter().filter(|(f, t, ..)| *f == node || *t == node).collect() + } + + fn object<'a>(d: &'a Drawing, kind: &str) -> &'a crate::foreign::ForeignObject { + d.foreign.objects.iter().find(|o| o.kind == kind).unwrap() + } + + fn group(o: &crate::foreign::ForeignObject, marker: &str, code: i32) -> String { + let at = o.tags.iter().position(|t| t.code == 100 && t.value == marker).unwrap(); + o.tags.iter().skip(at + 1).find(|t| t.code == code).unwrap().value.clone() + } + + fn table(d: &Drawing, act: i32) -> (Vec, Vec>) { + let m = dynamic_block(d, "B").unwrap(); + match &m.actions.iter().find(|a| a.node == act).unwrap().kind { + ActionKind::Lookup { columns, rows } => (columns.clone(), rows.clone()), + k => panic!("{k:?}"), + } + } + + #[test] + fn a_new_lookup_action_gives_its_parameter_and_reads_nothing() { + let (d, [.., lk, act]) = block(); + let m = dynamic_block(&d, "B").unwrap(); + let p = m.parameters.iter().find(|p| p.node == lk).unwrap(); + assert!(matches!(&p.kind, ParameterKind::Lookup { label, .. } if label == "Size")); + assert_eq!((p.element.as_str(), p.grips.len()), ("Lookup", 1)); + assert_eq!(m.actions.iter().find(|a| a.node == act).unwrap().name, "Lookup1"); + let (columns, rows) = table(&d, act); + assert!(rows.is_empty()); + assert_eq!(columns.len(), 1); + let c = &columns[0]; + assert_eq!((c.node, c.property.as_str(), c.lookup, c.unmatched.as_str(), c.reverse), (lk, "lookupString", true, "Custom", false)); + assert_eq!(group(object(&d, "BLOCKLOOKUPPARAMETER"), "AcDbBlockLookUpParameter", 94), act.to_string(), "the parameter names its table"); + assert_eq!(group(object(&d, "BLOCKLOOKUPACTION"), "AcDbBlockElement", 1071), "8"); + assert_eq!(object(&d, "BLOCKLOOKUPGRIP").tags.last().unwrap().value, "AcDbBlockLookUpGrip"); + // Only the edge from the action to its parameter. + let g = graph(&d); + assert_eq!(of(&g, act), [(act, lk, 1, None)]); + // The lookup grip is linked before its parameter's location components, as visibility's. + let grip = p.grips[0]; + assert_eq!(of(&g, lk).first(), Some(&(grip, lk, 1, None))); + let again = add_action(&mut d.clone(), "B", &ActionSpec::Lookup { parameter: lk, at: v(0.0, 0.0) }); + assert!(again.unwrap_err().contains("already associated")); + } + + #[test] + fn a_table_is_written_as_autocad_writes_it() { + let (mut d, [lin, pt, vis, lk, act]) = block(); + let cols = [ + col(lin, "UpdatedDistance", false), + col(pt, "UpdatedX", false), + col(pt, "UpdatedY", false), + col(vis, "VisibilityState", false), + col(lk, "lookupString", true), + ]; + let rows = [row(&["10", "5", "2", "visibilitystate0", "Big"]), row(&["6.0", "3", "2", "Small", "Small"]), row(&["", "", "", "", ""])]; + set_lookup_table(&mut d, "B", act, &cols, &rows).unwrap(); + let (columns, rows) = table(&d, act); + assert_eq!(rows, [row(&["10", "5", "2", "VisibilityState0", "Big"]), row(&["6", "3", "2", "Small", "Small"])]); + let props: Vec<(i32, &str, bool, bool)> = columns.iter().map(|c| (c.node, c.property.as_str(), c.lookup, c.reverse)).collect(); + assert_eq!( + props, + [ + (lin, "UpdatedDistance", false, false), + (pt, "UpdatedX", false, false), + (pt, "UpdatedY", false, false), + (vis, "VisibilityState", false, false), + (lk, "lookupString", true, true) + ] + ); + // Types and units as AutoCAD writes them. + let o = object(&d, "BLOCKLOOKUPACTION"); + let types: Vec<&str> = o.tags.iter().filter(|t| t.code == 95 || t.code == 96).map(|t| t.value.as_str()).collect(); + assert_eq!(types, ["40", "2", "40", "2", "40", "2", "1", "0", "1", "0"]); + assert_eq!(group(o, "AcDbBlockElement", 1071), "0"); + assert_eq!(o.tags.last().map(|t| (t.code, t.value.as_str())), Some((280, "1"))); + // An edge each way per parameter read (the point's two columns: kind 2), then the lookup. + let lk_pair = Some((lk, act)); + assert_eq!( + of(&graph(&d), act), + [ + (lin, act, 1, Some((act, lin))), + (act, lin, 1, Some((lin, act))), + (pt, act, 2, Some((act, pt))), + (act, pt, 2, Some((pt, act))), + (vis, act, 1, Some((act, vis))), + (act, vis, 1, Some((vis, act))), + (act, lk, 1, lk_pair), + (lk, act, 1, Some((act, lk))), + ] + ); + let g = graph(&d); + let ai = g.nodes.iter().find(|n| n.id == act).unwrap().index; + assert!(g.edges.iter().filter(|e| e.from == ai || e.to == ai).all(|e| e.flags == 4), "a pair is flagged 4"); + // Filled again, the same edges, not more. + set_lookup_table(&mut d, "B", act, &cols, &[row(&["10", "5", "2", "Small", "Big"])]).unwrap(); + assert_eq!(of(&graph(&d), act).len(), 8); + // Emptied, it is back to its first form. + set_lookup_table(&mut d, "B", act, &[col(lk, "lookupString", true)], &[]).unwrap(); + assert_eq!(of(&graph(&d), act), [(act, lk, 1, None)]); + assert!(graph(&d).edges.iter().all(|e| e.flags == 0), "an edge on its own isn't flagged"); + assert_eq!(group(object(&d, "BLOCKLOOKUPACTION"), "AcDbBlockElement", 1071), "8"); + } + + #[test] + fn the_dialogs_rules_refuse_what_autocad_refuses() { + let (d, [lin, pt, vis, lk, act]) = block(); + let cols = [col(lin, "UpdatedDistance", false), col(vis, "VisibilityState", false), col(lk, "", true)]; + let set = |rows: &[Vec]| set_lookup_table(&mut d.clone(), "B", act, &cols, rows); + assert_eq!(set(&[row(&["10", "Small", "A"]), row(&["10.0", "small", "B"])]).unwrap_err(), "Duplicate row of input values found."); + assert!(set(&[row(&["10", "Nope", "A"])]).unwrap_err().contains("not a visibility state")); + assert!(set(&[row(&["ten", "Small", "A"])]).unwrap_err().contains("needs a number")); + assert!(set(&[row(&["10", "Small", ""])]).unwrap_err().contains("needs a value")); + assert!(set(&[row(&["10", "Small"])]).unwrap_err().contains("cells")); + // Repeated lookup values: read only. + let mut d2 = d.clone(); + set_lookup_table(&mut d2, "B", act, &cols, &[row(&["10", "Small", "A"]), row(&["5", "Small", "a"])]).unwrap(); + assert!(!table(&d2, act).0[2].reverse); + // Columns that can't be: a lookup parameter as an input, the wrong value, twice, without + // the action's own lookup column, an input as a lookup column. + let bad = |cols: &[TableColumn]| set_lookup_table(&mut d.clone(), "B", act, cols, &[]).unwrap_err(); + assert!(bad(&[col(lk, "lookupString", false), col(lk, "lookupString", true)]).contains("only be a lookup column")); + assert!(bad(&[col(pt, "UpdatedDistance", false), col(lk, "", true)]).contains("can't read")); + assert!(bad(&[col(lin, "distance", false), col(lin, "UpdatedDistance", false), col(lk, "", true)]).contains("twice")); + assert!(bad(&[col(lin, "UpdatedDistance", false)]).contains("can't be removed")); + assert!(bad(&[col(lin, "UpdatedDistance", true), col(lk, "", true)]).contains("not a lookup parameter")); + assert!(set_lookup_table(&mut d.clone(), "B", lin, &cols, &[]).is_err(), "not an action"); + } + + #[test] + fn erasing_a_parameter_takes_its_columns_and_a_lookup_parameter_its_table() { + let (mut d, [lin, pt, vis, lk, act]) = block(); + let cols = [col(lin, "UpdatedDistance", false), col(pt, "UpdatedX", false), col(vis, "VisibilityState", false), col(lk, "", true)]; + set_lookup_table(&mut d, "B", act, &cols, &[row(&["10", "5", "Small", "Big"]), row(&["6", "5", "Small", "Small"])]).unwrap(); + erase_elements(&mut d, "B", &[lin]).unwrap(); + let (columns, rows) = table(&d, act); + assert_eq!(columns.iter().map(|c| c.node).collect::>(), [pt, vis, lk]); + assert_eq!(rows, [row(&["5", "Small", "Big"])], "the row that now repeats the first's inputs goes"); + assert!(!dynamic_block(&d, "B").unwrap().actions.iter().any(|a| a.name == "Move"), "the distance's move went with it"); + let g = graph(&d); + assert!( + g.edges.iter().all(|e| e.links[4] < 0 || g.edges.iter().any(|p| p.index == e.links[4] && p.from == e.to && p.to == e.from)), + "pairs kept" + ); + assert_eq!(erase_elements(&mut d, "B", &[lk]).unwrap(), [lk, act]); + assert!(dynamic_block(&d, "B").unwrap().actions.is_empty()); + assert!(graph(&d).edges.iter().all(|e| e.links[4] < 0)); + } + + #[test] + fn erasing_a_lookup_action_leaves_its_parameter_without_a_table() { + let (mut d, [.., lk, act]) = block(); + erase_elements(&mut d, "B", &[act]).unwrap(); + assert_eq!(group(object(&d, "BLOCKLOOKUPPARAMETER"), "AcDbBlockLookUpParameter", 94), "0"); + add_action(&mut d, "B", &ActionSpec::Lookup { parameter: lk, at: v(0.0, 0.0) }).unwrap(); + } + + #[test] + fn the_actions_own_lookup_column_stays_first_whatever_order_it_is_given_in() { + let (mut d, [lin, .., lk, act]) = block(); + let spec = + ParameterSpec::Lookup { at: v(-4.0, 7.0), label: Some("Other".into()), name: None, description: String::new(), show: true, grips: 1 }; + let other = add_parameter(&mut d, "B", &spec).unwrap(); + let rows = [row(&["1", "x", "a"]), row(&["2", "y", "b"])]; + set_lookup_table(&mut d, "B", act, &[col(lin, "UpdatedDistance", false), col(other, "", true), col(lk, "", true)], &rows).unwrap(); + let (cols, cells) = table(&d, act); + assert_eq!(cols.iter().map(|c| c.node).collect::>(), [lin, lk, other]); + assert_eq!(cells, [row(&["1", "a", "x"]), row(&["2", "b", "y"])]); + // The other lookup column can go; the action's own can't, whichever comes first. + let without = |keep: i32| [col(lin, "UpdatedDistance", false), col(keep, "", true)]; + assert!(set_lookup_table(&mut d.clone(), "B", act, &without(other), &[]).unwrap_err().contains("can't be removed")); + set_lookup_table(&mut d, "B", act, &without(lk), &[]).unwrap(); + } + + #[test] + fn lookup_values_that_read_the_same_number_repeat() { + let (mut d, [lin, .., lk, act]) = block(); + let cols = [col(lin, "UpdatedDistance", false), col(lk, "", true)]; + set_lookup_table(&mut d, "B", act, &cols, &[row(&["1", "10"]), row(&["2", "10.0"])]).unwrap(); + assert!(!table(&d, act).0[1].reverse, "10 and 10.0 repeat"); + assert_eq!(cell_key(" 10 "), cell_key("1e1")); + assert_eq!(cell_key("-0"), cell_key("0")); + assert_eq!(cell_key("Small"), cell_key("SMALL")); + assert_ne!(cell_key("10"), cell_key("10.5")); + } + + #[test] + fn a_table_at_its_row_limit_is_written_and_too_many_cells_are_refused() { + let (mut d, [lin, .., lk, act]) = block(); + let cols = [col(lin, "UpdatedDistance", false), col(lk, "", true)]; + let rows: Vec> = (0..MAX_LOOKUP_ROWS).map(|i| vec![i.to_string(), format!("v{i}")]).collect(); + set_lookup_table(&mut d, "B", act, &cols, &rows).unwrap(); + assert_eq!(table(&d, act).1.len(), MAX_LOOKUP_ROWS); + assert!(table(&d, act).0[1].reverse, "every lookup value differs"); + let wide = vec![col(lk, "", true); MAX_CELLS / MAX_LOOKUP_ROWS + 1]; + let err = set_lookup_table(&mut d.clone(), "B", act, &wide, &vec![Vec::new(); MAX_LOOKUP_ROWS]).unwrap_err(); + assert!(err.contains("cells"), "{err}"); + } + + #[test] + fn an_erase_refused_partway_leaves_the_tables_as_they_were() { + let (mut d, [lin, .., lk, act]) = block(); + let cols = [col(lin, "UpdatedDistance", false), col(lk, "", true)]; + set_lookup_table(&mut d, "B", act, &cols, &[row(&["1", "a"])]).unwrap(); + let before = (*d.foreign).clone(); + // The distance's column goes first; the unknown id is refused after that. + assert!(erase_elements(&mut d, "B", &[lin, 9999]).is_err()); + assert!(*d.foreign == before, "nothing changed"); + assert_eq!(table(&d, act).0.len(), 2); + // A change that fails is undone whatever it did before failing. + let r: Result<(), String> = all_or_nothing(&mut d, |d| { + std::sync::Arc::make_mut(&mut d.foreign).objects.clear(); + Err("refused".into()) + }); + assert!(r.is_err()); + assert!(*d.foreign == before); + } + + #[test] + fn hostile_tables_are_refused() { + let (d, [lin, .., lk, act]) = block(); + let cols = [col(lin, "UpdatedDistance", false), col(lk, "", true)]; + let rows = vec![row(&["1", "a"]); MAX_LOOKUP_ROWS + 1]; + assert!(set_lookup_table(&mut d.clone(), "B", act, &cols, &rows).is_err()); + let many = vec![col(lk, "", true); MAX_COLUMNS + 1]; + assert!(set_lookup_table(&mut d.clone(), "B", act, &many, &[]).is_err()); + for cell in ["NaN", "inf", "-1", "1e400"] { + assert!(set_lookup_table(&mut d.clone(), "B", act, &cols, &[row(&[cell, "a"])]).is_err(), "{cell}"); + } + assert!(set_lookup_table(&mut d.clone(), "Nope", act, &cols, &[]).is_err()); + assert!(set_lookup_table(&mut d.clone(), "B", 9999, &cols, &[]).is_err()); + } +} diff --git a/crates/doc/src/dynblock/marks.rs b/crates/doc/src/dynblock/marks.rs new file mode 100644 index 0000000000..62365c57ed --- /dev/null +++ b/crates/doc/src/dynblock/marks.rs @@ -0,0 +1,70 @@ +//! 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 }, + /// A visibility or lookup parameter: a list grip (a triangle pointing down) at `at` when it + /// has one, its label beside it. + List { node: i32, at: Vec3, label: String, grip: bool }, + /// Another parameter: its name at `at`. + Parameter { node: i32, at: Vec3, label: String }, + /// An action: a badge with its name at `at`. + Action { node: i32, at: Vec3, name: String }, +} + +impl Mark { + /// The graph id of the parameter this marks (`None` for an action). + pub fn parameter_node(&self) -> Option { + match self { + Mark::Linear { node, .. } | Mark::Point { node, .. } | Mark::List { node, .. } | Mark::Parameter { node, .. } => Some(*node), + Mark::Action { .. } => None, + } + } +} + +/// Block `name`'s parameters and actions as the Block Editor draws them (empty when it has none). +pub fn marks(d: &Drawing, name: &str) -> Vec { + let Some(m) = dynamic_block(d, name) else { return Vec::new() }; + 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, .. } => Mark::List { node: p.node, at: *at, label, grip: grip(0) }, + ParameterKind::BasePoint { at } => Mark::Parameter { node: p.node, at: *at, label }, + ParameterKind::Other { .. } => continue, + }); + } + 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/reference.rs b/crates/doc/src/dynblock/reference.rs index 8ab0a14204..a14e5a064a 100644 --- a/crates/doc/src/dynblock/reference.rs +++ b/crates/doc/src/dynblock/reference.rs @@ -321,9 +321,9 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec bool { let mut any = false; for a in &m.actions { @@ -335,7 +335,7 @@ fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool { let settable = |c: &super::LookupColumn| { m.parameters.iter().find(|p| p.node == c.node).is_some_and(|p| super::apply::column(&p.kind, &c.property).is_some()) }; - if !columns.iter().all(settable) { + if !columns.iter().any(|c| c.lookup && c.node == node && c.reverse) || !columns.iter().all(settable) { return false; } } diff --git a/crates/doc/src/dynblock/write.rs b/crates/doc/src/dynblock/write.rs new file mode 100644 index 0000000000..cabde61bf8 --- /dev/null +++ b/crates/doc/src/dynblock/write.rs @@ -0,0 +1,916 @@ +//! 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, VisibilityState, 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. +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). +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 }, + /// Named visibility states (Visibility1) of `objects`, at `at`, with 0 or 1 grip: one state, + /// `VisibilityState0`, showing them all. A block has one at most. + Visibility { at: Vec3, label: Option, objects: Vec, grips: u8 }, + /// A value picked from a lookup table (Lookup1), at `at`, with 0 or 1 grip. `name` is its name + /// in the Block Editor (default Lookup), `description` the property's, and `show` whether + /// references show it in Properties. Its table comes with a lookup action (BACTION). + Lookup { at: Vec3, label: Option, name: Option, description: String, show: bool, grips: u8 }, +} + +/// What a grip is: a linear parameter's (pointing along `Vec3`), a point's, or a visibility or +/// lookup parameter's (a list to pick from). +#[derive(Clone, Copy, Debug, PartialEq)] +enum GripKind { + Linear(Vec3), + Xy, + Visibility, + Lookup, +} + +impl GripKind { + fn is_list(self) -> bool { + matches!(self, GripKind::Visibility | GripKind::Lookup) + } +} + +/// Which point of a two-point parameter an action follows. +#[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 }, + /// The lookup table of lookup parameter `parameter`, empty until it is filled + /// ([`set_lookup_table`](super::set_lookup_table)). A lookup parameter has one at most. + Lookup { parameter: i32, at: Vec3 }, +} + +/// One node of the evaluation graph: its index, flags, graph id, object and the first and last +/// of its incoming and outgoing edges (edge indices, -1 for none). +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Node { + pub(super) index: i32, + pub(super) flags: i32, + pub(super) id: i32, + pub(super) handle: Handle, + pub(super) links: [i32; 4], +} + +/// One edge: its index, flags, kind (1 from a parameter, 2 from a grip; between a lookup action +/// and a parameter, how many of the parameter's values the table has), the nodes it joins +/// (indices) and its neighbours in their lists: previous and next incoming of `to`, previous and +/// next outgoing of `from`, then the edge running the other way between the same nodes (a lookup +/// table's, which reads and sets its parameters), -1 for none. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Edge { + pub(super) index: i32, + pub(super) flags: i32, + pub(super) kind: i32, + pub(super) from: i32, + pub(super) to: i32, + pub(super) links: [i32; 5], +} + +/// An evaluation graph object being extended. +pub(super) struct Graph { + pub(super) handle: Handle, + /// Its groups before `100 AcDbEvalGraph`, as they were. + pub(super) head: Vec, + /// The highest graph id handed out (96, 97), which AutoCAD keeps after nodes are erased: + /// ids aren't used again. + pub(super) last_id: i32, + pub(super) nodes: Vec, + pub(super) edges: Vec, +} + +pub(super) fn tag(code: i32, value: impl ToString) -> RawTag { + RawTag { code, value: value.to_string() } +} + +pub(super) 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). + pub(super) fn read(o: &ForeignObject) -> Option { + let at = o.tags.iter().position(|t| t.code == 100 && t.value.eq_ignore_ascii_case("AcDbEvalGraph"))?; + let head = o.tags.get(..at)?.to_vec(); + let body = o.tags.get(at + 1..)?; + let int = |t: Option<&RawTag>, code: i32| t.filter(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()); + let last_id = body.iter().take_while(|t| t.code == 96 || t.code == 97).filter_map(|t| t.value.trim().parse::().ok()).max().unwrap_or(0); + let mut i = body.iter().position(|t| t.code != 96 && t.code != 97).unwrap_or(body.len()); + let (mut nodes, mut edges) = (Vec::new(), Vec::new()); + while body.get(i).is_some_and(|t| t.code == 91) { + 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, last_id, nodes, edges }) + } + + /// A new, empty graph owned by dictionary `dict`. + fn new(handle: Handle, dict: Handle) -> Graph { + let head = vec![tag(5, handle.hex()), tag(102, "{ACAD_REACTORS"), tag(330, dict.hex()), tag(102, "}"), tag(330, dict.hex())]; + Graph { handle, head, last_id: 0, nodes: Vec::new(), edges: Vec::new() } + } + + pub(super) fn tags(&self) -> Vec { + let mut out = self.head.clone(); + out.push(tag(100, "AcDbEvalGraph")); + let last = self.nodes.iter().map(|n| n.id).max().unwrap_or(0).max(self.last_id); + out.push(tag(96, last)); + out.push(tag(97, last)); + for n in &self.nodes { + out.extend([tag(91, n.index), tag(93, n.flags), tag(95, n.id), tag(360, n.handle.hex())]); + out.extend(n.links.iter().map(|l| tag(92, l))); + } + 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).max(self.last_id).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 + } + + /// Link `edges` again, in order, after the nodes' links were cleared: (from, to, kind, flags, + /// pair), `pair` the position in `edges` of the edge running the other way (-1 for none). + pub(super) fn relink(&mut self, edges: &[(i32, i32, i32, i32, i32)]) { + self.edges.clear(); + for n in &mut self.nodes { + n.links = [-1; 4]; + } + for &(from, to, kind, flags, _) in edges { + self.link(from, to, kind); + if let Some(e) = self.edges.last_mut() { + e.flags = flags; + } + } + // Edge indices are the positions in `edges` now. + for (e, &(.., pair)) in self.edges.iter_mut().zip(edges) { + e.links[4] = if pair >= 0 && usize::try_from(pair).is_ok_and(|p| p < edges.len()) { pair } else { -1 }; + } + } + + /// The graph's edges as [`relink`](Self::relink) takes them, except those `drop` refuses, + /// with node indices mapped by `index` (an edge to a node it maps to `None` is dropped too). + pub(super) fn kept_edges(&self, drop: impl Fn(&Edge) -> bool, index: impl Fn(i32) -> Option) -> Vec<(i32, i32, i32, i32, i32)> { + let kept: Vec<(&Edge, i32, i32)> = self.edges.iter().filter(|e| !drop(e)).filter_map(|e| Some((e, index(e.from)?, index(e.to)?))).collect(); + let position = |old: i32| kept.iter().position(|(e, ..)| e.index == old).and_then(|p| i32::try_from(p).ok()).unwrap_or(-1); + kept.iter().map(|(e, from, to)| (*from, *to, e.kind, e.flags, if e.links[4] >= 0 { position(e.links[4]) } else { -1 })).collect() + } + + fn node_mut(&mut self, index: i32) -> Option<&mut Node> { + self.nodes.iter_mut().find(|n| n.index == index) + } + + 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. + pub(super) fn link(&mut self, from: i32, to: i32, kind: i32) { + let index = self.edges.iter().map(|e| e.index).max().map_or(0, |m| m.saturating_add(1)); + let last_out = self.node_mut(from).map_or(-1, |n| n.links[3]); + let last_in = self.node_mut(to).map_or(-1, |n| n.links[1]); + 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, kind: GripKind) -> i32 { + let (gh, gid) = (self.d.new_handle(), self.graph.next_id()); + let (xid, yid) = (gid.saturating_add(1), gid.saturating_add(2)); + let mut tags = element_head(gh, self.graph.handle, gid, name, 0); + tags.extend([tag(100, "AcDbBlockGrip"), tag(91, xid), tag(92, yid)]); + point(&mut tags, 1010, at); + // A visibility or lookup grip is the only one AutoCAD writes 280 0 on. + tags.extend([tag(280, i32::from(!kind.is_list())), tag(93, -1)]); + let dxf = match kind { + GripKind::Linear(dir) => { + tags.extend([tag(100, "AcDbBlockLinearGrip"), real(140, dir.x), real(141, dir.y), real(142, dir.z)]); + self.class("BLOCKLINEARGRIP", "AcDbBlockLinearGrip"); + "BLOCKLINEARGRIP" + } + GripKind::Xy => { + tags.push(tag(100, "AcDbBlockXYGrip")); + self.class("BLOCKXYGRIP", "AcDbBlockXYGrip"); + "BLOCKXYGRIP" + } + GripKind::Visibility => { + tags.push(tag(100, "AcDbBlockVisibilityGrip")); + self.class("BLOCKVISIBILITYGRIP", "AcDbBlockVisibilityGrip"); + "BLOCKVISIBILITYGRIP" + } + GripKind::Lookup => { + tags.push(tag(100, "AcDbBlockLookUpGrip")); + self.class("BLOCKLOOKUPGRIP", "AcDbBlockLookupGrip"); + "BLOCKLOOKUPGRIP" + } + }; + let grip = self.node(dxf, gh, gid, tags); + // AutoCAD links a list grip to its parameter before the location components. + if kind.is_list() { + self.graph.link(grip, param, 1); + } + self.class("BLOCKGRIPLOCATIONCOMPONENT", "AcDbBlockGripExpr"); + // Each component names the parameter it reads (its graph id). + let owner = self.graph.nodes.iter().find(|n| n.index == param).map_or(0, |n| n.id); + 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, owner), tag(300, comp)]); + let c = self.node("BLOCKGRIPLOCATIONCOMPONENT", h, id, tags); + self.graph.link(param, c, 1); + } + if !kind.is_list() { + 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 { + if self.name_free(base) { base.to_string() } else { self.numbered_name(base) } + } + + /// `base` and the lowest number from 1 not used as an element name in the block yet + /// (AutoCAD numbers lookup actions from Lookup1). + fn numbered_name(&self, base: &str) -> String { + (1..).map(|i| format!("{base}{i}")).find(|n| self.name_free(n)).unwrap_or_else(|| format!("{base}1")) + } + + /// No parameter or action of the block has element name `name` (any case). + fn name_free(&self, name: &str) -> bool { + dynamic_block(self.d, &self.record) + .is_none_or(|m| !m.parameters.iter().map(|p| &p.element).chain(m.actions.iter().map(|a| &a.name)).any(|u| u.eq_ignore_ascii_case(name))) + } +} + +/// The handle the kept data uses for block `record`'s BLOCK_RECORD (a new one, registered, +/// when none refers to it yet). +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; + } + 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). +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 = || { + 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")) +} + +pub(super) 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 } => { + // 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 { + 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, GripKind::Linear(dir)) } else { 0 }; + let base_grip = + if *grips >= 2 { a.grip(param, *base, "Base Grip", ["UpdatedBaseX", "UpdatedBaseY"], 0.0, GripKind::Linear(-dir)) } else { 0 }; + let mut tags = element_head(h, a.graph.handle, id, &element, if *grips == 2 { 32 } else { 1 }); + tags.extend([tag(100, "AcDbBlockParameter"), tag(280, 1), tag(281, 0), tag(100, "AcDbBlock2PtParameter")]); + point(&mut tags, 1010, *base); + 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, GripKind::Xy) } else { 0 }; + let mut tags = element_head(h, a.graph.handle, id, &element, if *grips == 1 { 0 } else { 1 }); + tags.extend([tag(100, "AcDbBlockParameter"), tag(280, 1), tag(281, 0), tag(100, "AcDbBlock1PtParameter")]); + point(&mut tags, 1010, *at); + 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) + } + ParameterSpec::Visibility { at, label, objects, grips } => { + if !finite(*at) { + return Err("Invalid point.".into()); + } + if *grips > 1 { + return Err("A visibility parameter has 0 or 1 grip.".into()); + } + if objects.len() > MAX_ACTION_ITEMS { + return Err(format!("A visibility parameter controls at most {MAX_ACTION_ITEMS} objects.")); + } + let record = name.trim().to_ascii_uppercase(); + let m = dynamic_block(d, &record); + if m.as_ref().is_some_and(|m| m.parameters.iter().any(|p| matches!(p.kind, ParameterKind::Visibility { .. }))) { + return Err("The block already has a visibility parameter.".into()); + } + // The other parameters and their grips show in the first state. + let active: Vec = m.map(|m| parameter_objects(&m, None)).unwrap_or_default(); + let label = label.clone().unwrap_or_else(|| free_label(d, &record, "Visibility")); + let mut a = Author::open(d, name)?; + let element = a.element_name("Visibility State"); + let (h, id) = (a.d.new_handle(), a.graph.next_id()); + let param = a.graph.add_node(id, h); + let first_grip = a.new.len(); + let grip = if *grips == 1 { a.grip(param, *at, "Grip", ["UpdatedX", "UpdatedY"], 0.0, GripKind::Visibility) } else { 0 }; + let mut tags = element_head(h, a.graph.handle, id, &element, 16); + tags.extend([tag(100, "AcDbBlockParameter"), tag(280, 1), tag(281, 0), tag(100, "AcDbBlock1PtParameter")]); + point(&mut tags, 1010, *at); + tags.extend([tag(93, grip), tag(170, 0), tag(171, 0)]); + let state = VisibilityState { name: "VisibilityState0".into(), visible: objects.clone(), active }; + tags.extend(visibility_tags(&label, "", objects, std::slice::from_ref(&state))); + a.new.insert(first_grip, ForeignObject { handle: h, kind: "BLOCKVISIBILITYPARAMETER".into(), tags }); + a.class("BLOCKVISIBILITYPARAMETER", "AcDbBlockVisibilityParameter"); + a.finish(); + Ok(id) + } + ParameterSpec::Lookup { at, label, name: element, description, show, grips } => { + if !finite(*at) { + return Err("Invalid point.".into()); + } + if *grips > 1 { + return Err("A lookup parameter has 0 or 1 grip.".into()); + } + let record = name.trim().to_ascii_uppercase(); + let label = label.clone().unwrap_or_else(|| free_label(d, &record, "Lookup")); + let mut a = Author::open(d, name)?; + let element = match element.as_deref().map(str::trim).filter(|e| !e.is_empty()) { + Some(e) if !a.name_free(e) => return Err(format!("A parameter or action is already named \"{e}\".")), + Some(e) => e.to_string(), + None => a.element_name("Lookup"), + }; + let (h, id) = (a.d.new_handle(), a.graph.next_id()); + let param = a.graph.add_node(id, h); + let first_grip = a.new.len(); + let grip = if *grips == 1 { a.grip(param, *at, "Grip", ["UpdatedX", "UpdatedY"], 0.0, GripKind::Lookup) } else { 0 }; + let mut tags = element_head(h, a.graph.handle, id, &element, if *grips == 1 { 0 } else { 1 }); + tags.extend([tag(100, "AcDbBlockParameter"), tag(280, i32::from(*show)), tag(281, 0), tag(100, "AcDbBlock1PtParameter")]); + point(&mut tags, 1010, *at); + tags.extend([tag(93, grip), tag(170, 0), tag(171, 0)]); + // 94: its lookup action's graph id, none yet. + tags.extend([tag(100, "AcDbBlockLookUpParameter"), tag(303, &label), tag(304, description.trim()), tag(94, 0)]); + a.new.insert(first_grip, ForeignObject { handle: h, kind: "BLOCKLOOKUPPARAMETER".into(), tags }); + a.class("BLOCKLOOKUPPARAMETER", "AcDbBlockLookupParameter"); + a.finish(); + Ok(id) + } + } +} + +/// Most visibility states one parameter is written with. +pub const MAX_VISIBILITY_STATES: usize = 1_000; + +/// The visibility parameter's own section: label, description, the objects it controls and its +/// states (each the objects shown in it and the parameters and grips active in it). +fn visibility_tags(label: &str, description: &str, controlled: &[Handle], states: &[VisibilityState]) -> Vec { + let mut out = vec![tag(100, "AcDbBlockVisibilityParameter"), tag(281, 1), tag(301, label), tag(302, description), tag(91, 0)]; + out.push(tag(93, controlled.len())); + out.extend(controlled.iter().map(|h| tag(331, h.hex()))); + out.push(tag(92, states.len())); + for s in states { + out.extend([tag(303, &s.name), tag(94, s.visible.len())]); + out.extend(s.visible.iter().map(|h| tag(332, h.hex()))); + out.push(tag(95, s.active.len())); + out.extend(s.active.iter().map(|h| tag(333, h.hex()))); + } + out +} + +/// The objects of block `m`'s parameters other than its visibility parameter, their grips and +/// the block's actions (all of them, or parameter or action `only`'s): what a visibility state +/// lists as active in it. +pub fn parameter_objects(m: &super::DynamicBlock, only: Option) -> Vec { + let grip = |id: &i32| m.grip_objects.iter().find(|(g, _)| g == id).map(|(_, h)| *h); + let params = m + .parameters + .iter() + .filter(|p| !matches!(p.kind, ParameterKind::Visibility { .. }) && only.is_none_or(|n| n == p.node)) + .flat_map(|p| std::iter::once(p.handle).chain(p.grips.iter().filter(|g| **g != 0).filter_map(grip))); + params.chain(m.actions.iter().filter(|a| only.is_none_or(|n| n == a.node)).map(|a| a.handle)).collect() +} + +/// Keep block `name`'s visibility parameter in step with `objects`, the block's objects: as +/// AutoCAD does, one it doesn't control yet (drawn in the Block Editor) becomes controlled and +/// shown in state `current` only (the first state when `None` or not found), and objects no +/// longer in the block leave its lists. Nothing happens without a visibility parameter. +pub fn adopt_objects(d: &mut Drawing, name: &str, objects: &[Handle], current: Option<&str>) -> Result<(), String> { + let Some(m) = dynamic_block(d, name) else { return Ok(()) }; + let Some(ParameterKind::Visibility { controlled, states, .. }) = + m.parameters.into_iter().map(|p| p.kind).find(|k| matches!(k, ParameterKind::Visibility { .. })) + else { + return Ok(()); + }; + let alive: std::collections::HashSet = objects.iter().copied().collect(); + let known: std::collections::HashSet = controlled.iter().copied().collect(); + let new: Vec = objects.iter().filter(|h| !known.contains(h)).copied().collect(); + let gone = controlled.iter().any(|h| !alive.contains(h)) || states.iter().any(|s| s.visible.iter().any(|h| !alive.contains(h))); + if new.is_empty() && !gone { + return Ok(()); + } + let at = current.and_then(|c| states.iter().position(|s| s.name.eq_ignore_ascii_case(c))).unwrap_or(0); + let mut controlled: Vec = controlled.into_iter().filter(|h| alive.contains(h)).collect(); + controlled.extend(new.iter().copied()); + let mut states = states; + for (i, s) in states.iter_mut().enumerate() { + s.visible.retain(|h| alive.contains(h)); + if i == at { + s.visible.extend(new.iter().copied()); + } + } + set_visibility(d, name, &controlled, &states) +} + +/// Rewrite block `name`'s visibility parameter: the objects it `controlled` and its `states` +/// (in order; the first is the one new references start in). +pub fn set_visibility(d: &mut Drawing, name: &str, controlled: &[Handle], states: &[VisibilityState]) -> Result<(), String> { + if states.is_empty() { + return Err("A visibility parameter needs at least one visibility state.".into()); + } + if states.len() > MAX_VISIBILITY_STATES { + return Err(format!("A visibility parameter has at most {MAX_VISIBILITY_STATES} states.")); + } + let too_many = |v: &[Handle]| v.len() > MAX_ACTION_ITEMS; + if too_many(controlled) || states.iter().any(|s| too_many(&s.visible) || too_many(&s.active)) { + return Err(format!("A visibility state lists at most {MAX_ACTION_ITEMS} objects.")); + } + for (i, s) in states.iter().enumerate() { + if s.name.trim().is_empty() { + return Err("A visibility state needs a name.".into()); + } + if states.iter().take(i).any(|o| o.name.eq_ignore_ascii_case(&s.name)) { + return Err(format!("Visibility state \"{}\" already exists.", s.name)); + } + } + let m = dynamic_block(d, name).ok_or("The block has no visibility parameter.")?; + let (handle, label, description) = m + .parameters + .iter() + .find_map(|p| match &p.kind { + ParameterKind::Visibility { label, description, .. } => Some((p.handle, label.clone(), description.clone())), + _ => None, + }) + .ok_or("The block has no visibility parameter.")?; + let f = std::sync::Arc::make_mut(&mut d.foreign); + let o = f.objects.iter_mut().find(|o| o.handle == handle).ok_or("The block's visibility parameter is missing.")?; + let at = o + .tags + .iter() + .position(|t| t.code == 100 && t.value.eq_ignore_ascii_case("AcDbBlockVisibilityParameter")) + .ok_or("The block's visibility parameter can't be changed.")?; + // Its section is the object's last; anything after it would be a layout this doesn't know. + if o.tags.iter().skip(at + 1).any(|t| t.code == 100) { + return Err("The block's visibility parameter can't be changed.".into()); + } + o.tags.truncate(at); + o.tags.extend(visibility_tags(&label, &description, controlled, states)); + Ok(()) +} + +/// Add action `spec` to block `name` (any case); its graph id. The parameter it follows must be +/// 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) + } + ActionSpec::Lookup { parameter, at } => return add_lookup_action(d, name, *parameter, *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")), + // (A lookup action returned above.) + ActionSpec::Move { .. } | ActionSpec::Lookup { .. } => ("BLOCKMOVEACTION", "AcDbBlockMoveAction", a.element_name("Move")), + }; + let mut tags = element_head(h, a.graph.handle, id, &element, 0); + tags.extend([tag(100, "AcDbBlockAction"), tag(70, 0), tag(71, selection.len())]); + 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) +} + +/// Add an empty lookup table to lookup parameter `parameter` of block `name`; its graph id. As in +/// AutoCAD, it reads nothing yet and gives the parameter's value (one lookup column), and the +/// parameter names it (`94`). +fn add_lookup_action(d: &mut Drawing, name: &str, parameter: i32, at: Vec3) -> Result { + if !finite(at) { + return Err("Invalid point.".into()); + } + let m = dynamic_block(d, name).ok_or("The block has no parameters; add one first (BPARAMETER).")?; + let p = m.parameters.iter().find(|p| p.node == parameter).ok_or_else(|| format!("No parameter {parameter} in the block."))?; + if !matches!(p.kind, ParameterKind::Lookup { .. }) { + return Err(format!("A {} can't have a lookup action.", p.element)); + } + if super::lookup::table_of(&m, parameter).is_some() { + return Err("Lookup parameter already associated with a lookup table.".into()); + } + let param_handle = p.handle; + let mut a = Author::open(d, name)?; + let pindex = a.graph.index_of(parameter).ok_or_else(|| format!("No parameter {parameter} in the block."))?; + let (h, id) = (a.d.new_handle(), a.graph.next_id()); + let element = a.numbered_name("Lookup"); + let column = super::TableColumn { node: parameter, property: "lookupString".into(), lookup: true, unmatched: "Custom".into(), reverse: false }; + // 1071 is 8 on a table with no inputs yet, 0 once it has some. + let mut tags = element_head(h, a.graph.handle, id, &element, 8); + tags.extend([tag(100, "AcDbBlockAction"), tag(70, 0), tag(71, 0)]); + point(&mut tags, 1010, at); + tags.extend(super::lookup::table_tags(&[column], &[])); + let node = a.node("BLOCKLOOKUPACTION", h, id, tags); + a.graph.link(node, pindex, 1); + a.class("BLOCKLOOKUPACTION", "AcDbBlockLookupAction"); + a.finish(); + super::lookup::set_action_of(d, param_handle, id); + Ok(id) +} + +/// Give every object of `store`, block `name`'s objects, an element tag (`AcDbBlockRepETag` +/// xdata: `1070 1`, `1071` tag, `1005` the object itself) when it has none or has another +/// object's (a copy), and keep the next free tag on the block's record, as AutoCAD does. Only for +/// 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`. +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); +} + +/// The object entry `key` of dictionary `dict` names. +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() { + 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 0ce4ca3934..197bf280bb 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -60,6 +60,11 @@ pub struct BlockEdit { base: Vec2, /// The editor is open on the drawing itself ([`CURRENT_DRAWING`]). pub current: bool, + /// The visibility state the editor shows (BVSTATE Set); `None` for the block's first. + pub visibility: Option, + /// The parameters and actions picked in the editor (graph ids): MOVE, ERASE and Delete act on + /// them with the selected objects, and their points have grips. + pub picked: Vec, } /// Why a block can't be opened in the Block Editor, if it can't. @@ -103,6 +108,80 @@ 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 { + // Parameters the visibility state shown leaves out aren't drawn, as in AutoCAD. + let inactive = self.inactive_parameters(editor); + self.all_marks(editor).into_iter().filter(|m| m.parameter_node().is_none_or(|n| !inactive.contains(&n))).collect() + } + + /// [`BlockEdit::marks`] with the parameters the visibility state shown leaves out too (BVMODE 1 + /// draws them dimmed; [`BlockEdit::inactive_parameters`] names them). + pub fn all_marks(&self, editor: &Drawing) -> Vec { + use cadcraft_doc::dynblock::Mark; + let off = self.base.to3(0.0); + let mut out = cadcraft_doc::dynblock::marks(editor, &self.name); + 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::List { at, .. } | Mark::Parameter { at, .. } | Mark::Action { at, .. } => *at = *at - off, + } + } + out + } + + /// The visibility state the editor shows: its name, the objects it hides (none without a + /// visibility parameter). `editor` is the editor's drawing. + pub fn visibility_state(&self, editor: &Drawing) -> Option<(String, Vec)> { + use cadcraft_doc::dynblock::ParameterKind; + let m = cadcraft_doc::dynblock::dynamic_block(editor, &self.name)?; + let (controlled, states) = m.parameters.into_iter().find_map(|p| match p.kind { + ParameterKind::Visibility { controlled, states, .. } => Some((controlled, states)), + _ => None, + })?; + let state = self.visibility.as_deref().and_then(|v| states.iter().find(|s| s.name.eq_ignore_ascii_case(v))).or(states.first())?; + let shown: std::collections::HashSet<_> = state.visible.iter().copied().collect(); + Some((state.name.clone(), controlled.into_iter().filter(|h| !shown.contains(h)).collect())) + } + + /// Graph ids of the parameters the visibility state the editor shows doesn't list as active + /// (the visibility parameter itself always shows). + pub fn inactive_parameters(&self, editor: &Drawing) -> Vec { + use cadcraft_doc::dynblock::ParameterKind; + let Some(m) = cadcraft_doc::dynblock::dynamic_block(editor, &self.name) else { return Vec::new() }; + let Some(states) = m.parameters.iter().find_map(|p| match &p.kind { + ParameterKind::Visibility { states, .. } => Some(states), + _ => None, + }) else { + return Vec::new(); + }; + let Some(state) = self.visibility.as_deref().and_then(|v| states.iter().find(|s| s.name.eq_ignore_ascii_case(v))).or(states.first()) else { + return Vec::new(); + }; + m.parameters + .iter() + .filter(|p| !matches!(p.kind, ParameterKind::Visibility { .. }) && !state.active.contains(&p.handle)) + .map(|p| p.node) + .collect() + } + + /// Hide in `editor` (the editor's drawing) what the visibility state it shows hides, and show + /// the rest, as AutoCAD's Block Editor does with BVMODE 0; with `bvmode` (1) hide nothing. + pub fn show_visibility_state(&self, editor: &mut Drawing, bvmode: bool) { + let hidden = if bvmode { Vec::new() } else { self.visibility_state(editor).map(|(_, h)| h).unwrap_or_default() }; + let hidden: std::collections::BTreeSet<_> = hidden.into_iter().filter(|h| editor.model.get(*h).is_some()).collect(); + if editor.hidden_objects != hidden { + editor.hidden_objects = hidden; + } + } + /// The editor's objects in block coordinates, ready to be the block's: unchanged objects are /// the block's own, the others are moved back from the editor's origin to the base point. fn block_objects(&self, editor: &Drawing) -> EntityStore { @@ -132,12 +211,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."))); @@ -170,9 +259,24 @@ 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; 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) { + remap = cadcraft_doc::dynblock::copy_definition(&mut d, &self.name, name, &mut entities).map_err(EngineError::Other)?; + cadcraft_doc::dynblock::restore_definition(&mut d, host, &self.name); + } + // Objects drawn in the editor show in the visibility state it shows only, as in AutoCAD. + let handles: Vec = entities.iter().map(|e| e.handle).collect(); + cadcraft_doc::dynblock::adopt_objects(&mut d, name, &handles, self.visibility.as_deref()).map_err(EngineError::Other)?; + // A dynamic block's objects carry element tags, which its references' copies are paired + // with; objects added in the editor get theirs here. + cadcraft_doc::dynblock::tag_elements(&mut d, name, &mut entities); b.entities = entities; d.blocks.insert(key, Arc::new(b)); - Ok(d) + Ok((d, remap)) } } @@ -225,6 +329,12 @@ impl DocState { /// Open the Block Editor on block `name` (BEDIT). /// With `create`, a name no block has yet starts a new, empty block, which BSAVE creates. pub fn open_block_editor(&mut self, name: &str, create: bool) -> Result<()> { + self.open_block_editor_with(name, create, false) + } + + /// [`DocState::open_block_editor`] with BVMODE `bvmode`: objects the first visibility state + /// hides are hidden (false) or left shown for the canvas to dim (true). + pub fn open_block_editor_with(&mut self, name: &str, create: bool, bvmode: bool) -> Result<()> { if let Some(open) = self.block_editor() { return Err(EngineError::Other(format!("The Block Editor is already open on \"{open}\"; close it first (BCLOSE)."))); } @@ -238,6 +348,8 @@ impl DocState { original: EntityStore::new(), base: Vec2::ZERO, current: true, + visibility: None, + picked: Vec::new(), }); return Ok(()); } @@ -258,9 +370,21 @@ impl DocState { d.constraints.clear(); d.hidden_objects.clear(); let host = Box::new(self.clone()); - let editor = Arc::new(d); - self.doc = editor.clone(); - self.enter_block_editor(BlockEdit { name: block.name.clone(), host, saved: editor, original: block.entities.clone(), base, current: false }); + let mut be = BlockEdit { + name: block.name.clone(), + host, + saved: self.doc.clone(), + original: block.entities.clone(), + base, + current: false, + visibility: None, + picked: Vec::new(), + }; + // The editor shows the block's first visibility state (its other objects hidden). + be.show_visibility_state(&mut d, bvmode); + be.saved = Arc::new(d); + self.doc = be.saved.clone(); + self.enter_block_editor(be); Ok(()) } @@ -289,8 +413,17 @@ impl DocState { /// (BSAVEAS), which the editor then edits. One undo step in the drawing. pub fn save_block_editor(&mut self, as_name: Option<&str>) -> Result<()> { let Some(be) = &self.block_edit else { return Err(EngineError::Other("The Block Editor is not open.".into())) }; + // Objects drawn in the editor join its visibility states here too, so the editor and the + // block agree. + let handles: Vec = self.doc.model.iter().map(|e| e.handle).collect(); + let mut d = (*self.doc).clone(); + cadcraft_doc::dynblock::adopt_objects(&mut d, &be.name, &handles, be.visibility.as_deref()).map_err(EngineError::Other)?; + if !Arc::ptr_eq(&d.foreign, &self.doc.foreign) { + self.doc = Arc::new(d); + } + let Some(be) = &self.block_edit else { return Ok(()) }; let name = as_name.unwrap_or(&be.name).to_string(); - let d = 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 @@ -305,10 +438,23 @@ impl DocState { restore_saved_definition(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()) { - 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(); @@ -355,3 +501,93 @@ impl DocState { Ok(()) } } + +impl crate::Session { + /// Show in the Block Editor what the visibility state it shows shows (BVSTATE): the other + /// objects hidden, or with BVMODE 1 left for the canvas to dim. Nothing outside the editor. + pub(crate) fn refresh_block_visibility(&mut self) -> Result<()> { + let bvmode = self.settings.bvmode; + // Without a drawing there is no Block Editor (SETVAR BVMODE from the Start tab). + let Ok(st) = self.state() else { return Ok(()) }; + let Some(be) = &st.block_edit else { return Ok(()) }; + let hidden = if bvmode { Vec::new() } else { be.visibility_state(&st.doc).map(|(_, h)| h).unwrap_or_default() }; + let hidden: std::collections::BTreeSet<_> = hidden.into_iter().filter(|h| st.doc.model.get(*h).is_some()).collect(); + if hidden != st.doc.hidden_objects { + self.doc_mut()?.hidden_objects = hidden; + } + Ok(()) + } + + /// The parameters and actions picked in the Block Editor (graph ids), those still there. + pub fn picked_elements(&self) -> Vec { + let Ok(st) = self.state() else { return Vec::new() }; + let Some(be) = &st.block_edit else { return Vec::new() }; + if be.picked.is_empty() { + return Vec::new(); + } + let Some(m) = cadcraft_doc::dynblock::dynamic_block(&st.doc, &be.name) else { return Vec::new() }; + be.picked.iter().copied().filter(|n| m.parameters.iter().any(|p| p.node == *n) || m.actions.iter().any(|a| a.node == *n)).collect() + } + + /// Pick parameters and actions `nodes` in the Block Editor (added to those picked with + /// `add`; none and not `add` picks nothing). + pub fn pick_elements(&mut self, nodes: &[i32], add: bool) -> Result<()> { + let st = self.state_mut()?; + let Some(be) = st.block_edit.as_mut() else { return Ok(()) }; + if !add { + be.picked.clear(); + } + for n in nodes { + if !be.picked.contains(n) { + be.picked.push(*n); + } + } + Ok(()) + } + + /// Move the picked parameters and actions by `d` (MOVE with them picked); they stay picked. + /// One that can't be moved yet (a kind from another file, such as a polar parameter) stays + /// where it is and is reported, so MOVE never stops after the objects have moved. + pub(crate) fn move_picked_elements(&mut self, d: Vec2) -> Result { + let nodes = self.picked_elements(); + if nodes.is_empty() || d == Vec2::ZERO { + return Ok(0); + } + let name = self.state()?.block_edit.as_ref().map(|b| b.name.clone()).unwrap_or_default(); + let mut doc = self.doc()?.clone(); + let (mut moved, mut stayed) = (0, 0); + for n in &nodes { + // Each on a copy: a refused one leaves the others' moves alone. + let mut trial = doc.clone(); + match cadcraft_doc::dynblock::move_element(&mut trial, &name, *n, d.to3(0.0)) { + Ok(()) => { + doc = trial; + moved += 1; + } + Err(_) => stayed += 1, + } + } + if stayed > 0 { + self.echo(format!("{stayed} parameter(s) of a kind that can't be moved yet stayed where they were.")); + } + if moved > 0 { + *self.doc_mut()? = doc; + } + Ok(moved) + } + + /// Erase the picked parameters and actions (ERASE, Delete), as AutoCAD erases them: a + /// parameter takes its actions along. Nothing is picked afterwards. + pub(crate) fn erase_picked_elements(&mut self) -> Result { + let nodes = self.picked_elements(); + self.pick_elements(&[], false)?; + if nodes.is_empty() { + return Ok(0); + } + let name = self.state()?.block_edit.as_ref().map(|b| b.name.clone()).unwrap_or_default(); + let mut doc = self.doc()?.clone(); + let erased = cadcraft_doc::dynblock::erase_elements(&mut doc, &name, &nodes).map_err(EngineError::Other)?; + *self.doc_mut()? = doc; + Ok(erased.len()) + } +} diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 181aacd287..3e7490c83c 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -19,7 +19,11 @@ use crate::{Accept, AttribAsk, AttribEntry, EngineError, Input, Interactive, Ori mod attdef; pub(crate) mod attedit; +mod bauthor; +mod belement; +mod blookup; mod burst; +mod bvstate; mod description; mod dyngrip; mod extract; @@ -103,6 +107,10 @@ pub fn specs() -> Vec { .chain(refedit::specs()) .chain(xclip::specs()) .chain(bedit::specs()) + .chain(bauthor::specs()) + .chain(belement::specs()) + .chain(bvstate::specs()) + .chain(blookup::specs()) .collect() } diff --git a/crates/engine/src/cmd/blocks/bauthor.rs b/crates/engine/src/cmd/blocks/bauthor.rs new file mode 100644 index 0000000000..5b8121fcaf --- /dev/null +++ b/crates/engine/src/cmd/blocks/bauthor.rs @@ -0,0 +1,836 @@ +//! 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, a value from a lookup +//! table); an action is what changing it does to the block's objects (stretch them, move them) or, +//! for a lookup parameter, its lookup table (filled with BLOOKUPTABLE). Both are written into the +//! block's dynamic data ([`cadcraft_doc::dynblock::add_parameter`], [`add_action`]) as AutoCAD +//! writes its own, so the block works as a dynamic block here and in AutoCAD. Only while the +//! Block Editor is open on a block; points are in the editor's coordinates (the block's base point +//! at the origin). + +use cadcraft_doc::dynblock::{ + ActionKind, ActionSpec, Mark, ParamPoint, ParameterKind, ParameterSpec, add_action, add_parameter, dynamic_block, marks, +}; +use cadcraft_doc::{Drawing, EntityKind, Handle}; +use cadcraft_geom::{Vec2, Vec3}; +use serde_json::{Value, json}; + +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) + .alias(&["-bparameter"]) + .params( + "{type: \"linear\"|\"point\"|\"visibility\"|\"lookup\", linear: start: [x,y], end: [x,y], labelAt?: [x,y] (where the label goes; default on the line); point: at: [x,y], labelAt?: [x,y]; visibility: at: [x,y] (one state, VisibilityState0, showing every object; one per block); lookup: at: [x,y], name?: its name in the editor (default Lookup), description?: text, palette?: bool (shown in Properties; default true); label?: property name (default Distance1/Position1/Visibility1/Lookup1…), grips?: 0|1|2 (linear, default 2) or 0|1 (point, visibility, lookup, default 1)} → {node, element, label} (editor coordinates)", + ) + .enabled(authoring) + .interactive(|_| Ok(Box::new(BparameterM::default()))), + CommandSpec::new("baction", "Action", run_baction) + .alias(&["-baction"]) + .params( + "{parameter: graph id or property name (\"Distance1\"), type: \"stretch\"|\"move\"|\"lookup\" (a lookup parameter's, and the default for one: its empty lookup table, one per parameter; fill it with BLOOKUPTABLE), point?: \"start\"|\"second\" (which end of a linear parameter it follows, default second), handles: [objects], frame?: [[x,y],[x,y]] (stretch: corners) | polygon?: [[x,y]…] (stretch: a crossing polygon), at?: [x,y] (where the action shows; default the parameter's point)} → {node, name} (editor coordinates)", + ) + .enabled(authoring) + .interactive(|_| Ok(Box::new(BactionM::default()))), + ] +} + +/// 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("visibility") => { + let at = point_param(p, "at").ok_or_else(|| bad("bparameter", "`at` ([x, y]) is required"))?; + let objects = s.doc()?.model.iter().map(|e| e.handle).collect(); + ParameterSpec::Visibility { at: to_block(at, base), label, objects, grips: grips_param("bparameter", p, 1, 1)? } + } + Some("lookup") => { + let at = point_param(p, "at").ok_or_else(|| bad("bparameter", "`at` ([x, y]) is required"))?; + let show = match p.get("palette") { + None | Some(Value::Null) => true, + Some(v) => v.as_bool().ok_or_else(|| bad("bparameter", "`palette` is true or false"))?, + }; + ParameterSpec::Lookup { + at: to_block(at, base), + label, + name: str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string), + description: str_param(p, "description").unwrap_or_default().to_string(), + show, + grips: grips_param("bparameter", p, 1, 1)?, + } + } + Some(other) if ["alignment", "base", "polar", "xy", "rotation", "flip"].contains(&other) => { + return Err(bad("bparameter", format!("{other} parameters are not available yet"))); + } + _ => return Err(bad("bparameter", "`type` is \"linear\", \"point\", \"visibility\" or \"lookup\"")), + }; + let visibility = matches!(spec, ParameterSpec::Visibility { .. }); + let node = add_parameter(s.doc_mut()?, &block, &spec).map_err(|e| bad("bparameter", e))?; + // A parameter added after visibility states shows its grips in the state the editor shows. + if !visibility { + super::bvstate::parameter_added(s, node)?; + } + let m = cadcraft_doc::dynblock::dynamic_block(s.doc()?, &block); + let made = m.as_ref().and_then(|m| m.parameters.iter().find(|p| p.node == node)); + Ok(json!({ "node": node, "element": made.map(|p| p.element.clone()), "label": made.and_then(|p| p.kind.label().map(str::to_string)) })) +} + +/// 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, + }, + /// A lookup parameter (its action is its lookup table). + Lookup { + node: i32, + at: Vec2, + }, +} + +impl Followed { + fn node(&self) -> i32 { + match self { + Followed::Linear { node, .. } | Followed::Point { node, .. } | Followed::Lookup { node, .. } => *node, + } + } +} + +/// The parameters of `block` an action can follow, in editor coordinates. +fn followable(d: &Drawing, block: &str, base: Vec2) -> Vec { + let lookups: Vec = dynamic_block(d, block) + .map(|m| m.parameters.iter().filter(|p| matches!(p.kind, ParameterKind::Lookup { .. })).map(|p| p.node).collect()) + .unwrap_or_default(); + marks(d, block) + .into_iter() + .filter_map(|m| match m { + Mark::Linear { node, base: b, end, .. } => Some(Followed::Linear { node, base: b.xy() - base, end: end.xy() - base }), + Mark::Point { node, at, .. } => Some(Followed::Point { node, at: at.xy() - base }), + Mark::List { node, at, .. } if lookups.contains(&node) => Some(Followed::Lookup { node, at: at.xy() - base }), + _ => None, + }) + .collect() +} + +/// Whether lookup parameter `node` of `block` has its lookup table already (one per parameter). +fn has_table(d: &Drawing, block: &str, node: i32) -> bool { + dynamic_block(d, block).is_some_and(|m| { + m.actions.iter().any(|a| matches!(&a.kind, ActionKind::Lookup { columns, .. } if columns.iter().any(|c| c.lookup && c.node == node))) + }) +} + +/// The parameter named by `v`: its graph id, or its property name ("Distance1"). +fn parameter_named(d: &Drawing, block: &str, base: Vec2, v: &Value) -> Result { + let list = followable(d, block, base); + 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 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, .. } | Followed::Lookup { at, .. } => *at, + }; + let at = to_block(at.unwrap_or(shown), base); + match (param, kind) { + (Followed::Lookup { .. }, "lookup") => {} + (Followed::Lookup { .. }, _) => return Err(bad("baction", "a lookup parameter's action is its lookup table (`type`: \"lookup\")")), + (_, "lookup") => return Err(bad("baction", "a lookup action needs a lookup parameter")), + _ => {} + } + let spec = match kind { + "stretch" => { + let frame = frame.ok_or_else(|| bad("baction", "a stretch needs `frame` (two corners) or `polygon`"))?; + 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 }, + "lookup" => ActionSpec::Lookup { parameter: param.node(), at }, + "array" | "scale" | "rotate" | "flip" | "polarstretch" => { + return Err(bad("baction", format!("{kind} actions are not available yet"))); + } + _ => return Err(bad("baction", "`type` is \"stretch\", \"move\" or \"lookup\"")), + }; + let node = add_action(s.doc_mut()?, &block, &spec).map_err(|e| bad("baction", e))?; + // Active in the visibility state the editor shows, as a parameter added there is. + super::bvstate::parameter_added(s, node)?; + let name = cadcraft_doc::dynblock::dynamic_block(s.doc()?, &block).and_then(|m| m.actions.into_iter().find(|a| a.node == node)).map(|a| a.name); + Ok(json!({ "node": node, "name": name })) +} + +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 = match (str_param(p, "type"), ¶m) { + (Some(t), _) => t.trim().to_ascii_lowercase().replace(' ', ""), + // A lookup parameter has one kind of action, and it acts on no objects. + (None, Followed::Lookup { .. }) => "lookup".to_string(), + (None, _) => return Err(bad("baction", "`type` is required")), + }; + if kind == "lookup" { + return add(s, ¶m, &kind, ParamPoint::End, &[], None, point_param(p, "at")); + } + let point = match str_param(p, "point").map(str::to_ascii_lowercase).as_deref() { + None | Some("second") | Some("end") => ParamPoint::End, + Some("start") | Some("base") => ParamPoint::Base, + 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, + } +} + +/// The name a new parameter gets by default: `prefix` alone when free (element names only, as +/// for the element "Lookup"), else `prefix` and the lowest free number; property labels +/// (`labels`) always take a number (Lookup1). +fn next_name(s: &Session, prefix: &str, labels: bool) -> String { + let used: Vec = s + .state() + .ok() + .and_then(|st| dynamic_block(&st.doc, &st.block_edit.as_ref()?.name)) + .map(|m| { + if labels { + m.parameters.iter().filter_map(|p| p.kind.label().map(str::to_string)).collect() + } else { + m.parameters.iter().map(|p| p.element.clone()).chain(m.actions.iter().map(|a| a.name.clone())).collect() + } + }) + .unwrap_or_default(); + let free = |n: &str| !used.iter().any(|u| u.eq_ignore_ascii_case(n)); + if !labels && free(prefix) { + return prefix.to_string(); + } + (1..).map(|i| format!("{prefix}{i}")).find(|n| free(n)).unwrap_or_else(|| format!("{prefix}1")) +} + +/// Options AutoCAD offers that are not available yet: answered with a message. +fn not_yet(s: &mut Session, what: &str) -> Result { + s.echo(format!("{what} is not available yet.")); + Ok(Step::Continue) +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum PStage { + #[default] + Type, + Start, + End, + LinearLabel, + LinearGrips, + Location, + PointLabel, + PointGrips, + VisibilityGrips, + /// Typing the property name, then back to the stage it was asked at. + Label(&'static str), + /// A lookup parameter's name in the editor, its description, and whether Properties shows it. + Name, + Description, + Palette, +} + +/// BPARAMETER's prompts, as AutoCAD asks them on the command line. +#[derive(Default)] +struct BparameterM { + stage: PStage, + linear: bool, + visibility: bool, + lookup: bool, + /// A lookup parameter's name, description and "not in Properties" (Palette No). + name: Option, + description: String, + hidden: bool, + start: Vec2, + end: Vec2, + label_at: Vec2, + 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.lookup { + json!({ "type": "lookup", "at": [self.start.x, self.start.y], "label": label, "name": self.name, "description": self.description, "palette": !self.hidden, "grips": grips }) + } else if self.visibility { + json!({ "type": "visibility", "at": [self.start.x, self.start.y], "label": label, "grips": grips }) + } else if self.linear { + json!({ "type": "linear", "start": [self.start.x, self.start.y], "end": [self.end.x, self.end.y], "labelAt": [self.label_at.x, self.label_at.y], "label": label, "grips": grips }) + } 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 if self.visibility || self.lookup { + &[("Name", "N"), ("Label", "L"), ("Description", "D"), ("Palette", "P")] + } 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 if self.visibility || self.lookup => { + Prompt::new("Specify parameter location", Accept::POINT).kw(&["Name", "Label", "Description", "Palette"]) + } + PStage::Location => Prompt::new("Specify parameter location", Accept::POINT).kw(&["Name", "Label", "Chain", "Description", "Palette"]), + PStage::PointGrips | PStage::VisibilityGrips => Prompt::new("Enter number of grips", KW).kw(&["0", "1"]).default("1"), + PStage::Label("lookup") => { + Prompt::new("Enter lookup property label", Accept::TEXT).default(self.label.clone().unwrap_or_else(|| next_name(s, "Lookup", true))) + } + PStage::Label(what) => Prompt::new(format!("Enter {what} property label"), Accept::TEXT), + PStage::Name => { + Prompt::new("Enter parameter name", Accept::TEXT).default(self.name.clone().unwrap_or_else(|| next_name(s, "Lookup", false))) + } + PStage::Description => Prompt::new("Enter property description", Accept::TEXT), + PStage::Palette => { + Prompt::new("Display property in Properties palette", KW).kw(&["Yes", "No"]).default(if self.hidden { "No" } else { "Yes" }) + } + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + 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("Visibility") => (self.visibility, self.stage) = (true, PStage::Location), + Some("looKup") => (self.lookup, self.stage) = (true, PStage::Location), + Some(other) => return Err(EngineError::Other(format!("{other} parameters are not available yet."))), + None => s.echo("Invalid option keyword."), + } + } + PStage::Start | PStage::Location => match (&i, self.options(&i)) { + (Input::Point(p), _) => { + self.start = *p; + self.stage = if self.linear { + PStage::End + } else if self.visibility || self.lookup { + PStage::VisibilityGrips + } else { + PStage::PointLabel + }; + } + (_, Some("Label")) => { + self.stage = PStage::Label(if self.linear { + "distance" + } else if self.lookup { + "lookup" + } else if self.visibility { + "visibility" + } else { + "position" + }) + } + (_, Some("Name")) if self.lookup => self.stage = PStage::Name, + (_, Some("Description")) if self.lookup => self.stage = PStage::Description, + (_, Some("Palette")) if self.lookup => self.stage = PStage::Palette, + (_, Some(other)) => return not_yet(s, other), + _ => {} + }, + 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 | PStage::VisibilityGrips => { + 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 }; + } + PStage::Name => { + match &i { + Input::Text(t) | Input::Keyword(t) if !t.trim().is_empty() => self.name = Some(t.trim().to_string()), + _ => {} + } + self.stage = PStage::Location; + } + PStage::Description => { + if let Some(t) = text_of(&i) { + self.description = t.trim().to_string(); + } + self.stage = PStage::Location; + } + PStage::Palette => { + match (&i, text_of(&i).and_then(|t| keyword(t, &[("Yes", "Y"), ("No", "N")]))) { + (Input::Enter, _) => {} + (_, Some(k)) => self.hidden = k == "No", + _ => { + s.echo("Invalid option keyword."); + return Ok(Step::Continue); + } + } + self.stage = PStage::Location; + } + } + Ok(Step::Continue) + } + 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 if self.kind == "lookup" => Prompt::new("Specify action location", Accept::POINT), + 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, .. } | Followed::Lookup { at, .. } => (*at - *p).len(), + }; + let list = followable(s.doc()?, &block, base); + list.into_iter().map(|f| (near(&f), f)).filter(|(d, _)| *d <= reach).min_by(|a, b| a.0.total_cmp(&b.0)).map(|(_, f)| f) + } + 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 { + // A lookup parameter's action is its table, asked for no type or objects. + Some(Followed::Lookup { node, .. }) if has_table(s.doc()?, &block, node) => { + s.echo("Lookup parameter already associated with a lookup table."); + } + Some(f @ Followed::Lookup { .. }) => { + self.param = Some(f); + self.kind = "lookup"; + self.stage = AStage::Location; + } + Some(f) => { + self.param = Some(f); + self.stage = AStage::Type; + } + None => s.echo("No linear, point or lookup 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..eae69b27f0 100644 --- a/crates/engine/src/cmd/blocks/bedit.rs +++ b/crates/engine/src/cmd/blocks/bedit.rs @@ -145,7 +145,8 @@ fn open(s: &mut Session, name: &str, create: bool, save: Option) -> Result /// [`open`] with the Block Editor closed. fn open_closed(s: &mut Session, name: &str, create: bool) -> Result { let new = create && !name.eq_ignore_ascii_case(crate::blockedit::CURRENT_DRAWING) && s.doc()?.block(name).is_none(); - s.state_mut()?.open_block_editor(name, create)?; + let bvmode = s.settings.bvmode; + s.state_mut()?.open_block_editor_with(name, create, bvmode)?; let name = s.state()?.block_editor().unwrap_or(name).to_string(); // The block's objects with room around them (and the editor's bar above them). s.zoom_extents()?; @@ -159,7 +160,7 @@ fn open_closed(s: &mut Session, name: &str, create: bool) -> Result { let dynamic = |be: &crate::blockedit::BlockEdit| crate::blockedit::has_dynamic_data(&be.host.doc, if be.current { "*Model_Space" } else { &be.name }); if s.state().is_ok_and(|st| st.block_edit.as_ref().is_some_and(dynamic)) { - s.echo("This is a dynamic block: 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, point, visibility and lookup parameters with stretch, move and lookup actions, BVSTATE, BVHIDE and BVSHOW edit visibility states, BLOOKUPTABLE fills lookup tables; its other parameters and actions are kept as they are."); } Ok(json!({ "block": name, "new": new })) } diff --git a/crates/engine/src/cmd/blocks/belement.rs b/crates/engine/src/cmd/blocks/belement.rs new file mode 100644 index 0000000000..547617b71a --- /dev/null +++ b/crates/engine/src/cmd/blocks/belement.rs @@ -0,0 +1,218 @@ +//! Picking, moving and erasing a dynamic block's parameters and actions in the Block Editor, as +//! AutoCAD's editor treats them: they are picked like objects (the UI picks them on a click), +//! MOVE and ERASE (and Delete) act on the picked ones with the selected objects, and a picked +//! one's points have grips (a linear parameter's ends and label line, a point parameter's +//! location and label, a visibility or lookup parameter's location, an action's location). +//! Erasing a parameter erases its actions. Points are in the editor's coordinates (the block's +//! base point at the origin). + +use cadcraft_doc::EntityKind; +use cadcraft_doc::dynblock::{self, ElementPoint}; +use cadcraft_geom::Vec2; +use serde_json::{Value, json}; + +use crate::cmd::{CommandSpec, bad, point_param, str_param}; +use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Running, Session, Step}; + +pub(super) fn specs() -> Vec { + vec![ + CommandSpec::new("blocks.element.select", "Pick Parameters and Actions", run_select) + .params("{nodes?: [graph ids] (none: pick nothing), add?: bool (add to those picked)} → {picked}") + .enabled(editing), + CommandSpec::new("blocks.element.move", "Move Parameters and Actions", run_move) + .params("{nodes?: [graph ids] (default the picked ones), delta: [dx, dy]} → {moved}") + .enabled(editing), + CommandSpec::new("blocks.element.point", "Move a Parameter's Point", run_point) + .params("{node: graph id, point: \"base\"|\"end\"|\"at\"|\"label\", to: [x, y]} (editor coordinates)") + .enabled(editing), + CommandSpec::new("blocks.element.points", "Parameter Points", run_points) + .params("{node: graph id} → {points: [{point, at}]} (editor coordinates; read-only)") + .enabled(editing), + CommandSpec::new("blocks.element.erase", "Erase Parameters and Actions", run_erase) + .params("{nodes?: [graph ids] (default the picked ones)} → {erased: [graph ids]} (a parameter's actions go with it)") + .enabled(editing), + ] +} + +/// The Block Editor is open on a block. +fn editing(s: &Session) -> std::result::Result<(), String> { + match s.state() { + Ok(st) => match &st.block_edit { + Some(be) if be.current => Err("This editor is open on the drawing itself, which has no parameters or actions.".into()), + Some(_) => Ok(()), + None => Err("Open a block in the Block Editor first (BEDIT).".into()), + }, + Err(e) => Err(e.to_string()), + } +} + +/// The edited block and its base point (the editor's origin). +fn edited(s: &Session) -> Result<(String, Vec2)> { + editing(s).map_err(EngineError::Other)?; + let be = s.state()?.block_edit.as_ref().ok_or_else(|| EngineError::Other("The Block Editor is not open.".into()))?; + Ok((be.name.clone(), be.base())) +} + +fn nodes_param(cmd: &str, p: &Value, s: &Session) -> Result> { + match p.get("nodes") { + None | Some(Value::Null) => Ok(s.picked_elements()), + Some(Value::Array(a)) if a.len() <= dynblock::MAX_ACTION_ITEMS => { + a.iter().map(|v| v.as_i64().and_then(|n| i32::try_from(n).ok()).ok_or_else(|| bad(cmd, format!("{v} is not a graph id")))).collect() + } + Some(_) => Err(bad(cmd, "`nodes` is a list of graph ids")), + } +} + +fn node_param(cmd: &str, p: &Value) -> Result { + p.get("node").and_then(Value::as_i64).and_then(|n| i32::try_from(n).ok()).ok_or_else(|| bad(cmd, "`node`: a graph id")) +} + +fn point_name(p: ElementPoint) -> &'static str { + match p { + ElementPoint::Base => "base", + ElementPoint::End => "end", + ElementPoint::At => "at", + ElementPoint::Label => "label", + } +} + +fn run_select(s: &mut Session, p: &Value) -> Result { + let (block, _) = edited(s)?; + let nodes = match p.get("nodes") { + None | Some(Value::Null) => Vec::new(), + _ => nodes_param("blocks.element.select", p, s)?, + }; + let m = dynblock::dynamic_block(s.doc()?, &block); + let known = |n: &i32| m.as_ref().is_some_and(|m| m.parameters.iter().any(|p| p.node == *n) || m.actions.iter().any(|a| a.node == *n)); + if let Some(n) = nodes.iter().find(|n| !known(n)) { + return Err(bad("blocks.element.select", format!("no parameter or action {n} in the block"))); + } + let add = p.get("add").and_then(Value::as_bool).unwrap_or(false); + s.pick_elements(&nodes, add)?; + Ok(json!({ "picked": s.picked_elements() })) +} + +fn run_move(s: &mut Session, p: &Value) -> Result { + let (block, _) = edited(s)?; + let nodes = nodes_param("blocks.element.move", p, s)?; + let d = point_param(p, "delta").ok_or_else(|| bad("blocks.element.move", "`delta`: [dx, dy]"))?; + let mut doc = s.doc()?.clone(); + for n in &nodes { + dynblock::move_element(&mut doc, &block, *n, d.to3(0.0)).map_err(|e| bad("blocks.element.move", e))?; + } + *s.doc_mut()? = doc; + Ok(json!({ "moved": nodes.len() })) +} + +fn run_point(s: &mut Session, p: &Value) -> Result { + let (block, base) = edited(s)?; + let node = node_param("blocks.element.point", p)?; + let which = match str_param(p, "point").map(str::to_ascii_lowercase).as_deref() { + Some("base") | Some("start") => ElementPoint::Base, + Some("end") => ElementPoint::End, + Some("at") => ElementPoint::At, + Some("label") => ElementPoint::Label, + _ => return Err(bad("blocks.element.point", "`point` is \"base\", \"end\", \"at\" or \"label\"")), + }; + let to = point_param(p, "to").ok_or_else(|| bad("blocks.element.point", "`to`: [x, y]"))?; + let mut doc = s.doc()?.clone(); + dynblock::set_element_point(&mut doc, &block, node, which, (to + base).to3(0.0)).map_err(|e| bad("blocks.element.point", e))?; + *s.doc_mut()? = doc; + Ok(json!({ "node": node })) +} + +fn run_points(s: &mut Session, p: &Value) -> Result { + let (block, base) = edited(s)?; + let node = node_param("blocks.element.points", p)?; + let pts: Vec = dynblock::element_points(s.doc()?, &block, node) + .into_iter() + .map(|(w, at)| json!({ "point": point_name(w), "at": [at.x - base.x, at.y - base.y] })) + .collect(); + Ok(json!({ "points": pts })) +} + +fn run_erase(s: &mut Session, p: &Value) -> Result { + let (block, _) = edited(s)?; + let nodes = nodes_param("blocks.element.erase", p, s)?; + if nodes.is_empty() { + return Ok(json!({ "erased": [] })); + } + let mut doc = s.doc()?.clone(); + let erased = dynblock::erase_elements(&mut doc, &block, &nodes).map_err(|e| bad("blocks.element.erase", e))?; + *s.doc_mut()? = doc; + let left: Vec = s.picked_elements().into_iter().filter(|n| !erased.contains(n)).collect(); + s.pick_elements(&left, false)?; + Ok(json!({ "erased": erased })) +} + +/// A picked parameter's or action's grip being dragged (click it, then click where it goes). +struct ElementGrip { + node: i32, + which: ElementPoint, + /// Where the grip is, in the editor (the rubber band's start). + from: Vec2, +} + +impl Interactive for ElementGrip { + fn name(&self) -> &'static str { + "GRIP" + } + + fn prompt(&self, _s: &Session) -> Prompt { + Prompt::new("** STRETCH ** Specify stretch point", Accept::POINT).kw(&["eXit"]).base(self.from) + } + + fn input(&mut self, s: &mut Session, i: Input) -> Result { + let to = match i { + Input::Point(p) => p, + Input::Deferred(d) => d.at, + Input::Keyword(k) if k == "eXit" => return Ok(Step::Done), + Input::Enter | Input::Cancel => return Ok(Step::Done), + _ => return Err(EngineError::Other("Requires a point.".into())), + }; + let (block, base) = edited(s)?; + let mut doc = s.doc()?.clone(); + dynblock::set_element_point(&mut doc, &block, self.node, self.which, (to + base).to3(0.0)).map_err(EngineError::Other)?; + *s.doc_mut()? = doc; + Ok(Step::Done) + } + + fn preview(&self, _s: &Session, c: Vec2) -> Vec { + vec![crate::cmd::helpers::line(self.from, c)] + } +} + +impl Session { + /// The grips of the parameters and actions picked in the Block Editor: (graph id, point, + /// where it is in the editor). + pub fn element_grips(&self) -> Vec<(i32, ElementPoint, Vec2)> { + let Ok((block, base)) = edited(self) else { return Vec::new() }; + let Ok(d) = self.doc() else { return Vec::new() }; + self.picked_elements() + .into_iter() + .flat_map(|n| dynblock::element_points(d, &block, n).into_iter().map(move |(w, at)| (n, w, at.xy() - base))) + .collect() + } + + /// Start dragging point `which` of picked parameter or action `node` (the UI's click on its + /// grip in the Block Editor): the next point puts it there. + pub fn start_element_grip(&mut self, node: i32, which: ElementPoint) -> Result<()> { + if self.running.is_some() { + self.cancel(); + } + let from = self + .element_grips() + .into_iter() + .find(|(n, w, _)| *n == node && *w == which) + .map(|(_, _, at)| at) + .ok_or_else(|| EngineError::Other("no such grip".into()))?; + let machine = crate::guard::Guarded::wrap(Box::new(ElementGrip { node, which, from })); + let st = self.state()?; + let (before, selection_before) = (st.doc.clone(), st.selection.clone()); + self.running = Some(Running { id: "grip".into(), machine, before, selection_before }); + self.pending_window = None; + self.point_mods.clear(); + self.echo("** STRETCH **"); + Ok(()) + } +} diff --git a/crates/engine/src/cmd/blocks/blookup.rs b/crates/engine/src/cmd/blocks/blookup.rs new file mode 100644 index 0000000000..103ae24ce5 --- /dev/null +++ b/crates/engine/src/cmd/blocks/blookup.rs @@ -0,0 +1,359 @@ +//! BLOOKUPTABLE: the lookup table of a dynamic block's lookup action, in the Block Editor. A +//! lookup action (BACTION on a lookup parameter) starts empty; its table lists input properties +//! (a distance, a position's X or Y, a visibility state) and lookup properties (lookup +//! parameters), and each row gives the lookup values for one set of inputs. A reference then shows +//! the lookup value its inputs match ("Custom" when none does) and, when the lookup property +//! allows reverse lookup, setting it sets the row's inputs. The rules are AutoCAD's Property +//! Lookup Table dialog's ([`cadcraft_doc::dynblock::set_lookup_table`]); the UI opens that dialog +//! for BLOOKUPTABLE typed, and JSON calls fill the table directly. + +use cadcraft_doc::dynblock::{ + ActionKind, DynamicBlock, MAX_LOOKUP_ROWS, ParameterKind, TableColumn, column_property, dynamic_block, input_properties, marks, set_lookup_table, +}; +use serde_json::{Value, json}; + +use crate::cmd::{CommandSpec, bad}; +use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; + +pub(super) fn specs() -> Vec { + vec![ + CommandSpec::new("blookuptable", "Lookup Table", run) + .params( + "{action?: graph id, action name (\"Lookup1\") or its lookup parameter's property name (default the block's only lookup action); to fill it: inputs?: [input property names: \"Distance1\", \"Position1 X\", \"Position1 Y\", \"Visibility1\"] (default the table's), lookups?: [lookup parameter property names] (default the table's; its own first), rows?: [[a cell per input, then per lookup]] (numbers in block units, visibility states by name), unmatched?: text (shown when no row matches; default Custom) | {property: text}, reverse?: bool | [lookup property names] (allow reverse lookup; default as it was)} → {action, name, columns: [{name, parameter, property, lookup, unmatched, reverse}], rows} (no fill: just the table); or {tables: [those fills, each naming its action]} → {tables: [...]}: several tables as one change (one undo step; a table refused leaves every table as it was)", + ) + .enabled(editing) + .interactive(|_| Ok(Box::new(BlookupM))), + ] +} + +/// The Block Editor is open on a block (lookup tables belong to a block). +fn editing(s: &Session) -> std::result::Result<(), String> { + match s.state() { + Ok(st) => match &st.block_edit { + Some(be) if be.current => Err("Lookup tables belong to a block; this editor is open on the drawing itself.".into()), + Some(_) => Ok(()), + None => Err("Open a block in the Block Editor first (BEDIT).".into()), + }, + Err(e) => Err(e.to_string()), + } +} + +/// The edited block's name and its dynamic data. +fn block(s: &Session) -> Result<(String, DynamicBlock)> { + editing(s).map_err(EngineError::Other)?; + let st = s.state()?; + let be = st.block_edit.as_ref().ok_or_else(|| EngineError::Other("The Block Editor is not open.".into()))?; + let m = dynamic_block(&st.doc, &be.name).ok_or_else(none_yet)?; + Ok((be.name.clone(), m)) +} + +fn none_yet() -> EngineError { + bad("blookuptable", "the block has no lookup action; add a lookup parameter (BPARAMETER Lookup) and its action (BACTION)") +} + +/// The block's lookup actions: (graph id, name). +pub fn lookup_actions(m: &DynamicBlock) -> Vec<(i32, String)> { + m.actions.iter().filter(|a| matches!(a.kind, ActionKind::Lookup { .. })).map(|a| (a.node, a.name.clone())).collect() +} + +/// The lookup action `v` names: its graph id, its name, or the property name of the lookup +/// parameter it gives; none: the block's only one. +fn action_named(m: &DynamicBlock, v: Option<&Value>) -> Result { + let actions = lookup_actions(m); + let by_text = |t: &str| { + let t = t.trim(); + actions.iter().find(|(_, n)| n.eq_ignore_ascii_case(t)).map(|(id, _)| *id).or_else(|| { + let p = m.parameters.iter().find(|p| matches!(&p.kind, ParameterKind::Lookup { label, .. } if label.eq_ignore_ascii_case(t)))?; + m.actions + .iter() + .find(|a| matches!(&a.kind, ActionKind::Lookup { columns, .. } if columns.iter().any(|c| c.lookup && c.node == p.node))) + .map(|a| a.node) + }) + }; + let found = match v { + None | Some(Value::Null) => match actions.as_slice() { + [] => return Err(none_yet()), + [(id, _)] => Some(*id), + many => { + let names: Vec<&str> = many.iter().map(|(_, n)| n.as_str()).collect(); + return Err(bad("blookuptable", format!("the block has {} lookup actions; name one (`action`): {}", many.len(), names.join(", ")))); + } + }, + Some(Value::Number(n)) => n.as_i64().and_then(|n| i32::try_from(n).ok()).filter(|n| actions.iter().any(|(id, _)| id == n)), + Some(Value::String(t)) => t.trim().parse::().ok().filter(|n| actions.iter().any(|(id, _)| id == n)).or_else(|| by_text(t)), + Some(_) => None, + }; + found.ok_or_else(|| bad("blookuptable", format!("no lookup action {}", v.map(Value::to_string).unwrap_or_default()))) +} + +/// Lookup action `action`'s table as BLOOKUPTABLE reports it. +pub fn describe(m: &DynamicBlock, action: i32) -> Value { + let Some(a) = m.actions.iter().find(|a| a.node == action) else { return Value::Null }; + let ActionKind::Lookup { columns, rows } = &a.kind else { return Value::Null }; + let columns: Vec = columns + .iter() + .map(|c| { + json!({ + "name": column_property(m, c.node, &c.property), + "parameter": c.node, + "property": c.property, + "lookup": c.lookup, + "unmatched": c.unmatched, + "reverse": c.lookup && c.reverse, + }) + }) + .collect(); + json!({ "action": action, "name": a.name, "columns": columns, "rows": rows }) +} + +/// A cell given in JSON: text, or a number written as text. +fn cell(v: &Value) -> Option { + match v { + Value::String(t) => Some(t.clone()), + Value::Number(n) => Some(n.to_string()), + Value::Null => Some(String::new()), + _ => None, + } +} + +fn names(p: &Value, key: &str) -> Result>> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Array(a)) if a.len() <= 1_000 => a + .iter() + .map(|v| v.as_str().map(str::to_string).ok_or_else(|| bad("blookuptable", format!("`{key}` lists property names")))) + .collect::>() + .map(Some), + Some(_) => Err(bad("blookuptable", format!("`{key}` is a list of property names"))), + } +} + +/// The most tables one `tables` call fills. +const MAX_TABLES: usize = 1_000; + +fn run(s: &mut Session, p: &Value) -> Result { + match p.get("tables") { + None | Some(Value::Null) => fill(s, p), + Some(tables) => fill_all(s, tables), + } +} + +/// `tables`: several lookup tables filled as one change, as the Property Lookup Table dialog's OK +/// writes every table edited in it. The session records one undo step for the command, and a +/// table that is refused puts the drawing back as it was, so no table is half written. +fn fill_all(s: &mut Session, tables: &Value) -> Result { + let list = match tables { + Value::Array(list) if list.len() <= MAX_TABLES => list, + _ => return Err(bad("blookuptable", format!("`tables` is a list of at most {MAX_TABLES} tables"))), + }; + let before = s.state()?.doc.clone(); + let mut filled = Vec::with_capacity(list.len()); + for t in list { + let one = match t { + Value::Object(o) if !o.contains_key("tables") => fill(s, t), + _ => Err(bad("blookuptable", "each of `tables` is one table's fill: {action, inputs?, lookups?, rows?, unmatched?, reverse?}")), + }; + match one { + Ok(v) => filled.push(v), + Err(e) => { + s.state_mut()?.doc = before; + let action = t.get("action").map(Value::to_string).unwrap_or_default(); + return Err(bad("blookuptable", format!("lookup table {action} was refused, so no table was changed: {}", reason(e)))); + } + } + } + Ok(json!({ "tables": filled })) +} + +/// An error's message without the command name it already carries. +fn reason(e: EngineError) -> String { + match e { + EngineError::BadParams { msg, .. } => msg, + e => e.to_string(), + } +} + +/// One lookup table: listed, or filled from `p`. +fn fill(s: &mut Session, p: &Value) -> Result { + let (name, m) = block(s)?; + let action = action_named(&m, p.get("action"))?; + let fill = ["inputs", "lookups", "rows", "unmatched", "reverse"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); + if !fill { + return Ok(describe(&m, action)); + } + let Some(ActionKind::Lookup { columns: old, rows: old_rows }) = m.actions.iter().find(|a| a.node == action).map(|a| &a.kind) else { + return Err(none_yet()); + }; + let inputs = input_properties(&m); + // A column of the table as it is, kept by name. + let kept = |node: i32, property: &str, lookup: bool| { + old.iter().find(|c| c.node == node && c.lookup == lookup && c.property.eq_ignore_ascii_case(property)) + }; + let mut columns: Vec = Vec::new(); + match names(p, "inputs")? { + Some(list) => { + for n in list { + let (_, node, property) = inputs.iter().find(|(shown, ..)| shown.eq_ignore_ascii_case(n.trim())).ok_or_else(|| { + bad( + "blookuptable", + format!( + "no input property \"{}\"; the block has: {}", + n.trim(), + inputs.iter().map(|(n, ..)| n.as_str()).collect::>().join(", ") + ), + ) + })?; + let unmatched = kept(*node, property, false).map(|c| c.unmatched.clone()).unwrap_or_default(); + columns.push(TableColumn { node: *node, property: property.clone(), lookup: false, unmatched, reverse: false }); + } + } + None => columns.extend(old.iter().filter(|c| !c.lookup).map(|c| TableColumn { + node: c.node, + property: c.property.clone(), + lookup: false, + unmatched: c.unmatched.clone(), + reverse: false, + })), + } + match names(p, "lookups")? { + Some(list) => { + for n in list { + let node = m + .parameters + .iter() + .find(|q| matches!(&q.kind, ParameterKind::Lookup { label, .. } if label.eq_ignore_ascii_case(n.trim()))) + .map(|q| q.node) + .ok_or_else(|| bad("blookuptable", format!("no lookup property \"{}\"", n.trim())))?; + let k = kept(node, "lookupString", true); + columns.push(TableColumn { + node, + property: "lookupString".into(), + lookup: true, + unmatched: k.map(|c| c.unmatched.clone()).unwrap_or_default(), + reverse: k.is_some_and(|c| c.reverse), + }); + } + } + None => columns.extend(old.iter().filter(|c| c.lookup).map(|c| TableColumn { + node: c.node, + property: c.property.clone(), + lookup: true, + unmatched: c.unmatched.clone(), + reverse: c.reverse, + })), + } + // What references show when no row matches. + match p.get("unmatched") { + None | Some(Value::Null) => {} + Some(Value::String(t)) => columns.iter_mut().for_each(|c| c.unmatched = t.clone()), + Some(Value::Object(o)) => { + for (k, v) in o { + let t = v.as_str().ok_or_else(|| bad("blookuptable", "`unmatched` values are text"))?; + let c = columns + .iter_mut() + .find(|c| column_property(&m, c.node, &c.property).eq_ignore_ascii_case(k.trim())) + .ok_or_else(|| bad("blookuptable", format!("no column \"{k}\" in the table")))?; + c.unmatched = t.to_string(); + } + } + Some(_) => Err(bad("blookuptable", "`unmatched` is text or {property: text}"))?, + } + match p.get("reverse") { + None | Some(Value::Null) => {} + Some(Value::Bool(b)) => columns.iter_mut().filter(|c| c.lookup).for_each(|c| c.reverse = *b), + Some(Value::Array(list)) => { + for c in columns.iter_mut().filter(|c| c.lookup) { + let shown = column_property(&m, c.node, &c.property); + c.reverse = list.iter().any(|v| v.as_str().is_some_and(|n| n.trim().eq_ignore_ascii_case(&shown))); + } + } + Some(_) => Err(bad("blookuptable", "`reverse` is true, false or a list of lookup property names"))?, + } + let rows: Vec> = match p.get("rows") { + None | Some(Value::Null) => { + // The table's rows, when its columns stay as they were. + let same = + columns.len() == old.len() && columns.iter().zip(old).all(|(a, b)| a.node == b.node && a.property.eq_ignore_ascii_case(&b.property)); + if same || old_rows.is_empty() { + old_rows.clone() + } else { + return Err(bad("blookuptable", "the columns changed; give `rows` for them")); + } + } + Some(Value::Array(rows)) if rows.len() <= MAX_LOOKUP_ROWS => rows + .iter() + .map(|r| match r { + Value::Array(cells) if cells.len() <= 1_000 => { + cells.iter().map(|c| cell(c).ok_or_else(|| bad("blookuptable", "a cell is text or a number"))).collect::>>() + } + _ => Err(bad("blookuptable", "each of `rows` is a list of cells")), + }) + .collect::>()?, + Some(_) => return Err(bad("blookuptable", format!("`rows` is a list of at most {MAX_LOOKUP_ROWS} rows"))), + }; + set_lookup_table(s.doc_mut()?, &name, action, &columns, &rows).map_err(|e| bad("blookuptable", e))?; + let m = dynamic_block(s.doc()?, &name).ok_or_else(none_yet)?; + Ok(describe(&m, action)) +} + +/// BLOOKUPTABLE on the command line (the UI opens the dialog instead): pick a lookup action, and +/// its table is listed. +struct BlookupM; + +impl Interactive for BlookupM { + fn name(&self) -> &'static str { + "BLOOKUPTABLE" + } + fn prompt(&self, _s: &Session) -> Prompt { + Prompt::new("Select lookup action", Accept::POINT) + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + let at = match i { + Input::Cancel | Input::Enter => return Ok(Step::Cancel), + Input::Point(p) => p, + Input::Text(t) | Input::Keyword(t) => { + let (_, m) = block(s)?; + let action = action_named(&m, Some(&Value::String(t)))?; + list(s, &m, action); + return Ok(Step::Done); + } + _ => return Ok(Step::Continue), + }; + let (name, m) = block(s)?; + let base = s.state()?.block_edit.as_ref().map(|b| b.base()).unwrap_or_default(); + let reach = (s.pixel_size() * s.settings.pickbox.max(1.0) * 3.0).max(1e-9); + let actions = lookup_actions(&m); + let hit = marks(s.doc()?, &name) + .into_iter() + .filter_map(|k| match k { + cadcraft_doc::dynblock::Mark::Action { node, at: a, .. } if actions.iter().any(|(id, _)| *id == node) => { + Some((node, (a.xy() - base - at).len())) + } + _ => None, + }) + .filter(|(_, d)| *d <= reach) + .min_by(|a, b| a.1.total_cmp(&b.1)); + match hit { + Some((action, _)) => { + list(s, &m, action); + Ok(Step::Done) + } + None => { + s.echo("Nothing Selected."); + Ok(Step::Continue) + } + } + } +} + +/// Echo action `action`'s table: its columns, then each row. +fn list(s: &mut Session, m: &DynamicBlock, action: i32) { + let t = describe(m, action); + let heads: Vec = + t["columns"].as_array().map(|c| c.iter().map(|c| c["name"].as_str().unwrap_or_default().to_string()).collect()).unwrap_or_default(); + s.echo(format!("{}: {}", t["name"].as_str().unwrap_or_default(), heads.join(" | "))); + for r in t["rows"].as_array().into_iter().flatten() { + let cells: Vec<&str> = r.as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + s.echo(format!(" {}", cells.join(" | "))); + } +} diff --git a/crates/engine/src/cmd/blocks/bvstate.rs b/crates/engine/src/cmd/blocks/bvstate.rs new file mode 100644 index 0000000000..a73f4d181d --- /dev/null +++ b/crates/engine/src/cmd/blocks/bvstate.rs @@ -0,0 +1,538 @@ +//! BVSTATE, BVHIDE and BVSHOW: the visibility states of a dynamic block in the Block Editor. +//! A block's visibility parameter (BPARAMETER Visibility) names sets of its objects; a reference +//! shows one set at a time. The editor shows one state, hiding the objects that state hides; +//! BVSTATE makes, picks and deletes states, BVHIDE and BVSHOW change what a state shows. As in +//! AutoCAD, an object drawn in the editor shows in the state the editor shows only, and so do the +//! grips of a parameter added there. + +use cadcraft_doc::Handle; +use cadcraft_doc::dynblock::{ + MAX_VISIBILITY_STATES, ParameterKind, VisibilityState, adopt_objects, dynamic_block, parameter_objects, set_visibility, +}; +use serde_json::{Value, json}; + +use crate::cmd::curves::{KW, handle_value}; +use crate::cmd::machines::{SelOutcome, SelectPhase}; +use crate::cmd::{CommandSpec, bad, str_param}; +use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; + +pub(super) fn specs() -> Vec { + vec![ + CommandSpec::new("bvstate", "Visibility States", run_bvstate) + .alias(&["-bvstate"]) + .params( + "{new?: name, visibility?: \"hide\"|\"show\"|\"current\" (what the new state shows: nothing, every object, or what the current state shows; default current) | set?: name (the state the editor shows) | delete?: name or [names] | rename?: name, to: new name | order?: [every state's name, in the new order] | ops?: [any of these, run in turn as one step (the Visibility States dialog's OK)]} → {current, states} (no option: just the list)", + ) + .enabled(visibility_editing) + .interactive(|_| Ok(Box::new(BvstateM::default()))), + CommandSpec::new("bvhide", "Make Invisible", |s, p| run_hide_show(s, p, false)) + .params("{handles?: [objects] (default the selection), all?: bool (in every state; default the current one)} → {current, hidden}") + .enabled(visibility_editing) + .interactive(|_| Ok(Box::new(BvhideM::new(false)))), + CommandSpec::new("bvshow", "Make Visible", |s, p| run_hide_show(s, p, true)) + .params("{handles?: [objects] (default the selection), all?: bool (in every state; default the current one)} → {current, shown}") + .enabled(visibility_editing) + .interactive(|_| Ok(Box::new(BvhideM::new(true)))), + ] +} + +/// The Block Editor is open on a block (visibility states belong to a block). +fn visibility_editing(s: &Session) -> std::result::Result<(), String> { + match s.state() { + Ok(st) => match &st.block_edit { + Some(be) if be.current => Err("Visibility states belong to a block; this editor is open on the drawing itself.".into()), + Some(_) => Ok(()), + None => Err("Open a block in the Block Editor first (BEDIT).".into()), + }, + Err(e) => Err(e.to_string()), + } +} + +/// The edited block's visibility parameter: the block, the objects it controls, its states and +/// the index of the one the editor shows. Objects drawn in the editor since are adopted first. +struct Vis { + block: String, + controlled: Vec, + states: Vec, + current: usize, +} + +fn read(s: &mut Session) -> Result { + visibility_editing(s).map_err(EngineError::Other)?; + let (block, shown) = { + let be = s.state()?.block_edit.as_ref().ok_or_else(|| EngineError::Other("The Block Editor is not open.".into()))?; + (be.name.clone(), be.visibility.clone()) + }; + let objects: Vec = s.doc()?.model.iter().map(|e| e.handle).collect(); + let none = || EngineError::Other("The block has no visibility parameter; add one first (BPARAMETER Visibility).".into()); + // A doc change only when there is something to adopt. + let mut d = s.doc()?.clone(); + adopt_objects(&mut d, &block, &objects, shown.as_deref()).map_err(EngineError::Other)?; + if !std::sync::Arc::ptr_eq(&d.foreign, &s.doc()?.foreign) { + *s.doc_mut()? = d; + } + let m = dynamic_block(s.doc()?, &block).ok_or_else(none)?; + let (controlled, states) = m + .parameters + .into_iter() + .find_map(|p| match p.kind { + ParameterKind::Visibility { controlled, states, .. } => Some((controlled, states)), + _ => None, + }) + .ok_or_else(none)?; + let current = shown.as_deref().and_then(|v| states.iter().position(|s| s.name.eq_ignore_ascii_case(v))).unwrap_or(0); + Ok(Vis { block, controlled, states, current }) +} + +impl Vis { + fn current_name(&self) -> String { + self.states.get(self.current).map(|s| s.name.clone()).unwrap_or_default() + } + + fn find(&self, name: &str) -> Option { + self.states.iter().position(|s| s.name.eq_ignore_ascii_case(name.trim())) + } + + /// Write the states back and show the current one in the editor. + fn write(self, s: &mut Session) -> Result { + set_visibility(s.doc_mut()?, &self.block, &self.controlled, &self.states).map_err(EngineError::Other)?; + let current = self.current_name(); + show(s, Some(current.clone()))?; + Ok(self.summary(current)) + } + + fn summary(&self, current: String) -> Value { + json!({ "current": current, "states": self.states.iter().map(|s| s.name.clone()).collect::>() }) + } +} + +/// Make `state` the one the editor shows and hide what it hides. +fn show(s: &mut Session, state: Option) -> Result<()> { + if let Some(be) = s.state_mut()?.block_edit.as_mut() { + be.visibility = state; + } + s.refresh_block_visibility() +} + +/// A parameter just added (graph id `node`) to the edited block: active in the state the editor +/// shows only, as AutoCAD adds it, so references show its grips in that state. +pub(super) fn parameter_added(s: &mut Session, node: i32) -> Result<()> { + let Ok(mut v) = read(s) else { return Ok(()) }; + let Some(m) = dynamic_block(s.doc()?, &v.block) else { return Ok(()) }; + let added = parameter_objects(&m, Some(node)); + if added.is_empty() { + return Ok(()); + } + if let Some(state) = v.states.get_mut(v.current) { + let new: Vec = added.into_iter().filter(|h| !state.active.contains(h)).collect(); + state.active.extend(new); + } + v.write(s).map(|_| ()) +} + +/// What a new state shows. +#[derive(Clone, Copy, Debug, PartialEq)] +enum NewShows { + Nothing, + Everything, + Current, +} + +fn new_state(s: &mut Session, name: &str, shows: NewShows) -> Result { + let name = name.trim(); + if name.is_empty() { + return Err(bad("bvstate", "a visibility state needs a name")); + } + let mut v = read(s)?; + if v.find(name).is_some() { + return Err(bad("bvstate", format!("visibility state \"{name}\" already exists"))); + } + let state = match shows { + NewShows::Nothing => VisibilityState { name: name.to_string(), visible: Vec::new(), active: Vec::new() }, + NewShows::Everything => { + let active = dynamic_block(s.doc()?, &v.block).map(|m| parameter_objects(&m, None)).unwrap_or_default(); + VisibilityState { name: name.to_string(), visible: v.controlled.clone(), active } + } + NewShows::Current => VisibilityState { name: name.to_string(), ..v.states.get(v.current).cloned().unwrap_or_default() }, + }; + v.states.push(state); + // The new state is the one the editor shows. + v.current = v.states.len().saturating_sub(1); + v.write(s) +} + +fn set_state(s: &mut Session, name: &str) -> Result { + let mut v = read(s)?; + v.current = v.find(name).ok_or_else(|| bad("bvstate", format!("no visibility state \"{}\"", name.trim())))?; + v.write(s) +} + +fn delete_states(s: &mut Session, names: &[String]) -> Result { + let mut v = read(s)?; + let shown = v.current_name(); + for n in names { + if v.find(n).is_none() { + return Err(bad("bvstate", format!("no visibility state \"{}\"", n.trim()))); + } + } + v.states.retain(|st| !names.iter().any(|n| n.trim().eq_ignore_ascii_case(&st.name))); + if v.states.is_empty() { + return Err(bad("bvstate", "a block keeps at least one visibility state")); + } + // The editor keeps the state it showed, else shows the first. + v.current = v.find(&shown).unwrap_or(0); + v.write(s) +} + +fn rename_state(s: &mut Session, from: &str, to: &str) -> Result { + let to = to.trim(); + if to.is_empty() { + return Err(bad("bvstate", "`to`: the state's new name")); + } + let mut v = read(s)?; + let i = v.find(from).ok_or_else(|| bad("bvstate", format!("no visibility state \"{}\"", from.trim())))?; + if v.find(to).is_some_and(|j| j != i) { + return Err(bad("bvstate", format!("visibility state \"{to}\" already exists"))); + } + if let Some(st) = v.states.get_mut(i) { + st.name = to.to_string(); + } + v.write(s) +} + +/// Most operations one `ops` list runs. +const MAX_OPS: usize = 1_000; + +fn run_bvstate(s: &mut Session, p: &Value) -> Result { + match p.get("ops") { + None | Some(Value::Null) => one_op(s, p), + Some(Value::Array(ops)) if ops.len() <= MAX_OPS => { + if ops.iter().any(|op| !op.is_object() || op.get("ops").is_some()) { + return Err(bad("bvstate", "each of `ops` is one operation: {new}, {set}, {delete}, {rename, to} or {order}")); + } + // All or nothing: a refused operation leaves the states as they were. + let before = s.doc()?.clone(); + let shown = s.state()?.block_edit.as_ref().and_then(|b| b.visibility.clone()); + for op in ops { + if let Err(e) = one_op(s, op) { + *s.doc_mut()? = before; + show(s, shown)?; + return Err(e); + } + } + let v = read(s)?; + let current = v.current_name(); + Ok(v.summary(current)) + } + Some(_) => Err(bad("bvstate", format!("`ops` is a list of at most {MAX_OPS} operations"))), + } +} + +/// Put the states in the order of `names` (every state once). +fn order_states(s: &mut Session, names: &[String]) -> Result { + let mut v = read(s)?; + let shown = v.current_name(); + let mut states = Vec::with_capacity(v.states.len()); + for n in names { + let i = v.find(n).ok_or_else(|| bad("bvstate", format!("no visibility state \"{}\"", n.trim())))?; + if states.iter().any(|st: &VisibilityState| st.name.eq_ignore_ascii_case(n.trim())) { + return Err(bad("bvstate", format!("\"{}\" is listed twice in `order`", n.trim()))); + } + states.push(v.states.get(i).cloned().unwrap_or_default()); + } + if states.len() != v.states.len() { + return Err(bad("bvstate", "`order` lists every visibility state once")); + } + v.states = states; + v.current = v.find(&shown).unwrap_or(0); + v.write(s) +} + +/// A list of names, or one name. +fn names_param(p: &Value, key: &str) -> Result>> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(n)) => Ok(Some(vec![n.clone()])), + Some(Value::Array(a)) if a.len() <= MAX_VISIBILITY_STATES => { + let names: Vec = a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect(); + if names.len() != a.len() || names.is_empty() { + return Err(bad("bvstate", format!("`{key}` is a state name or a list of names"))); + } + Ok(Some(names)) + } + Some(_) => Err(bad("bvstate", format!("`{key}` is a state name or a list of names"))), + } +} + +fn one_op(s: &mut Session, p: &Value) -> Result { + if let Some(name) = str_param(p, "new") { + let shows = match str_param(p, "visibility").map(|t| t.trim().to_ascii_lowercase()).as_deref() { + None | Some("current") => NewShows::Current, + Some("hide") | Some("hideall") | Some("hide all") => NewShows::Nothing, + Some("show") | Some("showall") | Some("show all") => NewShows::Everything, + Some(o) => return Err(bad("bvstate", format!("`visibility` is \"hide\", \"show\" or \"current\", not \"{o}\""))), + }; + return new_state(s, name, shows); + } + if let Some(name) = str_param(p, "set") { + return set_state(s, name); + } + if let Some(from) = str_param(p, "rename") { + let to = str_param(p, "to").ok_or_else(|| bad("bvstate", "`to`: the state's new name"))?; + return rename_state(s, from, to); + } + if let Some(names) = names_param(p, "delete")? { + return delete_states(s, &names); + } + if let Some(names) = names_param(p, "order")? { + return order_states(s, &names); + } + let v = read(s)?; + let current = v.current_name(); + Ok(v.summary(current)) +} + +/// BVHIDE (`visible` false) or BVSHOW: `handles` in the current state, or in every state. +fn hide_show(s: &mut Session, handles: &[Handle], all: bool, visible: bool) -> Result { + let cmd = if visible { "bvshow" } else { "bvhide" }; + if handles.is_empty() { + return Err(bad(cmd, "`handles`: the objects to change")); + } + if handles.len() > cadcraft_doc::dynblock::MAX_ACTION_ITEMS { + return Err(bad(cmd, "too many objects")); + } + let missing: Vec = handles.iter().filter(|h| s.doc().ok().and_then(|d| d.model.get(**h)).is_none()).map(|h| h.hex()).collect(); + if !missing.is_empty() { + return Err(bad(cmd, format!("no such object in the block: {}", missing.join(", ")))); + } + let mut v = read(s)?; + let current = v.current; + for (i, st) in v.states.iter_mut().enumerate() { + if !all && i != current { + continue; + } + if visible { + let new: Vec = handles.iter().filter(|h| !st.visible.contains(h)).copied().collect(); + st.visible.extend(new); + } else { + st.visible.retain(|h| !handles.contains(h)); + } + } + let n = handles.len(); + // A hidden object can't stay selected; nothing is selected afterwards. + s.set_selection(Vec::new()); + let mut out = v.write(s)?; + out[if visible { "shown" } else { "hidden" }] = json!(n); + Ok(out) +} + +fn run_hide_show(s: &mut Session, p: &Value, visible: bool) -> Result { + let cmd = if visible { "bvshow" } else { "bvhide" }; + let handles: Vec = match p.get("handles") { + Some(Value::Array(a)) => { + a.iter().map(|v| handle_value(v).ok_or_else(|| bad(cmd, format!("{v} is not an object handle")))).collect::>()? + } + Some(_) => return Err(bad(cmd, "`handles` is an array of object handles")), + None => s.selection(), + }; + let all = match p.get("all") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad(cmd, "`all` is true or false")), + }; + hide_show(s, &handles, all, visible) +} + +/// Read keyword input: `text` (any case, an optional leading `_`) against `options`, each +/// (keyword, its shortcut). +fn keyword<'a>(text: &str, options: &[(&'a str, &str)]) -> Option<&'a str> { + let t = text.trim(); + let t = t.strip_prefix('_').unwrap_or(t); + options.iter().find(|(k, short)| t.eq_ignore_ascii_case(k) || t.eq_ignore_ascii_case(short)).map(|(k, _)| *k) +} + +fn text_of(i: &Input) -> Option<&str> { + match i { + Input::Keyword(t) | Input::Text(t) => Some(t.as_str()), + _ => None, + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum VStage { + #[default] + Option, + NewName, + NewShows, + Set, + Delete, +} + +/// -BVSTATE's prompts, as AutoCAD asks them on the command line (BVSTATE's dialog isn't here +/// yet, so BVSTATE asks the same). +#[derive(Default)] +struct BvstateM { + stage: VStage, + name: String, +} + +const NEW_SHOWS: &[(&str, &str)] = &[("Hide all", "H"), ("Show all", "S"), ("Current visibility", "C")]; + +impl Interactive for BvstateM { + fn name(&self) -> &'static str { + "BVSTATE" + } + fn begin(&mut self, s: &mut Session) -> Result { + let v = read(s)?; + s.echo(format!("Current visibility state: {}", v.current_name())); + Ok(Step::Continue) + } + fn prompt(&self, _s: &Session) -> Prompt { + match self.stage { + VStage::Option => Prompt::new("Enter an option", KW).kw(&["New", "Set", "Delete"]).default("New"), + VStage::NewName => Prompt::new("Enter name of new visibility state", Accept::TEXT), + VStage::NewShows => Prompt::new("Enter object visibility for new state", KW) + .kw(&["Hide all", "Show all", "Current visibility"]) + .default("Current visibility"), + VStage::Set => Prompt::new("Enter visibility state name to make current or", Accept::TEXT).kw(&["?"]), + VStage::Delete => Prompt::new("Enter visibility state name(s) to delete", Accept::TEXT), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if matches!(i, Input::Cancel) { + return Ok(Step::Cancel); + } + match self.stage { + VStage::Option => { + let choice = match &i { + Input::Enter => Some("New"), + _ => text_of(&i).and_then(|t| keyword(t, &[("New", "N"), ("Set", "S"), ("Delete", "D")])), + }; + match choice { + Some("New") => self.stage = VStage::NewName, + Some("Set") => self.stage = VStage::Set, + Some(_) => self.stage = VStage::Delete, + None => s.echo("Invalid option keyword."), + } + } + VStage::NewName => { + let Some(t) = text_of(&i).map(str::trim).filter(|t| !t.is_empty()) else { + return Ok(Step::Cancel); + }; + let exists = read(s)?.find(t).is_some(); + if exists { + s.echo(format!("Visibility state \"{t}\" already exists.")); + } else { + self.name = t.to_string(); + self.stage = VStage::NewShows; + } + } + VStage::NewShows => { + let shows = match &i { + Input::Enter => Some(NewShows::Current), + _ => text_of(&i).and_then(|t| keyword(t, NEW_SHOWS)).map(|k| match k { + "Hide all" => NewShows::Nothing, + "Show all" => NewShows::Everything, + _ => NewShows::Current, + }), + }; + match shows { + Some(shows) => return new_state(s, &self.name, shows).map(|_| Step::Done), + None => s.echo("Invalid option keyword."), + } + } + VStage::Set => match text_of(&i).map(str::trim) { + Some("?") => { + let v = read(s)?; + for st in &v.states { + s.echo(format!(" {}", st.name)); + } + } + Some(t) if !t.is_empty() => { + if read(s)?.find(t).is_some() { + return set_state(s, t).map(|_| Step::Done); + } + s.echo(format!("Visibility state \"{t}\" not found.")); + } + _ => return Ok(Step::Cancel), + }, + VStage::Delete => { + let Some(t) = text_of(&i).map(str::trim).filter(|t| !t.is_empty()) else { + return Ok(Step::Cancel); + }; + let names: Vec = t.split(',').map(|n| n.trim().to_string()).filter(|n| !n.is_empty()).collect(); + match delete_states(s, &names) { + Ok(_) => return Ok(Step::Done), + Err(e) => s.echo(e.to_string()), + } + } + } + Ok(Step::Continue) + } +} + +/// BVHIDE's or BVSHOW's prompts, as AutoCAD asks them. +struct BvhideM { + show: bool, + select: SelectPhase, + picked: Vec, + asking: bool, +} + +impl BvhideM { + fn new(show: bool) -> Self { + BvhideM { show, select: SelectPhase::default(), picked: Vec::new(), asking: false } + } +} + +impl Interactive for BvhideM { + fn name(&self) -> &'static str { + if self.show { "BVSHOW" } else { "BVHIDE" } + } + fn begin(&mut self, s: &mut Session) -> Result { + read(s)?; + s.echo(if self.show { "Select objects to make visible:" } else { "Select objects to hide:" }); + self.select = SelectPhase::begin(s); + if self.select.done { + self.picked = self.select.picked.clone(); + self.asking = true; + } + Ok(Step::Continue) + } + fn prompt(&self, _s: &Session) -> Prompt { + if self.asking { + let msg = + if self.show { "Make visible for current state or all visibility states" } else { "Hide for current state or all visibility states" }; + Prompt::new(msg, KW).kw(&["Current", "All"]).default("Current") + } else { + self.select.prompt() + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if matches!(i, Input::Cancel) { + return Ok(Step::Cancel); + } + if !self.asking { + match self.select.feed(s, &i)? { + SelOutcome::More => {} + SelOutcome::Empty => return Ok(Step::Done), + SelOutcome::Done(hs) => { + self.picked = hs; + self.asking = true; + } + } + return Ok(Step::Continue); + } + let all = match &i { + Input::Enter => Some(false), + _ => text_of(&i).and_then(|t| keyword(t, &[("Current", "C"), ("All", "A")])).map(|k| k == "All"), + }; + match all { + Some(all) => hide_show(s, &self.picked, all, self.show).map(|_| Step::Done), + None => { + s.echo("Invalid option keyword."); + Ok(Step::Continue) + } + } + } +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 9c4dc4c411..01860f2c04 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -60,7 +60,7 @@ pub fn specs() -> Vec { .params("{} (only into a drawing other than the one copied from)") .enabled(clipboard::can_paste_orig) .interactive(|_| Ok(Box::new(PasteM { mode: PasteMode::Orig }))), - CommandSpec::new("erase.selection", "Clear", run_clear).menu(&["Edit", "Clear"]).key("Delete").enabled(has_selection).params("{}"), + CommandSpec::new("erase.selection", "Clear", run_clear).menu(&["Edit", "Clear"]).key("Delete").enabled(clearable).params("{}"), CommandSpec::new("selectall", "Select All", run_selectall).menu(&["Edit", "Select All"]).key("Cmd+A").alias(&["ai_selall"]).noundo(), CommandSpec::new("ai_deselect", "Deselect All", run_deselect).params("{}").noundo(), CommandSpec::new("select", "Select", run_select) @@ -546,10 +546,16 @@ fn run_pasteorig(s: &mut Session, _p: &Value) -> Result { Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::>() })) } +/// Something to clear: selected objects, or parameters and actions picked in the Block Editor. +fn clearable(s: &Session) -> std::result::Result<(), String> { + if !s.picked_elements().is_empty() { Ok(()) } else { has_selection(s) } +} + fn run_clear(s: &mut Session, _p: &Value) -> Result { let mut hs = s.selection(); hs.retain(|h| !super::curves::is_locked(s, *h)); - let n = super::modify::erase_kept(s, &hs)?; + // The Block Editor's picked parameters and actions go too. + let n = s.erase_picked_elements()? + super::modify::erase_kept(s, &hs)?; s.set_selection(Vec::new()); Ok(json!({ "erased": n })) } diff --git a/crates/engine/src/cmd/modify/select_then.rs b/crates/engine/src/cmd/modify/select_then.rs index 98fdf15a6f..da83a180bc 100644 --- a/crates/engine/src/cmd/modify/select_then.rs +++ b/crates/engine/src/cmd/modify/select_then.rs @@ -85,7 +85,7 @@ impl SelectThen { // Immediate operations once selection is done. match self.op { Op::Erase => { - let n = erase(s, &self.objs)?; + let n = erase(s, &self.objs, true)?; let _ = n; Ok(Step::Done) } @@ -537,6 +537,12 @@ impl Interactive for SelectThen { } fn begin(&mut self, s: &mut Session) -> Result { self.sel = SelectPhase::begin(s); + // Parameters or actions picked in the Block Editor are a selection for MOVE and ERASE. + if !self.sel.done && matches!(self.op, Op::Move | Op::Erase) && !s.picked_elements().is_empty() { + // Selected objects come along only where PICKFIRST lets a selection count. + self.sel.picked = if s.settings.pickfirst { s.selection() } else { Vec::new() }; + self.sel.done = true; + } if self.sel.done { self.objs = self.sel.picked.clone(); return self.apply(s); @@ -644,12 +650,14 @@ impl Interactive for SelectThen { (Op::Move, 1, Input::Point(p)) => { let d = p - self.pts[0]; transform_entities(s, &self.objs, &Mat3::translate(d), false)?; + s.move_picked_elements(d)?; s.set_selection(Vec::new()); Ok(Step::Done) } (Op::Move, 1, Input::Enter) => { let d = self.pts[0]; transform_entities(s, &self.objs, &Mat3::translate(d), false)?; + s.move_picked_elements(d)?; s.set_selection(Vec::new()); Ok(Step::Done) } @@ -816,6 +824,9 @@ impl Interactive for DisplaceM { }; if d != Vec2::ZERO { transform_entities(s, &self.inner.objs, &Mat3::translate(d), self.inner.op == Op::Copy)?; + if self.inner.op == Op::Move { + s.move_picked_elements(d)?; + } } s.set_selection(Vec::new()); return Ok(Step::Done); diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index 814df6a263..2bcc97baae 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -112,17 +112,25 @@ fn edit_entities(s: &mut Session, hs: &[Handle], copy: bool, edit: impl Fn(&mut Ok(out) } -pub(super) fn erase(s: &mut Session, hs: &[Handle]) -> Result { +/// Whether a JSON call acts on the selection (no `handles` or `handle` given): only then do the +/// Block Editor's picked parameters and actions come along. +fn default_selection(p: &Value) -> bool { + p.get("handles").is_none_or(Value::is_null) && p.get("handle").is_none_or(Value::is_null) +} + +/// Erase `hs`, and with `picked` the Block Editor's picked parameters and actions too. +pub(super) fn erase(s: &mut Session, hs: &[Handle], picked: bool) -> Result { + let marks = if picked { s.erase_picked_elements()? } else { 0 }; let d = s.doc()?; let free: Vec = hs.iter().copied().filter(|h| !d.entity(*h).and_then(|e| d.layer(&e.common.layer)).is_some_and(|l| l.locked)).collect(); - let n = erase_kept(s, &free)?; + let n = marks + erase_kept(s, &free)?; s.set_selection(Vec::new()); Ok(n) } pub(super) fn run_erase(s: &mut Session, p: &Value) -> Result { let hs = targets(s, p)?; - let n = erase(s, &hs)?; + let n = erase(s, &hs, default_selection(p))?; Ok(json!({ "erased": n })) } @@ -139,7 +147,8 @@ pub(super) fn run_move(s: &mut Session, p: &Value) -> Result { let hs = targets(s, p)?; let d = delta_of("move", p)?; let moved = transform_entities(s, &hs, &Mat3::translate(d), false)?; - Ok(json!({ "moved": moved.len() })) + let marks = if default_selection(p) { s.move_picked_elements(d)? } else { 0 }; + Ok(json!({ "moved": moved.len() + marks })) } pub(super) fn run_copy(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/file_access/commands.rs b/crates/engine/src/file_access/commands.rs index 9be1b5d604..5129d50653 100644 --- a/crates/engine/src/file_access/commands.rs +++ b/crates/engine/src/file_access/commands.rs @@ -275,6 +275,17 @@ pub const NO_FILES: &[&str] = &[ "bsave", "bsaveas", "bclose", + "bparameter", + "baction", + "bvstate", + "bvhide", + "bvshow", + "blookuptable", + "blocks.element.select", + "blocks.element.point", + "blocks.element.points", + "blocks.element.move", + "blocks.element.erase", "erase", "oops", "move", diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index 003068a633..a34bfd80ef 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -601,6 +601,8 @@ impl Session { } else { self.pending_window = None; self.set_selection(Vec::new()); + // The Block Editor's picked parameters and actions too. + let _ = self.pick_elements(&[], false); } } diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rs index 89579a7493..e26744b993 100644 --- a/crates/engine/src/settings.rs +++ b/crates/engine/src/settings.rs @@ -75,6 +75,9 @@ pub struct Settings { /// FILEDIA: kept for routines that switch file dialogs off around a script; no command reads it yet. pub filedia: bool, pub pickadd: bool, + /// BVMODE: objects the Block Editor's visibility state hides are hidden (false, 0) or shown + /// dimmed and can be picked (true, 1), as BVSHOW needs them. + pub bvmode: bool, /// COPYMODE: COPY makes one copy and ends (true, 1), or copies until Enter (false, 0). pub copymode: bool, /// PICKDRAG: false = two-click windows (0), true = clicks or dragging (2). @@ -185,6 +188,7 @@ impl Default for Settings { cmdecho: true, filedia: true, pickadd: true, + bvmode: false, copymode: false, pickdrag: true, pickstyle: 1, diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index 7b3cd23890..bf34e16c51 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -42,6 +42,7 @@ const SESSION_VARS: &[&str] = &[ "PLOTTRANSPARENCYOVERRIDE", "SELECTIONCYCLING", "SELECTSIMILARMODE", + "BVMODE", "OBJECTISOLATIONMODE", "QPMODE", "HIGHLIGHT", @@ -147,6 +148,7 @@ pub fn get(s: &Session, name: &str) -> Option { "CMDECHO" => json!(i32::from(st.cmdecho)), "FILEDIA" => json!(i32::from(st.filedia)), "PICKADD" => json!(i32::from(st.pickadd)), + "BVMODE" => json!(i32::from(st.bvmode)), "COPYMODE" => json!(i32::from(st.copymode)), "PICKDRAG" => json!(i32::from(st.pickdrag) * 2), "PICKSTYLE" => json!(st.pickstyle), @@ -410,6 +412,10 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> { "CMDECHO" => st.cmdecho = small(v, 1).ok_or_else(bad)? == 1, "FILEDIA" => st.filedia = small(v, 1).ok_or_else(bad)? == 1, "PICKADD" => st.pickadd = as_bool(v).ok_or_else(bad)?, + "BVMODE" => { + st.bvmode = as_bool(v).ok_or_else(bad)?; + s.refresh_block_visibility()?; + } "COPYMODE" => st.copymode = small(v, 1).ok_or_else(bad)? == 1, "PICKDRAG" => st.pickdrag = as_i(v).filter(|b| matches!(b, 0 | 2)).map(|b| b == 2).ok_or_else(bad)?, "PICKSTYLE" => st.pickstyle = as_i(v).filter(|b| (0..=3).contains(b)).and_then(|b| u8::try_from(b).ok()).ok_or_else(bad)?, diff --git a/crates/engine/tests/it/block_authoring.rs b/crates/engine/tests/it/block_authoring.rs new file mode 100644 index 0000000000..e85f1928b2 --- /dev/null +++ b/crates/engine/tests/it/block_authoring.rs @@ -0,0 +1,437 @@ +//! 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, parameter_objects}; +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)]); +} + +/// 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, 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(); + 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("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. 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); + + // 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)]); +} + +/// 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(); + 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", "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": [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" }), + json!({ "type": "point", "at": [0, 0], "grips": 2 }), + json!({ "type": "point", "at": [0, 0], "label": 7 }), + ] { + 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(); + 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); +} + +/// The edited block's visibility states: (name, visible objects, active parameter objects). +fn states(s: &Session) -> Vec<(String, Vec, Vec)> { + let st = s.state().unwrap(); + let name = st.block_edit.as_ref().map_or("Box".to_string(), |b| b.name.clone()); + let m = dynamic_block(s.doc().unwrap(), &name).unwrap(); + m.parameters + .into_iter() + .find_map(|p| match p.kind { + ParameterKind::Visibility { states, .. } => Some(states.into_iter().map(|s| (s.name, s.visible, s.active)).collect()), + _ => None, + }) + .unwrap() +} + +fn hidden(s: &Session) -> Vec { + s.doc().unwrap().hidden_objects.iter().copied().collect() +} + +/// A parameter's object and its grips' (what a visibility state lists as active). +fn param_objects(s: &Session, node: i32) -> Vec { + parameter_objects(&dynamic_block(s.doc().unwrap(), "Box").unwrap(), Some(node)) +} + +/// The states AutoCAD made in the same steps (recorded with -BVSTATE, BVHIDE and BVSHOW): +/// Hide all hides objects and parameters; Show all shows them all; Current visibility copies; +/// an object drawn or a parameter added shows in the state the editor shows only. +#[test] +fn visibility_states_follow_autocads_rules() { + let mut s = Session::new(); + let (r, c, i) = boxed(&mut s); + let (r, c) = (h(&r), h(&c)); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + assert!(s.execute("bvstate", &json!({})).is_err(), "no visibility parameter yet"); + s.execute("bparameter", &json!({ "type": "linear", "start": [0, -1], "end": [10, -1] })).unwrap(); + let v = s.execute("bparameter", &json!({ "type": "visibility", "at": [0, 6] })).unwrap(); + assert_eq!(v["label"], "Visibility1"); + let linear = param_objects(&s, 1); + assert_eq!(linear.len(), 3, "the parameter and its two grips"); + assert_eq!(states(&s), [("VisibilityState0".to_string(), vec![r, c], linear.clone())]); + + let out = s.execute("bvstate", &json!({ "new": "Hid", "visibility": "hide" })).unwrap(); + assert_eq!(out, json!({ "current": "Hid", "states": ["VisibilityState0", "Hid"] })); + assert_eq!(hidden(&s), [r, c], "the editor shows the new state"); + s.execute("bvshow", &json!({ "handles": [c.hex()] })).unwrap(); + assert_eq!(hidden(&s), [r]); + s.execute("bvstate", &json!({ "new": "Shown", "visibility": "show" })).unwrap(); + s.execute("bvhide", &json!({ "handles": [r.hex()] })).unwrap(); + s.execute("bvstate", &json!({ "new": "Copy" })).unwrap(); + s.execute("bvhide", &json!({ "handles": [c.hex()], "all": true })).unwrap(); + s.execute("bvstate", &json!({ "set": "hid" })).unwrap(); + let p = s.execute("bparameter", &json!({ "type": "point", "at": [2, 2] })).unwrap()["node"].as_i64().unwrap() as i32; + let point = param_objects(&s, p); + let line = s.execute("line", &json!({ "points": [[0, 0], [10, 5]] })).unwrap(); + let line = h(&if line["handle"].is_null() { line["handles"][0].clone() } else { line["handle"].clone() }); + s.execute("bsave", &json!({})).unwrap(); + let want = [ + ("VisibilityState0".to_string(), vec![r], linear.clone()), + ("Hid".to_string(), vec![line], point), + ("Shown".to_string(), vec![], linear.clone()), + ("Copy".to_string(), vec![], linear.clone()), + ]; + assert_eq!(states(&s), want); + + // Rename and delete; the last state stays. + s.execute("bvstate", &json!({ "rename": "Copy", "to": "Spare" })).unwrap(); + let out = s.execute("bvstate", &json!({ "delete": ["Spare", "Shown"] })).unwrap(); + assert_eq!(out, json!({ "current": "Hid", "states": ["VisibilityState0", "Hid"] })); + assert!(s.execute("bvstate", &json!({ "delete": ["VisibilityState0", "Hid"] })).is_err()); + assert!(s.execute("bvstate", &json!({ "new": "hid" })).is_err(), "names are case-insensitive"); + s.execute("bclose", &json!({})).unwrap(); + assert!(s.doc().unwrap().hidden_objects.is_empty(), "the editor's hiding stays in the editor"); + + // A reference shows each state's objects. + s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Visibility1", "value": "Hid" })).unwrap(); + let d = s.doc().unwrap(); + let EntityKind::Insert(ins) = &d.entity(h(&i)).unwrap().kind else { panic!() }; + let shown: Vec = d.block(&ins.block).unwrap().entities.iter().map(|e| e.common.visible).collect(); + assert_eq!(shown, [false, false, true], "only the line drawn in Hid"); +} + +#[test] +fn visibility_commands_ask_as_autocad_does() { + let mut s = Session::new(); + let (r, c, _) = boxed(&mut s); + let (r, c) = (h(&r), h(&c)); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + s.script("BPARAMETER V\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Specify parameter location"); + s.script("0,6\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Enter number of grips"); + s.script("\n").unwrap(); + assert!(s.running.is_none()); + s.script("-BVSTATE\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Enter an option"); + s.script("N\nHid\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Enter object visibility for new state"); + s.script("H\n").unwrap(); + assert!(s.running.is_none()); + assert_eq!(hidden(&s), [r, c]); + s.script("BVSTATE\nS\n?\n").unwrap(); + s.script("VisibilityState0\n").unwrap(); + assert!(s.running.is_none()); + assert!(hidden(&s).is_empty()); + s.script("BVHIDE\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Select objects"); + s.input(Input::Pick(vec![c])).unwrap(); + s.script("\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Hide for current state or all visibility states"); + s.script("A\n").unwrap(); + assert_eq!(hidden(&s), [c]); + // BVMODE 1 leaves hidden objects on the canvas (dimmed there) so BVSHOW can pick them. + s.execute("setvar", &json!({ "name": "BVMODE", "value": 1 })).unwrap(); + assert!(hidden(&s).is_empty()); + s.script("BVSHOW\n").unwrap(); + s.input(Input::Pick(vec![c])).unwrap(); + s.script("\n\n").unwrap(); + assert!(s.running.is_none()); + assert_eq!(s.execute("getvar", &json!({ "name": "BVMODE" })).unwrap()["value"], json!(1)); + s.execute("setvar", &json!({ "name": "BVMODE", "value": 0 })).unwrap(); + assert!(hidden(&s).is_empty(), "the circle shows in the current state again"); + s.script("BVHIDE\n").unwrap(); + s.input(Input::Pick(vec![c])).unwrap(); + s.script("\nA\n").unwrap(); + assert_eq!(hidden(&s), [c]); + s.script("BVSTATE\nD\nHid\n").unwrap(); + assert_eq!(states(&s), [("VisibilityState0".to_string(), vec![r], vec![])]); +} + +#[test] +fn hostile_visibility_params_never_panic() { + let mut s = Session::new(); + let (r, _, _) = boxed(&mut s); + assert!(s.execute("bvhide", &json!({ "handles": [r] })).is_err(), "only in the Block Editor"); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + s.execute("bparameter", &json!({ "type": "visibility", "at": [0, 6] })).unwrap(); + assert!(s.execute("bparameter", &json!({ "type": "visibility", "at": [0, 6] })).is_err(), "one per block"); + let many: Vec = (0..20_001).map(|_| r.clone()).collect(); + for (cmd, p) in [ + ("bvstate", json!(null)), + ("bvstate", json!({ "new": "" })), + ("bvstate", json!({ "new": 5 })), + ("bvstate", json!({ "new": "X", "visibility": "sideways" })), + ("bvstate", json!({ "set": "Nope" })), + ("bvstate", json!({ "delete": 7 })), + ("bvstate", json!({ "delete": [] })), + ("bvstate", json!({ "delete": "Nope" })), + ("bvstate", json!({ "rename": "VisibilityState0" })), + ("bvstate", json!({ "rename": "Nope", "to": "X" })), + ("bvstate", json!({ "ops": 5 })), + ("bvstate", json!({ "ops": [{ "ops": [] }] })), + ("bvstate", json!({ "ops": [7] })), + ("bvstate", json!({ "ops": (0..1_001).map(|_| json!({})).collect::>() })), + ("bvstate", json!({ "order": ["Nope"] })), + ("bvstate", json!({ "order": ["VisibilityState0", "VisibilityState0"] })), + ("bvstate", json!({ "order": [] })), + ("bvstate", json!({ "order": 3 })), + ("bvhide", json!({ "handles": [] })), + ("bvhide", json!({ "handles": ["zz"] })), + ("bvhide", json!({ "handles": ["FFFFFF"] })), + ("bvhide", json!({ "handles": many })), + ("bvshow", json!({ "handles": [r], "all": "yes" })), + ("bparameter", json!({ "type": "visibility", "at": [f64::MAX, 0], "grips": 9 })), + ] { + let _ = s.execute(cmd, &p); + } + for i in 0..50 { + s.execute("bvstate", &json!({ "new": format!("S{i}"), "visibility": "show" })).unwrap(); + } + // Reordering keeps every state and the one shown. + s.execute("bvstate", &json!({ "set": "S3" })).unwrap(); + let mut names: Vec = (0..50).rev().map(|i| format!("S{i}")).collect(); + names.push("VisibilityState0".into()); + let out = s.execute("bvstate", &json!({ "order": names })).unwrap(); + assert_eq!((&out["current"], &out["states"][0], &out["states"][50]), (&json!("S3"), &json!("S49"), &json!("VisibilityState0"))); + s.script("-BVSTATE\nD\n,,,\n").unwrap(); + s.input(Input::Cancel).unwrap(); + assert!(s.running.is_none()); +} diff --git a/crates/engine/tests/it/block_elements.rs b/crates/engine/tests/it/block_elements.rs new file mode 100644 index 0000000000..dc54629588 --- /dev/null +++ b/crates/engine/tests/it/block_elements.rs @@ -0,0 +1,230 @@ +//! Picking, moving and erasing parameters and actions in the Block Editor, as AutoCAD's editor +//! does (recorded in AutoCAD: erasing a parameter erases its actions; moving one moves its +//! points, grips and label; moving an action moves only where it shows). + +use cadcraft_engine::doc::dynblock::{ActionKind, ElementPoint, ParameterKind, dynamic_block}; +use cadcraft_engine::doc::{EntityKind, Handle}; +use cadcraft_engine::geom::{Vec2, Vec3}; +use cadcraft_engine::{Input, Session}; +use serde_json::{Value, json}; + +/// Block "Box" (a 10 × 5 rectangle at the origin, a circle) in the Block Editor with a linear +/// parameter (node 1) under it, a stretch of the rectangle's right edge (node 8) and a point +/// parameter (node 9). Returns the rectangle's handle. +fn authored() -> (Session, Handle) { + let mut s = Session::new(); + let made = |v: Value| if v["handle"].is_null() { v["handles"][0].clone() } else { v["handle"].clone() }; + let r = made(s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 5] })).unwrap()); + let c = made(s.execute("circle", &json!({ "center": [5, 2.5], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "Box", "base": [0, 0], "handles": [r, c], "keep": "delete" })).unwrap(); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + let rect = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::LwPolyline(_))).unwrap().handle; + s.execute("bparameter", &json!({ "type": "linear", "start": [0, -1], "end": [10, -1], "labelAt": [5, -3] })).unwrap(); + let a = s + .execute("baction", &json!({ "parameter": 1, "type": "stretch", "frame": [[8, -2], [12, 6]], "handles": [rect.hex()], "at": [12, -3] })) + .unwrap(); + assert_eq!(a["node"], 8); + let p = s.execute("bparameter", &json!({ "type": "point", "at": [2, 2], "labelAt": [3, 3] })).unwrap(); + assert_eq!(p["node"], 9); + (s, rect) +} + +fn names(s: &Session) -> Vec { + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + m.parameters.iter().map(|p| p.element.clone()).chain(m.actions.iter().map(|a| a.name.clone())).collect() +} + +/// The graph's nodes (index, id) as written. +fn graph_nodes(s: &Session) -> Vec<(i32, i32)> { + let d = s.doc().unwrap(); + let g = d.foreign.objects.iter().find(|o| o.kind == "ACAD_EVALUATION_GRAPH").unwrap(); + let at = g.tags.iter().position(|t| t.value == "AcDbEvalGraph").unwrap(); + let body = &g.tags[at + 3..]; + body.chunks(8).take_while(|c| c[0].code == 91).map(|c| (c[0].value.parse().unwrap(), c[2].value.parse().unwrap())).collect() +} + +#[test] +fn deleting_a_picked_parameter_erases_its_actions_as_autocad_does() { + let (mut s, _) = authored(); + s.execute("blocks.element.select", &json!({ "nodes": [1] })).unwrap(); + assert_eq!(s.picked_elements(), [1]); + let objects = s.doc().unwrap().foreign.objects.len(); + s.execute("erase.selection", &json!({})).unwrap(); + assert_eq!(names(&s), ["Point"], "the stretch went with its parameter"); + assert_eq!(objects - s.doc().unwrap().foreign.objects.len(), 8, "parameter, 2 grips, 4 components, action"); + // As in AutoCAD's file: indices close up, graph ids stay. + assert_eq!(graph_nodes(&s), [(0, 9), (1, 10), (2, 11), (3, 12)]); + // The graph's id counter (96, 97) keeps the highest id given out, as AutoCAD's does; with the + // node count there AutoCAD didn't take the block as dynamic from DXF. + let d = s.doc().unwrap(); + let g = d.foreign.objects.iter().find(|o| o.kind == "ACAD_EVALUATION_GRAPH").unwrap(); + let counters: Vec<&str> = g.tags.iter().filter(|t| t.code == 96 || t.code == 97).map(|t| t.value.as_str()).collect(); + assert_eq!(counters, ["12", "12"]); + assert!(s.picked_elements().is_empty()); + // Undo brings them back. + s.execute("u", &json!({})).unwrap(); + assert_eq!(names(&s), ["Linear", "Point", "Stretch"]); + // An action alone goes alone. + s.execute("blocks.element.erase", &json!({ "nodes": [8] })).unwrap(); + assert_eq!(names(&s), ["Linear", "Point"]); + // The block saves and stays dynamic. + s.execute("bclose", &json!({})).unwrap(); + assert_eq!(dynamic_block(s.doc().unwrap(), "Box").unwrap().parameters.len(), 2); +} + +#[test] +fn moving_picked_parameters_moves_their_points_grips_and_labels() { + let (mut s, _) = authored(); + s.execute("blocks.element.select", &json!({ "nodes": [1, 8] })).unwrap(); + s.execute("move", &json!({ "delta": [0, -2] })).unwrap(); + s.execute("blocks.element.select", &json!({ "nodes": [9] })).unwrap(); + s.script("MOVE\n0,0\n1,1\n").unwrap(); + assert!(s.running.is_none(), "MOVE takes the picked parameter as its selection"); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let ParameterKind::Linear { base, end, .. } = &m.parameters[0].kind else { panic!() }; + assert_eq!((*base, *end), (Vec3::new(0.0, -3.0, 0.0), Vec3::new(10.0, -3.0, 0.0))); + let ParameterKind::Point { at, .. } = &m.parameters[1].kind else { panic!() }; + assert_eq!(*at, Vec3::new(3.0, 3.0, 0.0)); + let a = &m.actions[0]; + assert_eq!(a.at, Vec3::new(12.0, -5.0, 0.0)); + let ActionKind::Stretch { frame, .. } = &a.kind else { panic!() }; + assert_eq!(frame, &[Vec2::new(8.0, -2.0), Vec2::new(12.0, 6.0)], "the frame stays, as in AutoCAD"); + // Grips follow (in the editor's coordinates). + s.execute("blocks.element.select", &json!({ "nodes": [1, 9] })).unwrap(); + let grips = s.element_grips(); + assert!(grips.contains(&(1, ElementPoint::Base, Vec2::new(0.0, -3.0))), "{grips:?}"); + assert!(grips.contains(&(1, ElementPoint::Label, Vec2::new(5.0, -5.0))), "the label line stays 2 below: {grips:?}"); + assert!(grips.contains(&(9, ElementPoint::Label, Vec2::new(4.0, 4.0))), "{grips:?}"); +} + +#[test] +fn a_picked_parameters_grip_moves_one_point() { + let (mut s, _) = authored(); + s.execute("blocks.element.select", &json!({ "nodes": [1] })).unwrap(); + s.start_element_grip(1, ElementPoint::End).unwrap(); + s.input(Input::Point(Vec2::new(14.0, -1.0))).unwrap(); + assert!(s.running.is_none()); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let ParameterKind::Linear { end, .. } = &m.parameters[0].kind else { panic!() }; + assert_eq!(*end, Vec3::new(14.0, -1.0, 0.0)); + // The block works with the new length: a reference's Distance1 starts at 14. + s.execute("bclose", &json!({})).unwrap(); + let i = s.execute("insert", &json!({ "name": "Box", "at": [50, 0] })).unwrap()["handle"].clone(); + let props = s.execute("blocks.reference", &json!({ "handle": i })).unwrap(); + assert_eq!(props["properties"][0]["value"], "14.0000"); + // One undo step per grip edit. + let mut s = authored().0; + s.execute("blocks.element.select", &json!({ "nodes": [8] })).unwrap(); + s.execute("blocks.element.point", &json!({ "node": 8, "point": "at", "to": [20, 20] })).unwrap(); + assert_eq!(dynamic_block(s.doc().unwrap(), "Box").unwrap().actions[0].at, Vec3::new(20.0, 20.0, 0.0)); +} + +#[test] +fn escape_and_erase_work_on_picked_elements() { + let (mut s, _) = authored(); + s.execute("blocks.element.select", &json!({ "nodes": [9] })).unwrap(); + s.execute("blocks.element.select", &json!({ "nodes": [1], "add": true })).unwrap(); + assert_eq!(s.picked_elements(), [9, 1]); + s.cancel(); + assert!(s.picked_elements().is_empty(), "Escape unpicks"); + s.execute("blocks.element.select", &json!({ "nodes": [9] })).unwrap(); + s.script("ERASE\n").unwrap(); + assert!(s.running.is_none(), "ERASE takes the picked parameter"); + assert_eq!(names(&s), ["Linear", "Stretch"]); +} + +#[test] +fn hostile_element_params_never_panic() { + let (mut s, _) = authored(); + let many: Vec = (0..20_001).collect(); + for (cmd, p) in [ + ("blocks.element.select", json!({ "nodes": [99] })), + ("blocks.element.select", json!({ "nodes": "1" })), + ("blocks.element.select", json!({ "nodes": many })), + ("blocks.element.move", json!({ "nodes": [1] })), + ("blocks.element.move", json!({ "nodes": [1], "delta": "far" })), + ("blocks.element.move", json!({ "nodes": [99], "delta": [1, 0] })), + ("blocks.element.point", json!({ "node": 1, "point": "end", "to": [0, -1] })), + ("blocks.element.point", json!({ "node": 1, "point": "middle", "to": [0, 0] })), + ("blocks.element.point", json!({ "node": 8, "point": "base", "to": [0, 0] })), + ("blocks.element.point", json!({ "node": 2, "point": "at", "to": [0, 0] })), + ("blocks.element.erase", json!({ "nodes": [2] })), + ("blocks.element.erase", json!({ "nodes": [99] })), + ] { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + } + assert_eq!(names(&s), ["Linear", "Point", "Stretch"], "nothing changed"); + assert_eq!(s.execute("blocks.element.points", &json!({ "node": -5 })).unwrap(), json!({ "points": [] })); + assert!(s.start_element_grip(42, ElementPoint::At).is_err()); + // Outside the editor. + s.execute("bclose", &json!({ "save": false })).unwrap(); + assert!(s.execute("blocks.element.select", &json!({ "nodes": [1] })).is_err()); +} + +/// A picked parameter of a kind that can't be moved yet (here a polar parameter, as AutoCAD's +/// blocks have) stays put; MOVE still moves the objects and the other picked ones, once. +#[test] +fn move_leaves_a_parameter_it_cannot_move_and_finishes() { + let (mut s, rect) = authored(); + { + let d = s.doc_mut().unwrap(); + let f = std::sync::Arc::make_mut(&mut d.foreign); + let o = f.objects.iter_mut().find(|o| o.kind == "BLOCKLINEARPARAMETER").unwrap(); + o.kind = "BLOCKPOLARPARAMETER".into(); + } + s.execute("blocks.element.select", &json!({ "nodes": [1, 9] })).unwrap(); + s.execute("select", &json!({ "handles": [rect.hex()] })).unwrap(); + s.script("MOVE\n0,0\n1,0\n").unwrap(); + assert!(s.running.is_none(), "MOVE finished"); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let ParameterKind::Polar { base, .. } = &m.parameters[0].kind else { panic!("{:?}", m.parameters[0].kind) }; + assert_eq!(*base, Vec3::new(0.0, -1.0, 0.0), "the polar parameter stayed"); + let ParameterKind::Point { at, .. } = &m.parameters[1].kind else { panic!() }; + assert_eq!(*at, Vec3::new(3.0, 2.0, 0.0), "the point parameter moved"); + let EntityKind::LwPolyline(pl) = &s.doc().unwrap().entity(rect).unwrap().kind else { panic!() }; + assert_eq!(pl.vertices[0].p, Vec2::new(1.0, 0.0), "the rectangle moved once"); +} + +/// BVMODE can be set before any drawing is open (saved settings load at startup), like the +/// other session variables. +#[test] +fn bvmode_is_set_without_a_drawing() { + let mut s = Session::empty(); + cadcraft_engine::sysvars::set(&mut s, "BVMODE", &json!(1)).unwrap(); + assert!(s.settings.bvmode); + cadcraft_engine::sysvars::set(&mut s, "OSMODE", &json!(3)).unwrap(); +} + +/// A JSON MOVE or ERASE given `handles` acts on those objects only; picked parameters and +/// actions come along only when the command uses the selection. +#[test] +fn json_handles_leave_picked_elements_alone() { + let (mut s, rect) = authored(); + s.execute("blocks.element.select", &json!({ "nodes": [9] })).unwrap(); + s.execute("erase", &json!({ "handles": [] })).unwrap(); + assert_eq!(names(&s), ["Linear", "Point", "Stretch"], "an empty list erases nothing"); + s.execute("move", &json!({ "handles": [rect.hex()], "delta": [1, 0] })).unwrap(); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let ParameterKind::Point { at, .. } = &m.parameters[1].kind else { panic!() }; + assert_eq!(*at, Vec3::new(2.0, 2.0, 0.0), "the picked point parameter stayed"); + s.execute("move", &json!({ "delta": [1, 0] })).unwrap(); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let ParameterKind::Point { at, .. } = &m.parameters[1].kind else { panic!() }; + assert_eq!(*at, Vec3::new(3.0, 2.0, 0.0), "with the selection, it moves"); +} + +/// With PICKFIRST off a selection made before MOVE doesn't count; picked parameters still do. +#[test] +fn pickfirst_off_moves_picked_elements_without_the_selection() { + let (mut s, rect) = authored(); + s.settings.pickfirst = false; + s.execute("select", &json!({ "handles": [rect.hex()] })).unwrap(); + s.execute("blocks.element.select", &json!({ "nodes": [9] })).unwrap(); + s.script("MOVE\n0,0\n1,0\n").unwrap(); + assert!(s.running.is_none()); + let EntityKind::LwPolyline(pl) = &s.doc().unwrap().entity(rect).unwrap().kind else { panic!() }; + assert_eq!(pl.vertices[0].p, Vec2::new(0.0, 0.0), "the selected rectangle stayed"); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let ParameterKind::Point { at, .. } = &m.parameters[1].kind else { panic!() }; + assert_eq!(*at, Vec3::new(3.0, 2.0, 0.0)); +} diff --git a/crates/engine/tests/it/block_lookup.rs b/crates/engine/tests/it/block_lookup.rs new file mode 100644 index 0000000000..dca2700c98 --- /dev/null +++ b/crates/engine/tests/it/block_lookup.rs @@ -0,0 +1,337 @@ +//! Lookup parameters and tables in the Block Editor (BPARAMETER Lookup, BACTION Lookup, +//! BLOOKUPTABLE): a table authored here sets a reference's distances, positions and visibility +//! state from the lookup value picked, and shows the lookup value its inputs match. + +use cadcraft_engine::doc::dynblock::{ActionKind, ParameterKind, custom_properties, dynamic_block, parameter_objects}; +use cadcraft_engine::doc::{EntityKind, Handle}; +use cadcraft_engine::{Input, Session}; +use serde_json::{Value, json}; + +fn h(v: &Value) -> Handle { + cadcraft_engine::cmd::curves::handle_value(v).unwrap() +} + +/// Block "Box": a 10 × 5 rectangle from (5,5) and a circle on its right edge, base point (5,5), +/// and a reference at (100,0). Returns the reference. +fn boxed(s: &mut Session) -> Value { + let made = |v: Value| if v["handle"].is_null() { v["handles"][0].clone() } else { v["handle"].clone() }; + let r = made(s.execute("rectang", &json!({ "p1": [5, 5], "p2": [15, 10] })).unwrap()); + let c = made(s.execute("circle", &json!({ "center": [15, 7.5], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "Box", "base": [5, 5], "handles": [r, c], "keep": "delete" })).unwrap(); + s.execute("insert", &json!({ "name": "Box", "at": [100, 0] })).unwrap()["handle"].clone() +} + +/// In the Block Editor on "Box" (editor coordinates: the rectangle from (0,0) to (10,5), the +/// circle at (10,2.5)): Distance1 stretching the right edge, Position1 moving the circle, states +/// VisibilityState0 (both) and Small (the rectangle only), and lookup parameter Size with its +/// table. Returns the lookup action's graph id. +fn authored(s: &mut Session) -> i32 { + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + let d = s.doc().unwrap(); + let of = |rect: bool| d.model.iter().find(|e| matches!(e.kind, EntityKind::LwPolyline(_)) == rect).unwrap().handle.hex(); + let (r, c) = (of(true), of(false)); + s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0], "grips": 1 })).unwrap(); + s.execute("baction", &json!({ "parameter": "Distance1", "type": "stretch", "frame": [[9, -1], [11, 6]], "handles": [r] })).unwrap(); + s.execute("bparameter", &json!({ "type": "point", "at": [10, 2.5] })).unwrap(); + s.execute("baction", &json!({ "parameter": "Position1", "type": "move", "handles": [c] })).unwrap(); + s.execute("bparameter", &json!({ "type": "visibility", "at": [-2, 5] })).unwrap(); + s.execute("bvstate", &json!({ "new": "Small", "visibility": "show" })).unwrap(); + s.execute("bvhide", &json!({ "handles": [c] })).unwrap(); + let p = s.execute("bparameter", &json!({ "type": "lookup", "at": [-2, 7], "label": "Size" })).unwrap(); + assert_eq!((p["element"].as_str(), p["label"].as_str()), (Some("Lookup"), Some("Size"))); + let a = s.execute("baction", &json!({ "parameter": "Size", "at": [-2, 8] })).unwrap(); + assert_eq!(a["name"], "Lookup1"); + a["node"].as_i64().unwrap() as i32 +} + +/// Reference `i`'s rectangle corners, circle centre and which of them show. +fn shape(s: &Session, i: &Value) -> (Vec<(f64, f64)>, (f64, f64), Vec) { + let d = s.doc().unwrap(); + let EntityKind::Insert(ins) = &d.entity(h(i)).unwrap().kind else { panic!() }; + let b = d.block(&ins.block).unwrap(); + let rect = b + .entities + .iter() + .find_map(|e| if let EntityKind::LwPolyline(p) = &e.kind { Some(p.vertices.iter().map(|v| (v.p.x, v.p.y)).collect()) } else { None }); + let circle = b.entities.iter().find_map(|e| if let EntityKind::Circle(c) = &e.kind { Some((c.center.x, c.center.y)) } else { None }); + (rect.unwrap(), circle.unwrap(), b.entities.iter().map(|e| e.common.visible).collect()) +} + +fn custom(s: &Session, i: &Value) -> Vec<(String, String, bool)> { + custom_properties(s.doc().unwrap(), h(i)).unwrap().1.into_iter().map(|p| (p.name, p.value, p.editable)).collect() +} + +#[test] +fn a_lookup_table_authored_in_json_drives_references() { + let mut s = Session::new(); + let i = boxed(&mut s); + let act = authored(&mut s); + // Empty, as BACTION makes it. + let t = s.execute("blookuptable", &json!({})).unwrap(); + assert_eq!(t["name"], "Lookup1"); + assert_eq!( + t["columns"], + json!([{ "name": "Size", "parameter": t["columns"][0]["parameter"], "property": "lookupString", "lookup": true, "unmatched": "Custom", "reverse": false }]) + ); + let undo = s.state().unwrap().undo.len(); + let t = s + .execute( + "blookuptable", + &json!({ + "inputs": ["Distance1", "Position1 X", "Visibility1"], + "rows": [[10, 10, "VisibilityState0", "Big"], ["6", "6", "small", "Small"]], + "reverse": true, + }), + ) + .unwrap(); + assert_eq!(s.state().unwrap().undo.len(), undo + 1, "one undo step"); + assert_eq!(t["action"], act); + let names: Vec<&str> = t["columns"].as_array().unwrap().iter().map(|c| c["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Distance1", "Position1 X", "Visibility1", "Size"]); + assert_eq!(t["rows"], json!([["10", "10", "VisibilityState0", "Big"], ["6", "6", "Small", "Small"]])); + assert_eq!(t["columns"][3]["reverse"], true); + s.execute("bclose", &json!({})).unwrap(); + + // The block's own values match the first row. + assert!(custom(&s, &i).contains(&("Size".to_string(), "Big".to_string(), true)), "{:?}", custom(&s, &i)); + // Size → Small sets the row's distance, position and state. + s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Size", "value": "Small" })).unwrap(); + let (rect, circle, shown) = shape(&s, &i); + assert_eq!(rect, [(5.0, 5.0), (11.0, 5.0), (11.0, 10.0), (5.0, 10.0)]); + assert_eq!(circle, (11.0, 7.5)); + assert_eq!(shown, [true, false], "Small hides the circle"); + // Inputs matching no row show Custom; matching one again, its value. + s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Distance1", "value": "8" })).unwrap(); + assert!(custom(&s, &i).contains(&("Size".to_string(), "Custom".to_string(), true))); + s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Distance1", "value": "6" })).unwrap(); + assert!(custom(&s, &i).contains(&("Size".to_string(), "Small".to_string(), true))); +} + +#[test] +fn a_read_only_lookup_cannot_be_set() { + let mut s = Session::new(); + let i = boxed(&mut s); + authored(&mut s); + s.execute("blookuptable", &json!({ "inputs": ["Distance1"], "rows": [[10, "Big"], [6, "Small"]] })).unwrap(); + s.execute("bclose", &json!({})).unwrap(); + assert!(custom(&s, &i).contains(&("Size".to_string(), "Big".to_string(), false)), "read only unless reverse lookup is allowed"); + assert!(s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Distance1", "value": "6" })).is_ok()); + assert!(custom(&s, &i).contains(&("Size".to_string(), "Small".to_string(), false))); +} + +#[test] +fn lookup_prompts_ask_as_autocad_does() { + let mut s = Session::new(); + boxed(&mut s); + s.execute("bedit", &json!({ "name": "Box" })).unwrap(); + s.execute("bparameter", &json!({ "type": "lookup", "at": [-2, 9] })).unwrap(); + s.script("BPARAMETER K\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Specify parameter location"); + s.script("N\n").unwrap(); + let p = s.current_prompt().unwrap(); + assert_eq!((p.message.as_str(), p.default.as_deref()), ("Enter parameter name", Some("Lookup1"))); + s.script("Look2\nL\n").unwrap(); + let p = s.current_prompt().unwrap(); + assert_eq!((p.message.as_str(), p.default.as_deref()), ("Enter lookup property label", Some("Lookup2"))); + s.script("Size\nD\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Enter property description"); + s.script("desc\nP\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Display property in Properties palette"); + s.script("N\n-2,7\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Enter number of grips"); + s.script("0\n").unwrap(); + assert!(s.running.is_none()); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let p = m.parameters.iter().find(|p| p.element == "Look2").unwrap(); + assert!(matches!(&p.kind, ParameterKind::Lookup { label, description, .. } if label == "Size" && description == "desc")); + assert!(!p.show_properties && p.grips.iter().all(|g| *g == 0)); + + // BACTION on it asks only where the action goes; a second one is refused. + s.script("BACTION -2,7\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Specify action location"); + s.script("-2,8\n").unwrap(); + assert!(s.running.is_none()); + s.script("BACTION -2,7\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Select parameter", "already has its table"); + s.input(Input::Cancel).unwrap(); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + assert_eq!(m.actions.iter().filter(|a| matches!(a.kind, ActionKind::Lookup { .. })).count(), 1); + + // BLOOKUPTABLE on the command line: pick the action; its table is listed. + s.script("BLOOKUPTABLE\n").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Select lookup action"); + s.script("-2,8\n").unwrap(); + assert!(s.running.is_none()); +} + +#[test] +fn the_lookup_action_is_active_in_the_state_shown() { + let mut s = Session::new(); + boxed(&mut s); + let act = authored(&mut s); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let action = m.actions.iter().find(|a| a.node == act).unwrap().handle; + let Some(ParameterKind::Visibility { states, .. }) = + m.parameters.iter().map(|p| p.kind.clone()).find(|k| matches!(k, ParameterKind::Visibility { .. })) + else { + panic!() + }; + let small = states.iter().find(|st| st.name == "Small").unwrap(); + assert!(small.active.contains(&action), "added while Small is shown"); + assert!(!states[0].active.contains(&action)); + // A visibility state made to show everything lists the actions too, as AutoCAD's does. + s.execute("bvstate", &json!({ "new": "All", "visibility": "show" })).unwrap(); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let all = parameter_objects(&m, None); + let Some(ParameterKind::Visibility { states, .. }) = + m.parameters.iter().map(|p| p.kind.clone()).find(|k| matches!(k, ParameterKind::Visibility { .. })) + else { + panic!() + }; + assert_eq!(states.last().unwrap().active, all); + assert!(all.contains(&action)); +} + +#[test] +fn erasing_the_lookup_parameter_erases_its_table() { + let mut s = Session::new(); + boxed(&mut s); + authored(&mut s); + s.execute("blookuptable", &json!({ "inputs": ["Distance1", "Visibility1"], "rows": [[10, "VisibilityState0", "Big"], [6, "Small", "Small"]] })) + .unwrap(); + // Erasing an input takes its column. + let lin = dynamic_block(s.doc().unwrap(), "Box").unwrap().parameters.iter().find(|p| p.kind.label() == Some("Distance1")).unwrap().node; + s.execute("blocks.element.erase", &json!({ "nodes": [lin] })).unwrap(); + let t = s.execute("blookuptable", &json!({})).unwrap(); + assert_eq!(t["rows"], json!([["VisibilityState0", "Big"], ["Small", "Small"]])); + let size = dynamic_block(s.doc().unwrap(), "Box").unwrap().parameters.iter().find(|p| p.kind.label() == Some("Size")).unwrap().node; + s.execute("blocks.element.erase", &json!({ "nodes": [size] })).unwrap(); + assert!(s.execute("blookuptable", &json!({})).is_err(), "no lookup action left"); +} + +#[test] +fn hostile_lookup_params_never_panic() { + let mut s = Session::new(); + boxed(&mut s); + assert!(s.execute("blookuptable", &json!({})).is_err(), "only in the Block Editor"); + authored(&mut s); + let many: Vec = (0..20_001).map(|_| json!(["1", "a"])).collect(); + for p in [ + json!(null), + json!([]), + json!({ "action": "Nope" }), + json!({ "action": 9999 }), + json!({ "action": [1] }), + json!({ "inputs": "Distance1" }), + json!({ "inputs": [5] }), + json!({ "inputs": ["Nope"], "rows": [] }), + json!({ "inputs": ["Distance1"], "rows": 5 }), + json!({ "inputs": ["Distance1"], "rows": [5] }), + json!({ "inputs": ["Distance1"], "rows": [[{}, "a"]] }), + json!({ "inputs": ["Distance1"], "rows": [["1"]] }), + json!({ "inputs": ["Distance1"], "rows": [["NaN", "a"]] }), + json!({ "inputs": ["Distance1"], "rows": [["1e999", "a"]] }), + json!({ "inputs": ["Distance1"], "rows": many }), + json!({ "inputs": ["Distance1", "Distance1"], "rows": [] }), + json!({ "inputs": ["Distance1"], "lookups": ["Nope"], "rows": [] }), + json!({ "inputs": ["Distance1"], "lookups": [], "rows": [] }), + json!({ "unmatched": 5 }), + json!({ "unmatched": { "Nope": "x" } }), + json!({ "reverse": "yes" }), + json!({ "inputs": ["Distance1"] }), + json!({ "tables": 5 }), + json!({ "tables": [5] }), + json!({ "tables": [{ "tables": [] }] }), + json!({ "tables": (0..1_001).map(|_| json!({})).collect::>() }), + json!({ "tables": [{ "action": "Nope", "rows": [] }] }), + ] { + let _ = s.execute("blookuptable", &p); + } + let before = s.doc().unwrap().foreign.clone(); + assert!(s.execute("blookuptable", &json!({ "inputs": ["Distance1"], "rows": [["1", "a"], ["1.0", "b"]] })).is_err()); + assert_eq!(s.doc().unwrap().foreign, before, "a refused table changes nothing"); + for p in [ + json!({ "type": "lookup" }), + json!({ "type": "lookup", "at": [0, 0], "grips": 2 }), + json!({ "type": "lookup", "at": [0, 0], "palette": "no" }), + json!({ "type": "lookup", "at": [0, 0], "name": "Lookup" }), + ] { + assert!(s.execute("bparameter", &p).is_err(), "{p}"); + } + let _ = s.execute("bparameter", &json!({ "type": "lookup", "at": [1e308, f64::MAX] })); + for p in [ + json!({ "parameter": "Size" }), + json!({ "parameter": "Size", "type": "move", "handles": [] }), + json!({ "parameter": "Distance1", "type": "lookup" }), + ] { + assert!(s.execute("baction", &p).is_err(), "{p}"); + } + s.script("BLOOKUPTABLE\n1000,1000\n").unwrap(); + s.input(Input::Cancel).unwrap(); + s.script("BPARAMETER K N\n\nP\nmaybe\n").unwrap(); + s.input(Input::Cancel).unwrap(); +} + +#[test] +fn a_lookup_on_a_position_follows_its_point() { + let mut s = Session::new(); + let i = boxed(&mut s); + authored(&mut s); + s.execute("blookuptable", &json!({ "inputs": ["Position1 X"], "rows": [[10, "Big"], [6, "Small"]], "reverse": true })).unwrap(); + s.execute("bclose", &json!({})).unwrap(); + assert!(custom(&s, &i).contains(&("Size".to_string(), "Big".to_string(), true))); + let m = dynamic_block(s.doc().unwrap(), "Box").unwrap(); + let size = m.parameters.iter().find(|p| matches!(p.kind, ParameterKind::Lookup { .. })).unwrap().node; + // The lookup value the reference keeps (written to its data, as AutoCAD writes it). + let kept = |s: &Session| match cadcraft_engine::doc::dynblock::reference(s.doc().unwrap(), h(&i)).unwrap().values.get(&size) { + Some(cadcraft_engine::doc::dynblock::Value::Text { value }) => value.clone(), + v => format!("{v:?}"), + }; + // Typed in Properties. + s.execute("blocks.reference.set", &json!({ "handle": i, "name": "Position1 X", "value": "6" })).unwrap(); + assert!(custom(&s, &i).contains(&("Size".to_string(), "Small".to_string(), true)), "{:?}", custom(&s, &i)); + assert_eq!(kept(&s), "Small"); + // Dragged by its grip (the reference is at (100,0), so the block's x = 10 is at 110). + let node = m.parameters.iter().find(|p| matches!(p.kind, ParameterKind::Point { .. })).unwrap().node; + cadcraft_engine::doc::dynblock::drag_grip( + s.doc_mut().unwrap(), + h(&i), + node, + cadcraft_engine::doc::dynblock::GripPart::At, + cadcraft_engine::geom::Vec2::new(110.0, 2.5), + ) + .unwrap(); + assert!(custom(&s, &i).contains(&("Size".to_string(), "Big".to_string(), true)), "{:?}", custom(&s, &i)); + assert_eq!(kept(&s), "Big"); +} + +/// The Property Lookup Table dialog's OK writes every table edited in it as one `tables` call: +/// one undo step takes them all back, and a table that is refused leaves every table as it was. +#[test] +fn several_tables_are_written_as_one_step_or_not_at_all() { + let mut s = Session::new(); + boxed(&mut s); + let size = authored(&mut s); + s.execute("bparameter", &json!({ "type": "lookup", "at": [-2, 9], "label": "Finish" })).unwrap(); + let finish = s.execute("baction", &json!({ "parameter": "Finish" })).unwrap()["node"].as_i64().unwrap() as i32; + let rows = |s: &mut Session, action: i32| s.execute("blookuptable", &json!({ "action": action })).unwrap()["rows"].clone(); + let steps = |s: &Session| s.state().unwrap().undo.len(); + let original = (rows(&mut s, size), rows(&mut s, finish)); + let before = steps(&s); + // The second table repeats a row of inputs: refused, and the first isn't written either. + let good = json!({ "action": size, "inputs": ["Distance1"], "rows": [[10, "Big"], [6, "Small"]] }); + let refused = json!({ "action": finish, "inputs": ["Distance1"], "rows": [[1, "Matt"], ["1.0", "Gloss"]] }); + let e = s.execute("blookuptable", &json!({ "tables": [good, refused] })).unwrap_err().to_string(); + assert!(e.contains("no table was changed"), "{e}"); + assert_eq!((rows(&mut s, size), rows(&mut s, finish)), original); + assert_eq!(steps(&s), before, "nothing written, no undo step"); + // Both accepted: written together, as one undo step. + let finish_rows = json!({ "action": finish, "inputs": ["Distance1"], "rows": [[1, "Matt"], [2, "Gloss"]] }); + let r = s.execute("blookuptable", &json!({ "tables": [good, finish_rows] })).unwrap(); + assert_eq!(r["tables"].as_array().map(Vec::len), Some(2)); + assert_eq!(rows(&mut s, size), json!([["10", "Big"], ["6", "Small"]])); + assert_eq!(rows(&mut s, finish), json!([["1", "Matt"], ["2", "Gloss"]])); + assert_eq!(steps(&s), before + 1, "one undo step for both tables"); + s.undo().unwrap(); + assert_eq!((rows(&mut s, size), rows(&mut s, finish)), original, "one Undo restores both tables"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 3d6679d95b..824d5dc07e 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -20,8 +20,11 @@ mod attrib_props; mod attribute_tag_matching; mod attribute_tools; mod attribute_value_baseline; +mod block_authoring; mod block_description; +mod block_elements; mod block_keep; +mod block_lookup; mod block_redefine; mod blockreplace; mod break_closed_polyline; diff --git a/crates/io/tests/it/dynblock_author.rs b/crates/io/tests/it/dynblock_author.rs new file mode 100644 index 0000000000..8c05864405 --- /dev/null +++ b/crates/io/tests/it/dynblock_author.rs @@ -0,0 +1,420 @@ +//! 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, MAX_VISIBILITY_STATES, Mark, ParamPoint, ParameterKind, ParameterSpec, VisibilityState, add_action, add_parameter, + dynamic_block, set_property, set_visibility, tag_elements, +}; +use cadcraft_doc::{Drawing, EntityKind, Handle}; +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(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 }, + ]; + 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")); +} + +/// 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)); +} + +/// BOX with a visibility parameter (one grip) over both of its objects. +fn visible() -> (Drawing, i32) { + let mut d = box_drawing(); + let spec = ParameterSpec::Visibility { at: v(0.0, 6.0), label: None, objects: vec![h("30"), h("31")], grips: 1 }; + let p = add_parameter(&mut d, "BOX", &spec).unwrap(); + (d, p) +} + +#[test] +fn an_authored_visibility_parameter_reads_back_and_links_as_autocad_does() { + let (d, p) = visible(); + let m = dynamic_block(&d, "BOX").unwrap(); + let param = &m.parameters[0]; + assert_eq!((p, param.element.as_str(), param.grips.as_slice()), (1, "Visibility State", [2].as_slice())); + let ParameterKind::Visibility { at, label, controlled, states, .. } = ¶m.kind else { panic!("{param:?}") }; + assert_eq!((*at, label.as_str(), controlled.as_slice()), (v(0.0, 6.0), "Visibility1", [h("30"), h("31")].as_slice())); + assert_eq!(states.len(), 1); + assert_eq!((states[0].name.as_str(), states[0].visible.as_slice()), ("VisibilityState0", [h("30"), h("31")].as_slice())); + assert!(states[0].active.is_empty(), "no other parameters to show"); + // AutoCAD's own layout: the grip feeds the parameter first, then the parameter its two + // location components, every edge of kind 1. + let (nodes, edges) = graph(&d); + assert_eq!(nodes, vec![(0, 1, vec![0, 0, 1, 2]), (1, 2, vec![-1, -1, 0, 0]), (2, 3, vec![1, 1, -1, -1]), (3, 4, vec![2, 2, -1, -1])]); + assert_eq!(edges, vec![(1, 1, 0, vec![-1, -1, -1, -1, -1]), (1, 0, 2, vec![-1, -1, -1, 2, -1]), (1, 0, 3, vec![-1, -1, 1, -1, -1])]); + for c in ["BLOCKVISIBILITYPARAMETER", "BLOCKVISIBILITYGRIP"] { + assert!(d.foreign.classes.iter().any(|k| k.iter().any(|t| t.code == 1 && t.value == c)), "class {c}"); + } + // The Block Editor draws it with its list grip. + let marks = cadcraft_doc::dynblock::marks(&d, "BOX"); + assert!(matches!(&marks[..], [Mark::List { node: 1, grip: true, label, .. }] if label == "Visibility1"), "{marks:?}"); + let mut again = d.clone(); + let second = ParameterSpec::Visibility { at: v(0.0, 0.0), label: None, objects: Vec::new(), grips: 0 }; + assert!(add_parameter(&mut again, "BOX", &second).is_err(), "one visibility parameter per block"); +} + +#[test] +fn visibility_states_survive_a_save_and_drive_references() { + let (mut d, _) = visible(); + let states = vec![ + VisibilityState { name: "Both".into(), visible: vec![h("30"), h("31")], active: Vec::new() }, + VisibilityState { name: "Circle only".into(), visible: vec![h("31")], active: Vec::new() }, + ]; + set_visibility(&mut d, "BOX", &[h("30"), h("31")], &states).unwrap(); + let again = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + let m = dynamic_block(&again, "BOX").unwrap(); + let ParameterKind::Visibility { states: read, .. } = &m.parameters[0].kind else { panic!() }; + assert_eq!(read, &states); + + set_property(&mut d, h("40"), "Visibility1", "Circle only").unwrap(); + let EntityKind::Insert(i) = &d.entity(h("40")).unwrap().kind else { panic!() }; + let b = d.block(&i.block).unwrap(); + let shown: Vec = b.entities.iter().map(|e| e.common.visible).collect(); + assert_eq!(shown, [false, true], "the rectangle hidden, the circle shown"); +} + +#[test] +fn bad_visibility_states_are_refused() { + let (mut d, _) = visible(); + let st = |n: &str| VisibilityState { name: n.into(), visible: Vec::new(), active: Vec::new() }; + assert!(set_visibility(&mut d, "BOX", &[], &[]).is_err(), "no states"); + assert!(set_visibility(&mut d, "BOX", &[], &[st("A"), st("a")]).is_err(), "names are case-insensitive"); + assert!(set_visibility(&mut d, "BOX", &[], &[st(" ")]).is_err(), "a name"); + assert!(set_visibility(&mut box_drawing(), "BOX", &[], &[st("A")]).is_err(), "no visibility parameter"); + let many: Vec = (0..=MAX_VISIBILITY_STATES).map(|i| st(&i.to_string())).collect(); + assert!(set_visibility(&mut d, "BOX", &[], &many).is_err()); + let before = d.foreign.clone(); + let hostile = ParameterSpec::Visibility { at: v(f64::NAN, 0.0), label: None, objects: Vec::new(), grips: 0 }; + assert!(add_parameter(&mut d, "BOX", &hostile).is_err()); + let hostile = ParameterSpec::Visibility { at: v(0.0, 0.0), label: None, objects: Vec::new(), grips: 2 }; + assert!(add_parameter(&mut box_drawing(), "BOX", &hostile).is_err()); + assert_eq!(d.foreign, before); +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index e3d58fbe8f..7ecc6c8860 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -31,6 +31,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/blookup.rs b/crates/ui-egui/src/blookup.rs new file mode 100644 index 0000000000..71b35baffc --- /dev/null +++ b/crates/ui-egui/src/blookup.rs @@ -0,0 +1,803 @@ +//! The Property Lookup Table dialog: BLOOKUPTABLE typed, or a double-click on a lookup action in +//! the Block Editor (as in AutoCAD), while the Block Editor is open on a block with one. As AutoCAD's dialog: the +//! action's input properties (left) and lookup properties (right) as columns, one row per set of +//! inputs, a blank row at the end to add one, then the `` row (what a reference shows +//! when no row matches, editable for each lookup property) and whether each lookup property can be +//! set on a reference ("Allow reverse lookup", only while its values don't repeat) or is "Read +//! only". Add Properties... adds columns, Audit checks the table, OK writes it as one step +//! (`blookuptable {inputs, lookups, rows, unmatched, reverse}`); Cancel changes nothing. A block +//! with several lookup actions picks one at the top (the one picked in the editor first). JSON +//! calls skip the dialog. + +use cadcraft_engine::doc::dynblock::{ + ActionKind, DynamicBlock, ParameterKind, cell_key, column_property, dynamic_block, input_properties, set_lookup_table, +}; +use egui::{RichText, Stroke, vec2}; +use serde_json::{Map, Value, json}; + +use crate::CadApp; +use crate::theme::Tokens; + +/// One column as the dialog edits it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Column { + /// The property name shown ("Distance1", "Position1 X", "Size"). + pub name: String, + pub parameter: i32, + pub property: String, + pub lookup: bool, + pub unmatched: String, + pub reverse: bool, + /// A visibility state column's states (its cells are picked from them). + pub states: Vec, +} + +/// The Add Parameter Properties dialog's fields: which list, and the properties ticked in it. +#[derive(Clone, Debug, Default)] +pub struct Adding { + pub lookup: bool, + pub ticked: Vec, +} + +/// The dialog's state while it is open: the table as it will be written on OK. +#[derive(Clone, Debug, Default)] +pub struct State { + /// The block's lookup actions (graph id, name) and the one shown. + pub actions: Vec<(i32, String)>, + pub action: i32, + /// Input columns first, then lookup columns. + pub columns: Vec, + /// One cell per column; the blank row at the end isn't kept here. + pub rows: Vec>, + /// The Add Parameter Properties dialog, while open. + pub adding: Option, + /// Audit's verdict or why OK was refused (`true`: a problem). + pub message: Option<(String, bool)>, + /// The tables of the other lookup actions shown since the dialog opened, as last edited: the + /// Action name list switches between them without losing what was typed, and OK writes every + /// one that changed. + drafts: std::collections::BTreeMap, +} + +impl State { + /// Load action `action` of block `m` into the dialog. + fn load(m: &DynamicBlock, action: i32) -> State { + let actions: Vec<(i32, String)> = + m.actions.iter().filter(|a| matches!(a.kind, ActionKind::Lookup { .. })).map(|a| (a.node, a.name.clone())).collect(); + let Some(ActionKind::Lookup { columns, rows }) = m.actions.iter().find(|a| a.node == action).map(|a| &a.kind) else { + return State { actions, action, ..State::default() }; + }; + let columns = columns + .iter() + .map(|c| Column { + name: column_property(m, c.node, &c.property), + parameter: c.node, + property: c.property.clone(), + lookup: c.lookup, + unmatched: c.unmatched.clone(), + reverse: c.lookup && c.reverse, + states: states_of(m, c.node, &c.property), + }) + .collect(); + State { actions, action, columns, rows: rows.clone(), ..State::default() } + } + + fn inputs(&self) -> usize { + self.columns.iter().filter(|c| !c.lookup).count() + } + + /// Whether lookup column `j`'s values repeat (or it has none): it can't be reversed then. Cells + /// compare as the table compares them when it is written ([`cell_key`]: `10` and `10.0` repeat). + fn repeats(&self, j: usize) -> bool { + let mut seen = std::collections::HashSet::new(); + let mut any = false; + for v in self.rows.iter().filter_map(|r| r.get(j)).filter(|v| !v.trim().is_empty()) { + any = true; + if !seen.insert(cell_key(v)) { + return true; + } + } + !any + } + + /// Add `column` with an empty cell in every row: an input after the other inputs, a lookup + /// column last. + fn add_column(&mut self, column: Column) { + let at = if column.lookup { self.columns.len() } else { self.inputs() }; + self.columns.insert(at, column); + for r in &mut self.rows { + r.insert(at.min(r.len()), String::new()); + } + } + + /// Remove column `j` (not the action's own lookup column, the first lookup column). + fn remove_column(&mut self, j: usize) { + if !self.removable(j) { + return; + } + self.columns.remove(j); + for r in &mut self.rows { + if j < r.len() { + r.remove(j); + } + } + } + + fn removable(&self, j: usize) -> bool { + j != self.inputs() && j < self.columns.len() + } + + /// Show action `id`: the current table is kept as a draft, and `id`'s draft, if it has one, + /// comes back as it was left; otherwise its table is loaded from block `m`. + fn switch_to(&mut self, m: &DynamicBlock, id: i32) { + if id == self.action { + return; + } + let mut drafts = std::mem::take(&mut self.drafts); + let mut next = drafts.remove(&id).unwrap_or_else(|| State::load(m, id)); + let mut current = std::mem::take(self); + (current.adding, current.message) = (None, None); + drafts.insert(current.action, current); + next.drafts = drafts; + *self = next; + } + + /// The tables OK writes: each other action's draft that differs from block `m`'s table, then + /// the one shown (always, as before there were drafts). + fn to_write(&self, m: &DynamicBlock) -> Vec<&State> { + let saved = |st: &State| { + let s = State::load(m, st.action); + s.columns == st.columns && s.rows == st.rows + }; + self.drafts.values().filter(|d| !saved(d)).chain(std::iter::once(self)).collect() + } + + /// The `blookuptable` parameters writing this table. + fn params(&self) -> Value { + let names = |lookup: bool| self.columns.iter().filter(|c| c.lookup == lookup).map(|c| c.name.clone()).collect::>(); + let mut unmatched = Map::new(); + for c in &self.columns { + unmatched.insert(c.name.clone(), json!(c.unmatched)); + } + let reverse: Vec = + self.columns.iter().enumerate().filter(|(j, c)| c.lookup && c.reverse && !self.repeats(*j)).map(|(_, c)| c.name.clone()).collect(); + let rows: Vec<&Vec> = self.rows.iter().filter(|r| r.iter().any(|c| !c.trim().is_empty())).collect(); + json!({ "action": self.action, "inputs": names(false), "lookups": names(true), "rows": rows, "unmatched": unmatched, "reverse": reverse }) + } + + /// The table written into a copy of drawing `d`'s block `block`: `Err` with AutoCAD's reason + /// when it would be refused (Audit, and OK before writing). + fn audit(&self, d: &cadcraft_engine::doc::Drawing, block: &str) -> Result<(), String> { + let mut d = d.clone(); + let columns: Vec = self + .columns + .iter() + .enumerate() + .map(|(j, c)| cadcraft_engine::doc::dynblock::TableColumn { + node: c.parameter, + property: c.property.clone(), + lookup: c.lookup, + unmatched: c.unmatched.clone(), + reverse: c.reverse && !self.repeats(j), + }) + .collect(); + set_lookup_table(&mut d, block, self.action, &columns, &self.rows) + } +} + +/// A visibility column's states (empty for other columns). +fn states_of(m: &DynamicBlock, node: i32, property: &str) -> Vec { + if !property.eq_ignore_ascii_case("VisibilityState") { + return Vec::new(); + } + m.parameters + .iter() + .find(|p| p.node == node) + .and_then(|p| match &p.kind { + ParameterKind::Visibility { states, .. } => Some(states.iter().map(|s| s.name.clone()).collect()), + _ => None, + }) + .unwrap_or_default() +} + +/// The edited block's name and dynamic data, when the Block Editor is open on a block. +fn edited(app: &CadApp) -> Option<(String, DynamicBlock, Vec)> { + let st = app.session.state().ok()?; + let be = st.block_edit.as_ref()?; + if be.current { + return None; + } + Some((be.name.clone(), dynamic_block(&st.doc, &be.name)?, be.picked.clone())) +} + +/// BLOOKUPTABLE typed or from the Block Editor's bar without parameters opens the dialog when the +/// edited block has a lookup action (the one picked in the editor, else its first); otherwise +/// BLOOKUPTABLE runs and says why it can't. +pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option> { + if id != "blookuptable" || !params.is_null() { + return None; + } + let (_, m, picked) = edited(app)?; + let lookups: Vec = m.actions.iter().filter(|a| matches!(a.kind, ActionKind::Lookup { .. })).map(|a| a.node).collect(); + let action = lookups.iter().copied().find(|a| picked.contains(a)).or_else(|| lookups.first().copied())?; + open(app, action).then_some(Ok(Value::Null)) +} + +/// Open the dialog on action `node` of the edited block when it is a lookup action (a +/// double-click on its mark); whether it opened. +pub fn open(app: &mut CadApp, node: i32) -> bool { + let Some((_, m, _)) = edited(app) else { return false }; + if !m.actions.iter().any(|a| a.node == node && matches!(a.kind, ActionKind::Lookup { .. })) { + return false; + } + app.blookup = State::load(&m, node); + app.ui.dialog = Some("blookuptable".into()); + true +} + +/// The Property Lookup Table window (and Add Parameter Properties over it). +pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { + let t = Tokens::get(); + let Some((block, m, _)) = edited(app) else { + *open = false; + return; + }; + let (mut ok, mut cancel, mut audit) = (false, false, false); + let mut st = std::mem::take(&mut app.blookup); + let modal = st.adding.is_some(); + let mut switch: Option = None; + egui::Window::new(crate::tl!("Property Lookup Table")) + .id(egui::Id::unique("Property Lookup Table")) + .open(open) + .collapsible(false) + .resizable(true) + .default_width(760.0) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.add_enabled_ui(!modal, |ui| { + ui.horizontal(|ui| { + ui.label(crate::tl!("Action name:")); + let current = st.actions.iter().find(|(id, _)| *id == st.action).map(|(_, n)| n.clone()).unwrap_or_default(); + if st.actions.len() > 1 { + egui::ComboBox::from_id_salt("blookup-action").selected_text(current).show_ui(ui, |ui| { + for (id, n) in &st.actions { + if ui.selectable_label(*id == st.action, n.as_str()).clicked() && *id != st.action { + switch = Some(*id); + } + } + }); + } else { + ui.label(RichText::new(current).color(t.text)); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(crate::tl!("Audit")).clicked() { + audit = true; + } + if ui.button(crate::tl!("Add Properties...")).clicked() { + st.adding = Some(Adding::default()); + st.message = None; + } + }); + }); + ui.add_space(6.0); + egui::ScrollArea::both().id_salt("blookup-table").auto_shrink([false, true]).max_height(420.0).show(ui, |ui| { + table(ui, &mut st); + }); + ui.add_space(6.0); + if let Some((msg, problem)) = &st.message { + let color = if *problem { t.warn } else { t.accent }; + egui::Frame::new().stroke(Stroke::new(1.0, color)).corner_radius(3.0).inner_margin(vec2(8.0, 4.0)).show(ui, |ui| { + ui.colored_label(color, msg); + }); + } + ui.separator(); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(crate::tl!("Cancel")).clicked() { + cancel = true; + } + if ui.button(crate::tl!("OK")).clicked() { + ok = true; + } + }); + }); + }); + }); + if st.adding.is_some() { + add_dialog(ctx, &mut st, &m); + } + if let Some(id) = switch { + st.switch_to(&m, id); + } + if audit { + st.message = Some(match st.audit(&app.session.state().map(|s| s.doc.clone()).unwrap_or_default(), &block) { + Ok(()) => (crate::i18n::t("No errors have been found in the Property Lookup Table.").to_string(), false), + Err(e) => (e, true), + }); + } + if ok { + match write_tables(app, &st, &m, &block) { + Ok(()) => *open = false, + Err((action, e)) => { + // The table that was refused is shown with the reason. + st.switch_to(&m, action); + st.message = Some((e, true)); + app.blookup = st; + return; + } + } + } + if cancel { + *open = false; + } + app.blookup = st; +} + +/// OK: write the changed tables of `st` (every edited action's, then the one shown) as one +/// `blookuptable` command, so one Undo takes them all back and a table the engine refuses leaves +/// every table as it was. Each is audited first, so a table AutoCAD would refuse stops OK before +/// anything is written; `Err` names its action (the one shown when the engine refuses) and the +/// reason. +fn write_tables(app: &mut CadApp, st: &State, m: &DynamicBlock, block: &str) -> Result<(), (i32, String)> { + let tables = st.to_write(m); + let doc = app.session.state().map(|s| s.doc.clone()).unwrap_or_default(); + for t in &tables { + t.audit(&doc, block).map_err(|e| (t.action, e))?; + } + let params: Vec = tables.iter().map(|t| t.params()).collect(); + app.run("blookuptable", json!({ "tables": params })).map(|_| ()).map_err(|e| (st.action, e)) +} + +/// The grid's row height, header height and row-number column width. +const ROW_H: f32 = 26.0; +const HEAD_H: f32 = 28.0; +const NUM_W: f32 = 34.0; + +/// A column's width: wider for a list (a visibility state, a lookup's reverse-lookup choice). +fn col_width(c: &Column) -> f32 { + if c.states.is_empty() && !c.lookup { 120.0 } else { 180.0 } +} + +/// What the grid asks for once drawn: a column to remove, a row to delete. +#[derive(Default)] +struct Edits { + remove: Option, + delete_row: Option, +} + +/// The table, as AutoCAD lays it out: Input Properties and Lookup Properties side by side, each +/// a grid with its header, a row per set of inputs, a blank row that adds one when filled in, +/// then the `` row and (lookups) the reverse-lookup row. Right-click a header to +/// remove the property, a row number to delete the row. +fn table(ui: &mut egui::Ui, st: &mut State) { + let inputs = st.inputs(); + let len = st.columns.len(); + let mut edits = Edits::default(); + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = 12.0; + pane(ui, st, crate::tl!("Input Properties"), 0..inputs, true, &mut edits); + pane(ui, st, crate::tl!("Lookup Properties"), inputs..len, false, &mut edits); + }); + if let Some(j) = edits.remove { + st.remove_column(j); + } + if let Some(r) = edits.delete_row + && r < st.rows.len() + { + st.rows.remove(r); + } +} + +/// One side of the table: columns `cols` (with row numbers when `numbers`). +fn pane(ui: &mut egui::Ui, st: &mut State, title: &str, cols: std::ops::Range, numbers: bool, edits: &mut Edits) { + let t = Tokens::get(); + let n = st.rows.len(); + // The data rows, the blank row, and reverse lookup: both sides line up. + let rows = n + 3; + let num_w = if numbers { NUM_W } else { 0.0 }; + let widths: Vec = cols.clone().filter_map(|j| st.columns.get(j)).map(col_width).collect(); + let w = num_w + if widths.is_empty() { 240.0 } else { widths.iter().sum() }; + let font = egui::FontId::proportional(13.0); + ui.vertical(|ui| { + ui.label(RichText::new(title).strong().color(t.text)); + ui.add_space(2.0); + let (rect, _) = ui.allocate_exact_size(vec2(w, HEAD_H + ROW_H * rows as f32), egui::Sense::hover()); + let p = ui.painter_at(rect.expand(1.0)); + let top = rect.top() + HEAD_H; + let row_y = |r: usize| top + ROW_H * r as f32; + // Backgrounds: the cells, the header, the row numbers, and the rows after the data. + p.rect_filled(rect, 3.0, t.field); + p.rect_filled(egui::Rect::from_min_size(rect.min, vec2(w, HEAD_H)), egui::CornerRadius { nw: 3, ne: 3, sw: 0, se: 0 }, t.panel); + if numbers { + p.rect_filled(egui::Rect::from_min_max(egui::pos2(rect.left(), top), egui::pos2(rect.left() + num_w, rect.bottom())), 0.0, t.panel); + } + p.rect_filled(egui::Rect::from_min_max(egui::pos2(rect.left() + num_w, row_y(n + 1)), rect.max), 0.0, t.panel.gamma_multiply(0.55)); + let line = Stroke::new(1.0, t.border); + for r in 0..rows { + p.hline(rect.x_range(), row_y(r), line); + } + let mut x = rect.left() + num_w; + if numbers { + p.vline(x, rect.y_range(), line); + } + for cw in &widths { + x += cw; + if x < rect.right() - 1.0 { + p.vline(x, rect.y_range(), line); + } + } + p.rect_stroke(rect, 3.0, line, egui::StrokeKind::Inside); + if widths.is_empty() { + let hint = crate::tl!("Add Properties... adds input properties"); + p.text(rect.center(), egui::Align2::CENTER_CENTER, hint, font.clone(), t.text_dim); + return; + } + + // Headers: right-click one to remove its property (not the action's own lookup). + let mut x = rect.left() + num_w; + for (k, j) in cols.clone().enumerate() { + let (Some(c), Some(cw)) = (st.columns.get(j), widths.get(k)) else { continue }; + let hr = egui::Rect::from_min_size(egui::pos2(x, rect.top()), vec2(*cw, HEAD_H)); + let color = if c.lookup { t.accent } else { t.text }; + p.text(hr.left_center() + vec2(8.0, 0.0), egui::Align2::LEFT_CENTER, &c.name, egui::FontId::proportional(13.0), color); + let removable = st.removable(j); + ui.interact(hr, ui.scope_id().with(("blookup-head", j)), egui::Sense::click()).context_menu(|ui| { + if ui.add_enabled(removable, egui::Button::new(crate::tl!("Remove Property"))).clicked() { + edits.remove = Some(j); + ui.close(); + } + }); + x += cw; + } + + // Row numbers: right-click one to delete its row; `*` marks the row that adds one. + if numbers { + for r in 0..=n { + let nr = egui::Rect::from_min_size(egui::pos2(rect.left(), row_y(r)), vec2(num_w, ROW_H)); + let label = if r < n { format!("{}", r + 1) } else { "*".to_string() }; + p.text(nr.center(), egui::Align2::CENTER_CENTER, label, font.clone(), t.text_dim); + if r < n { + ui.interact(nr, ui.scope_id().with(("blookup-row", r)), egui::Sense::click()).context_menu(|ui| { + if ui.button(crate::tl!("Delete Row")).clicked() { + edits.delete_row = Some(r); + ui.close(); + } + }); + } + } + } + + // The cells: text, or a visibility state picked from its list. + let cell_rect = |k: usize, r: usize| { + let x = rect.left() + num_w + widths.iter().take(k).sum::(); + egui::Rect::from_min_size(egui::pos2(x, row_y(r)), vec2(widths.get(k).copied().unwrap_or(0.0), ROW_H)).shrink(1.0) + }; + let blank = vec![String::new(); st.columns.len()]; + for r in 0..=n { + let mut row = st.rows.get(r).cloned().unwrap_or_else(|| blank.clone()); + for (k, j) in cols.clone().enumerate() { + let (Some(c), Some(cell)) = (st.columns.get(j), row.get_mut(j)) else { continue }; + let cr = cell_rect(k, r); + if c.states.is_empty() { + let edit = egui::TextEdit::singleline(cell) + .frame(egui::Frame::NONE) + .margin(vec2(8.0, 0.0)) + .align(egui::Align2::LEFT_CENTER) + .id_salt(("blookup-cell", r, j)); + ui.put(cr.with_min_x(cr.min.x + 6.0), edit); + } else { + ui.scope_builder(egui::UiBuilder::new().max_rect(cr.shrink2(vec2(4.0, 1.0))), |ui| { + flat(ui); + egui::ComboBox::from_id_salt(("blookup-state", r, j)).width(cr.width() - 8.0).selected_text(cell.as_str()).show_ui( + ui, + |ui| { + for s in &c.states { + if ui.selectable_label(cell == s, s.as_str()).clicked() { + *cell = s.clone(); + } + } + }, + ); + }); + } + } + if r < n { + if let Some(old) = st.rows.get_mut(r) { + *old = row; + } + } else if row.iter().any(|c| !c.trim().is_empty()) { + st.rows.push(row); + } + } + + // What references show when no row matches: under the inputs, each lookup's + // value (editable) under the lookups; then whether each lookup can be set backwards. + if numbers { + let ur = egui::Rect::from_min_max(egui::pos2(rect.left() + num_w, row_y(n + 1)), egui::pos2(rect.right(), row_y(n + 2))); + let italic = egui::FontId::new(13.0, egui::FontFamily::Proportional); + p.text(ur.left_center() + vec2(8.0, 0.0), egui::Align2::LEFT_CENTER, "", italic, t.text_dim); + return; + } + let repeats: Vec = cols.clone().map(|j| st.repeats(j)).collect(); + for (k, j) in cols.clone().enumerate() { + let Some(c) = st.columns.get_mut(j) else { continue }; + let edit = egui::TextEdit::singleline(&mut c.unmatched) + .frame(egui::Frame::NONE) + .margin(vec2(8.0, 0.0)) + .align(egui::Align2::LEFT_CENTER) + .id_salt(("blookup-unmatched", j)); + let ur = cell_rect(k, n + 1); + ui.put(ur.with_min_x(ur.min.x + 6.0), edit); + let can = !repeats.get(k).copied().unwrap_or(true); + let shown = if c.reverse && can { crate::tl!("Allow reverse lookup") } else { crate::tl!("Read only") }; + let rr = cell_rect(k, n + 2); + ui.scope_builder(egui::UiBuilder::new().max_rect(rr.shrink2(vec2(4.0, 1.0))), |ui| { + flat(ui); + ui.add_enabled_ui(can, |ui| { + egui::ComboBox::from_id_salt(("blookup-reverse", j)).width(rr.width() - 8.0).selected_text(shown).show_ui(ui, |ui| { + if ui.selectable_label(c.reverse, crate::tl!("Allow reverse lookup")).clicked() { + c.reverse = true; + } + if ui.selectable_label(!c.reverse, crate::tl!("Read only")).clicked() { + c.reverse = false; + } + }); + }) + .response + .on_disabled_hover_text(crate::tl!("Read only while lookup values repeat")); + }); + } + }); +} + +/// A list inside a grid cell: no button background until hovered, so it reads as the cell. +fn flat(ui: &mut egui::Ui) { + let w = &mut ui.style_mut().visuals.widgets; + w.inactive.weak_bg_fill = egui::Color32::TRANSPARENT; + w.inactive.bg_stroke = Stroke::NONE; +} + +/// The properties the Add Parameter Properties dialog lists: (name, type shown, column). +fn addable(st: &State, m: &DynamicBlock, lookup: bool) -> Vec<(String, String, Column)> { + let has = |node: i32, property: &str| st.columns.iter().any(|c| c.parameter == node && c.property.eq_ignore_ascii_case(property)); + if lookup { + // Lookup parameters no table gives yet. + let taken = |node: i32| { + m.actions.iter().any(|a| matches!(&a.kind, ActionKind::Lookup { columns, .. } if columns.iter().any(|c| c.lookup && c.node == node))) + }; + return m + .parameters + .iter() + .filter_map(|p| match &p.kind { + ParameterKind::Lookup { label, .. } if !has(p.node, "lookupString") && !taken(p.node) => Some(( + label.clone(), + p.element.clone(), + Column { name: label.clone(), parameter: p.node, property: "lookupString".into(), lookup: true, ..Column::default() }, + )), + _ => None, + }) + .collect(); + } + input_properties(m) + .into_iter() + .filter(|(_, node, prop)| !has(*node, prop)) + .map(|(name, node, property)| { + let kind = match m.parameters.iter().find(|p| p.node == node).map(|p| &p.kind) { + Some(ParameterKind::Linear { .. }) => crate::i18n::t("Linear"), + Some(ParameterKind::Point { .. }) => crate::i18n::t("Point"), + _ => crate::i18n::t("Visibility State"), + }; + let states = states_of(m, node, &property); + (name.clone(), kind.to_string(), Column { name, parameter: node, property, states, ..Column::default() }) + }) + .collect() +} + +/// The Add Parameter Properties dialog: input or lookup properties to tick and add. +fn add_dialog(ctx: &egui::Context, st: &mut State, m: &DynamicBlock) { + let Some(mut adding) = st.adding.take() else { return }; + let (mut ok, mut cancel) = (false, false); + let mut open = true; + let list = addable(st, m, adding.lookup); + egui::Window::new(crate::tl!("Add Parameter Properties")) + .id(egui::Id::unique("Add Parameter Properties")) + .open(&mut open) + .collapsible(false) + .resizable(false) + .order(egui::Order::Foreground) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.set_min_width(340.0); + ui.label(crate::tl!("Parameter properties:")); + egui::Frame::new().stroke(Stroke::new(1.0, Tokens::get().border)).inner_margin(4.0).show(ui, |ui| { + ui.set_min_height(160.0); + egui::Grid::new("blookup-add").striped(true).show(ui, |ui| { + ui.label(RichText::new(crate::tl!("Name")).strong()); + ui.label(RichText::new(crate::tl!("Type")).strong()); + ui.end_row(); + for (name, kind, _) in &list { + let mut on = adding.ticked.contains(name); + if ui.checkbox(&mut on, name.as_str()).changed() { + if on { + adding.ticked.push(name.clone()); + } else { + adding.ticked.retain(|n| n != name); + } + } + ui.label(kind.as_str()); + ui.end_row(); + } + }); + }); + ui.group(|ui| { + ui.label(crate::tl!("Property type")); + let before = adding.lookup; + ui.radio_value(&mut adding.lookup, false, crate::tl!("Add input properties")); + ui.radio_value(&mut adding.lookup, true, crate::tl!("Add lookup properties")); + if adding.lookup != before { + adding.ticked.clear(); + } + }); + ui.separator(); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(crate::tl!("Cancel")).clicked() { + cancel = true; + } + if ui.button(crate::tl!("OK")).clicked() { + ok = true; + } + }); + }); + }); + if ok { + for (name, _, column) in list { + if adding.ticked.contains(&name) { + st.add_column(column); + } + } + return; + } + if cancel || !open { + return; + } + st.adding = Some(adding); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// An app in the Block Editor on block "B" (a rectangle and a circle) with Distance1, + /// Position1, Visibility1 (VisibilityState0, Small), lookup parameter Size and its action. + fn editing() -> CadApp { + let mut app = CadApp::new(cadcraft_engine::Session::empty(), crate::Services::default()); + let s = &mut app.session; + s.execute("new", &Value::Null).unwrap(); + let made = |v: Value| if v["handle"].is_null() { v["handles"][0].clone() } else { v["handle"].clone() }; + let r = made(s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 5] })).unwrap()); + let c = made(s.execute("circle", &json!({ "center": [10, 2.5], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [r, c], "keep": "delete" })).unwrap(); + s.execute("bedit", &json!({ "name": "B" })).unwrap(); + s.execute("bparameter", &json!({ "type": "linear", "start": [0, 0], "end": [10, 0] })).unwrap(); + s.execute("bparameter", &json!({ "type": "point", "at": [10, 2.5] })).unwrap(); + s.execute("bparameter", &json!({ "type": "visibility", "at": [-2, 5] })).unwrap(); + s.execute("bvstate", &json!({ "new": "Small", "visibility": "show" })).unwrap(); + s.execute("bparameter", &json!({ "type": "lookup", "at": [-2, 7], "label": "Size" })).unwrap(); + app + } + + #[test] + fn blookuptable_opens_the_dialog_and_ok_writes_the_table_in_one_step() { + let mut app = editing(); + assert!(route(&mut app, "blookuptable", &Value::Null).is_none(), "no lookup action: BLOOKUPTABLE says why"); + let act = app.session.execute("baction", &json!({ "parameter": "Size" })).unwrap()["node"].as_i64().unwrap() as i32; + assert!(!open(&mut app, 1), "a parameter isn't a lookup action"); + assert!(open(&mut app, act), "a double-click on the lookup action opens its table"); + app.ui.dialog = None; + assert!(route(&mut app, "blookuptable", &json!({})).is_none(), "JSON calls skip the dialog"); + assert!(route(&mut app, "blookuptable", &Value::Null).is_some()); + assert_eq!(app.ui.dialog.as_deref(), Some("blookuptable")); + let mut st = app.blookup.clone(); + assert_eq!(st.columns.iter().map(|c| c.name.as_str()).collect::>(), ["Size"]); + let st_m = dynamic_block(&app.session.state().unwrap().doc, "B").unwrap(); + let inputs = addable(&st, &st_m, false); + assert_eq!( + inputs.iter().map(|(n, k, _)| (n.as_str(), k.as_str())).collect::>(), + [("Distance1", "Linear"), ("Position1 X", "Point"), ("Position1 Y", "Point"), ("Visibility1", "Visibility State")] + ); + for (_, _, c) in inputs.into_iter().filter(|(n, ..)| n != "Position1 Y") { + st.add_column(c); + } + assert_eq!(st.columns.iter().map(|c| c.name.as_str()).collect::>(), ["Distance1", "Position1 X", "Visibility1", "Size"]); + assert_eq!(st.columns[2].states, ["VisibilityState0", "Small"]); + st.rows = vec![ + ["10", "10", "VisibilityState0", "Big"].map(String::from).to_vec(), + ["6", "6", "Small", "Small"].map(String::from).to_vec(), + ["", "", "", ""].map(String::from).to_vec(), + ]; + st.columns[3].reverse = true; + st.columns[3].unmatched = "Other".into(); + let block = "B"; + st.audit(&app.session.state().unwrap().doc, block).unwrap(); + let before = app.session.state().unwrap().undo.len(); + app.run("blookuptable", st.params()).unwrap(); + assert_eq!(app.session.state().unwrap().undo.len(), before + 1, "one undo step"); + let t = app.session.execute("blookuptable", &json!({})).unwrap(); + assert_eq!(t["rows"], json!([["10", "10", "VisibilityState0", "Big"], ["6", "6", "Small", "Small"]])); + assert_eq!((t["columns"][3]["unmatched"].clone(), t["columns"][3]["reverse"].clone()), (json!("Other"), json!(true))); + // Opened again, the dialog shows what was written. + route(&mut app, "blookuptable", &Value::Null).unwrap().unwrap(); + assert_eq!(app.blookup.rows.len(), 2); + assert!(app.blookup.columns[3].reverse); + } + + #[test] + fn switching_actions_keeps_each_tables_edits_and_ok_writes_them_all() { + let mut app = editing(); + let size = app.session.execute("baction", &json!({ "parameter": "Size" })).unwrap()["node"].as_i64().unwrap() as i32; + app.session.execute("bparameter", &json!({ "type": "lookup", "at": [-2, 9], "label": "Finish" })).unwrap(); + let finish = app.session.execute("baction", &json!({ "parameter": "Finish" })).unwrap()["node"].as_i64().unwrap() as i32; + assert!(open(&mut app, size)); + let m = dynamic_block(&app.session.state().unwrap().doc, "B").unwrap(); + // A row typed into Size's table, then Finish shown and edited too. + app.blookup.rows = vec![vec!["Big".into()]]; + app.blookup.switch_to(&m, finish); + assert!(app.blookup.rows.is_empty(), "Finish's own table"); + app.blookup.rows = vec![vec!["Matt".into()]]; + // Back to Size: its row is still there; and Finish's too, when it is shown again. + app.blookup.switch_to(&m, size); + assert_eq!(app.blookup.rows, [vec!["Big".to_string()]]); + app.blookup.switch_to(&m, finish); + assert_eq!(app.blookup.rows, [vec!["Matt".to_string()]]); + // OK writes both tables, as one step: one Undo restores both, Redo writes both again. + let rows = |app: &mut CadApp, action: i32| app.session.execute("blookuptable", &json!({ "action": action })).unwrap()["rows"].clone(); + let original = (rows(&mut app, size), rows(&mut app, finish)); + let undo_steps = app.session.state().unwrap().undo.len(); + let st = app.blookup.clone(); + write_tables(&mut app, &st, &m, "B").unwrap(); + assert_eq!(rows(&mut app, size), json!([["Big"]])); + assert_eq!(rows(&mut app, finish), json!([["Matt"]])); + assert_eq!(app.session.state().unwrap().undo.len(), undo_steps + 1, "one OK, one undo step"); + app.session.undo().unwrap(); + assert_eq!((rows(&mut app, size), rows(&mut app, finish)), original, "one Undo restores both tables"); + app.session.redo().unwrap(); + assert_eq!(rows(&mut app, size), json!([["Big"]])); + assert_eq!(rows(&mut app, finish), json!([["Matt"]])); + } + + #[test] + fn audit_and_reverse_lookup_follow_autocads_rules() { + let mut app = editing(); + app.session.execute("baction", &json!({ "parameter": "Size" })).unwrap(); + route(&mut app, "blookuptable", &Value::Null).unwrap().unwrap(); + let mut st = app.blookup.clone(); + let m = dynamic_block(&app.session.state().unwrap().doc, "B").unwrap(); + let d1 = addable(&st, &m, false).into_iter().next().unwrap().2; + st.add_column(d1); + st.rows = vec![vec!["10".into(), "Big".into()], vec!["10.0".into(), "Small".into()]]; + let doc = app.session.state().unwrap().doc.clone(); + assert_eq!(st.audit(&doc, "B").unwrap_err(), "Duplicate row of input values found."); + st.rows = vec![vec!["10".into(), "Big".into()], vec!["6".into(), "big".into()]]; + assert!(st.repeats(1), "repeated lookup values: read only"); + st.columns[1].reverse = true; + assert_eq!(st.params()["reverse"], json!([])); + // The action's own lookup column stays; an input can go, its cells with it. + assert!(!st.removable(1)); + st.remove_column(1); + assert_eq!(st.columns.len(), 2); + st.remove_column(0); + assert_eq!(st.columns.iter().map(|c| c.name.as_str()).collect::>(), ["Size"]); + assert_eq!(st.rows, [vec!["Big".to_string()], vec!["big".to_string()]]); + // Lookup parameters another table gives aren't offered as lookup columns. + app.session.execute("bparameter", &json!({ "type": "lookup", "at": [-2, 9] })).unwrap(); + let m = dynamic_block(&app.session.state().unwrap().doc, "B").unwrap(); + assert_eq!( + addable(&st, &m, true).iter().map(|(n, k, _)| (n.as_str(), k.as_str())).collect::>(), + [("Lookup1", "Lookup2")], + "label, then its name in the editor" + ); + } +} diff --git a/crates/ui-egui/src/bvstate.rs b/crates/ui-egui/src/bvstate.rs new file mode 100644 index 0000000000..05f80e42a6 --- /dev/null +++ b/crates/ui-egui/src/bvstate.rs @@ -0,0 +1,472 @@ +//! The Visibility States dialog: BVSTATE typed, or Visibility States on the Block Editor's bar, +//! while the Block Editor is open on a block with a visibility parameter. It lists the block's +//! states with the one the editor shows checked, and makes (New…), renames, deletes, reorders +//! (Move Up, Move Down) and picks (Set current) states, as AutoCAD's dialog does. Changes are +//! kept in the dialog until OK, which runs them as one BVSTATE step (`bvstate {ops}`); Cancel +//! changes nothing. JSON calls and -BVSTATE skip it. + +use cadcraft_engine::doc::dynblock::{ParameterKind, dynamic_block}; +use egui::{RichText, Stroke, vec2}; +use serde_json::{Value, json}; + +use crate::CadApp; +use crate::theme::Tokens; + +/// What a new state shows, as the New Visibility State dialog offers it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum NewShows { + Hide, + Show, + #[default] + Unchanged, +} + +impl NewShows { + fn param(self) -> &'static str { + match self { + NewShows::Hide => "hide", + NewShows::Show => "show", + NewShows::Unchanged => "current", + } + } +} + +/// The New Visibility State dialog's fields. +#[derive(Clone, Debug, Default)] +pub struct NewState { + pub name: String, + pub shows: NewShows, + pub error: Option, +} + +/// The dialog's state while it is open: the states as they will be after OK. +#[derive(Clone, Debug, Default)] +pub struct State { + /// The states, in order. + pub names: Vec, + /// The state the editor will show (checked). + pub current: String, + /// The row picked in the list. + pub selected: usize, + /// The changes made so far, as `bvstate` operations, run in turn on OK. + pub ops: Vec, + /// The row being renamed and the name typed. + pub renaming: Option<(usize, String)>, + /// The New Visibility State dialog, while open. + pub new: Option, + /// Why the last change or OK was refused. + pub error: Option, +} + +impl State { + fn has(&self, name: &str, except: Option) -> bool { + self.names.iter().enumerate().any(|(i, n)| Some(i) != except && n.eq_ignore_ascii_case(name.trim())) + } + + /// A name no state has: "VisibilityState" and the lowest free number. + fn free_name(&self) -> String { + (0..).map(|i| format!("VisibilityState{i}")).find(|n| !self.has(n, None)).unwrap_or_default() + } + + fn set_current(&mut self, i: usize) { + if let Some(n) = self.names.get(i).cloned() + && n != self.current + { + self.ops.push(json!({ "set": n })); + self.current = n; + } + } + + /// Add state `new` (it becomes the one shown, as AutoCAD makes it); `Err` with why not. + fn add(&mut self, new: &NewState) -> Result<(), String> { + let name = new.name.trim(); + if name.is_empty() { + return Err(crate::i18n::t("A visibility state needs a name.").to_string()); + } + if self.has(name, None) { + return Err(format!("{} \"{name}\"", crate::i18n::t("A visibility state already has the name"))); + } + self.ops.push(json!({ "new": name, "visibility": new.shows.param() })); + self.names.push(name.to_string()); + self.current = name.to_string(); + self.selected = self.names.len().saturating_sub(1); + Ok(()) + } + + /// Rename row `i` to `to`; `Err` with why not. + fn rename(&mut self, i: usize, to: &str) -> Result<(), String> { + let to = to.trim(); + let Some(old) = self.names.get(i).cloned() else { return Ok(()) }; + if to == old { + return Ok(()); + } + if to.is_empty() { + return Err(crate::i18n::t("A visibility state needs a name.").to_string()); + } + if self.has(to, Some(i)) { + return Err(format!("{} \"{to}\"", crate::i18n::t("A visibility state already has the name"))); + } + self.ops.push(json!({ "rename": old, "to": to })); + if self.current == old { + self.current = to.to_string(); + } + if let Some(n) = self.names.get_mut(i) { + *n = to.to_string(); + } + Ok(()) + } + + /// Whether row `i` can be deleted: not the state shown, and not the last one. + fn deletable(&self, i: usize) -> bool { + self.names.len() > 1 && self.names.get(i).is_some_and(|n| *n != self.current) + } + + fn delete(&mut self, i: usize) { + if !self.deletable(i) { + return; + } + let n = self.names.remove(i); + self.ops.push(json!({ "delete": n })); + self.selected = self.selected.min(self.names.len().saturating_sub(1)); + } + + /// Move row `i` one place up (`up`) or down. + fn shift(&mut self, i: usize, up: bool) { + let j = if up { i.checked_sub(1) } else { i.checked_add(1).filter(|j| *j < self.names.len()) }; + let Some(j) = j else { return }; + self.names.swap(i, j); + self.selected = j; + self.ops.push(json!({ "order": self.names })); + } +} + +/// The edited block's states and the one the editor shows, when the Block Editor is open on a +/// block with a visibility parameter. +fn current_states(app: &CadApp) -> Option<(Vec, String)> { + let st = app.session.state().ok()?; + let be = st.block_edit.as_ref()?; + let m = dynamic_block(&st.doc, &be.name)?; + let names: Vec = m.parameters.into_iter().find_map(|p| match p.kind { + ParameterKind::Visibility { states, .. } => Some(states.into_iter().map(|s| s.name).collect()), + _ => None, + })?; + let current = be.visibility_state(&st.doc).map(|(n, _)| n).or_else(|| names.first().cloned())?; + Some((names, current)) +} + +/// BVSTATE typed or from the Block Editor's bar without parameters opens the dialog when the +/// edited block has visibility states; otherwise BVSTATE runs and says why it can't. +pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option> { + if id != "bvstate" || !params.is_null() { + return None; + } + let (names, current) = current_states(app)?; + let selected = names.iter().position(|n| *n == current).unwrap_or(0); + app.bvstate = State { names, current, selected, ..State::default() }; + app.ui.dialog = Some("bvstate".into()); + Some(Ok(Value::Null)) +} + +/// The Visibility States window (and New Visibility State over it). +pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { + let t = Tokens::get(); + let (mut ok, mut cancel) = (false, false); + let mut st = std::mem::take(&mut app.bvstate); + let modal = st.new.is_some(); + egui::Window::new(crate::tl!("Visibility States")) + .id(egui::Id::unique("Visibility States")) + .open(open) + .collapsible(false) + .resizable(false) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.add_enabled_ui(!modal, |ui| { + ui.label(crate::tl!("Visibility states:")); + ui.horizontal_top(|ui| { + egui::Frame::new().fill(t.field).stroke(Stroke::new(1.0, t.border)).corner_radius(4.0).inner_margin(4.0).show(ui, |ui| { + ui.set_min_size(vec2(300.0, 230.0)); + egui::ScrollArea::vertical().id_salt("bvstate-list").max_height(230.0).min_scrolled_height(230.0).show(ui, |ui| { + ui.set_width(300.0); + list(ui, &mut st); + }); + }); + ui.vertical(|ui| { + let w = vec2(120.0, 0.0); + let i = st.selected; + let is_current = st.names.get(i).is_some_and(|n| *n == st.current); + if ui.add_enabled(!is_current, egui::Button::new(crate::tl!("Set current")).min_size(w)).clicked() { + st.set_current(i); + } + if ui.add(egui::Button::new(crate::tl!("New...")).min_size(w)).clicked() { + st.new = Some(NewState { name: st.free_name(), ..NewState::default() }); + } + if ui.add_enabled(st.renaming.is_none(), egui::Button::new(crate::tl!("Rename")).min_size(w)).clicked() { + st.renaming = st.names.get(i).map(|n| (i, n.clone())); + } + if ui.add_enabled(st.deletable(i), egui::Button::new(crate::tl!("Delete")).min_size(w)).clicked() { + st.delete(i); + } + ui.add_space(18.0); + if ui.add_enabled(i > 0, egui::Button::new(crate::tl!("Move Up")).min_size(w)).clicked() { + st.shift(i, true); + } + if ui.add_enabled(i + 1 < st.names.len(), egui::Button::new(crate::tl!("Move Down")).min_size(w)).clicked() { + st.shift(i, false); + } + }); + }); + if let Some(e) = &st.error { + ui.colored_label(t.warn, e); + } + ui.separator(); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(crate::tl!("Cancel")).clicked() { + cancel = true; + } + if ui.button(crate::tl!("OK")).clicked() { + ok = true; + } + }); + }); + }); + }); + if st.new.is_some() { + new_dialog(ctx, &mut st); + } + if ok { + // A rename still being typed counts. + if let Some((i, to)) = st.renaming.take() + && let Err(e) = st.rename(i, &to) + { + st.error = Some(e); + app.bvstate = st; + return; + } + if !st.ops.is_empty() + && let Err(e) = app.run("bvstate", json!({ "ops": st.ops })) + { + st.error = Some(e); + app.bvstate = st; + return; + } + *open = false; + } + if cancel { + *open = false; + } + app.bvstate = st; +} + +/// The states, the one shown checked; the row being renamed is a text box. +fn list(ui: &mut egui::Ui, st: &mut State) { + let t = Tokens::get(); + ui.with_layout(egui::Layout::top_down_justified(egui::Align::Min), |ui| { + for i in 0..st.names.len() { + let name = st.names.get(i).cloned().unwrap_or_default(); + if let Some((r, typed)) = &mut st.renaming + && *r == i + { + let edit = ui.add(egui::TextEdit::singleline(typed).desired_width(280.0)); + edit.request_focus(); + if ui.input(|k| k.key_pressed(egui::Key::Escape)) { + st.renaming = None; + } else if edit.lost_focus() { + let to = typed.clone(); + st.renaming = None; + st.error = st.rename(i, &to).err(); + } + continue; + } + let check = if name == st.current { "✔ " } else { " " }; + let row = ui.selectable_label(st.selected == i, RichText::new(format!("{check}{name}")).color(t.text)); + if row.clicked() { + st.selected = i; + st.error = None; + } + // Double-click shows that state, as Set current does. + if row.double_clicked() { + st.set_current(i); + } + } + }); +} + +/// The New Visibility State dialog: a name and what the new state shows. +fn new_dialog(ctx: &egui::Context, st: &mut State) { + let Some(mut new) = st.new.take() else { return }; + let t = Tokens::get(); + let (mut ok, mut cancel) = (false, false); + let mut open = true; + egui::Window::new(crate::tl!("New Visibility State")) + .id(egui::Id::unique("New Visibility State")) + .open(&mut open) + .collapsible(false) + .resizable(false) + .order(egui::Order::Foreground) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.set_min_width(460.0); + ui.label(crate::tl!("Visibility state name:")); + let edit = ui.add(egui::TextEdit::singleline(&mut new.name).desired_width(460.0)); + if edit.changed() { + new.error = None; + } + if edit.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + ok = true; + } + ui.add_space(6.0); + ui.group(|ui| { + ui.label(crate::tl!("Visibility options for new states")); + ui.radio_value(&mut new.shows, NewShows::Hide, crate::tl!("Hide all existing objects in new state")); + ui.radio_value(&mut new.shows, NewShows::Show, crate::tl!("Show all existing objects in new state")); + ui.radio_value(&mut new.shows, NewShows::Unchanged, crate::tl!("Leave visibility of existing objects unchanged in new state")); + }); + if let Some(e) = &new.error { + ui.colored_label(t.warn, e); + } + ui.separator(); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(crate::tl!("Cancel")).clicked() { + cancel = true; + } + if ui.button(crate::tl!("OK")).clicked() { + ok = true; + } + }); + }); + }); + if ok { + match st.add(&new) { + Ok(()) => return, + Err(e) => new.error = Some(e), + } + } + if cancel || !open { + return; + } + st.new = Some(new); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn state() -> State { + State { names: vec!["A".into(), "B".into(), "C".into()], current: "A".into(), ..State::default() } + } + + #[test] + fn changes_become_bvstate_operations_in_order() { + let mut st = state(); + st.add(&NewState { name: "D".into(), shows: NewShows::Hide, error: None }).unwrap(); + assert_eq!((st.current.as_str(), st.selected), ("D", 3), "a new state is the one shown"); + st.rename(1, "Bee").unwrap(); + st.shift(1, true); + st.delete(2); + st.set_current(0); + assert_eq!(st.names, ["Bee", "A", "D"]); + assert_eq!(st.current, "Bee"); + assert_eq!( + st.ops, + vec![ + json!({ "new": "D", "visibility": "hide" }), + json!({ "rename": "B", "to": "Bee" }), + json!({ "order": ["Bee", "A", "C", "D"] }), + json!({ "delete": "C" }), + json!({ "set": "Bee" }), + ] + ); + } + + /// An app in the Block Editor on block "B" (a rectangle and a circle); with `visibility`, the + /// block has a visibility parameter. Returns (app, rectangle, circle). + fn editing(visibility: bool) -> (CadApp, String, String) { + let mut app = CadApp::new(cadcraft_engine::Session::empty(), crate::Services::default()); + let s = &mut app.session; + s.execute("new", &Value::Null).unwrap(); + let made = |v: Value| if v["handle"].is_null() { v["handles"][0].clone() } else { v["handle"].clone() }; + let r = made(s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 5] })).unwrap()); + let c = made(s.execute("circle", &json!({ "center": [5, 2.5], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [r, c], "keep": "delete" })).unwrap(); + s.execute("bedit", &json!({ "name": "B" })).unwrap(); + if visibility { + s.execute("bparameter", &json!({ "type": "visibility", "at": [0, 6] })).unwrap(); + } + // The editor's objects (the block's, with the block's handles). + let d = app.session.doc().unwrap(); + let of = + |rect: bool| d.model.iter().find(|e| matches!(e.kind, cadcraft_engine::doc::EntityKind::LwPolyline(_)) == rect).unwrap().handle.hex(); + let (r, c) = (of(true), of(false)); + (app, r, c) + } + + /// Object Visibility ▸ in the right-click menu's entries, if there. + fn object_visibility(app: &CadApp) -> Option { + crate::context_menu::entries(app) + .into_iter() + .flatten() + .find(|e| matches!(e, crate::menus::Entry::Sub { label, .. } if label == "Object Visibility")) + } + + #[test] + fn the_shortcut_menu_hides_and_shows_selected_objects() { + let (mut app, _, c) = editing(false); + let h = cadcraft_engine::cmd::curves::handle_value(&json!(c)).unwrap(); + assert!(object_visibility(&app).is_none(), "only with a selection"); + app.session.set_selection(vec![h]); + assert!(!object_visibility(&app).unwrap().enabled(), "greyed out without a visibility parameter"); + app.session.execute("bparameter", &json!({ "type": "visibility", "at": [0, 6] })).unwrap(); + app.session.set_selection(vec![h]); + assert!(object_visibility(&app).unwrap().enabled()); + crate::context_menu::choose(&mut app, "visibility:hide"); + assert!(app.session.doc().unwrap().hidden_objects.contains(&h)); + app.session.execute("setvar", &json!({ "name": "BVMODE", "value": 1 })).unwrap(); + app.session.set_selection(vec![h]); + crate::context_menu::choose(&mut app, "visibility:show-all"); + app.session.execute("setvar", &json!({ "name": "BVMODE", "value": 0 })).unwrap(); + assert!(app.session.doc().unwrap().hidden_objects.is_empty()); + } + + #[test] + fn bvstate_opens_the_dialog_and_ok_applies_its_changes_as_one_step() { + let (mut app, _, _) = editing(false); + assert!(route(&mut app, "bvstate", &Value::Null).is_none(), "no visibility parameter: BVSTATE says why"); + let (mut app, _, _) = editing(true); + assert!(route(&mut app, "bvstate", &json!({ "set": "X" })).is_none(), "JSON calls skip the dialog"); + assert!(route(&mut app, "bvstate", &Value::Null).is_some()); + assert_eq!(app.ui.dialog.as_deref(), Some("bvstate")); + assert_eq!((app.bvstate.names.clone(), app.bvstate.current.clone()), (vec!["VisibilityState0".to_string()], "VisibilityState0".to_string())); + let mut st = app.bvstate.clone(); + st.add(&NewState { name: "Empty".into(), shows: NewShows::Hide, error: None }).unwrap(); + st.rename(0, "Full").unwrap(); + let before = app.session.state().unwrap().undo.len(); + app.run("bvstate", json!({ "ops": st.ops })).unwrap(); + assert_eq!(app.session.state().unwrap().undo.len(), before + 1, "one undo step"); + let out = app.session.execute("bvstate", &json!({})).unwrap(); + assert_eq!(out, json!({ "current": "Empty", "states": ["Full", "Empty"] })); + // A refused operation undoes the ones before it. + let bad = json!({ "ops": [{ "new": "Third" }, { "delete": "Nope" }] }); + assert!(app.run("bvstate", bad).is_err()); + assert_eq!(app.session.execute("bvstate", &json!({})).unwrap()["states"], json!(["Full", "Empty"])); + } + + #[test] + fn refused_changes_say_why_and_change_nothing() { + let mut st = state(); + assert!(st.add(&NewState { name: "b".into(), ..NewState::default() }).is_err(), "names are case-insensitive"); + assert!(st.add(&NewState { name: " ".into(), ..NewState::default() }).is_err()); + assert!(st.rename(0, "c").is_err()); + assert!(!st.deletable(0), "the state shown can't be deleted"); + st.delete(0); + st.shift(0, true); + st.shift(2, false); + st.rename(9, "X").unwrap(); + assert_eq!(st.names, ["A", "B", "C"]); + assert!(st.ops.is_empty()); + assert_eq!(st.free_name(), "VisibilityState0"); + } +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 0a654d64be..151bad85fb 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -660,6 +660,7 @@ fn paint_pointer_overlay(frame: &mut CanvasPaint<'_>, paper_rect: Option, // spin the CPU with the low-latency present mode (`gpu::surface_config`). } struct DoubleClickContext<'a> { + ctx: &'a egui::Context, inside: bool, double: bool, hover: Option, @@ -670,8 +671,8 @@ struct DoubleClickContext<'a> { active_clip: &'a Option, } -fn handle_double_click(app: &mut CadApp, ctx: DoubleClickContext<'_>) -> Option { - let DoubleClickContext { inside, double, hover, xf, xf_paper, scale, active_viewport, active_clip } = ctx; +fn handle_double_click(app: &mut CadApp, context: DoubleClickContext<'_>) -> Option { + let DoubleClickContext { ctx, inside, double, hover, xf, xf_paper, scale, active_viewport, active_clip } = context; if inside && double && !app.session.prompting() @@ -704,10 +705,12 @@ fn handle_double_click(app: &mut CadApp, ctx: DoubleClickContext<'_>) -> Option< return None; } - let mut hatch_dialog = false; // Double-click a hatch (no command running) to edit it in the Hatch Edit dialog. The click is - // used up: it must not also start a grip edit on the hatch's centre grip below. - if inside + // used up: it must not also start a grip edit on the hatch's centre grip below. In the Block + // Editor, double-clicking a lookup action opens its lookup table, as in AutoCAD. + let mut hatch_dialog = inside && double && blockedit::double_click(app, ctx, &xf, hover); + if !hatch_dialog + && inside && double && app.session.running.is_none() && let Some(hp) = hover @@ -821,11 +824,11 @@ fn handle_presses(app: &mut CadApp, ui: &egui::Ui, context: &PressContext) -> bo } // Selection cycling: the press picks a row of the open list, or opens the list over // overlapping objects (#1149). Its release must not count again. - if cycle_click(app, &xf, Some(pos), Some(xf.to_world(pos)), m.shift) { + if cycle_click(app, ui.ctx(), &xf, Some(pos), Some(xf.to_world(pos)), m.shift) { app.canvas.press = Some(press::Press::new(pos, false)); continue; } - if press_takes(app, &xf, pos) { + if press_takes(app, &xf, ui.ctx(), pos) { let opened = press_at(app, &xf, ui.ctx(), pos, m); app.canvas.press = Some(press::Press::new(pos, opened)); } else if !app.session.realtime_zoom_active() && !app.session.realtime_pan_active() { @@ -845,7 +848,10 @@ fn handle_presses(app: &mut CadApp, ui: &egui::Ui, context: &PressContext) -> bo click_used = true; if p.is_on_grip() { if grip_clicks && let Some((at, m)) = p.grip_click(pos) { - if let Some(g) = crate::dyngrips::at(app, &xf, Some(at)) { + if let Some(t) = blockedit::target(app, ui.ctx(), &xf, Some(at)) { + // The Block Editor's parameters and actions, and their grips, before objects. + blockedit::click(app, t, m.shift); + } else if let Some(g) = crate::dyngrips::at(app, &xf, Some(at)) { crate::dyngrips::click(app, g); } else if let Some(g) = grip_at(app, &xf, Some(at)) { click_grip(app, g, m.shift); @@ -976,6 +982,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { let Some(hatch_dialog) = handle_double_click( app, DoubleClickContext { + ctx: ui.ctx(), inside, double: dbl_primary, hover: hover_pos, @@ -1028,7 +1035,8 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { app.canvas.press = None; } let pressed_primary = pressed_primary && !picked && !hatch_dialog && !idle_dbl; - let cycled = pressed_primary && !click_used && !middle_down && cycle_click(app, &xf, hover_pos, raw_world.filter(|_| inside), mods.shift); + let cycled = + pressed_primary && !click_used && !middle_down && cycle_click(app, ui.ctx(), &xf, hover_pos, raw_world.filter(|_| inside), mods.shift); // Clicks the presses above left alone: on grips, and during ZOOM Realtime. if inside && pressed_primary @@ -1056,6 +1064,9 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { if let Err(e) = result { app.session.echo(e.to_string()); } + } else if let Some(t) = blockedit::target(app, ui.ctx(), &xf, hover_pos) { + // The Block Editor's parameters and actions, and their grips, before objects. + blockedit::click(app, t, mods.shift); } else if let Some(g) = crate::dyngrips::at(app, &xf, hover_pos) { crate::dyngrips::click(app, g); } else if let Some(g) = grip_at(app, &xf, hover_pos) { @@ -1161,16 +1172,16 @@ fn track_cursor(app: &mut CadApp, raw: Option, xf: &Xf, ctx: &egui::Contex } /// Whether the press at `pos` is acted on when the button goes down ([`press_at`]): at any prompt -/// and on the drawing with no command running. Grips (with no command running), ZOOM Realtime and -/// PAN keep their clicks. -fn press_takes(app: &mut CadApp, xf: &Xf, pos: Pos2) -> bool { +/// and on the drawing with no command running. Grips and the Block Editor's parameters and actions +/// (with no command running), ZOOM Realtime and PAN keep their clicks. +fn press_takes(app: &mut CadApp, xf: &Xf, ctx: &egui::Context, pos: Pos2) -> bool { if app.session.realtime_zoom_active() || app.session.realtime_pan_active() { return false; } if app.session.prompting() { return true; } - crate::dyngrips::at(app, xf, Some(pos)).is_none() && grip_at(app, xf, Some(pos)).is_none() + crate::dyngrips::at(app, xf, Some(pos)).is_none() && grip_at(app, xf, Some(pos)).is_none() && blockedit::target(app, ctx, xf, Some(pos)).is_none() } /// Act on a press at `pos`: at a prompt the point goes in (snapped as the cursor would be there); diff --git a/crates/ui-egui/src/canvas/blockedit.rs b/crates/ui-egui/src/canvas/blockedit.rs index e8d981b749..395923c9dd 100644 --- a/crates/ui-egui/src/canvas/blockedit.rs +++ b/crates/ui-egui/src/canvas/blockedit.rs @@ -1,10 +1,24 @@ //! 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. A block with visibility +//! states gets Visibility Mode (BVMODE), the state shown (picked from a list, as AutoCAD's +//! Visibility panel offers it), Visibility States, Make Visible and Make Invisible; with BVMODE 1 +//! the objects the state hides are drawn dimmed. +//! +//! Parameters and actions are picked with a click ([`target`], [`click`]; Shift+click unpicks), +//! as in AutoCAD's editor: picked ones are drawn heavier with grips at their points, and clicking +//! a grip moves that point. MOVE, ERASE and Delete act on them (the engine's +//! `blocks.element.*`). +use std::sync::Arc; + +use cadcraft_engine::doc::Handle; +use cadcraft_engine::doc::dynblock::{ElementPoint, Mark, ParameterKind, dynamic_block}; use cadcraft_engine::geom::Vec2; -use egui::{Rect, RichText, Stroke, vec2}; -use serde_json::json; +use cadcraft_render::DisplayList; +use egui::{Align2, Color32, FontId, Painter, Pos2, Rect, RichText, Shape, Stroke, vec2}; +use serde_json::{Value, json}; use super::Xf; use crate::CadApp; @@ -20,6 +34,59 @@ fn editing(app: &CadApp) -> Option<(String, bool)> { st.block_editor().map(|n| (n.to_string(), st.block_unsaved())) } +/// The edited block's visibility states: their names, the one shown, and what it hides. +#[derive(Clone, Default)] +struct States { + names: Vec, + current: String, + hidden: Vec, +} + +/// [`States`] when the block has a visibility parameter, worked out once per drawing revision +/// and state shown. +fn states(app: &CadApp, ctx: &egui::Context) -> Option> { + type Cache = Option<((u64, u64, Option), Option>)>; + let st = app.session.state().ok()?; + let be = st.block_edit.as_ref()?; + let key = (st.uid, st.revision, be.visibility.clone()); + let cid = egui::Id::unique("cadcraft-block-editor-states"); + if let Some((k, v)) = ctx.data(|d| d.get_temp::(cid)).flatten() + && k == key + { + return v; + } + let names: Option> = dynamic_block(&st.doc, &be.name).and_then(|m| { + m.parameters.into_iter().find_map(|p| match p.kind { + ParameterKind::Visibility { states, .. } => Some(states.into_iter().map(|s| s.name).collect()), + _ => None, + }) + }); + let v = names.zip(be.visibility_state(&st.doc)).map(|(names, (current, hidden))| Arc::new(States { names, current, hidden })); + ctx.data_mut(|d| d.insert_temp::(cid, Some((key, v.clone())))); + v +} + +/// The objects the visibility state hides, dimmed (BVMODE 1 leaves them on the canvas to pick). +fn paint_dimmed(app: &CadApp, ctx: &egui::Context, p: &Painter, xf: &Xf, hidden: &[Handle]) { + type Cache = Option<((u64, u64, usize, i64), Arc)>; + let Ok(st) = app.session.state() else { return }; + let band = xf.scale.max(1e-300).log2().round() as i64; + let key = (st.uid, st.revision, hidden.len(), band); + let cid = egui::Id::unique("cadcraft-block-editor-dimmed"); + let list = match ctx.data(|d| d.get_temp::(cid)).flatten() { + Some((k, l)) if k == key => l, + _ => { + let opts = cadcraft_render::Options { tolerance: 0.5 / xf.scale.max(1e-12), ..Default::default() }; + let l = Arc::new(cadcraft_render::build_entities(&st.doc, hidden.iter().filter_map(|h| st.doc.entity(*h)).map(|e| e.as_ref()), &opts)); + ctx.data_mut(|d| d.insert_temp::(cid, Some((key, l.clone())))); + l + } + }; + // The canvas colour drawn over them, a little wider, fades them toward the background. + let all: Vec = (0..list.prims.len()).collect(); + super::draw_highlight(p, xf, &list, &all, Tokens::get().canvas.gamma_multiply(0.7), super::Look { width: 2.0, dashed: false }); +} + /// Tint the drawing area while the Block Editor is open (under the drawing). pub(super) fn wash(app: &CadApp, p: &egui::Painter, rect: Rect) { if editing(app).is_some() { @@ -39,7 +106,19 @@ 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); + paint_grips(app, p, xf); + let vis = states(app, ctx); + if app.session.settings.bvmode + && let Some(v) = &vis + && !v.hidden.is_empty() + { + paint_dimmed(app, ctx, p, xf, &v.hidden); + } let mut action: Option<(&str, bool)> = None; + let mut pick: Option = None; + let bvmode = app.session.settings.bvmode; + let mut toggle_mode = false; egui::Area::new(id()).order(egui::Order::Foreground).pivot(egui::Align2::CENTER_TOP).fixed_pos(rect.center_top() + vec2(0.0, 8.0)).show( ctx, |ui| { @@ -62,10 +141,43 @@ pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, p: &egui::Painter, xf if ui.button(crate::tl!("Close Block Editor")).clicked() { action = Some(("bclose", true)); } + if let Some(v) = &vis { + ui.separator(); + // BVMODE: whether objects the state hides show dimmed (on) or not at all. + if ui + .selectable_label(bvmode, crate::tl!("Visibility Mode")) + .on_hover_text(crate::tl!("Show the objects this visibility state hides, dimmed (BVMODE)")) + .clicked() + { + toggle_mode = true; + } + egui::ComboBox::from_id_salt("cadcraft-block-editor-state").selected_text(v.current.as_str()).show_ui(ui, |ui| { + for n in &v.names { + if ui.selectable_label(*n == v.current, n.as_str()).clicked() && *n != v.current { + pick = Some(n.clone()); + } + } + }); + if ui.button(crate::tl!("Visibility States")).clicked() { + action = Some(("bvstate", true)); + } + if ui.button(crate::tl!("Make Visible")).clicked() { + action = Some(("bvshow", true)); + } + if ui.button(crate::tl!("Make Invisible")).clicked() { + action = Some(("bvhide", true)); + } + } }); }); }, ); + if toggle_mode { + let _ = app.run("setvar", json!({ "name": "BVMODE", "value": i32::from(!bvmode) })); + } + if let Some(n) = pick { + let _ = app.run("bvstate", json!({ "set": n })); + } match action { // Prompting commands start like a menu item; BSAVE needs no answer. Some((id, true)) => app.start(id), @@ -75,3 +187,216 @@ pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, p: &egui::Painter, xf None => {} } } + +/// The edited block's parameters and actions and, with BVMODE 1, the graph ids of the parameters +/// the visibility state shown leaves out (drawn dimmed; without BVMODE they aren't drawn), worked +/// out once per drawing revision, visibility state shown and BVMODE. +fn marks(app: &CadApp, ctx: &egui::Context) -> Arc<(Vec, Vec)> { + type Cache = Option<((u64, u64, Option, bool), Arc<(Vec, Vec)>)>; + let Ok(st) = app.session.state() else { return Arc::default() }; + let Some(be) = &st.block_edit else { return Arc::default() }; + let bvmode = app.session.settings.bvmode; + let key = (st.uid, st.revision, be.visibility.clone(), bvmode); + let cid = egui::Id::unique("cadcraft-block-editor-marks"); + if let Some((k, m)) = ctx.data(|d| d.get_temp::(cid)).flatten() + && k == key + { + return m; + } + let m = Arc::new(if bvmode { (be.all_marks(&st.doc), be.inactive_parameters(&st.doc)) } else { (be.marks(&st.doc), Vec::new()) }); + ctx.data_mut(|d| d.insert_temp::(cid, Some((key, m.clone())))); + m +} + +/// What a click in the Block Editor hits first: a picked parameter's or action's grip, or a +/// parameter or action. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Target { + Grip(i32, ElementPoint), + Mark(i32), +} + +/// How far from the cursor (screen points) a mark or grip still counts as hit. +const REACH: f32 = 6.0; + +fn segment_distance(a: Pos2, b: Pos2, p: Pos2) -> f32 { + let d = b - a; + let t = if d.length_sq() <= 1e-6 { 0.0 } else { ((p - a).dot(d) / d.length_sq()).clamp(0.0, 1.0) }; + (a + d * t).distance(p) +} + +/// About where a label of `text` drawn at `at` with `align` lies (12-point text). +fn label_rect(at: Pos2, align: Align2, text: &str) -> Rect { + let size = vec2(7.0 * text.chars().count() as f32, 14.0); + align.anchor_size(at, size) +} + +/// The graph id a mark stands for (a parameter's or an action's). +fn mark_node(m: &Mark) -> i32 { + match m { + Mark::Action { node, .. } => *node, + other => other.parameter_node().unwrap_or(0), + } +} + +/// The grip or mark under `pos`, when the Block Editor is open with no command running. +pub(super) fn target(app: &CadApp, ctx: &egui::Context, xf: &Xf, pos: Option) -> Option { + let pos = pos?; + if app.session.prompting() || editing(app).is_none() { + return None; + } + if let Some((n, w, _)) = app.session.element_grips().into_iter().find(|(_, _, at)| xf.to_screen(*at).distance(pos) <= REACH) { + return Some(Target::Grip(n, w)); + } + mark_at(app, ctx, xf, pos).map(Target::Mark) +} + +/// The graph id of the parameter or action whose mark is under `pos` (grips aside). +fn mark_at(app: &CadApp, ctx: &egui::Context, xf: &Xf, pos: Pos2) -> Option { + let to = |v: cadcraft_engine::geom::Vec3| xf.to_screen(v.xy()); + let marks = marks(app, ctx); + marks + .0 + .iter() + .find(|m| match m { + Mark::Linear { base, end, offset, label, .. } => { + let (a, b) = (base.xy(), end.xy()); + let dir = (b - a).normalized(); + let shift = Vec2::new(-dir.y, dir.x) * *offset; + let (da, db) = (xf.to_screen(a + shift), xf.to_screen(b + shift)); + let (sa, sb) = (to(*base), to(*end)); + [(sa, da), (sb, db), (da, db)].iter().any(|(p, q)| segment_distance(*p, *q, pos) <= REACH) + || label_rect(da + (db - da) * 0.5, Align2::CENTER_BOTTOM, label).contains(pos) + } + Mark::Point { at, label_at, label, .. } => { + let (s, l) = (to(*at), to(*label_at)); + s.distance(pos) <= REACH || segment_distance(s, l, pos) <= REACH || label_rect(l, Align2::LEFT_BOTTOM, label).contains(pos) + } + Mark::List { at, label, .. } => { + let s = to(*at); + s.distance(pos) <= REACH + 2.0 || label_rect(s + vec2(8.0, 0.0), Align2::LEFT_CENTER, label).contains(pos) + } + Mark::Parameter { at, label, .. } => label_rect(to(*at), Align2::LEFT_BOTTOM, label).contains(pos), + Mark::Action { at, name, .. } => label_rect(to(*at), Align2::CENTER_CENTER, name).expand2(vec2(4.0, 2.0)).contains(pos), + }) + .map(mark_node) +} + +/// A double-click on a lookup action's mark opens its Property Lookup Table; whether it did. +/// The first click picked it, so its grip may be under the cursor too: the mark wins. +pub(super) fn double_click(app: &mut CadApp, ctx: &egui::Context, xf: &Xf, pos: Option) -> bool { + let Some(pos) = pos else { return false }; + if app.session.prompting() || editing(app).is_none() { + return false; + } + mark_at(app, ctx, xf, pos).is_some_and(|n| crate::blookup::open(app, n)) +} + +/// A click on `t`: a grip starts moving its point; a parameter or action is picked (Shift+click +/// unpicks it). +pub(super) fn click(app: &mut CadApp, t: Target, shift: bool) { + let r = match t { + Target::Grip(n, w) => app.session.start_element_grip(n, w).map(|_| Value::Null).map_err(|e| e.to_string()), + Target::Mark(n) => { + let picked = app.session.picked_elements(); + if shift && picked.contains(&n) { + let rest: Vec = picked.into_iter().filter(|p| *p != n).collect(); + app.run("blocks.element.select", json!({ "nodes": rest })) + } else { + app.run("blocks.element.select", json!({ "nodes": [n], "add": true })) + } + } + }; + if let Err(e) = r { + app.session.echo(e); + } +} + +/// The picked parameters' and actions' grips: squares at their points, as entity grips. +fn paint_grips(app: &CadApp, p: &Painter, xf: &Xf) { + let t = Tokens::get(); + for (_, _, at) in app.session.element_grips() { + let r = Rect::from_center_size(xf.to_screen(at), vec2(9.0, 9.0)); + p.rect_filled(r, 0.0, t.grip); + p.rect_stroke(r, 0.0, Stroke::new(1.0, t.canvas), egui::StrokeKind::Middle); + } +} + +/// A filled arrow at `at` pointing along screen direction `u`, as a linear parameter's grip. +fn arrow(p: &Painter, at: Pos2, u: egui::Vec2, color: Color32) { + let n = vec2(-u.y, u.x); + 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 font = FontId::proportional(12.0); + let to = |v: cadcraft_engine::geom::Vec3| xf.to_screen(v.xy()); + let marks = marks(app, ctx); + let (all, inactive) = &*marks; + let picked = app.session.picked_elements(); + for m in all { + // A parameter the visibility state leaves out shows dimmed (BVMODE 1). + let dim = m.parameter_node().is_some_and(|n| inactive.contains(&n)); + let fade = |c: Color32| if dim { c.gamma_multiply(0.35) } else { c }; + let (accent, grip_dyn) = (fade(t.accent), fade(t.grip_dyn)); + // Picked ones are drawn heavier. + let width = if picked.contains(&mark_node(m)) { 2.5 } else { 1.0 }; + let line = Stroke::new(width, accent); + match m { + Mark::Linear { base, end, offset, label, base_grip, end_grip, .. } => { + let (a, b) = (base.xy(), end.xy()); + 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, grip_dyn); + } + if *end_grip { + arrow(p, sb, u, grip_dyn); + } + p.text(da + (db - da) * 0.5, Align2::CENTER_BOTTOM, label, font.clone(), accent); + } + Mark::Point { at, label_at, label, grip, .. } => { + let (s, l) = (to(*at), to(*label_at)); + p.line_segment([s, l], line); + if *grip { + p.rect_filled(Rect::from_center_size(s, vec2(8.0, 8.0)), 0.0, 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(), accent); + } + Mark::List { at, label, grip, .. } => { + // A list grip: a triangle pointing down, the label to its right. + let s = to(*at); + if *grip { + let pts = vec![s + vec2(-6.0, -5.0), s + vec2(6.0, -5.0), s + vec2(0.0, 6.0)]; + p.add(Shape::convex_polygon(pts, grip_dyn, Stroke::new(1.0, fade(t.canvas)))); + } + p.text(s + vec2(8.0, 0.0), Align2::LEFT_CENTER, label, font.clone(), accent); + } + Mark::Parameter { at, label, .. } => { + p.text(to(*at), Align2::LEFT_BOTTOM, label, font.clone(), accent); + } + 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(width, t.warn), egui::StrokeKind::Middle); + p.galley(r.min + vec2(4.0, 2.0), g, t.text); + } + } + } +} diff --git a/crates/ui-egui/src/canvas/cycle.rs b/crates/ui-egui/src/canvas/cycle.rs index e7dae44bc7..d5b1872cb4 100644 --- a/crates/ui-egui/src/canvas/cycle.rs +++ b/crates/ui-egui/src/canvas/cycle.rs @@ -20,7 +20,7 @@ impl CycleList { /// A click while selection cycling's list is open picks the row under it (anywhere else just /// closes the list); otherwise a click over overlapping objects that a pick would choose between /// opens the list (SELECTIONCYCLING 2). True when the click was used up here. -pub(super) fn cycle_click(app: &mut CadApp, xf: &Xf, hover: Option, world: Option, shift: bool) -> bool { +pub(super) fn cycle_click(app: &mut CadApp, ctx: &egui::Context, xf: &Xf, hover: Option, world: Option, shift: bool) -> bool { // Only where a click picks objects; a click that places a point goes through. let picks = app.session.click_picks(); if let Some((_, hs, i)) = app.canvas.hover_cycle.take() @@ -40,7 +40,8 @@ pub(super) fn cycle_click(app: &mut CadApp, xf: &Xf, hover: Option, world: return true; } let (Some(hp), Some(w)) = (hover, world) else { return false }; - if crate::dyngrips::at(app, xf, hover).is_some() || grip_at(app, xf, hover).is_some() { + // Grips, and the Block Editor's parameters, actions and their grips, take the click first. + if crate::dyngrips::at(app, xf, hover).is_some() || grip_at(app, xf, hover).is_some() || super::blockedit::target(app, ctx, xf, hover).is_some() { return false; } let hs = app.session.cycling_candidates(w); diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index d0a09d3ee1..01707b7ff1 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -2,7 +2,9 @@ //! //! - **No command running** ([`entries`], opened by holding the button: a quick right-click is //! Enter, which repeats the last command): Repeat the last command, Recent Commands, the -//! Clipboard and Isolate; with a selection the editing commands, Draw Order, Group, the edit +//! Clipboard and Isolate; in the Block Editor with a selection, Object Visibility (hide or show +//! the objects in the current or every visibility state; greyed out without a visibility +//! parameter); with a selection the editing commands, Draw Order, Group, the edit //! commands of the selected object type, Select Similar and Deselect All; then Undo/Redo, //! Pan/Zoom, Quick Select, Find, Properties and Options. //! - **While a command runs** ([`command_entries`]): a quick right-click is Enter; holding the @@ -60,6 +62,8 @@ pub const TYPE: &str = "type:"; pub const KEYWORD: &str = "keyword:"; /// An object snap menu item ([`choose_snap`]). pub const SNAP: &str = "snap:"; +/// An Object Visibility item: BVHIDE or BVSHOW on the selection ([`choose_visibility`]). +pub const VISIBILITY: &str = "visibility:"; /// Dimension Style ▸ item: the selected dimensions take the style that follows. pub const DIM_STYLE: &str = "dimstyle:"; /// Precision ▸ item: the selected dimensions show this many decimal places (an override). @@ -113,6 +117,10 @@ pub fn entries(app: &CadApp) -> Vec> { .collect(); first.extend(sub("Recent Commands", recent)); push(&mut groups, first); + let selected = !app.session.selection().is_empty(); + if selected { + push(&mut groups, visibility_entries(app).into_iter().collect()); + } // In the Block Editor: save the block or go back to the drawing. if app.session.state().is_ok_and(|st| st.block_edit.is_some()) { push(&mut groups, items(app, &["bsave", "bsaveas", "bclose"])); @@ -120,7 +128,10 @@ pub fn entries(app: &CadApp) -> Vec> { let mut clip: Vec = sub("Clipboard", items(app, CLIPBOARD)).into_iter().collect(); clip.extend(sub("Isolate", items(app, ISOLATE))); push(&mut groups, clip); - let selected = !app.session.selection().is_empty(); + // Only parameters or actions picked in the Block Editor: what acts on them. + if !selected && !app.session.picked_elements().is_empty() { + push(&mut groups, items(app, &["erase", "move"])); + } if selected { let mut edit: Vec = EDIT.iter().filter_map(|(id, label)| item(app, id, *label)).collect(); edit.extend(sub("Draw Order", items(app, DRAW_ORDER))); @@ -137,6 +148,40 @@ pub fn entries(app: &CadApp) -> Vec> { groups } +/// Object Visibility ▸ in the Block Editor (AutoCAD's shortcut menu there): hide or show the +/// selected objects in the current visibility state or all of them. Its items are greyed out when +/// the block has no visibility parameter. +fn visibility_entries(app: &CadApp) -> Option { + use cadcraft_engine::doc::dynblock::{ParameterKind, dynamic_block}; + let st = app.session.state().ok()?; + let be = st.block_edit.as_ref()?; + let has = !be.current + && dynamic_block(&st.doc, &be.name).is_some_and(|m| m.parameters.iter().any(|p| matches!(p.kind, ParameterKind::Visibility { .. }))); + let item = |label: &str, id: &str| Entry::Item { label: label.into(), id: format!("{VISIBILITY}{id}"), shortcut: None, enabled: has }; + Some(Entry::Sub { + label: "Object Visibility".into(), + children: vec![ + item("Hide for Current State", "hide"), + item("Show for Current State", "show"), + item("Hide for All States", "hide-all"), + item("Show for All States", "show-all"), + ], + }) +} + +/// Run an Object Visibility item on the selection. +fn choose_visibility(app: &mut CadApp, what: &str) { + let (cmd, all) = match what { + "hide" => ("bvhide", false), + "show" => ("bvshow", false), + "hide-all" => ("bvhide", true), + "show-all" => ("bvshow", true), + _ => return, + }; + let handles: Vec = app.session.selection().iter().map(|h| h.hex()).collect(); + let _ = app.run(cmd, serde_json::json!({ "handles": handles, "all": all })); +} + /// The edit commands of the selected objects' type (when they are all of one type), with their /// labels: Edit Text for text, Block Editor and Edit Attributes for block references, Hatch Edit /// and Generate Boundary for hatches, Polyline Edit, Spline Edit… @@ -308,6 +353,8 @@ pub fn choose(app: &mut CadApp, id: &str) { } } else if let Some(s) = id.strip_prefix(SNAP) { choose_snap(app, s); + } else if let Some(v) = id.strip_prefix(VISIBILITY) { + choose_visibility(app, v); } else if id.starts_with("textedit:") { // The Edit Text window of the single selected text object; the id carries the handle. app.ui.dialog = Some(id.to_string()); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index bc770780dc..8a290aeb1a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -34,6 +34,8 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "commands" => commands(app, ctx, &mut open), "attedit" => crate::attedit::dialog(app, ctx, &mut open), "bedit" => crate::bedit::dialog(app, ctx, &mut open), + "bvstate" => crate::bvstate::dialog(app, ctx, &mut open), + "blookuptable" => crate::blookup::dialog(app, ctx, &mut open), "authoring" => crate::bedit::authoring_dialog(app, ctx, &mut open), "wblock" => crate::wblock::dialog(app, ctx, &mut open), "stylesmanager" => crate::plotstyles::dialog(app, ctx, &mut open), diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 15607f953a..87bd572911 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1531,3 +1531,14 @@ menu View 视图 # ArtCraft feature naming Additional Tools 其他工具 + Parameter 参数 + Action 动作 + Visibility States 可见性状态 + Make Visible 使可见 + Make Invisible 使不可见 + Pick Parameters and Actions 拾取参数和动作 + Erase Parameters and Actions 擦除参数和动作 + Move Parameters and Actions 移动参数和动作 + Move a Parameter's Point 移动参数的点 + Parameter Points 参数点 + Lookup Table 查寻表 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f159a296f2..f2025d7872 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -23,6 +23,8 @@ pub mod attedit; pub mod attentry; pub mod autosave; pub mod bedit; +pub mod blookup; +pub mod bvstate; pub mod canvas; pub mod capture; pub mod chrome; @@ -406,6 +408,10 @@ pub struct CadApp { /// The startup update check and its prompt (desktop; [`updates_ui`]). #[cfg(not(target_arch = "wasm32"))] pub updates_rt: updates_ui::Runtime, + /// The Visibility States dialog ([`bvstate`]). + pub bvstate: bvstate::State, + /// The Property Lookup Table dialog ([`blookup`]). + pub blookup: blookup::State, } impl CadApp { @@ -471,6 +477,8 @@ impl CadApp { wblock: wblock::State::default(), #[cfg(not(target_arch = "wasm32"))] updates_rt: updates_ui::Runtime::default(), + bvstate: bvstate::State::default(), + blookup: blookup::State::default(), pending_pick: None, } } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index b8bc3e25f4..dccfff9228 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -169,6 +169,12 @@ fn route_ui_subsystems(app: &mut CadApp, id: &str, params: &Value) -> Option }, } +impl Entry { + /// An item that can run, or a submenu with one. + pub fn enabled(&self) -> bool { + match self { + Entry::Item { enabled, .. } => *enabled, + Entry::Sub { children, .. } => children.iter().any(Entry::enabled), + } + } +} + /// The full menu tree from the command registry plus UI commands, in registration order. pub fn tree(app: &CadApp) -> Vec<(String, Vec)> { let mut out: Vec<(String, Vec)> = MENUS.iter().map(|m| (m.to_string(), Vec::new())).collect(); @@ -816,10 +832,13 @@ pub(crate) fn entry_ui(ui: &mut egui::Ui, e: &Entry, clicked: &mut Option { - ui.menu_button(crate::i18n::menu(label), |ui| { - for c in children { - entry_ui(ui, c, clicked); - } + // A submenu none of whose items can run is greyed out. + ui.add_enabled_ui(children.iter().any(Entry::enabled), |ui| { + ui.menu_button(crate::i18n::menu(label), |ui| { + for c in children { + entry_ui(ui, c, clicked); + } + }); }); } }