Files
cadcraft/crates/engine/src/cmd/blocks/insert_file.rs
T
Obtrusive8276andClaude Opus 5.5 65ed2fb7f0 Blocks palette: previews, block libraries and placement (#2122)
* Blocks palette: list/medium/large icon modes, visible-only preview cache, grab-and-drop placement

* Address CodeRabbit review: repeat-placement tracking, Arc<Drawing> clone, contains_pointer, docstrings

* Keep repeat INSERT inside engine state machine and leave canvas hover check intact

* Handle Repeat/NoRepeat across all INSERT stages and bound preview work budget

* Fix Blocks palette review findings and preflight polyline previews

* Fix Blocks palette review findings and menu click ownership

* Restore bounded hatch thumbnails and exclude navigation clicks

* Support faithful hatch previews with shared work budget and bounded contour fallback

* Allow checking Repeat placement while block insertion is already in progress

* Address PR 2122 review feedback on hatch budget, ViewCube hit-testing and preview test

* Charge leader and wipeout expansion and bound MLeader array inserts in preview preflight

* Charge MLeader paths in preview preflight and match ViewCube hit-testing to displayed sheet

* Allow block insertion while rename editor is open and clarify hatch preview docs

* Limit palette repeat placement to palette-started insertions

* Account hatch preview comparisons as work occurs

* Bound attribute thumbnail work and preserve palette rotation

* Charge spline sampling work to the block preview budget

* Charge splines at 1/32 of their sampling cap so ordinary blocks still preview

* Charge text lengths in block preview budget and preserve inline INSERT arguments

* Bound MText column metadata in block previews

* Allow detailed block palette previews

* Explain refused block previews and keep them cached while scrolling

Previews now return Ready, Empty or Unavailable(reason) instead of an
ambiguous empty display list, so a refused thumbnail is no longer shown
like an empty block. Preflight separates input, computation and retained
output, and reuses the geometry/render sampling rules at a thumbnail
tolerance instead of a 4,000-sample worst case. A 64 MiB / 512-result LRU
replaces retain_visible. Insertion never depends on preview success.

Also: invalid-but-finite splines draw as their control polygon, and the
insertion-point prompt advertises REpeat so R keeps meaning Rotate.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Remove changes unrelated to the Blocks palette

Drop the contributor entry and the two xtask test adjustments so the PR
only contains palette, preview and insertion changes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Document the functions touched by the Blocks palette preview work

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Keep placement on unchanged rename and tighten palette click ownership

Confirming a block name unchanged no longer cancels the INSERT in progress.
Command-line releases are not placed as points when two arrive in one frame,
and menu ownership of a press is taken from the press position of the last
press in the frame.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Translate palette refusal messages and track canvas click ownership per release

Mark the five preview refusal texts for translation and add the palette status
texts to the other catalogs. Give each primary release in a frame the owner of
its own press, and place a release at its own position when the cursor has
moved onto a menu or a new press has begun.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Treat navigation controls as release owners in batched canvas clicks

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Track INSERT ownership and refuse palette edits during a foreign INSERT

The palette now cancels only the INSERT it started (identified by a per-run serial), advertises REpeat/NoRepeat at every numeric and point prompt, and refuses Edit, Create, Rename and Delete while an INSERT it did not start is running, so undoing that insertion cannot also undo a palette edit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Keep clicks on command-line keywords from placing canvas points

The command line now records one rectangle covering the bar and every inline keyword, and the canvas treats a press, release or ordinary click there as the command line's, so a keyword pushed past the bar by a long prompt cannot also send a point.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Decide whether the ViewCube is shown from the current space, not the display list

The display list is rebuilt after a frame's clicks are handled, so right after a layout switch it was stale or cleared. A click where the ViewCube had just disappeared was dropped, and a click on one that had just appeared reached the drawing as a point. Painting and hit-testing now share viewcube_shown, which follows the layout space.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Treat only a refused charge as hatch budget exhaustion

Spending the hatch budget exactly left zero remaining, which hatch::draw and the preview builder read as exhaustion, so a valid preview could lose its hatches or be refused. HatchBudget now records a refused reservation separately and both checks use it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Keep CLOSEALL's confirmation, widen the command-line click area, persist the Blocks window choice

Only {json} calls and INSERT with inline arguments bypass the UI router, so CLOSEALL Y still asks before discarding drawings. The command line's click rectangle now includes the history lines or window, the resize grip and the AutoComplete rows. The floating-window preference of the Blocks palette is saved and restored with the other preferences.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Update Z and axis presets with a comma scale; grey the palette's Y scale when exploding

A comma-separated scale preset now sets Z to the size of X and the axis presets to X, Y and that Z, so an earlier Scale cannot leave a stale Z. The Blocks palette disables its Y scale while Explode is on, with a tooltip saying the exploded insertion scales both axes by X.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Fix doc comments on the BLOCK and ATTDEF input methods and the INSERT tests

BlockM::input and AttdefM::input named the INSERT state machine; the NoRepeat description sat on the comma-scale test instead of the repeat test, and the two newer INSERT tests had none of their own.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Reset the Verify counter between repeated INSERT placements

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Blocks palette: previews, block libraries and placement

Rewrite this PR on a smaller base. The Blocks window becomes a dockable
palette with a Current Drawing tab and a Libraries tab, icon and list views,
a kept list of block libraries (folders and DWG/DXF files) and one-click
placement through the existing interactive INSERT.

- Previews are built only for the visible tiles, a few per frame, under a
  time and point budget, in a bounded least-recently-used cache.
- BLOCKLIBRARY, BLOCKLIBIMPORT and BLOCKLIBRARIES are commands; importing a
  library block brings only the layers, linetypes, styles and blocks it needs.
- INSERT: Enter at the insertion point ends the command, as in AutoCAD.
- Hostile library files and block data are bounded; nothing panics.
- The canvas, ViewCube, command-line and interactive INSERT changes of the
  earlier version are gone.
- Translations in all interface languages.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Blocks palette: read libraries off the UI thread, bound preview work

CodeRabbit's reviews of f2ae408 and 62bff60:

- A library is listed on a worker thread (the web reads it at once), with
  a "Reading the library..." message in every catalog. Refresh waits for
  the read, and now parses the file again even when its size and time
  look the same. `list_library` is what BLOCKLIBRARY answers, without a
  session.
- A preview's work is counted before anything is drawn: vertices, text,
  and the blocks references, dimensions and multileaders draw. An object
  with nothing in it still costs one visit. The pass that finds the size
  draws no dashes, and a block of points no longer scans the drawing's
  extents.
- A block listing keeps the first blocks by name without sorting the
  whole table, for BLOCKSPALETTE too.
- Merging a drawing removes nothing from a drawing too big for the purge
  scan: past its limit, a layer or style in use can look unused.

Also fixed: a block with more than 100,000 references could lose the
blocks it needs on import, because the walk counted repeated names. The
same count in `used_blocks`, which PURGE shares, could drop the arrowhead
of a merged dimension style, so that limit goes too: each block is walked
once, so the walk ends, cycles included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Blocks palette: repeat a placement only after its own INSERT placed

The palette took any new handle as proof that its INSERT had placed the
block. Queued control requests can cancel that INSERT and run another
command to its end between two frames, and that command's handles then
started a placement nobody asked for.

The session now says how the last command ended: `commands_started`
numbers the commands, nested transparent ones left out, and
`last_finished` holds the number of the last one that ended by itself and
whether it added to the drawing. The palette repeats only when that is its
own INSERT, which also removes its handle counter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Blocks palette: a command started after a placement ends the repeat

A command with no prompt, such as REGEN, started right after INSERT placed
the block left `last_finished` on that INSERT, so the palette started
placing again after the user had moved on. The palette now also requires
that no command has started since.

A JSON command still does not end the repeat, on purpose: it never stops a
running command, so one that lands a frame later finds the next INSERT
running and leaves it alone. Ending the repeat only when it lands before
the frame would make the result depend on timing. A test pins this.

Also adds the doc comments CodeRabbit's coverage check asks for, on this
PR's own functions and tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* INSERT: a cancelled placement takes no undo step

INSERT wrote INSNAME when the name was given, so cancelling it left a
changed drawing and an undo step that undid nothing visible. Repeat
Placement, on by default, always ends with a cancelled INSERT, so the first
undo after placing a block from the palette appeared to do nothing.

INSNAME is now written when the block is placed. A cancelled INSERT no
longer offers its name as the next default.

Tests go through the palette where they only imitated it: the scale set in
the palette, and the two undo steps of a block from a library. The palette
places with two clicks, so the wording about a drag is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Block import: keep what a block names and says about itself

BLOCKLIBIMPORT defined a new block from the chosen one's objects and base
point, so its description, annotative flag, units and explodable flag were
lost. They now come along.

The import's clean-up uses PURGE's scan, which only read the linetypes of
objects and layers. A linetype named only by a dimension style, a dimension
override, a multiline style, a multiline's copy of its style or an attribute
override looked unused, so the import dropped it and PURGE removed it while
the style still named it. The scan reads them all now.

A reference to a renamed anonymous block kept the drawing's block of that
name when it spelled the name in another case, or when it was a multileader's
block content. Both now take the new name, found as Drawing::block finds a
block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* INSERT: Enter asks again at the insertion point, arrowheads follow renames

This PR made Enter and Space at the insertion point end INSERT, "as in
AutoCAD". AutoCAD 2027 does not: from -INSERT, from its palette and during
repeated placement it answers that a point or option is needed and asks
again. Only Escape ends it, so that change is gone.

A file named at the block name prompt defines its block before the insertion
point is asked for, and Escape keeps that definition, which is what AutoCAD
2027 does too. A test pins it.

An anonymous arrowhead block renamed by a merge kept its old name in the
dimension styles that came along and in dimension overrides, so they pointed
at this drawing's block. Both follow the rename now; a style this drawing
already had keeps its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Block import and palette: keep every named style and layer, skip unused counts

Selective import uses PURGE's scans, which missed dimension styles named by
leaders, text styles named by linetype pattern elements, table cell styles,
dimension DIMTXSTY overrides and multiline or multileader-content attributes,
plus layers and linetypes named by attributes on multileader block content.
They all count as in use now.

The palette asks BLOCKSPALETTE for no reference counts so it does not read
every object after each edit, and cancels any running command before importing
a library block so the import keeps its own undo step.

* Blocks palette: a quick right-click at the insertion point cancels the placement

A placement started from the palette had no way out with the mouse: Enter at
the insertion point asks again, as AutoCAD 2027 does, and a quick right-click
is Enter. At that prompt only, for an INSERT the palette started, a quick
right-click now ends the command like Escape, which also ends Repeat
Placement. A typed INSERT and the scale and rotation prompts keep Enter, and
holding the button still opens the command menu.

Escape, the menu's Cancel and this right-click share one function that also
clears the half-typed text and the IME preedit; the menu's Cancel left the
preedit behind.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Blocks palette: a transparent command no longer stops Repeat Placement

A 'ZOOM or 'PAN run while the palette's INSERT asks for the insertion point
shows the prompt `>>ZOOM`, which the palette took for another command and so
stopped repeating the placement. A transparent command inside the INSERT does
not start a command; it is now the count of commands started that tells
whether the user moved on. A test pins it.

The blocklibrary params string names the `truncated` field both results
return.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Blocks palette: a transparent command ending inside INSERT is not its end; bound library reads

A transparent command that finishes inside a running one ('ZOOM in an INSERT)
recorded its end under the outer command's number. With an object added
meanwhile, cancelling the resumed INSERT looked like a placement and the
palette started another. Only a top-level command records its end now.

Switching quickly between big libraries started a reading thread for each. At
most four libraries are read at once; a further one waits, and the palette
says it is reading until a place comes back.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Blocks palette: BLOCKLIBIMPORT never replaces a block; BLOCKSPALETTE counts every object that draws one

BLOCKLIBIMPORT refuses a name the drawing already has (any letter case),
the rule the palette already follows, so a direct JSON call can no longer
change existing references. BLOCKSPALETTE counts block references,
dimensions and multileader block content through `referenced_block`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Blocks palette: a library file must be named .dwg or .dxf

cached_drawing read any regular path, and the reader sniffs the bytes, so a
DXF named part.bin was listed by BLOCKLIBRARY, imported by BLOCKLIBIMPORT and
loaded by the palette. It now refuses other names before the cache lookup, so
the three callers share the check. Regression test with a part.bin.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Blocks palette: library listing needs no drawing; a preview's two passes share one deadline

BLOCKLIBRARY and BLOCKLIBRARIES ignore the session but had the has_doc guard,
so the palette opened on the Start tab got "no drawing open", kept an empty
library list and never reloaded it. They are now always enabled; BLOCKLIBIMPORT
still needs a drawing.

outline() gave each of its two build passes the full PREVIEW_DEADLINE, so one
preview could take twice the limit. The detailed pass now gets what the coarse
pass left.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Blocks palette: a dimension override given as a number names its style, linetype or arrowhead

DIMOVERRIDE keeps a number as given (DIMTXSTY 123) and the dimension is
drawn with it as text, but the in-use scans only read strings, so PURGE,
style deletion and import cleanup could drop a style, linetype or
arrowhead block still in use. `purge::override_name` reads either, for
text styles, linetypes, arrowheads (main's `override_arrows` had the same
defect) and the arrowhead rename at import, which now rewrites an
override only when its block is really renamed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Blocks palette: put show()'s doc comment back on show()

right_click_cancels_placing had been inserted between show()'s doc comment
(the cursor-visibility contract, #1701) and show() itself, so the contract
documented the wrong function. Moved, no code change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* i18n(ka): add the 27 Blocks palette strings

Georgian rows for the strings this PR adds to the other catalogs (cargo test -p cadcraft-ui-egui translation_gaps -- --ignored --nocapture lists none of them any more).

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-18 08:43:17 +07:00

715 lines
33 KiB
Rust

//! INSERT of a drawing file (`-INSERT C:\parts\bolt.dxf`, `bolt=C:\parts\bolt.dwg`, JSON `file`)
//! and exploded insertion (`*name`).
//!
//! A file becomes a block named after it (or after the part before `=`): its model space, with
//! the file's `$INSBASE` as the base point, plus the layers, linetypes, styles and blocks it needs
//! (names this drawing already has keep this drawing's definitions). The file is read through the
//! host's io hooks like OPEN, so the engine stays I/O-agnostic.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use cadcraft_doc::{Block, Drawing, Entity, EntityKind, Handle};
use serde_json::{Value, json};
use super::super::file::io;
use super::super::modify::explode_kind;
use super::purge::{Kind, candidates, is_arrow_override, override_arrows, override_name, scan_reads_everything};
use super::{referenced_block, references_block, valid_block_name};
use crate::cmd::{bad, str_param};
use crate::{EngineError, Result, Session};
/// A drawing file named at the block name prompt.
#[derive(Clone, Debug)]
pub(super) struct FileRef {
/// The block to define.
pub name: String,
pub path: String,
/// `name=path`: redefine the block without asking.
explicit: bool,
}
impl FileRef {
/// Whether to ask before redefining: a plain path whose block already exists.
pub fn ask_redefine(&self, s: &Session) -> bool {
!self.explicit && s.doc().is_ok_and(|d| d.block(&self.name).is_some())
}
/// Read the file and (re)define its block. Returns the block's name.
pub fn define(&self, s: &mut Session) -> Result<String> {
let src = read_drawing(&self.path)?;
define_from(s, &src, &self.name, false)
}
}
/// The file `t` names at the block name prompt: `name=path` (`name=` alone: the file `name`), or a
/// path (it has a folder separator or a .dwg/.dxf extension) that isn't the name of a block.
pub(super) fn file_ref(s: &Session, t: &str) -> Option<FileRef> {
let t = t.trim();
// A block of this drawing is that block, whatever its name looks like: a name read from a file
// must not pass for `name=path` and make INSERT read another file (CWE-74).
if s.doc().is_ok_and(|d| d.block(t).is_some()) {
return None;
}
if let Some((name, path)) = t.split_once('=') {
let name = name.trim();
let path = if path.trim().is_empty() { name } else { path.trim() };
return (!name.is_empty()).then(|| FileRef { name: name.to_string(), path: path.to_string(), explicit: true });
}
let lower = t.to_ascii_lowercase();
let pathlike = t.contains(['/', '\\']) || lower.ends_with(".dwg") || lower.ends_with(".dxf");
if !pathlike {
return None;
}
Some(FileRef { name: stem(t), path: t.to_string(), explicit: false })
}
/// The file name without folders and extension (either separator, so Windows paths work anywhere).
pub(super) fn stem(path: &str) -> String {
let file = path.rsplit(['/', '\\']).next().unwrap_or(path);
match file.rsplit_once('.') {
Some((stem, _)) if !stem.is_empty() => stem.to_string(),
_ => file.to_string(),
}
}
/// Read a drawing file through the io hooks; a path without extension tries .dwg, then .dxf.
pub(super) fn read_drawing(path: &str) -> Result<Drawing> {
let hooks = io().ok_or_else(|| bad("insert", "file formats are not available in this build"))?;
let has_ext = stem(path) != path.rsplit(['/', '\\']).next().unwrap_or(path);
let candidates = if has_ext { vec![path.to_string()] } else { vec![path.to_string(), format!("{path}.dwg"), format!("{path}.dxf")] };
let mut last = None;
for p in candidates {
match read_file(&p) {
Ok(bytes) => return (hooks.read)(&bytes, &p).map_err(|e| bad("insert", format!("{p}: {e}"))),
Err(e) => last = Some(e),
}
}
Err(last.unwrap_or_else(|| bad("insert", format!("{path}: file not found"))))
}
fn read_file(_path: &str) -> Result<Vec<u8>> {
#[cfg(not(target_arch = "wasm32"))]
{
crate::capped_read::read_capped(std::path::Path::new(_path), crate::cmd::file::MAX_DRAWING_BYTES)
.map_err(|e| bad("insert", format!("{_path}: {e}")))
}
#[cfg(target_arch = "wasm32")]
Err(bad("insert", "paths are not available on the web"))
}
/// (Re)define block `name` from `src`'s model space with base point `$INSBASE`, adding the
/// layers, linetypes, styles and blocks of `src` this drawing doesn't have. With `only_needed`
/// the layers, linetypes and styles that nothing uses are left out again, as when a block is
/// taken from a library drawing: only what the block needs comes along. Nothing changes when the
/// definition fails (an invalid name, or a block that would contain itself).
pub(super) fn define_from(s: &mut Session, src: &Drawing, name: &str, only_needed: bool) -> Result<String> {
if !valid_block_name(name) {
return Err(bad("insert", format!("\"{name}\" is not a valid block name")));
}
let mut d = s.doc()?.clone();
let before = TableNames::of(&d);
// Redefining keeps the existing definition's name (block names are case-insensitive).
let name = d.blocks.keys().find(|k| k.eq_ignore_ascii_case(name)).cloned().unwrap_or_else(|| name.to_string());
let own_dim_styles = names_of(&d, Kind::Dimstyles);
merge_tables(&mut d, src);
let mut renames = crate::cmd::merge::block_renames(&d, src, Some(&name));
if only_needed {
// The other blocks of the file are not copied at all.
let need = needed_blocks(src);
renames.retain(|from, _| need.contains(&from.to_ascii_uppercase()));
}
let renames = Renames::new(renames);
rename_style_arrows(&mut d, &own_dim_styles, &renames);
for (from, to) in &renames.exact {
let Some(b) = src.blocks.get(from) else { continue };
let mut nb = (**b).clone();
nb.name = to.clone();
nb.entities = Default::default();
for e in b.entities.iter() {
let e = adopt(&mut d, src, e, &renames);
nb.entities.push(e);
}
d.blocks.insert(to.clone(), Arc::new(nb));
}
let mut b = Block::new(&name);
b.base = src.header.point("INSBASE").filter(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite()).unwrap_or_default();
let mut ents = Vec::new();
for e in src.model.iter() {
let e = adopt(&mut d, src, e, &renames);
d.ensure_layer(&e.common.layer);
ents.push(e);
}
if references_block(&d, &ents, &name) {
return Err(bad("insert", format!("Block \"{name}\" references itself.")));
}
for e in ents {
b.entities.push(e);
}
d.blocks.insert(name.clone(), Arc::new(b));
if only_needed {
drop_unused_new(&mut d, &before, &name);
}
*s.doc_mut()? = d;
Ok(name)
}
/// The tables a drawing merge adds to, in an order where removing the unused entries of one
/// frees the next (blocks free layers, layers free linetypes, dimension styles free text styles).
const MERGED: [Kind; 8] =
[Kind::Blocks, Kind::Dimstyles, Kind::MleaderStyles, Kind::MlineStyles, Kind::TableStyles, Kind::Layers, Kind::Linetypes, Kind::TextStyles];
/// The names (lower case) in one of those tables.
fn names_of(d: &Drawing, kind: Kind) -> BTreeSet<String> {
let lower = |it: &mut dyn Iterator<Item = &String>| it.map(|n| n.to_ascii_lowercase()).collect::<BTreeSet<String>>();
match kind {
Kind::Blocks => lower(&mut d.blocks.keys()),
Kind::Dimstyles => lower(&mut d.dim_styles.iter().map(|t| &t.name)),
Kind::MleaderStyles => lower(&mut d.mleader_styles.iter().map(|t| &t.name)),
Kind::MlineStyles => lower(&mut d.mline_styles.iter().map(|t| &t.name)),
Kind::TableStyles => lower(&mut d.table_styles.iter().map(|t| &t.name)),
Kind::Layers => lower(&mut d.layers.iter().map(|t| &t.name)),
Kind::Linetypes => lower(&mut d.linetypes.iter().map(|t| &t.name)),
Kind::TextStyles => lower(&mut d.text_styles.iter().map(|t| &t.name)),
_ => BTreeSet::new(),
}
}
/// The names in the merged tables, by kind.
struct TableNames(Vec<(Kind, BTreeSet<String>)>);
impl TableNames {
fn of(d: &Drawing) -> Self {
TableNames(MERGED.iter().map(|k| (*k, names_of(d, *k))).collect())
}
}
/// Upper-case names of the blocks `roots` and every block they need, through nested references,
/// dimension blocks, multileader block content and dimension arrowheads.
fn reachable(d: &Drawing, roots: Vec<String>) -> BTreeSet<String> {
let mut seen = BTreeSet::new();
let mut todo = roots;
// Each block is walked once, so this ends, cycles included.
while let Some(n) = todo.pop() {
if !seen.insert(n.to_ascii_uppercase()) {
continue;
}
let Some(b) = d.block(&n) else { continue };
for e in b.entities.iter() {
todo.extend(referenced_block(e));
if let EntityKind::Dimension(dm) = &e.kind {
todo.extend(override_arrows(dm));
}
}
}
seen
}
/// Upper-case names of the blocks the model space of `src` needs: the ones it refers to, what
/// those need, and the arrowheads of its dimension styles.
fn needed_blocks(src: &Drawing) -> BTreeSet<String> {
let mut roots: Vec<String> = Vec::new();
for e in src.model.iter() {
roots.extend(referenced_block(e));
if let EntityKind::Dimension(dm) = &e.kind {
roots.extend(override_arrows(dm));
}
}
for st in &src.dim_styles {
let arrows = [&st.arrow_block, &st.arrow_block1, &st.arrow_block2, &st.leader_arrow_block];
roots.extend(arrows.into_iter().map(|n| n.trim().to_string()).filter(|n| !n.is_empty()));
}
reachable(src, roots)
}
/// Remove the blocks, layers, linetypes and styles that were not in the drawing `before` and that
/// nothing uses (PURGE's scan), in an order where removing one frees the next. `keep` is the
/// block just defined: nothing refers to it yet, so it and the blocks it needs stay. Nothing goes
/// from a drawing too big for that scan: an unused entry stays, but a used one would be lost.
fn drop_unused_new(d: &mut Drawing, before: &TableNames, keep: &str) {
if !scan_reads_everything(d) {
return;
}
// Removing a dimension style frees its arrowhead block, which an earlier table already
// scanned: scan again until a pass removes nothing (a chain is never longer than the tables).
for _ in 0..MERGED.len() {
if !drop_unused_pass(d, before, keep) {
break;
}
}
}
/// One scan of the merged tables; `true` when it removed something.
fn drop_unused_pass(d: &mut Drawing, before: &TableNames, keep: &str) -> bool {
let mut removed = false;
for (kind, old) in &before.0 {
// Nothing was added to this table: nothing to scan for.
if names_of(d, *kind).is_subset(old) {
continue;
}
let keep_blocks = if matches!(kind, Kind::Blocks) { reachable(d, vec![keep.to_string()]) } else { BTreeSet::new() };
let fresh: BTreeSet<String> = candidates(d, *kind)
.into_iter()
.filter(|n| !old.contains(&n.to_ascii_lowercase()) && !keep_blocks.contains(&n.to_ascii_uppercase()))
.map(|n| n.to_ascii_lowercase())
.collect();
let gone = |name: &str| fresh.contains(&name.to_ascii_lowercase());
removed |= !fresh.is_empty();
match kind {
Kind::Blocks => d.blocks.retain(|k, _| !gone(k)),
Kind::Dimstyles => d.dim_styles.retain(|t| !gone(&t.name)),
Kind::MleaderStyles => d.mleader_styles.retain(|t| !gone(&t.name)),
Kind::MlineStyles => d.mline_styles.retain(|t| !gone(&t.name)),
Kind::TableStyles => d.table_styles.retain(|t| !gone(&t.name)),
Kind::Layers => d.layers.retain(|t| !gone(&t.name)),
Kind::Linetypes => d.linetypes.retain(|t| !gone(&t.name)),
Kind::TextStyles => d.text_styles.retain(|t| !gone(&t.name)),
_ => {}
}
}
removed
}
/// Add the source's layers, linetypes and styles that this drawing doesn't have (a name that
/// exists keeps this drawing's definition).
fn merge_tables(d: &mut Drawing, src: &Drawing) {
use crate::cmd::merge::merge_named as merge;
merge(&mut d.layers, &src.layers, |l| &l.name);
merge(&mut d.linetypes, &src.linetypes, |l| &l.name);
merge(&mut d.text_styles, &src.text_styles, |t| &t.name);
merge(&mut d.dim_styles, &src.dim_styles, |t| &t.name);
merge(&mut d.mleader_styles, &src.mleader_styles, |t| &t.name);
merge(&mut d.table_styles, &src.table_styles, |t| &t.name);
merge(&mut d.mline_styles, &src.mline_styles, |t| &t.name);
}
/// The names the copied source blocks take, found as `Drawing::block` finds a block: a reference
/// may spell a name differently from its definition.
struct Renames {
exact: BTreeMap<String, String>,
upper: BTreeMap<String, String>,
}
impl Renames {
fn new(exact: BTreeMap<String, String>) -> Self {
let mut upper = BTreeMap::new();
for (from, to) in &exact {
upper.entry(from.to_ascii_uppercase()).or_insert_with(|| to.clone());
}
Renames { exact, upper }
}
fn get(&self, name: &str) -> Option<&String> {
self.exact.get(name).or_else(|| self.upper.get(&name.to_ascii_uppercase()))
}
}
/// Point the dimension styles the source brought at their renamed arrowhead blocks. The styles
/// this drawing already had (`own`) name this drawing's blocks.
fn rename_style_arrows(d: &mut Drawing, own: &BTreeSet<String>, renames: &Renames) {
for st in d.dim_styles.iter_mut().filter(|t| !own.contains(&t.name.to_ascii_lowercase())) {
for arrow in [&mut st.arrow_block, &mut st.arrow_block1, &mut st.arrow_block2, &mut st.leader_arrow_block] {
if let Some(n) = renames.get(arrow.trim()) {
arrow.clone_from(n);
}
}
}
}
/// A copy of a source entity for this drawing: a fresh handle, block references renamed, and
/// links to other source objects (associative dimension points) dropped.
fn adopt(d: &mut Drawing, src: &Drawing, e: &Entity, renames: &Renames) -> Entity {
let mut e = e.clone();
let old = e.handle;
e.handle = d.new_handle();
// An attribute definition keeps its field: its extension dictionary and the objects in it.
if matches!(e.kind, EntityKind::AttDef(_))
&& let Some(root) = src.foreign.entities.get(&old).and_then(|x| x.xdict)
{
let tree = src.foreign.tree(root);
let fresh: Vec<Handle> = (0..tree.len() + 2).map(|_| d.new_handle()).collect();
let foreign = Arc::make_mut(&mut d.foreign);
foreign.adopt_tree(&src.foreign, &tree, &fresh, e.handle);
foreign.entities.entry(e.handle).or_default().xdict = fresh.first().copied();
}
match &mut e.kind {
EntityKind::Insert(i) => {
if let Some(n) = renames.get(&i.block) {
i.block = n.clone();
}
}
EntityKind::Dimension(dm) => {
dm.assoc.clear();
if let Some(n) = dm.block.as_ref().and_then(|b| renames.get(b)) {
dm.block = Some(n.clone());
}
for (key, value) in dm.overrides.iter_mut() {
// Only a block that was renamed changes the value: a number naming a block that
// kept its name stays as it was given.
if is_arrow_override(key)
&& let Some(b) = override_name(value)
&& let Some(n) = renames.get(&b).filter(|n| **n != b)
{
*value = json!(n);
}
}
}
EntityKind::MLeader(m) => {
if let Some(b) = &mut m.block
&& let Some(n) = renames.get(&b.block)
{
b.block = n.clone();
}
}
_ => {}
}
e
}
/// Replace block reference `h` by the objects of its block (an exploded insertion).
pub(super) fn explode_insert(s: &mut Session, h: Handle) -> Result<Vec<Handle>> {
let space = s.space();
let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?;
let parts = explode_kind(s.doc()?, &e).unwrap_or_default();
let d = s.doc_mut()?;
d.remove_entity(h);
let mut out = Vec::new();
for mut p in parts {
p.handle = d.new_handle();
out.push(p.handle);
if let Some(st) = d.space_mut(&space) {
st.push(p);
}
}
Ok(out)
}
/// The JSON INSERT parameters with `file` defined as a block and `*name` as `explode: true`.
pub(super) fn json_params(s: &mut Session, p: &Value) -> Result<Value> {
let mut p = p.clone();
let mut name = str_param(&p, "name").map(str::trim).map(str::to_string);
if let Some(n) = name.as_deref().and_then(|n| n.strip_prefix('*')) {
name = Some(n.trim().to_string());
p["explode"] = json!(true);
}
if let Some(path) = str_param(&p, "file").map(str::to_string) {
let n = name.clone().filter(|n| !n.is_empty()).unwrap_or_else(|| stem(&path));
name = Some(FileRef { name: n, path, explicit: true }.define(s)?);
}
if let Some(n) = name {
p["name"] = json!(n);
}
Ok(p)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn file_names_become_block_names() {
assert_eq!(stem("C:\\parts\\bolt.dxf"), "bolt");
assert_eq!(stem("/parts/nut.v2.DWG"), "nut.v2");
assert_eq!(stem("washer"), "washer");
let s = Session::new();
let f = file_ref(&s, "M8=parts/bolt.dwg").unwrap();
assert_eq!((f.name.as_str(), f.path.as_str(), f.explicit), ("M8", "parts/bolt.dwg", true));
let f = file_ref(&s, "bolt=").unwrap();
assert_eq!((f.name.as_str(), f.path.as_str()), ("bolt", "bolt"));
assert_eq!(file_ref(&s, "C:\\parts\\bolt.dxf").map(|f| f.name), Some("bolt".into()));
assert!(file_ref(&s, "BOLT").is_none());
}
/// A block holding very many references still reaches every block it needs.
#[test]
fn a_block_of_many_references_keeps_all_it_needs() {
let reference = |handle: u64, block: &str| {
let insert: cadcraft_doc::Insert = serde_json::from_value(json!({ "block": block, "insert": [0, 0, 0] })).unwrap();
Entity::new(Handle(handle), EntityKind::Insert(insert))
};
let mut big = Block::new("Big");
big.entities.push(reference(0x100, "Deep"));
for i in 0..100_001 {
big.entities.push(reference(0x200 + i, "Leaf"));
}
let mut d = Drawing::default();
d.blocks.insert("Big".into(), Arc::new(big));
d.blocks.insert("Deep".into(), Arc::new(Block::new("Deep")));
d.blocks.insert("Leaf".into(), Arc::new(Block::new("Leaf")));
assert!(reachable(&d, vec!["Big".into()]).contains("DEEP"));
}
/// A drawing with very many references does not lose the arrowhead of a merged dimension
/// style: the arrowheads are the last thing PURGE's walk looks at.
#[test]
fn many_references_keep_a_merged_arrowhead() {
let mut d = Drawing::new_metric();
d.blocks.insert("Leaf".into(), Arc::new(Block::new("Leaf")));
for i in 0..100_001 {
let insert: cadcraft_doc::Insert = serde_json::from_value(json!({ "block": "Leaf", "insert": [0, 0, 0] })).unwrap();
d.model.push(Entity::new(Handle(0x200 + i), EntityKind::Insert(insert)));
}
let before = TableNames::of(&d);
d.blocks.insert("Tip".into(), Arc::new(Block::new("Tip")));
d.dim_styles.push(cadcraft_doc::DimStyle { name: "Late".into(), arrow_block: "Tip".into(), ..Default::default() });
d.header.set_str("DIMSTYLE", "Late");
d.blocks.insert("Merged".into(), Arc::new(Block::new("Merged")));
drop_unused_new(&mut d, &before, "Merged");
assert!(d.block("Tip").is_some());
}
/// Past the purge scan's limit nothing is called unused: a merged block's dimension style and
/// layer stay even when the scan never reaches its objects.
#[test]
fn a_drawing_too_big_for_the_scan_keeps_what_was_merged() {
let mut s = Session::new();
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap();
let mut dim = (**s.doc().unwrap().model.iter().next().unwrap()).clone();
dim.common.layer = "Late".into();
if let EntityKind::Dimension(dm) = &mut dim.kind {
dm.style = "Late".into();
}
// One definition under many names: millions of objects for the scan, thousands in memory.
let mut filler = Block::new("Filler");
for i in 0..10_000 {
filler.entities.push(Entity::new(Handle(0x1000 + i), dim.kind.clone()));
}
let filler = Arc::new(filler);
let mut d = Drawing::new_metric();
for i in 0..501 {
d.blocks.insert(format!("F{i:03}"), filler.clone());
}
let before = TableNames::of(&d);
assert!(!scan_reads_everything(&d));
d.layers.push(cadcraft_doc::Layer { name: "Late".into(), ..Default::default() });
d.dim_styles.push(cadcraft_doc::DimStyle { name: "Late".into(), ..Default::default() });
// Sorted after every filler, so past the limit.
let mut merged = Block::new("Z");
merged.entities.push(dim);
d.blocks.insert("Z".into(), Arc::new(merged));
drop_unused_new(&mut d, &before, "Z");
assert!(d.layers.iter().any(|l| l.name == "Late"));
assert!(d.dim_styles.iter().any(|t| t.name == "Late"));
}
#[test]
fn inserted_file_brings_its_mline_styles() {
let mut src = Drawing::default();
src.mline_styles.push(cadcraft_doc::MLineStyle { name: "WALL".into(), ..Default::default() });
let mut d = Drawing::default();
merge_tables(&mut d, &src);
assert!(d.mline_styles.iter().any(|m| m.name == "WALL"));
// A style this drawing already has keeps its own definition.
let before = d.mline_styles.len();
merge_tables(&mut d, &src);
assert_eq!(d.mline_styles.len(), before);
}
/// A block reference, for the fixtures below.
fn reference(handle: u64, block: &str) -> Entity {
let insert: cadcraft_doc::Insert = serde_json::from_value(json!({ "block": block, "insert": [0, 0, 0] })).unwrap();
Entity::new(Handle(handle), EntityKind::Insert(insert))
}
/// An anonymous block `*U1` that its description tells apart.
fn anonymous(description: &str) -> Arc<Block> {
let mut b = Block::new("*U1");
b.description = description.into();
Arc::new(b)
}
/// Takes `model`, whose `*U1` is the file's, into a drawing with a `*U1` of its own, and says
/// which of the two the one object of block "Part" refers to.
fn colliding_block_after_import(model: Entity) -> String {
let mut src = Drawing::new_metric();
src.blocks.insert("*U1".into(), anonymous("from the file"));
src.model.push(model);
let mut s = Session::new();
s.doc_mut().unwrap().blocks.insert("*U1".into(), anonymous("from the drawing"));
define_from(&mut s, &src, "Part", true).unwrap();
let d = s.doc().unwrap();
let part = d.block("Part").unwrap();
let to = part.entities.iter().next().and_then(|e| referenced_block(e)).unwrap();
d.block(&to).unwrap().description.clone()
}
/// Block names are case-insensitive, so `*u1` is the file's `*U1` and takes its new name.
#[test]
fn a_renamed_block_is_found_whatever_the_case_of_the_reference() {
assert_eq!(colliding_block_after_import(reference(0x500, "*u1")), "from the file");
}
/// The block content of a multileader takes the new name like any other reference.
#[test]
fn a_multileader_follows_its_renamed_block() {
let EntityKind::Insert(content) = reference(0x500, "*U1").kind else { return };
let mut m: cadcraft_doc::MLeader =
serde_json::from_value(json!({ "leaders": [], "landing": [0, 0, 0], "dogleg": 0.0, "text": null })).unwrap();
m.block = Some(content);
assert_eq!(colliding_block_after_import(Entity::new(Handle(0x501), EntityKind::MLeader(m))), "from the file");
}
/// An arrowhead override given as a number names its block: the block comes along, and the
/// override is left as given when the block keeps its name.
#[test]
fn a_numeric_arrowhead_override_brings_its_block() {
let mut s = Session::new();
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap();
let mut dim = (**s.doc().unwrap().model.iter().next().unwrap()).clone();
if let EntityKind::Dimension(dm) = &mut dim.kind {
dm.overrides.insert("DIMBLK1".into(), json!(45));
}
let mut src = Drawing::new_metric();
src.blocks.insert("45".into(), Arc::new(Block::new("45")));
src.model.push(dim);
let mut t = Session::new();
define_from(&mut t, &src, "Part", true).unwrap();
let d = t.doc().unwrap();
assert!(d.block("45").is_some());
let e = d.block("Part").unwrap().entities.iter().next().unwrap().clone();
let EntityKind::Dimension(dm) = &e.kind else { panic!("not a dimension") };
assert_eq!(dm.overrides["DIMBLK1"], json!(45));
}
/// Arrowheads are references too: a dimension style that came along and a dimension's override
/// follow the renamed block, and a style this drawing already had keeps its own.
#[test]
fn arrowheads_follow_a_renamed_block() {
let mut s = Session::new();
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap();
let mut dim = (**s.doc().unwrap().model.iter().next().unwrap()).clone();
if let EntityKind::Dimension(dm) = &mut dim.kind {
dm.style = "Came".into();
dm.overrides.insert("DIMBLK1".into(), json!("*U1"));
}
let style = |name: &str| cadcraft_doc::DimStyle { name: name.into(), arrow_block: "*U1".into(), ..Default::default() };
let mut src = Drawing::new_metric();
src.blocks.insert("*U1".into(), anonymous("from the file"));
src.dim_styles.extend([style("Came"), style("Own")]);
src.model.push(dim);
let mut t = Session::new();
let d = t.doc_mut().unwrap();
d.blocks.insert("*U1".into(), anonymous("from the drawing"));
d.dim_styles.push(style("Own"));
define_from(&mut t, &src, "Part", true).unwrap();
let d = t.doc().unwrap();
let of = |name: &str| d.block(name).unwrap().description.clone();
let arrow = |name: &str| d.dim_styles.iter().find(|st| st.name == name).unwrap().arrow_block.clone();
assert_eq!(of(&arrow("Came")), "from the file");
assert_eq!(of(&arrow("Own")), "from the drawing");
let e = d.block("Part").unwrap().entities.iter().next().unwrap().clone();
let EntityKind::Dimension(dm) = &e.kind else { return };
assert_eq!(of(dm.overrides["DIMBLK1"].as_str().unwrap()), "from the file");
}
/// What the objects of an imported block name comes along, directly or through another table:
/// a leader's dimension style, a dimension's text style override, the text style in a linetype,
/// an attribute's layer and multiline text style, here on a block reference and on a
/// multileader's block content. What nothing names stays out.
#[test]
fn an_import_keeps_every_style_and_layer_its_objects_name() {
let mut s = Session::new();
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap();
let mut dim = (**s.doc().unwrap().model.iter().next().unwrap()).clone();
if let EntityKind::Dimension(dm) = &mut dim.kind {
dm.overrides.insert("DIMTXSTY".into(), json!("InOverride"));
}
let attrib = |style: &str, layer: &str| {
let mut a: cadcraft_doc::Attrib = serde_json::from_value(json!({
"tag": "A",
"text": { "insert": [0, 0, 0], "height": 1.0, "value": "1" },
"multiline": { "mtext": { "insert": [0, 0, 0], "height": 1.0, "contents": "1", "style": style }, "readAs": "1" },
}))
.unwrap();
a.props.layer = Some(layer.into());
a
};
let mut placed = reference(0x500, "Inner");
if let EntityKind::Insert(i) = &mut placed.kind {
i.attribs.push(attrib("InAttribute", "OnAttribute"));
}
let EntityKind::Insert(mut content) = reference(0x501, "Inner").kind else { return };
content.attribs.push(attrib("InContent", "OnContent"));
let mut multileader: cadcraft_doc::MLeader =
serde_json::from_value(json!({ "leaders": [], "landing": [0, 0, 0], "dogleg": 0.0, "text": null })).unwrap();
multileader.block = Some(content);
let leader: cadcraft_doc::Leader = serde_json::from_value(json!({ "vertices": [], "style": "ForLeader" })).unwrap();
let line = cadcraft_doc::Line { a: cadcraft_geom::Vec3::ZERO, b: cadcraft_geom::Vec3::new(1.0, 0.0, 0.0) };
let mut line = Entity::new(Handle(0x502), EntityKind::Line(line));
line.common.linetype = "WithText".into();
let mut src = Drawing::new_metric();
src.blocks.insert("Inner".into(), Arc::new(Block::new("Inner")));
for name in ["InOverride", "InAttribute", "InContent", "InLinetype", "Spare"] {
let mut t = src.text_styles[0].clone();
t.name = name.into();
src.text_styles.push(t);
}
for name in ["OnAttribute", "OnContent", "Unused"] {
src.layers.push(cadcraft_doc::Layer { name: name.into(), ..Default::default() });
}
let dash = cadcraft_doc::DashElement { style: Some("InLinetype".into()), ..cadcraft_doc::DashElement::dash(1.0) };
src.linetypes.push(cadcraft_doc::Linetype { name: "WithText".into(), description: String::new(), pattern: vec![dash] });
src.dim_styles.push(cadcraft_doc::DimStyle { name: "ForLeader".into(), ..Default::default() });
src.model.push(dim);
src.model.push(placed);
src.model.push(Entity::new(Handle(0x503), EntityKind::MLeader(multileader)));
src.model.push(Entity::new(Handle(0x504), EntityKind::Leader(leader)));
src.model.push(line);
let mut t = Session::new();
define_from(&mut t, &src, "Part", true).unwrap();
let d = t.doc().unwrap();
let styles: Vec<&str> = d.text_styles.iter().map(|t| t.name.as_str()).collect();
for name in ["InOverride", "InAttribute", "InContent", "InLinetype"] {
assert!(styles.contains(&name), "{name}: {styles:?}");
}
assert!(!styles.contains(&"Spare"), "{styles:?}");
let layers: Vec<&str> = d.layers.iter().map(|l| l.name.as_str()).collect();
assert!(layers.contains(&"OnAttribute") && layers.contains(&"OnContent"), "{layers:?}");
assert!(!layers.contains(&"Unused"), "{layers:?}");
assert!(d.dim_styles.iter().any(|st| st.name == "ForLeader"));
}
/// The text style of a table style's cell style is in use.
#[test]
fn a_table_style_keeps_its_cell_styles_text_style() {
let mut d = Drawing::new_metric();
let mut t = d.text_styles[0].clone();
t.name = "InCell".into();
d.text_styles.push(t);
let mut cell = cadcraft_doc::TableStyle::default().cell_style("Data");
cell.text_style = "InCell".into();
d.table_styles[0].cell_styles.push(cell);
assert!(!candidates(&d, Kind::TextStyles).iter().any(|n| n == "InCell"));
}
/// A linetype of the file stays when a dimension style that came along names it, and stays out
/// when only a style that did not come along does.
#[test]
fn a_linetype_follows_the_dimension_style_that_names_it() {
let mut s = Session::new();
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap();
let mut dim = (**s.doc().unwrap().model.iter().next().unwrap()).clone();
if let EntityKind::Dimension(dm) = &mut dim.kind {
dm.style = "Used".into();
}
let mut src = Drawing::new_metric();
for name in ["Kept", "Left"] {
let mut lt = src.linetypes[0].clone();
lt.name = name.into();
src.linetypes.push(lt);
}
src.dim_styles.push(cadcraft_doc::DimStyle { name: "Used".into(), dim_linetype: "Kept".into(), ..Default::default() });
src.dim_styles.push(cadcraft_doc::DimStyle { name: "Spare".into(), ext_linetype1: "Left".into(), ..Default::default() });
src.model.push(dim);
let mut t = Session::new();
define_from(&mut t, &src, "Part", true).unwrap();
let d = t.doc().unwrap();
assert!(d.linetypes.iter().any(|l| l.name == "Kept"));
assert!(!d.dim_styles.iter().any(|st| st.name == "Spare"));
assert!(!d.linetypes.iter().any(|l| l.name == "Left"));
}
}