Merge pull request #1855 from SBaksa/lisp-block-entities

AutoLISP: read block definitions: tblsearch BLOCK gives the first entity (-2), entnext and entget walk a block's entities (part of #1700)
This commit is contained in:
FredApps
2026-11-18 16:33:41 +07:00
committed by GitHub
5 changed files with 189 additions and 6 deletions
+7
View File
@@ -5,6 +5,9 @@
//! (`getpoint`, `pause`) and carry on later, so the interface keeps drawing while a routine
//! waits. Each drawing has its own symbols, as in AutoCAD. A run is one undo step.
/// A block-definition entity and its successor in the block, by handle.
pub type BlockSlots = HashMap<Handle, (Arc<cadcraft_doc::Entity>, Option<Handle>)>;
pub mod builtins;
mod drawing;
pub mod eval;
@@ -56,6 +59,9 @@ pub struct Env {
pub deleted: HashMap<Handle, (cadcraft_doc::Space, Arc<cadcraft_doc::Entity>)>,
/// Every entity's handle in creation order, for the drawing it was taken from (`entnext`).
pub order: Option<(usize, Arc<Vec<Handle>>)>,
/// Each block-definition entity with its successor in its block (None for the last), for the drawing
/// it was taken from: `entnext`'s indexed lookup, which also tells whether a handle is a block's.
pub block_next: Option<(usize, Arc<BlockSlots>)>,
/// `tblnext`'s place in each table.
pub tblnext: HashMap<String, usize>,
/// A block definition `entmake` has begun (a BLOCK list) and not yet ended (ENDBLK): the
@@ -77,6 +83,7 @@ impl Default for Env {
next_file: 1,
deleted: HashMap::new(),
order: None,
block_next: None,
tblnext: HashMap::new(),
pending_block: None,
printed_at: None,
+37
View File
@@ -234,3 +234,40 @@ fn a_definition_that_isnt_added_leaves_no_layer() {
assert_eq!(ok(&mut s, ENDBLK), "\"EB\"");
assert!(has(&s, "PARTS"), "the block's layer exists once it is added");
}
/// entnext walks entmade block entities in order through the cached successor index, and a
/// redefinition (same drawing, same block name) is not served from the stale index.
#[test]
fn entnext_walks_entmade_blocks_and_sees_a_redefinition() {
let mut s = session();
let walk = r#"(progn (setq e (cdr (assoc -2 (tblsearch "BLOCK" "EB"))) types nil)
(while e (setq types (cons (cdr (assoc 0 (entget e))) types) e (entnext e)))
(reverse types))"#;
for code in [BLOCK_EB, LINE, CIRCLE, ENDBLK] {
ok(&mut s, code);
}
assert_eq!(ok(&mut s, walk), "(\"LINE\" \"CIRCLE\")");
assert_eq!(ok(&mut s, walk), "(\"LINE\" \"CIRCLE\")", "second walk from the cache");
for code in [BLOCK_EB, CIRCLE, LINE, LINE, ENDBLK] {
ok(&mut s, code);
}
assert_eq!(ok(&mut s, walk), "(\"CIRCLE\" \"LINE\" \"LINE\")");
}
/// entget and handent reach every entity of an entmade block through the cached index, and a
/// redefinition shows the new entities, not the old ones.
#[test]
fn entget_and_handent_reach_every_block_entity_also_after_a_redefinition() {
let mut s = session();
let walk = r#"(progn (setq e (cdr (assoc -2 (tblsearch "BLOCK" "EB"))) r nil)
(while e (setq r (cons (list (cdr (assoc 0 (entget e))) (equal (handent (cdr (assoc 5 (entget e)))) e)) r) e (entnext e)))
(reverse r))"#;
for code in [BLOCK_EB, LINE, CIRCLE, LINE, ENDBLK] {
ok(&mut s, code);
}
assert_eq!(ok(&mut s, walk), "((\"LINE\" T) (\"CIRCLE\" T) (\"LINE\" T))");
for code in [BLOCK_EB, CIRCLE, ENDBLK] {
ok(&mut s, code);
}
assert_eq!(ok(&mut s, walk), "((\"CIRCLE\" T))");
}
+59 -6
View File
@@ -7,16 +7,18 @@
//! [`crate::cmd::file::entity_codec`]), so what `entget` shows is what a DXF file holds, except
//! for angles, which are radians in a list and degrees in a file.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use cadcraft_doc::{Entity, Handle, Space};
use cadcraft_geom::Vec2;
use craft_dxf::Tag;
use super::LispError;
use super::builtins::args_err;
use super::eval::{Ctx, Flow, Need};
use super::value::{PickSet, Value, to_text};
use super::{BlockSlots, LispError};
use crate::{Input, Session};
fn arity(a: &[Value], min: usize, max: usize) -> Result<(), LispError> {
@@ -356,8 +358,15 @@ fn space_of(d: &cadcraft_doc::Drawing, h: Handle) -> Option<Space> {
pub fn entget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 1, 2)?;
let h = ename(&a[0])?;
let drawn = ctx.s.doc().is_ok_and(|d| d.entity(h).is_some());
let from_block = if drawn { None } else { block_entity(ctx, h) };
let Ok(d) = ctx.s.doc() else { return Ok(Flow::Value(Value::Nil)) };
let Some(e) = d.entity(h) else { return Ok(Flow::Value(Value::Nil)) };
// An entity of a block definition (#1700) has no layout.
let (e, in_block) = match (d.entity(h), &from_block) {
(Some(e), _) => (e, false),
(None, Some(e)) => (e, true),
(None, None) => return Ok(Flow::Value(Value::Nil)),
};
let (kind, mut tags) = (codec()?.groups)(d, e);
convert_angles(&kind, &mut tags, f64::to_radians);
let layout = match space_of(d, h) {
@@ -365,7 +374,7 @@ pub fn entget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
_ => "Model".into(),
};
let mut items = vec![Value::cons(Value::Int(-1), Value::Ename(h)), Value::cons(Value::Int(0), Value::str(&kind))];
let mut placed_layout = false;
let mut placed_layout = in_block;
for v in groups_to_list(&tags) {
// The layout name follows the AcDbEntity marker, as AutoCAD lists it.
let after_marker = !placed_layout && v.car().as_number() == Some(100.0) && matches!(v.cdr(), Value::Str(ref s) if &**s == "AcDbEntity");
@@ -493,6 +502,7 @@ fn end_block(ctx: &mut Ctx<'_>) -> Value {
}
let name = b.name.clone();
d.blocks.insert(name.clone(), Arc::new(b));
ctx.env.block_next = None;
ctx.s.touch();
Value::str(&name)
}
@@ -577,6 +587,30 @@ fn handles_in_order(ctx: &mut Ctx<'_>) -> Arc<Vec<Handle>> {
v
}
/// Every block-definition entity with its successor within its block, cached per drawing like
/// [`handles_in_order`]: one pass over the blocks, then `entnext`, `entget` and `handent` on a
/// block's entity are hash lookups instead of scans of the block (and of every block, to find
/// which holds the entity).
fn block_slots(ctx: &mut Ctx<'_>) -> Arc<BlockSlots> {
let Ok(st) = ctx.s.state() else { return Arc::default() };
let key = Arc::as_ptr(&st.doc) as usize;
if let Some((k, v)) = &ctx.env.block_next
&& *k == key
{
return v.clone();
}
let mut m = HashMap::new();
for b in st.doc.blocks.values() {
let mut it = b.entities.iter().peekable();
while let Some(e) = it.next() {
m.insert(e.handle, (e.clone(), it.peek().map(|n| n.handle)));
}
}
let m = Arc::new(m);
ctx.env.block_next = Some((key, m.clone()));
m
}
pub fn entlast(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 0, 0)?;
Ok(Flow::Value(handles_in_order(ctx).last().map(|h| Value::Ename(*h)).unwrap_or_default()))
@@ -584,6 +618,15 @@ pub fn entlast(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
pub fn entnext(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 0, 1)?;
// From an entity of a block definition: the next one in that block, nil after the last (#1700).
if let Some(v) = a.first().filter(|v| !v.is_nil()) {
let h = ename(v)?;
if ctx.s.doc().is_ok_and(|d| d.entity(h).is_none())
&& let Some((_, next)) = block_slots(ctx).get(&h)
{
return Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default()));
}
}
let order = handles_in_order(ctx);
let next = match a.first() {
None | Some(Value::Nil) => order.first().copied(),
@@ -599,10 +642,15 @@ pub fn entnext(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
pub fn handent(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 1, 1)?;
let s = string(&a[0])?;
let h = Handle::parse_hex(&s).filter(|h| ctx.s.doc().is_ok_and(|d| d.entity(*h).is_some()));
let h = Handle::parse_hex(&s).filter(|h| ctx.s.doc().is_ok_and(|d| d.entity(*h).is_some()) || block_entity(ctx, *h).is_some());
Ok(Flow::Value(h.map(Value::Ename).unwrap_or_default()))
}
/// Entity `h` of a block definition (#1700), by the cached index.
fn block_entity(ctx: &mut Ctx<'_>, h: Handle) -> Option<Arc<Entity>> {
block_slots(ctx).get(&h).map(|(e, _)| e.clone())
}
// ---------------- selection sets ----------------
/// `(ssget [mode] [pt1 [pt2]] [filter])`. Modes: "X" every entity, "L" the last, "P" the
@@ -992,12 +1040,17 @@ fn table_records(d: &cadcraft_doc::Drawing, table: &str) -> Vec<Value> {
.blocks
.values()
.map(|b| {
Value::list(vec![
let mut items = vec![
pair(0, Value::str("BLOCK")),
pair(2, Value::str(&b.name)),
pair(70, Value::Int(0)),
Value::list(vec![Value::Int(10), Value::Real(b.base.x), Value::Real(b.base.y), Value::Real(b.base.z)]),
])
];
// Its first entity (-2): entnext walks the rest of the definition (#1700).
if let Some(first) = b.entities.iter().next() {
items.push(pair(-2, Value::Ename(first.handle)));
}
Value::list(items)
})
.collect(),
"DIMSTYLE" => d
+82
View File
@@ -1048,6 +1048,88 @@ fn a_panic_inside_a_routine_ends_it_with_an_error() {
assert_eq!(ok(&mut s, "(+ 1 2)"), "3");
}
// ---------------- entities of block definitions (#1700) ----------------
/// A drawing with one linear dimension measuring 100 whose `*D1` block, as stored in the file,
/// says 99.5 (a stale block: the defpoints moved, the block wasn't rebuilt).
fn stale_dimension() -> Session {
let mut s = session();
s.execute("dimlinear", &serde_json::json!({"p1": [0, 0], "p2": [100, 0], "at": [50, -20], "rotation": 0})).unwrap();
let dxf = cadcraft_io::write_dxf(s.doc().unwrap());
// The *D1 block's MTEXT says 100 (100.0000 here); make the file say 99.5.
let lines: Vec<&str> = dxf.lines().collect();
let (mut kind, mut block, mut out, mut changed) = (String::new(), String::new(), Vec::new(), 0);
for (i, l) in lines.iter().enumerate() {
let code = if i % 2 == 0 { l.trim() } else { "" };
let value = lines.get(i + 1).map(|v| v.trim()).unwrap_or("");
if code == "0" {
kind = value.to_string();
}
if code == "2" && kind == "BLOCK" {
block = value.to_string();
}
if i % 2 == 1 && kind == "MTEXT" && block == "*D1" && lines.get(i - 1).map(|c| c.trim()) == Some("1") && l.trim().starts_with("100") {
out.push("99.5".to_string());
changed += 1;
continue;
}
out.push(l.to_string());
}
assert_eq!(changed, 1, "the fixture found the *D1 text");
let mut s = session();
s.open_drawing(cadcraft_io::read_dxf(out.join("\n").as_bytes()).unwrap(), "stale", None);
s
}
/// The issue's use: a routine reads the text a dimension's block stores and compares it with the
/// measurement, so it finds the stale block.
#[test]
fn a_routine_reads_the_text_a_dimension_block_stores() {
let mut s = stale_dimension();
let code = r#"(progn
(defun dtext (dim / e txt)
(setq e (cdr (assoc -2 (tblsearch "BLOCK" (cdr (assoc 2 (entget dim)))))))
(while e
(if (= (cdr (assoc 0 (entget e))) "MTEXT") (setq txt (cdr (assoc 1 (entget e)))))
(setq e (entnext e)))
txt)
(setq dim (entlast))
(list (dtext dim) (cdr (assoc 42 (entget dim)))))"#;
assert_eq!(ok(&mut s, code), "(\"99.5\" 100.0)");
}
/// tblsearch names a block's first entity (-2); entnext walks the definition in order and ends
/// with nil; entget lists each one (without a layout); handent finds them by handle.
#[test]
fn entnext_and_entget_walk_a_block_definition() {
let mut s = session();
let l = s.execute("line", &serde_json::json!({"points": [[0, 0], [10, 0]]})).unwrap()["handles"][0].as_str().unwrap().to_string();
let c = s.execute("circle", &serde_json::json!({"center": [5, 5], "radius": 2})).unwrap()["handle"].as_str().unwrap().to_string();
s.execute("block", &serde_json::json!({"name": "B", "base": [0, 0], "handles": [l, c], "keep": "delete"})).unwrap();
s.execute("line", &serde_json::json!({"points": [[50, 0], [60, 0]]})).unwrap();
let walk = r#"(progn (setq e (cdr (assoc -2 (tblsearch "BLOCK" "B"))) types nil)
(while e (setq types (cons (cdr (assoc 0 (entget e))) types) e (entnext e)))
(reverse types))"#;
assert_eq!(ok(&mut s, walk), "(\"LINE\" \"CIRCLE\")", "the block's own entities, not the drawing's");
let first = "(cdr (assoc -2 (tblsearch \"BLOCK\" \"B\")))";
assert_eq!(ok(&mut s, &format!("(assoc 410 (entget {first}))")), "nil", "no layout");
assert_eq!(ok(&mut s, &format!("(equal (handent (cdr (assoc 5 (entget {first})))) {first})")), "T");
// The drawing's own entities walk as before.
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget (entnext))))"), "\"LINE\"");
assert_eq!(ok(&mut s, "(entnext (entlast))"), "nil");
// Editing a block's entity through entmod or entdel isn't offered: nil, nothing changes.
assert_eq!(ok(&mut s, &format!("(entdel {first})")), "nil");
assert_eq!(ok(&mut s, &format!("(entmod (entget {first}))")), "nil");
assert_eq!(s.doc().unwrap().block("B").unwrap().entities.len(), 2);
}
#[test]
fn an_empty_block_has_no_first_entity() {
let mut s = session();
s.doc_mut().unwrap().blocks.insert("EMPTY".into(), std::sync::Arc::new(cadcraft_doc::Block::new("EMPTY")));
assert_eq!(ok(&mut s, "(assoc -2 (tblsearch \"BLOCK\" \"EMPTY\"))"), "nil");
}
#[test]
fn angtof_reads_the_string_in_the_given_units() {
let mut s = Session::new();
+4
View File
@@ -91,6 +91,10 @@ DXF file holds for the object, plus `-1` (its name) and `410` (its layout). Angl
are in radians, as in AutoCAD, where the file holds degrees; `entmake`, `entmod` and `ssget`
filters take radians too.
Block definitions can be read: `(tblsearch "BLOCK" name)` gives the block's first entity in group
-2, `entnext` goes from one entity of a definition to the next (nil after the last) and `entget`
lists them (without a layout, group 410). So a routine can read what a block stores, such as the
text of a dimension's `*D` block. `entmod` and `entdel` don't change a definition's entities.
`entmake` defines blocks: a BLOCK list (2 name, 70 flags, 10 base point, 4 description) begins a
definition, the entities made after it go into the block instead of the drawing, and an ENDBLK
list adds the block (redefining one of the same name) and returns its name. Flag 1 with a `*U`