Skip to content

Commit

Permalink
improve block section loading procedure #1136
Browse files Browse the repository at this point in the history
This makes the block loading process resilient to
faulty BLOCK entities.
  • Loading branch information
mozman committed Aug 2, 2024
1 parent 750e00f commit 2a67c32
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
2 changes: 2 additions & 0 deletions notes/pages/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
## Version 1.3.3 - dev
- ((65ed4f6c-edc8-4390-880c-c604a3fa5ec0))
- NEW: improve block section loading procedure
- {{issue 1136}}
- BUGFIX: `ezdxf.units.unit_name` always returns `unitless` in some environment
- contributed by #privet-kitty
- {{issue 1131}}
Expand Down
30 changes: 27 additions & 3 deletions src/ezdxf/sections/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,23 @@ def is_anonymous_block(name: str) -> bool:
return len(name) > 1 and name[0] == "*" and name[1] in "UEXDAT"


def recover_block_name(block: Block) -> str:
name = block.dxf.get("name", "")
if name:
return name
owner = block.dxf.get("owner", "")
if not owner:
return ""
doc = block.doc
# The owner of BLOCK is BLOCK_RECORD which also stores the block name
# as group code 2; DXF attribute name is "name"
if doc is not None and doc.entitydb is not None:
block_record = doc.entitydb.get(owner)
if isinstance(block_record, BlockRecord):
return block_record.dxf.get("name", "")
return ""


_MISSING_BLOCK_ = Block()


Expand Down Expand Up @@ -120,7 +137,7 @@ def load_block_record(
block: Block,
endblk: EndBlk,
block_entities: list[DXFEntity],
) -> BlockRecord:
) -> BlockRecord | None:
try:
block_record = cast("BlockRecord", block_records.get(block.dxf.name))
# Special case DXF R12 - has no BLOCK_RECORD table
Expand Down Expand Up @@ -159,7 +176,7 @@ def link_entities() -> Iterable["DXFEntity"]:
raise DXFStructureError("Critical structure error in BLOCKS section.")
# Remove SECTION entity
del entities[0]
content: list["DXFEntity"] = []
content: list[DXFEntity] = []
block: Block = _MISSING_BLOCK_
for entity in link_entities():
if isinstance(entity, Block):
Expand All @@ -173,8 +190,15 @@ def link_entities() -> Iterable["DXFEntity"]:
"Found ENDBLK without a preceding BLOCK, ignoring content."
)
else:
block_name = block.dxf.get("name", "")
if not block_name:
block.dxf.name = recover_block_name(block)
block_record = load_block_record(block, entity, content)
self.add(block_record)
if isinstance(block_record, BlockRecord):
self.add(block_record)
else:
handle = block.dxf.get("handle", "<undefined>")
logger.warning(f"Ignoring invalid BLOCK definition #{handle}.")
block = _MISSING_BLOCK_
content.clear()
else:
Expand Down

0 comments on commit 2a67c32

Please sign in to comment.