Compare commits

..
49 Commits
Author SHA1 Message Date
Tanish Manku 198c36b406 Merge #2765: images refuse oversized data before decoding 2026-11-19 15:33:03 -07:00
Tanish Manku 2101a81d62 Merge #2821: hostile-input fixes for SVG import and AutoLISP step accounting
No textual conflict, but main's #2072 (Nov 18) and this PR both fixed the
transformed-ellipse axis: #2072 takes the eigenvector of B*B^T (a drawing-
plane direction), this PR the eigenvector of B^T*B mapped through B. The
clean merge mixed the two (B*B^T's eigenvector mapped through B again).
Kept #2072's computation and this PR's convention that `major` is the axis
from the centre: major = axis * s_max. #2072's test measured `major - centre`
(the old absolute-point convention); it now reads `major` itself.
2026-11-19 15:32:44 -07:00
Tanish Manku 2827ccb6c8 Merge #2820: SHX fonts: a points bound on the glyph cache 2026-11-19 15:31:26 -07:00
Tanish Manku 8ec1e9a0a5 Stack t1: #1276: the reader's band reservations end with the read
reserved_handles only bridges a record read before its section is placed.
Kept on the drawing it was cloned with every undo snapshot, one entry per
band handle a file names. Once every record is placed the objects keep their
handles from new ones themselves, so the reader empties it.
2026-11-19 15:30:55 -07:00
Tanish Manku b184454275 Stack t1: #1276: run the exhausted-handles DXF round trip (#1921)
The writer now numbers its records past the top of the range in the
reserved band, skipping the drawing's handles, so the save no longer
repeats the model space record's handle.
2026-11-19 15:30:10 -07:00
Tanish Manku 077c054d18 Stack t1: #1276: bound the writer's handle walk
W::next_handle looped until it found a free handle; with the wrap into the
reserved band it could only end by finding one. Bound it by the count of
handles in use, as Drawing::next_handle is. Not reachable in practice (it
needs four billion objects), so there is no test.
2026-11-19 15:29:58 -07:00
Tanish Manku 5eafcc93bb Stack t1: #1276: records added on save after the top handle take free handles
Kept objects and missing application ids are numbered above the largest
handle written. When a file's object holds FFFFFFFFFFFFFFFF that count
saturated, so every added record was written with the object's handle.
Number them past the top in the reserved band instead, skipping handles
already written, with the walk bounded by their count.
2026-11-19 15:29:48 -07:00
Tanish Manku 7c366f7b5a Merge #1276: a handle at the top of the range leaves new objects their own
Conflict in Drawing::new_handle/next_handle with #2514. The resolution keeps
both rules: next_handle (HANDSEED) skips the handles of the file's objects
CADCraft rewrites (foreign.handles, #2514), and in the reserved band above
HANDLE_LIMIT also every handle an object or a reserved file record holds
(#913, #1921); off the top of the range it continues at the bottom of the
band, and new_handle takes exactly what next_handle reports.

The scan over all spaces and block definitions runs only for a candidate in
the band: below it the seed is kept above every object's handle. The walk is
bounded by the count of held handles, counted only once a handle is skipped.
2026-11-19 15:29:11 -07:00
moandClaude Opus 5.5 a39d637814 Merge remote-tracking branch 'origin/main' into parsers-hostile
crates/io/src/svg_read.rs is taken from main (c07b6a2f, the craft-svg based reader) and every SVG fix of this branch is re-applied on top of it, since all of them sit in the conversion of craft-svg's neutral_document shapes into entities, which stays on the cadcraft side: in add_rounded, the ellipse's major axis is the image B*v of the leading eigenvector (relative to the centre, so a rotated ellipse keeps its turn and a sheared circle gets the axes of its image) and the near-orthogonal test scales with the trace instead of a floor of 1 (tiny sheared circle); in add, an entity whose coordinates or extents are not finite (finite, box_finite, bulges_finite) is left out after it is charged against the vertex budget, and counted for a read note of its own, made by notes() apart from the note on what isn't read yet. Nothing is dropped: craft-svg's neutral_document::visit and path_data::parse_path only refuse non-finite numbers as written, not relative steps or transforms that overflow them; the overflow checks of craft-libs#881 (paths.rs, smooth_segments_after_a_close_relative_root_sizes_and_overflowing_steps) cover craft-svg's own paths::import, which cadcraft does not use. Against main's svg_read.rs alone, svg_ellipse_major_axis_is_relative_to_its_centre, svg_rotated_ellipse_keeps_its_turn, svg_sheared_circle_has_the_axes_of_its_image, svg_tiny_sheared_circle_has_the_axes_of_its_image, svg_coordinates_that_overflow_are_left_out, svg_shapes_whose_extents_overflow_are_left_out, svg_too_large_shapes_are_noted_apart_from_unread_content and svg_shapes_become_entities_in_millimetres fail; with the fixes re-applied they pass unchanged. No test is changed or removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:28:18 -05:00
moandClaude Opus 5.5 dc7e5cdd6e Merge remote-tracking branch 'origin/main' into shx-hostile
Main's SHX compiler, container reader and glyph interpreter now come from
craft-shx (#3193, #3194, #3195), so this branch's changes to compile.rs,
parse.rs and program.rs are dropped here (they move to a craft-libs pull
request) and only the points-budgeted glyph cache in mod.rs remains. The
tests of the moved code are removed with it:
a_far_extended_subshape_cell_is_cut_off,
subshape_fan_out_past_the_point_and_step_bounds_is_cut_off,
a_name_is_looked_for_in_its_first_kilobyte_only,
a_name_the_reader_would_drop_does_not_compile,
all_65535_shape_numbers_compile_and_a_repeat_is_found and
a_doubled_minus_sign_is_not_a_number.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:21:35 -05:00
midasmatterhorn e4f9b6aae3 io: the helper also checks the owner of the handle below the band 2026-11-15 22:03:05 +03:00
midasmatterhorn 140437e78e io: reserve a file's band handles before numbering handle-less entities
The handle pre-scan moves the seed past a file's ordinary handles, but
bump_handseed deliberately does not follow one at or above HANDLE_LIMIT
(#913). A handle-less entity read earlier is therefore numbered with the
band's first handle while the ENTITIES record that names it is still
unplaced; when the record is placed, EntityStore::push replaces the file's
entity with the generated handle.

Record the band handles the entity records of BLOCKS and ENTITIES name for
allocation, and have new_handle skip them. Reservation stays separate from
seed bumping: bump_handseed still ignores the reserved band, and a file's
band handles keep their identity.

Tests: a file whose handle-less model-space BLOCKS entity would take the
HANDLE_LIMIT handle of an ENTITIES record, with and without the CADCraft
seed record, keeps all three lines and their handles. Both fail without the
reservation (2 of 3 lines survive).
2026-11-14 18:40:40 +03:00
midasmatterhorn 528e2698fe io: reserve entity handles per section and give generated geometry free handles
Two holes in the handle bookkeeping, both found while checking the review:

- A CADCraft-marked file skips the handle pre-scan, so a handle-less entity
  in BLOCKS took a fresh handle the reader could hand out before a later
  ENTITIES record named the same handle; the second entity then replaced the
  first. Reserve the file's entity handles across BLOCKS and ENTITIES before
  anything is parsed, for marked files too. BLOCK and ENDBLK stay out, so
  structural handles do not move the saved seed.
- Generated dimension/arrowhead/table geometry read the writer's cursor
  directly. After the cursor skips an occupied handle its next value can be
  occupied too, so the generated records could reuse one of the drawing's
  handles; take them from next_handle, which skips every used handle.

Tests: a marked file with a handle-less block entity and an ENTITIES record
naming the same handle, and a drawing whose band handles make the writer wrap
while saving a dimension, both keep every handle distinct.
2026-11-14 17:18:05 +03:00
midasmatterhorn 764204540a engine: AUDIT finds ordinary handles behind a reserved-band one
A handle at or above HANDLE_LIMIT is deliberately not followed, but taking
the maximum over every handle let one such handle hide every ordinary one
behind it: the seed was never repaired past them and AUDIT reported a clean
drawing. Leave the reserved band out of the maximum, and cover a drawing
with both kinds of handle.
2026-11-14 17:17:20 +03:00
midasmatterhorn a516ce11eb io: a seed in the reserved band never hands out a handle an object holds
new_handle takes the first handle at or above the seed that no space or block
definition uses, wrapping into the band above HANDLE_LIMIT at the top of the
range. The writer's structural records skip the drawing's handles too, so a
file whose own handles sit at the bottom of the band is saved with distinct
records. AUDIT no longer reports the preserved top handles as a seed error its
own repair never fixes.
2026-11-13 00:03:08 +03:00
midasmatterhorn 03baa73ae5 Merge remote-tracking branch 'upstream/main' into pr-1276 2026-11-12 23:15:16 +03:00
moandClaude Opus 5.5 797c5df792 Merge remote-tracking branch 'origin/main' into parsers-hostile
main's #2741 makes nested callbacks share one allowance through
callback_used/callback_ceiling, which replaces this branch's own cap check in
call_sync. This branch's list-walk work counting, now also charged to
callback_used inside a callback, and the charging of a callback's work to its
caller's step are kept on top, through a callback_work field so that work is
not counted against callback_used twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 05:04:09 -05:00
wovadiandClaude Opus 5.5 736f56d320 Images: the full-path check is for builds that read files
`full_path` serves only the file read, which the web build doesn't have: it is
left out there, so the wasm check has no dead-code warning for it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:33:17 +01:00
wovadi a9b93676a4 Merge remote-tracking branch 'origin/main' into fix/image-attach-limits 2026-11-10 16:20:05 +01:00
wovadiandClaude Opus 5.5 19fc1f20be Images: line breaks in data don't count toward its limit; full Windows paths get no hint
Review follow-ups on #2765:
- The length check before decoding counts the base64 characters, not the line
  breaks and spaces decoding skips, so MIME-wrapped data of a file just under
  256 MB is taken. The whole text is still bounded (6% over the limit), which
  also bounds what decoding sets aside.
- A full Windows path (a drive or a share), which Linux and macOS read as
  relative, no longer gets "save the drawing first, or give a full path".
- The test sends text that isn't base64, so only the check before decoding
  gives the size message, and it no longer builds 0.6 GB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:20:05 +01:00
moandClaude Opus 5.5 31866fcf05 Merge remote-tracking branch 'origin/main' into parsers-hostile
The relative-height cap in crates/fonts/src/mtext.rs is taken from main (#1036),
which bounds a compounding `\H…x;` to 1e-3..1e3 times the MTEXT's own height; the
MAX_HEIGHT cap and its test from f13a1f2e are dropped as redundant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 06:38:11 -05:00
moandClaude Opus 5.5 ed8555875a LISP: a routine is charged the work its slices did
The driver added the slice length at each yield, so one step walking a
long list or running a long synchronous callback was charged as 400000
steps and a blocking routine could pass its cap by that work. It now adds
the machine's used steps after every slice and stops a waiting blocking
routine once they pass the cap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 10:40:50 -05:00
moandClaude Opus 5.5 6f862d7b4b SVG import: a tiny sheared ellipse keeps the axes of its image
The orthogonal-axes test now scales with the shape instead of using an
absolute floor, so a sub-micrometre sheared circle no longer takes one
of its skewed columns as the major axis.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 10:06:20 -05:00
moandClaude Opus 5.5 b1a34dc0ef SVG import: a rotated or sheared ellipse keeps the orientation of its image
The major axis was the leading eigenvector of the basis's Gram matrix scaled
to the semi-major length, but that eigenvector is a direction in the
ellipse's parameter space, not in the drawing, so a rotated ellipse came in
axis-aligned. The major axis is now that direction mapped through the basis.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:33:59 -05:00
moandClaude Opus 5.5 f24da7a85b SVG import: shapes too large to represent are noted as invalid, apart from what isn't read yet
A shape whose coordinates or extents overflow was listed under "CADCraft
doesn't read these yet", as if support were missing; the file itself is at
fault. Such shapes now get a read note of their own saying they were left out
as invalid, and the note on unread content keeps its wording.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 08:59:25 -05:00
moandClaude Opus 5.5 6a240a7076 SVG import: the finiteness check names every entity kind, so a new one must be decided
`finite` ended in a wildcard that passed any other kind unchecked, so a kind
the reader came to make later would skip the check silently. The kinds the
reader doesn't make are now listed, and a new `EntityKind` variant fails to
compile until it is placed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 08:58:18 -05:00
moandClaude Opus 5.5 f903621540 LISP: the long-list slice test measures the walk's charge, not the time it takes
The test ran `(while t (length l))` through the session and passed on main as
well, where the first slice walked the list for its whole budget before
yielding. It now builds a 32768-cell list in one run and gives a single
`(length l)` a 1000-step slice: the slice yields after the walk and the run
reports more than 32768 steps, where counting the walk as one step finished
`length` inside the slice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 08:57:57 -05:00
moandClaude Opus 5.5 063cbef279 SVG import: a shape whose extents overflow is left out too, not only one whose coordinates do
A circle with a finite centre and radius can still reach past the largest
number (`<circle cx="1" r="1"/>` under `scale(1e308)`), and so can an ellipse
whose box is wider than its axis or a polyline arc between finite vertices;
their bounds came out infinite or silently cut short. Such a shape is now left
out and counted in the read note like one with overflowing coordinates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:19:56 -05:00
moandClaude Opus 5.5 51f38b4eda SVG import: a shape left out for overflowing coordinates still counts against the vertex budget
The finiteness check came before the vertex charge, so a left-out shape cost
nothing, and a file of paths flattening to non-finite vertices did all that
work where the 8,000,000-vertex budget used to stop it. Each shape is now
charged first and then checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:15:23 -05:00
moandClaude Opus 5.5 348d767b93 LISP: each synchronous callback's cap counts only its own steps
Work the caller had queued before a callback (its list walks, and the charged
steps of the callbacks before it in the same step) was drained into the
callback's own count, so a `vl-sort` comparison counted every earlier
comparison too and the per-callback cap held for the whole sort. That work is
now set aside when a callback starts and charged back with the callback's own
steps, so the enclosing run still sees all of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:15:23 -05:00
moandClaude Opus 5.5 82779b50d0 SHX fonts: shape source with a name over 1,024 bytes is an error
The reader drops a record whose name runs on past 1,024 bytes, so such a source compiled into
a file without that shape. The error names the line of the definition.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:09:13 -05:00
moandClaude Opus 5.5 09d2e06862 SHX fonts: a glyph outlined by two threads at once is counted in the cache once
Both missed the cache, both outlined, and the second insert replaced the first entry while
its points were added again, so the point bound cleared the cache early. The later thread
now takes the entry already there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:08:22 -05:00
moandClaude Opus 5.5 16e0fa5293 SVG import: an ellipse's major axis is relative to its centre, not a point
`Ellipse::major` is a vector from the centre everywhere else (the DXF reader
and writer keep group 11 as the DXF Reference defines it, and rendering takes
its length as the radius), but the SVG reader stored the absolute point
centre + axis, so every ellipse away from the origin, and every circle under a
non-uniform transform, came in with the wrong axis length and direction. The
existing shapes test measured `major - center` and so passed with the absolute
point; it now reads `major` as the vector.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 00:21:17 -05:00
moandClaude Opus 5.5 f13a1f2e39 MTEXT: a relative height code grows no further than the largest absolute one
`\H1000x;` multiplied the current height each time it was read, so a run of
them made the height infinite and the laid-out strokes and bounds infinite or
NaN. A relative height now stops at the 1e6 an absolute `\H` may set (or the
height it starts from, when that is larger).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 00:16:17 -05:00
moandClaude Opus 5.5 44b0399aa6 LISP: a step's list walking and callback steps count against the slice, so a routine always yields
A machine step counted as one whatever it did: `(while t (length l))` over a
long list walked 400000 lists per slice and never gave the interface a frame,
and a callback retrying an endless inner callback gave each try a fresh cap
(10000^3 steps at three levels). List cells walked and the steps of synchronous
callbacks now count as steps of the step that made them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 00:16:17 -05:00
moandClaude Opus 5.5 bb91014ebd SHX fonts: shape source finds a repeated shape number with a set, not a scan
Each definition was compared with every one before it: 65,535 shapes (an 821 KB source)
took 2.8 s to compile. The error still names the line of the repeat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:53:42 -05:00
moandClaude Opus 5.5 b439879181 SHX fonts: look for a shape name's terminator in its first 1,024 bytes only
Big font index entries may point anywhere, so their records may overlap: 65,535 entries over
one 64 KB run without a NUL were each searched to the end, 4 G bytes and 1.7 s to read a
576 KB file (83 ms now). A record whose name runs on is dropped, as one without a terminator
was.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:53:42 -05:00
moandClaude Opus 5.5 5154f5757b SHX fonts: bound a font's glyph cache by its points as well as its glyphs
The cache was bounded only by count (16,384 glyphs), so a font whose glyphs are all at the
point bound could keep 2 GB alive for as long as it stays loaded. It is now also cleared
before it holds more than 2^20 points (16 MB).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:53:42 -05:00
moandClaude Opus 5.5 661e5e2dd9 SHX fonts: bound a glyph to 8,192 points and 32,768 steps
Every character of a text may draw a glyph's full budget, so the budget is what a small
hostile font multiplies: with 50,000 points and 200,000 steps an 11 KB font drew a
1,000-character line in 3 s and 1.7 GB, and a 21 KB one took 6.4 s to measure 2,000
characters. The new bounds still leave 128 full circles or 16 shapes of the format's
2,000 bytes per glyph.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:53:42 -05:00
moandClaude Opus 5.5 225407ca61 SHX fonts: an extended big font subshape cell is held to the coordinate bound
The cell offset of code 7,0 moved the pen without the check every other move has: nested
255-unit cells put it 255^n units away, and a location pushed there and popped became the
advance (1e33) or a stroke's first point past the bound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:53:42 -05:00
moandClaude Opus 5.5 01c003e407 SHX fonts: a shape source number with a doubled minus sign is an error, not an overflow
`--9223372036854775808` (or `-0-8000000000000000`) parsed its digits to i64::MIN and then
negated it, which panics with overflow checks on; any other doubled minus read as the
magnitude, so `*BIGFONT 4,--9223372036854775807` pushed escape ranges until 8 GB failed to
allocate (a 92-million count from a 161-byte source took 512 MB). Magnitudes must be
0..=0xFFFF.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:53:42 -05:00
moandClaude Opus 5.5 50644fb0c4 SVG import: shapes whose coordinates overflow to infinity or NaN are left out and noted
Finite numbers still overflow through transforms and relative path steps
(`M1e308 0 l1e308 0`, `scale(1e308)`), and the reader added the entities with
infinite or NaN coordinates, which break extents and rendering and change on a
DXF save. Such a shape is now skipped and counted in the read note.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:46:54 -05:00
zwork 23c55fc1a8 io: drop the renumbering plumbing the handle fix no longer needs 2026-11-04 17:51:09 +03:00
zwork 1a1d8404b6 io: a handle near the top of the range keeps its identity
Merged current main, which keeps a file's handles exactly as written: the
branch no longer renumbers them. A seed above HANDLE_LIMIT is not followed,
so new objects are allocated from the reserved range and never replace the
file's own object (#913). Round-trip handles near 2^64 survive a save.
2026-11-04 17:50:39 +03:00
wovadiandClaude Opus 5.5 f998f2f663 Images: check the decoded size of data too
Review follow-up on #2765: the longest base64 text allowed can hold one or two
bytes more than the 256 MB limit (it is not a multiple of three), so the decoded
bytes are checked against the limit as well. The length check before decoding
stays, to bound the allocation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:35:33 +01:00
wovadiandClaude Opus 5.5 f91d5ad38f Images: refuse oversized data before decoding, and say what to do with a relative path in an unsaved drawing
Follow-up to #2505: imageattach checks the length of base64 data against the
256 MB image limit before decoding it, and a relative path in an unsaved drawing
reports "save the drawing first, or give a full path".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 08:52:45 +01:00
midasmatterhorn aaaf654872 io: a group, sortents table or dimension link follows the entity the reader renumbered 2026-10-29 22:42:19 +03:00
midasmatterhorn cfc4fc5e88 Merge remote-tracking branch 'upstream/main' into fix-1276
# Conflicts:
#	crates/io/src/dxf_read.rs
2026-10-29 22:37:45 +03:00
midasmatterhorn bcac20dd5f io: a handle at the top of the range leaves new objects their own 2026-10-15 00:25:48 +03:00
50 changed files with 1281 additions and 2630 deletions
+76 -9
View File
@@ -44,6 +44,11 @@ pub use store::EntityStore;
pub use tables::*;
pub use xclip::{ClipBoundary, MAX_CLIP_VERTICES};
/// Handles at or above this are not followed: a file may name one (an object's handle, or its
/// `$HANDSEED`), and the four billion handles above the limit stay free for the drawing's own
/// growth. A file's handles keep their identity, however high they are (#913, #939).
pub const HANDLE_LIMIT: u64 = u64::MAX - 0xFFFF_FFFF;
/// File data CADCraft doesn't model, kept for saving (#528).
pub mod dynblock;
pub mod foreign;
@@ -127,6 +132,10 @@ pub struct Drawing {
pub scales: Vec<AnnoScale>,
/// Next free handle.
pub handseed: u64,
/// Handles a file's records hold in the reserved band, recorded while reading before the
/// record is placed: [`Drawing::new_handle`] skips them meanwhile. [`Drawing::bump_handseed`]
/// does not follow them (#913). Emptied once the file is read; never written to a file.
pub reserved_handles: BTreeSet<u64>,
/// Objects hidden for this session by ISOLATEOBJECTS / HIDEOBJECTS. Never written to a file:
/// a drawing opens with everything shown again.
pub hidden_objects: BTreeSet<Handle>,
@@ -200,6 +209,7 @@ impl Drawing {
parametric: Parametric::default(),
scales: imperial_scales(),
handseed: 0x100,
reserved_handles: BTreeSet::new(),
hidden_objects: BTreeSet::new(),
read_notes: Vec::new(),
refedit: None,
@@ -209,26 +219,83 @@ impl Drawing {
}
}
/// Allocate a fresh handle. It skips the handles the drawing's file gave the objects CADCraft
/// writes itself ([`foreign::Foreign::handles`]): AutoLISP names those objects by them, and a
/// file CADCraft wrote numbers them above its `$HANDSEED` (#495).
/// Allocate a fresh handle: [`Drawing::next_handle`], with the seed moved past it. Past the
/// top of the range the drawing goes on growing in the reserved band (#913).
pub fn new_handle(&mut self) -> Handle {
let h = self.next_handle();
self.handseed = h.0.saturating_add(1);
self.handseed = h.0.checked_add(1).unwrap_or(HANDLE_LIMIT);
h
}
/// The handle [`Drawing::new_handle`] gives out next (AutoCAD's `HANDSEED`), without taking it.
/// The handle [`Drawing::new_handle`] gives out next (AutoCAD's `HANDSEED`), without taking it:
/// the first one at or above the seed that nothing holds. It skips
/// - the handles the drawing's file gave the objects CADCraft writes itself
/// ([`foreign::Foreign::handles`]): AutoLISP names those objects by them, and a file
/// CADCraft wrote numbers them above its `$HANDSEED` (#495);
/// - handles an object or a file record being read holds in the reserved band above
/// [`HANDLE_LIMIT`]. A hostile or damaged file may name a `$HANDSEED` there, and a file
/// object may hold that same handle; the seed does not follow a file's handles in the band,
/// so taking it as-is would hand the file's object's handle to a new object and
/// `EntityStore` would replace it (#913, #1921);
/// - handle 0, which a file reads as "no handle".
///
/// Off the top of the range it goes on at the bottom of the band.
///
/// Cost: below the band the reader and [`Drawing::bump_handseed`] keep the seed above every
/// handle an object holds (AUDIT repairs a drawing where that fails), and reserved handles are
/// all in the band, so there only `foreign.handles` is looked up. The scan of every space and
/// block definition runs only for a candidate in the band. Every handle skipped is a distinct
/// one something holds, so the walk ends within one step more than the count of held handles.
pub fn next_handle(&self) -> Handle {
let held = |h: u64| {
h == 0
|| self.foreign.handles.contains_key(&Handle(h))
|| (h >= HANDLE_LIMIT && (self.reserved_handles.contains(&h) || self.handle_in_use(Handle(h))))
};
let mut h = self.handseed;
while self.foreign.handles.contains_key(&Handle(h)) && h < u64::MAX {
h = h.saturating_add(1);
// Counted only once a handle is skipped, so the usual first-try answer costs nothing.
let mut steps_left: Option<usize> = None;
while held(h) {
let left = steps_left.get_or_insert_with(|| self.held_handle_count());
let Some(rest) = left.checked_sub(1) else { break };
*left = rest;
h = h.checked_add(1).unwrap_or(HANDLE_LIMIT);
}
Handle(h)
}
/// Whether an object in any space or block definition already holds `h`.
fn handle_in_use(&self, h: Handle) -> bool {
self.model.contains(h) || self.layouts.iter().any(|l| l.entities.contains(h)) || self.blocks.values().any(|b| b.entities.contains(h))
}
/// An upper bound on how many handles [`Drawing::next_handle`] can find held, plus handle 0.
fn held_handle_count(&self) -> usize {
let spaces = self.layouts.iter().map(|l| l.entities.len()).chain(self.blocks.values().map(|b| b.entities.len()));
spaces
.fold(self.model.len(), usize::saturating_add)
.saturating_add(self.foreign.handles.len())
.saturating_add(self.reserved_handles.len())
.saturating_add(1)
}
/// Record a handle a file's record holds in the reserved band, before the record is placed in
/// the drawing, so [`Drawing::new_handle`] does not hand it to an object read earlier (#1276).
///
/// Only handles at or above [`HANDLE_LIMIT`] are recorded: below it [`Drawing::bump_handseed`]
/// already moves the seed past them. The reservation stays separate from the seed because the
/// writer's growth lives above the limit and a file's handles there are not followed (#913).
pub fn reserve_handle(&mut self, h: Handle) {
if h.0 >= HANDLE_LIMIT {
self.reserved_handles.insert(h.0);
}
}
/// Make sure future handles don't collide with `h` (after loading a file).
///
/// A handle at or above [`HANDLE_LIMIT`] is the file's own and stays as it is: it is not
/// followed, so a new object is never given the top handle and the file's object is never
/// replaced (#913). The handles above the limit are the drawing's room to grow.
pub fn bump_handseed(&mut self, h: Handle) {
if h.0 >= self.handseed {
self.handseed = h.0.saturating_add(1);
if h.0 >= self.handseed && h.0 < HANDLE_LIMIT {
self.handseed = h.0 + 1;
}
}
+1 -39
View File
@@ -931,49 +931,11 @@ pub struct Ucs {
pub y_axis: Vec3,
}
/// A saved layer state (LAYERSTATE), as AutoCAD keeps one in the LAYER table's
/// `ACAD_LAYERSTATES` dictionary.
/// A saved layer state (LAYERSTATE).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct LayerState {
pub name: String,
pub layers: Vec<Layer>,
/// The properties restoring sets ([`LayerState::ON`] …): AutoCAD's mask (group 91 of the
/// state's XRECORD). Bits CADCraft doesn't use are kept as read.
pub mask: u32,
/// The layer restoring makes current; empty, or a layer the drawing doesn't have, leaves the
/// current layer as it is (AutoCAD 2024, measured).
pub current: String,
/// Group 301 of the state's XRECORD: empty as AutoCAD 2024's -LAYER saves a state; a text a
/// file holds there is kept.
pub description: String,
}
impl Default for LayerState {
fn default() -> Self {
LayerState { name: String::new(), layers: Vec::new(), mask: LayerState::ALL, current: String::new(), description: String::new() }
}
}
impl LayerState {
pub const ON: u32 = 1;
pub const FROZEN: u32 = 2;
pub const LOCKED: u32 = 4;
pub const PLOT: u32 = 8;
pub const VP_FREEZE_NEW: u32 = 16;
pub const COLOR: u32 = 32;
pub const LINETYPE: u32 = 64;
pub const LINEWEIGHT: u32 = 128;
pub const PLOT_STYLE: u32 = 256;
pub const TRANSPARENCY: u32 = 1024;
/// Every property: the mask of AutoCAD 2024's -LAYER stAte Save with its defaults (2047; bit
/// 512, which no property toggles, is always set).
pub const ALL: u32 = 2047;
/// A state of every property of `layers`, with `current` the layer restoring makes current.
pub fn new(name: impl Into<String>, layers: Vec<Layer>, current: impl Into<String>) -> Self {
LayerState { name: name.into(), layers, current: current.into(), ..LayerState::default() }
}
}
/// A named group of entities (GROUP).
+28
View File
@@ -726,6 +726,34 @@ fn new_handles_skip_the_files_object_handles() {
assert_eq!(d.new_handle(), Handle(next + 3));
}
/// In the reserved band a new handle skips the file's kept object handles (#2514) and the handles
/// objects hold in model space, a layout and a block definition, or that a file record reserved
/// (#913); off the top of the range it goes on at the bottom of the band. HANDSEED reports the
/// handle `new_handle` takes.
#[test]
fn new_handles_in_the_reserved_band_skip_every_held_handle_and_wrap() {
let mut d = Drawing::new_metric();
let top = u64::MAX;
d.model.push(Entity::new(Handle(top - 4), line((0.0, 0.0), (1.0, 0.0))));
let mut sheet = Layout::new("Sheet", 1);
sheet.entities.push(Entity::new(Handle(top - 3), line((0.0, 0.0), (1.0, 0.0))));
d.layouts.push(sheet);
let mut b = Block::new("B");
b.entities.push(Entity::new(Handle(top - 2), line((0.0, 0.0), (1.0, 0.0))));
d.blocks.insert("B".into(), std::sync::Arc::new(b));
std::sync::Arc::make_mut(&mut d.foreign).handles.insert(Handle(top - 1), ("LAYER".into(), "0".into()));
d.reserve_handle(Handle(top));
d.model.push(Entity::new(Handle(HANDLE_LIMIT), line((0.0, 0.0), (1.0, 0.0))));
d.handseed = top - 5;
assert_eq!(d.new_handle(), Handle(top - 5));
assert_eq!(d.next_handle(), Handle(HANDLE_LIMIT + 1), "a held handle was offered");
assert_eq!(d.new_handle(), Handle(HANDLE_LIMIT + 1));
assert_eq!(d.handseed, HANDLE_LIMIT + 2);
// Handle 0 means "no handle" in a file; a seed there moves on.
d.handseed = 0;
assert_eq!(d.new_handle(), Handle(1));
}
/// Several spellings of one DIM field apply once, the last in the map's order, and none is rejected.
#[test]
fn dim_style_spellings_of_one_field_apply_once() {
+7 -1
View File
@@ -319,8 +319,14 @@ fn all_handles(d: &Drawing) -> HashSet<Handle> {
}
/// The next handle is above every handle in use, so new objects never take an existing one.
///
/// A handle at or above [`cadcraft_doc::HANDLE_LIMIT`] is the file's own and is deliberately not
/// followed: the seed never moves past it, and new objects take free handles in the band above
/// the limit. Reporting it would repeat the same repair on every audit, so it is not an issue.
/// Such a handle is left out of the maximum too, or the largest handle would hide every ordinary
/// one behind it and the seed would never be repaired past them.
fn handseed(d: &mut Drawing, out: &mut Vec<Issue>) {
let Some(max) = each_entity(d).map(|e| e.handle).max() else { return };
let Some(max) = each_entity(d).map(|e| e.handle).filter(|h| h.0 < cadcraft_doc::HANDLE_LIMIT).max() else { return };
if max.0 >= d.handseed {
out.push(issue(
"handseed",
+12 -72
View File
@@ -27,10 +27,6 @@ mod edit;
/// Most preview entities drawn while the array is edited.
const PREVIEW_LIMIT: usize = 2000;
/// Most objects whose key points are searched for a Key point base point.
const MAX_KEY_OBJECTS: usize = 10_000;
/// The prompt after the Key point option of a base point.
const KEY_POINT_PROMPT: &str = "Specify key point on source objects to use as base point";
/// Keyword-only prompts: each typed token is matched on its own (no free text).
const KEYWORDS: Accept = Accept { point: false, number: false, text: false, select: false, enter: true };
@@ -45,13 +41,13 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("arrayrect", "Rectangular Array", run_arrayrect)
.menu(&["Modify", "Array", "Rectangular Array"])
.params(
"{handles?, rows, cols, rowSpacing, colSpacing, levels? (1), levelSpacing?, rowElevation?, axisAngle? (degrees), base? ([x, y], default the objects' centre), keyPoint? ([x, y]: the base point is the objects' key point nearest it), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}",
"{handles?, rows, cols, rowSpacing, colSpacing, levels? (1), levelSpacing?, rowElevation?, axisAngle? (degrees), base? ([x, y], default the objects' centre), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}",
)
.interactive(|_| Ok(Box::new(RectM::default()))),
CommandSpec::new("arraypolar", "Polar Array", run_arraypolar)
.menu(&["Modify", "Array", "Polar Array"])
.params(
"{handles?, center, count, angle? (degrees, default 360), rotate?: bool, rows? (1), rowSpacing?, rowElevation?, levels? (1), levelSpacing?, base? ([x, y], default the first object's centre), keyPoint? ([x, y]: the base point is the objects' key point nearest it), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}",
"{handles?, center, count, angle? (degrees, default 360), rotate?: bool, rows? (1), rowSpacing?, rowElevation?, levels? (1), levelSpacing?, base? ([x, y], default the first object's centre), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}",
)
.interactive(|_| Ok(Box::new(PolarM::default()))),
CommandSpec::new("-array", "Array", classic::run_classic)
@@ -250,45 +246,6 @@ fn bounds(d: &Drawing, hs: &[Handle]) -> Bounds2 {
hs.iter().filter_map(|h| d.entity(*h).map(|e| cadcraft_doc::entity_bounds(d, e, 0))).fold(Bounds2::EMPTY, |a, b| a.union(&b))
}
/// The key point of `ents`, placed by `m`, nearest `at`: one of their grips (end points,
/// midpoints, centres, vertices, insertion points). `None` when they have none. More than
/// [`MAX_KEY_OBJECTS`] objects are refused: searching only some could miss the nearest one.
pub(crate) fn nearest_key_point<'a>(ents: impl Iterator<Item = &'a Entity>, m: &Mat3, at: Vec2) -> Result<Option<Vec2>> {
if !at.is_finite() {
return Ok(None);
}
let mut best: Option<(Vec2, f64)> = None;
for (n, e) in ents.enumerate() {
if n >= MAX_KEY_OBJECTS {
return Err(other(format!("Too many objects to search for a key point (at most {MAX_KEY_OBJECTS}); specify a point.")));
}
let mut k = e.kind.clone();
k.transform(m);
for g in k.grips().into_iter().filter(|g| g.is_finite()) {
let d = g.dist(at);
if best.is_none_or(|(_, bd)| d < bd) {
best = Some((g, d));
}
}
}
Ok(best.map(|b| b.0))
}
/// `keyPoint` of a JSON form: absent or null is none; anything else must be a point, rather than
/// be taken as none and the base point found another way.
pub(crate) fn key_point_param(cmd: &str, p: &Value) -> Result<Option<Vec2>> {
match p.get("keyPoint") {
None | Some(Value::Null) => Ok(None),
Some(_) => point_param(p, "keyPoint").map(Some).ok_or_else(|| bad(cmd, "`keyPoint` must be a point [x, y]")),
}
}
/// The key point of objects `hs` in the drawing nearest `at`.
pub(crate) fn key_point_of(d: &Drawing, hs: &[Handle], at: Vec2) -> Result<Vec2> {
nearest_key_point(hs.iter().filter_map(|h| d.entity(*h)).map(|e| &**e), &Mat3::IDENTITY, at)?
.ok_or_else(|| other("The objects have no key point; specify a point."))
}
/// The centre of the first object (the point a non-rotated polar copy is moved by).
fn first_center(d: &Drawing, hs: &[Handle]) -> Option<Vec2> {
hs.first().and_then(|h| d.entity(*h)).map(|e| cadcraft_doc::entity_bounds(d, e, 0).center()).filter(|c| c.is_finite())
@@ -429,10 +386,9 @@ fn run_arrayrect(s: &mut Session, p: &Value) -> Result<Value> {
row_elevation: f64_or(p, "rowElevation", 0.0),
});
let rs = f64_or(p, "rowSpacing", 1.0);
let base = match (key_point_param("arrayrect", p)?, point_param(p, "base")) {
(Some(k), _) => key_point_of(s.doc()?, &hs, k)?,
(None, Some(b)) => b,
(None, None) => Some(bounds(s.doc()?, &hs).center()).filter(|c| c.is_finite()).unwrap_or_default(),
let base = match point_param(p, "base") {
Some(b) => b,
None => Some(bounds(s.doc()?, &hs).center()).filter(|c| c.is_finite()).unwrap_or_default(),
};
let p2 = params(kind, levels, f64_or(p, "levelSpacing", rs));
let associative = bool_or(p, "associative", assoc_default(s));
@@ -446,10 +402,7 @@ fn run_arraypolar(s: &mut Session, p: &Value) -> Result<Value> {
let rows = count_or("arraypolar", p, "rows", 1)?;
let levels = count_or("arraypolar", p, "levels", 1)?;
check_size(s, n.saturating_mul(rows).saturating_mul(levels), hs.len())?;
let base = match key_point_param("arraypolar", p)? {
Some(k) => key_point_of(s.doc()?, &hs, k)?,
None => point_param(p, "base").or_else(|| s.doc().ok().and_then(|d| first_center(d, &hs))).unwrap_or(c),
};
let base = point_param(p, "base").or_else(|| s.doc().ok().and_then(|d| first_center(d, &hs))).unwrap_or(c);
let row_spacing = f64_or(p, "rowSpacing", 1.0);
let fill = f64_or(p, "angle", 360.0);
if !(fill.abs() >= 1e-9 && fill.abs() <= 360.0 + 1e-9) {
@@ -550,8 +503,6 @@ enum RStage {
Main,
Assoc,
Base,
/// Base point: Key point (a grip of the source objects).
BaseKey,
/// COUnt: columns, then rows.
CountCols,
CountRows,
@@ -712,7 +663,6 @@ impl Interactive for RectM {
.default("eXit"),
Assoc => assoc_prompt(self.assoc),
Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"),
BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT),
CountCols | ColsCount => cols(),
CountRows | RowsCount => rows(),
SpaceCols => dist("Specify the distance between columns", self.cs).kw(&["Unit cell"]),
@@ -762,12 +712,10 @@ impl Interactive for RectM {
self.base = self.centroid;
Main
}
(Base, Input::Keyword(_)) => BaseKey,
(BaseKey, Input::Point(p)) => {
self.base = key_point_of(s.doc()?, &self.objs, *p)?;
Main
(Base, Input::Keyword(_)) => {
s.echo("Key points are not available yet; specify a point.");
Base
}
(BaseKey, Input::Enter) => Base,
(CountCols | ColsCount, _) => match count(&i, self.cols, max_count(s, self.rows.saturating_mul(self.levels), n))? {
Some(c) => {
self.cols = c;
@@ -910,9 +858,6 @@ enum PStage {
Main,
Assoc,
Base,
/// Key point of the base point asked from the center prompt, or from the main prompt.
CenterBaseKey,
BaseKey,
Items,
Between,
Fill,
@@ -1089,7 +1034,6 @@ impl Interactive for PolarM {
match self.stage {
Center => Prompt::new("Specify center point of array", Accept::POINT).kw(&["Base point", "Axis of rotation"]),
CenterBase | Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"),
CenterBaseKey | BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT),
Main => Prompt::new("Select grip to edit array", Accept::POINT)
.kw(&["ASsociative", "Base point", "Items", "Angle between", "Fill angle", "ROWs", "Levels", "ROTate items", "eXit"])
.default("eXit"),
@@ -1148,14 +1092,10 @@ impl Interactive for PolarM {
self.base = None;
if stage == CenterBase { Center } else { Main }
}
(CenterBase, Input::Keyword(_)) => CenterBaseKey,
(Base, Input::Keyword(_)) => BaseKey,
(CenterBaseKey | BaseKey, Input::Point(p)) => {
self.base = Some(key_point_of(s.doc()?, &self.objs, *p)?);
if stage == CenterBaseKey { Center } else { Main }
(CenterBase | Base, Input::Keyword(_)) => {
s.echo("Key points are not available yet; specify a point.");
stage
}
(CenterBaseKey, Input::Enter) => CenterBase,
(BaseKey, Input::Enter) => Base,
(Items, _) => match count(&i, self.items, max_count(s, self.rows.saturating_mul(self.levels), n))? {
Some(c) => {
self.items = c;
+10 -49
View File
@@ -18,9 +18,7 @@ use super::super::helpers::v3;
use super::super::machines::{SelOutcome, SelectPhase, number};
use super::super::{CommandSpec, bad, bool_or, point_param, targets};
use super::{
KEY_POINT_PROMPT, KEYWORDS, angle, check_size, count, fmt, key_point_of, key_point_param, nearest_key_point, nesting, other, yes, yes_no,
};
use super::{KEYWORDS, angle, check_size, count, fmt, nesting, other, yes, yes_no};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
pub(super) fn specs() -> Vec<CommandSpec> {
@@ -28,7 +26,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
CommandSpec::new("arrayedit", "Edit Array", run_arrayedit)
.menu(&["Modify", "Object", "Array"])
.params(
"{handle, cols?, rows?, colSpacing?, rowSpacing?, axisAngle? (degrees), rowElevation?, levels?, levelSpacing?, items?, angle? (fill, degrees), angleBetween?, rotate?: bool, center? ([x, y]), base? ([x, y], the new base point), reset?: bool, replace?: {handles, base? ([x, y], default the objects' centre), items: [[i, j, level]…] | \"source\"}, keyPoint? ([x, y]: the new base point is the source objects' key point nearest it, on the item there), replace?.keyPoint? ([x, y]: the replacement objects' key point nearest it is their base point), source?: {item? ([i, j, level], default [0, 0, 0])} (places the source objects for editing; ARRAYCLOSE ends)}",
"{handle, cols?, rows?, colSpacing?, rowSpacing?, axisAngle? (degrees), rowElevation?, levels?, levelSpacing?, items?, angle? (fill, degrees), angleBetween?, rotate?: bool, center? ([x, y]), base? ([x, y], the new base point), reset?: bool, replace?: {handles, base? ([x, y], default the objects' centre), items: [[i, j, level]…] | \"source\"}, source?: {item? ([i, j, level], default [0, 0, 0])} (places the source objects for editing; ARRAYCLOSE ends)}",
)
.interactive(|_| Ok(Box::new(EditM::default()))),
CommandSpec::new("arrayclose", "Close Array Editing", run_arrayclose)
@@ -217,16 +215,6 @@ fn item_at(d: &Drawing, h: Handle, at: Vec2, tol: f64) -> Option<(u32, u32, u32)
best.map(|b| b.0)
}
/// ARRAYEDIT Key point: the key point of the source objects nearest `at`, with the objects as
/// placed at the item under `at` (within `tol`).
fn source_key_point(d: &Drawing, h: Handle, at: Vec2, tol: f64) -> Result<Vec2> {
let item = item_at(d, h, at, tol).ok_or_else(|| other("No array item there; specify a point on an item of the array."))?;
let (ins, blk, p) = array_of(d, h)?;
let src = d.block(&p.source).ok_or_else(|| other("The array's source block is missing."))?;
let m = ins.transform(blk.base.xy()).then_before(item_place(&p, item)?).then_before(Mat3::translate(-src.base.xy()));
nearest_key_point(src.entities.iter().map(|e| e.as_ref()), &m, at)?.ok_or_else(|| other("The source objects have no key point; specify a point."))
}
/// Move the base point of array `h` to world point `base` without moving the items.
fn rebase(s: &mut Session, h: Handle, base: Vec2) -> Result<()> {
let d = s.doc()?;
@@ -355,9 +343,6 @@ fn close_source(s: &mut Session, save: bool) -> Result<Value> {
// ---------------- JSON ----------------
/// How far outside an item's extents a JSON `keyPoint` may be.
const KEY_POINT_TOLERANCE: f64 = 1e-6;
fn item_param(v: &Value) -> Option<(u32, u32, u32)> {
let a = v.as_array()?;
let n = |k: usize| a.get(k).and_then(Value::as_u64).and_then(|x| u32::try_from(x).ok());
@@ -464,7 +449,9 @@ fn fill_from_between(b: f64, items: u32) -> Result<f64> {
fn run_arrayedit(s: &mut Session, p: &Value) -> Result<Value> {
let h = super::super::curves::handle_param(p, "handle").ok_or_else(|| bad("arrayedit", "`handle` (the array) is required"))?;
refuse_while_editing(s)?;
array_of(s.doc()?, h)?;
let (ins, blk, _) = array_of(s.doc()?, h)?;
let w = ins.transform(blk.base.xy());
let to_local = w.inverse().ok_or_else(|| other("The array's scale is zero."))?;
if bool_or(p, "reset", false) {
let (_, _, mut a) = array_of(s.doc()?, h)?;
a.replaced.clear();
@@ -472,10 +459,7 @@ fn run_arrayedit(s: &mut Session, p: &Value) -> Result<Value> {
}
if let Some(r) = p.get("replace").filter(|v| !v.is_null()) {
let hs = targets(s, r)?;
let base = match key_point_param("arrayedit", r)? {
Some(k) => key_point_of(s.doc()?, &hs, k)?,
None => point_param(r, "base").unwrap_or_else(|| s.doc().map(|d| centroid(d, &hs)).unwrap_or_default()),
};
let base = point_param(r, "base").unwrap_or_else(|| s.doc().map(|d| centroid(d, &hs)).unwrap_or_default());
let name = block_from(s, h, &hs, base)?;
let (_, _, mut a) = array_of(s.doc()?, h)?;
match r.get("items") {
@@ -493,13 +477,7 @@ fn run_arrayedit(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(b) = point_param(p, "base") {
rebase(s, h, b)?;
}
if let Some(k) = key_point_param("arrayedit", p)? {
let at = source_key_point(s.doc()?, h, k, KEY_POINT_TOLERANCE)?;
rebase(s, h, at)?;
}
// A new base point moves the array's insertion point: read `center` in its placement after.
let (ins, blk, mut a) = array_of(s.doc()?, h)?;
let to_local = ins.transform(blk.base.xy()).inverse().ok_or_else(|| other("The array's scale is zero."))?;
let (_, _, mut a) = array_of(s.doc()?, h)?;
let before = a.clone();
apply_params(&mut a, p, &to_local)?;
if a != before {
@@ -529,8 +507,6 @@ enum Stage {
Select,
Main,
Base,
/// Base point: Key point (of the source objects).
BaseKey,
ColsCount,
ColsSpace,
ColsTotal,
@@ -548,8 +524,6 @@ enum Stage {
/// REPlace: objects, their base point, then the items to replace.
RepSelect,
RepBase,
/// REPlace base point: Key point (of the replacement objects).
RepKey,
RepItems,
/// Source: the item whose objects are placed for editing.
SourceItem,
@@ -685,7 +659,6 @@ impl Interactive for EditM {
.kw(&["Source", "REPlace", "Base point", "Rows", "Columns", "Levels", "RESet", "eXit"])
.default("eXit"),
Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"),
BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT),
ColsCount => Prompt::new("Enter the number of columns", Accept::NUMBER).default(cols.to_string()),
ColsSpace => dist("Specify the distance between columns", cs).kw(&["Total"]),
ColsTotal => dist("Specify the distance between the first and last column", total(cols, cs)),
@@ -714,7 +687,6 @@ impl Interactive for EditM {
Rotate => Prompt::new("Rotate arrayed items?", KEYWORDS).kw(&["Yes", "No"]).default(yes(polar.as_ref().is_none_or(|k| k.rotate))),
RepSelect => Prompt::new("Select replacement objects", Accept::SELECT),
RepBase => Prompt::new("Select base point of replacement objects", Accept::POINT).kw(&["Key point"]).default("centroid"),
RepKey => Prompt::new("Specify key point on replacement objects to use as base point", Accept::POINT),
RepItems => Prompt::new("Select an item in array to replace", Accept::POINT).kw(&["Source objects"]),
SourceItem => Prompt::new("Select item in array", Accept::POINT),
}
@@ -774,21 +746,10 @@ impl Interactive for EditM {
}
Main
}
(Base, Input::Keyword(_)) => BaseKey,
(RepBase, Input::Keyword(_)) => RepKey,
(BaseKey, Input::Point(p)) => {
let tol = s.pixel_size() * s.settings.pickbox;
let at = source_key_point(s.doc()?, h, *p, tol)?;
rebase(s, h, at)?;
Main
(Base | RepBase, Input::Keyword(_)) => {
s.echo("Key points are not available yet; specify a point.");
stage
}
(BaseKey, Input::Enter) => Base,
(RepKey, Input::Point(p)) => {
let base = key_point_of(s.doc()?, &self.rep_objs, *p)?;
self.rep_block = Some(block_from(s, h, &self.rep_objs.clone(), base)?);
RepItems
}
(RepKey, Input::Enter) => RepBase,
(ColsCount | Items, _) => match count(&i, c64, self.max_for(s, r64.saturating_mul(l64)))? {
Some(n) => {
let n = super::count32(n);
+6 -164
View File
@@ -4,7 +4,6 @@
use cadcraft_doc::color::Color;
use cadcraft_doc::{AttribProps, Common, EntityKind, HAlign, Handle, Text, VAlign};
use cadcraft_geom::Vec3;
use serde_json::{Map, Value, json};
use crate::cmd::curves::KW;
@@ -154,19 +153,6 @@ fn set_value(text: &mut Text, value: String) {
}
}
/// Move `text` so the point it is placed by lands on `to`: the alignment point of justified text,
/// else the insertion point. Both points move by the same offset, so aligned and fit text keep the
/// baseline between them.
fn move_text(text: &mut Text, to: cadcraft_geom::Vec2) {
let anchor = match text.align_pt {
Some(ap) if !matches!((text.halign, text.valign), (HAlign::Left, VAlign::Baseline) | (HAlign::Aligned | HAlign::Fit, _)) => ap,
_ => text.insert,
};
let d = Vec3::new(to.x - anchor.x, to.y - anchor.y, 0.0);
text.insert = text.insert + d;
text.align_pt = text.align_pt.map(|ap| ap + d);
}
/// Change the properties set on attribute `k` of block reference `h`.
fn set_props(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut AttribProps)) -> Result<()> {
s.doc_mut()?.modify_entity(h, |e| {
@@ -179,18 +165,6 @@ fn set_props(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut Attri
Ok(())
}
/// Modify the attribute `k` of block reference `h`.
fn modify_attrib(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut cadcraft_doc::Attrib)) -> Result<()> {
s.doc_mut()?.modify_entity(h, |e| {
if let EntityKind::Insert(ins) = &mut e.kind
&& let Some(a) = ins.attribs.get_mut(k)
{
f(a);
}
})?;
Ok(())
}
/// The layer and colour attribute `k` of block reference `h` is drawn with: its own, else its
/// definition's (layer 0 is the reference's layer).
fn current_props(s: &Session, (h, k): (Handle, usize)) -> Option<(String, Color)> {
@@ -206,14 +180,6 @@ fn current_props(s: &Session, (h, k): (Handle, usize)) -> Option<(String, Color)
Some((layer, c.color))
}
/// The current text properties of attribute `k` of block reference `h`.
fn current_text(s: &Session, (h, k): (Handle, usize)) -> Option<cadcraft_doc::Text> {
let d = s.doc().ok()?;
let e = d.entity(h)?;
let EntityKind::Insert(ins) = &e.kind else { return None };
ins.attribs.get(k).map(|a| a.text.clone())
}
/// Replace every `find` in `value` with `with`, unless the result would be too long.
fn replaced(value: &str, find: &str, with: &str) -> Option<String> {
if find.is_empty() || !value.contains(find) {
@@ -326,10 +292,6 @@ enum Stage {
Select,
/// One at a time: what to do with the current attribute.
Option,
Position,
Height,
Angle,
Style,
ValueKind,
NewValue,
Layer,
@@ -403,7 +365,6 @@ impl Interactive for DashAtteditM {
}
fn prompt(&self, s: &Session) -> Prompt {
let cur = self.items.get(self.cur).and_then(|it| current_props(s, *it));
let cur_text = self.items.get(self.cur).and_then(|it| current_text(s, *it));
match self.stage {
Stage::OneAtATime => Prompt::new("Edit attributes one at a time?", KW).kw(&["Yes", "No"]).default("Y"),
Stage::VisibleOnly => Prompt::new("Edit only attributes visible on screen?", KW).kw(&["Yes", "No"]).default("Y"),
@@ -411,31 +372,7 @@ impl Interactive for DashAtteditM {
Stage::TagSpec => Prompt::new("Enter attribute tag specification", Accept::TEXT).default("*"),
Stage::ValueSpec => Prompt::new("Enter attribute value specification", Accept::TEXT).default("*"),
Stage::Select => Prompt::new("Select attributes", Accept::SELECT),
Stage::Option => {
Prompt::new("Enter an option", KW).kw(&["Value", "Position", "Height", "Angle", "Style", "Layer", "Color", "Next"]).default("N")
}
Stage::Position => Prompt::new("Enter new text insertion point", Accept::POINT),
Stage::Height => {
let p = Prompt::new("Enter new text height", Accept::POINT_OR_NUMBER);
match cur_text {
Some(t) => p.default(format!("{:.4}", t.height)),
None => p,
}
}
Stage::Angle => {
let p = Prompt::new("Enter new text rotation angle", Accept::POINT_OR_NUMBER);
match cur_text {
Some(t) => p.default(format!("{:.4}", t.rotation.to_degrees())),
None => p,
}
}
Stage::Style => {
let p = Prompt::new("Enter new text style", Accept::TEXT);
match cur_text {
Some(t) => p.default(t.style),
None => p,
}
}
Stage::Option => Prompt::new("Enter an option", KW).kw(&["Value", "Layer", "Color", "Next"]).default("N"),
Stage::ValueKind => Prompt::new("Enter type of value modification", KW).kw(&["Change", "Replace"]).default("R"),
Stage::NewValue => Prompt::new("Enter new attribute value", Accept::TEXT),
Stage::Layer => {
@@ -509,10 +446,6 @@ impl Interactive for DashAtteditM {
}
Stage::Option => match &i {
Input::Keyword(k) if k == "Value" => self.stage = Stage::ValueKind,
Input::Keyword(k) if k == "Position" => self.stage = Stage::Position,
Input::Keyword(k) if k == "Height" => self.stage = Stage::Height,
Input::Keyword(k) if k == "Angle" => self.stage = Stage::Angle,
Input::Keyword(k) if k == "Style" => self.stage = Stage::Style,
Input::Keyword(k) if k == "Layer" => self.stage = Stage::Layer,
Input::Keyword(k) if k == "Color" => self.stage = Stage::Color,
Input::Keyword(_) | Input::Enter => {
@@ -524,105 +457,14 @@ impl Interactive for DashAtteditM {
}
Input::Text(t) => {
let tl = t.trim().to_ascii_lowercase();
let opts = ["Value", "Position", "Height", "Angle", "Style", "Layer", "Color", "Next"];
match opts.iter().find(|k| !tl.is_empty() && k.to_ascii_lowercase().starts_with(&tl)) {
Some(&"Value") => self.stage = Stage::ValueKind,
Some(&"Position") => self.stage = Stage::Position,
Some(&"Height") => self.stage = Stage::Height,
Some(&"Angle") => self.stage = Stage::Angle,
Some(&"Style") => self.stage = Stage::Style,
Some(&"Layer") => self.stage = Stage::Layer,
Some(&"Color") => self.stage = Stage::Color,
Some(&"Next") => {
self.cur += 1;
if self.cur >= self.items.len() {
return Ok(Step::Done);
}
self.show_current(s);
}
_ => return Err(invalid_keyword()),
}
let later = ["Position", "Height", "Angle", "Style"];
return match later.iter().find(|k| !tl.is_empty() && k.to_ascii_lowercase().starts_with(&tl)) {
Some(k) => Err(EngineError::Other(format!("{k} is not available yet."))),
None => Err(invalid_keyword()),
};
}
_ => {}
},
Stage::Position => {
let p = match i {
Input::Point(p) => p,
Input::Enter => {
self.stage = Stage::Option;
return Ok(Step::Continue);
}
_ => return Ok(Step::Continue),
};
if let Some(it) = self.items.get(self.cur).copied() {
modify_attrib(s, it, |a| move_text(&mut a.text, p))?;
}
self.stage = Stage::Option;
}
Stage::Height => {
let h = match &i {
Input::Point(p) => {
let cur_pt = self.items.get(self.cur).and_then(|it| current_text(s, *it)).map(|t| t.insert.xy());
match cur_pt {
Some(base) => base.dist(*p).max(1e-9),
None => p.len().max(1e-9),
}
}
Input::Text(t) if !t.trim().is_empty() => crate::units::parse_distance(t.trim())
.filter(|v| *v > 0.0)
.ok_or_else(|| EngineError::Other("Requires a positive number.".into()))?,
Input::Enter => {
self.stage = Stage::Option;
return Ok(Step::Continue);
}
_ => return Ok(Step::Continue),
};
if let Some(it) = self.items.get(self.cur).copied() {
modify_attrib(s, it, |a| {
a.text.height = h;
})?;
}
self.stage = Stage::Option;
}
Stage::Angle => {
let ang = match &i {
Input::Point(p) => {
let cur_pt = self.items.get(self.cur).and_then(|it| current_text(s, *it)).map(|t| t.insert.xy());
match cur_pt {
Some(base) => base.angle_to(*p),
None => p.y.atan2(p.x),
}
}
Input::Text(t) if !t.trim().is_empty() => {
s.angle_settings().direction(t.trim()).ok_or_else(|| EngineError::Other("Requires an angle.".into()))?
}
Input::Enter => {
self.stage = Stage::Option;
return Ok(Step::Continue);
}
_ => return Ok(Step::Continue),
};
if let Some(it) = self.items.get(self.cur).copied() {
modify_attrib(s, it, |a| {
a.text.rotation = ang;
})?;
}
self.stage = Stage::Option;
}
Stage::Style => {
let Some(t) = text else { return Ok(Step::Continue) };
let t = t.trim();
if !t.is_empty() {
let st =
s.doc()?.text_style(t).map(|st| st.name.clone()).ok_or_else(|| EngineError::Other(format!("Cannot find style \"{t}\".")))?;
if let Some(it) = self.items.get(self.cur).copied() {
modify_attrib(s, it, |a| {
a.text.style = st;
})?;
}
}
self.stage = Stage::Option;
}
Stage::ValueKind => match &i {
Input::Keyword(k) if k == "Change" => self.stage = Stage::Find,
Input::Keyword(_) | Input::Enter => self.stage = Stage::NewValue,
+31 -3
View File
@@ -18,8 +18,13 @@ use crate::{Result, Session};
/// Most image files loaded per drawing.
const MAX_IMAGE_FILES: usize = 1000;
/// Largest image file read (bytes).
#[cfg(not(target_arch = "wasm32"))]
const MAX_IMAGE_BYTES: u64 = 256 << 20;
/// Longest base64 text taken for `data`: what a file of [`MAX_IMAGE_BYTES`] encodes to.
const MAX_IMAGE_BASE64: u64 = MAX_IMAGE_BYTES.div_ceil(3) * 4;
/// Longest `data` text with the line breaks and spaces base64 may carry (MIME breaks every 76
/// characters, under 3% more): the characters past [`MAX_IMAGE_BASE64`] are counted only up to
/// here, which also bounds what decoding sets aside.
const MAX_IMAGE_TEXT: u64 = MAX_IMAGE_BASE64 + MAX_IMAGE_BASE64 / 16;
/// Most decoded pixel bytes kept per drawing; images past it stay unloaded.
const MAX_LOADED_BYTES: u64 = 2 << 30;
/// Most image files decoded at the same time when a drawing opens.
@@ -70,11 +75,22 @@ fn paths(d: &Drawing) -> Vec<String> {
paths
}
/// Whether `path` is a full path here, or on Windows where a drawing may have been written (a
/// drive, `C:\maps\a.png`, or a share, `\\server\maps`), which other systems read as relative.
#[cfg(not(target_arch = "wasm32"))]
fn full_path(path: &str) -> bool {
let b = path.trim().as_bytes();
std::path::Path::new(path.trim()).is_absolute() || b.starts_with(b"\\\\") || matches!(b, [d, b':', b'\\' | b'/', ..] if d.is_ascii_alphabetic())
}
/// The contents of the image file saved as `path` in a drawing at `host`.
fn read_file(path: &str, host: Option<&str>) -> std::result::Result<Vec<u8>, String> {
#[cfg(not(target_arch = "wasm32"))]
{
let file = super::blocks::xref::find_file(path, host).ok_or("file not found")?;
let file = super::blocks::xref::find_file(path, host).ok_or_else(|| {
// An unsaved drawing has no folder for a relative path to be relative to.
if host.is_none() && !full_path(path) { "file not found (save the drawing first, or give a full path)" } else { "file not found" }
})?;
let len = std::fs::metadata(&file).map_err(|e| e.to_string())?.len();
if len > MAX_IMAGE_BYTES {
return Err(format!("the file is larger than {} MB", MAX_IMAGE_BYTES >> 20));
@@ -304,7 +320,19 @@ fn pixels(s: &Session, p: &Value, path: &str) -> Result<Arc<Raster>> {
let bytes = match p.get("data") {
Some(data) => {
let text = data.as_str().ok_or_else(|| bad(ID, "`data` must be base64 text"))?;
base64_decode(text).ok_or_else(|| bad(ID, "`data` is not valid base64"))?
// Refused before decoding, which would hold all of it in memory. Line breaks and
// spaces, which decoding skips, don't count.
let len = u64::try_from(text.len()).unwrap_or(u64::MAX);
let digits = || u64::try_from(text.bytes().filter(|b| !matches!(b, b'\n' | b'\r' | b' ')).count()).unwrap_or(u64::MAX);
if len > MAX_IMAGE_TEXT || (len > MAX_IMAGE_BASE64 && digits() > MAX_IMAGE_BASE64) {
return Err(bad(ID, format!("`data` is larger than {} MB", MAX_IMAGE_BYTES >> 20)));
}
let bytes = base64_decode(text).ok_or_else(|| bad(ID, "`data` is not valid base64"))?;
// The longest text allowed can still hold a byte or two more than the limit.
if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > MAX_IMAGE_BYTES {
return Err(bad(ID, format!("`data` is larger than {} MB", MAX_IMAGE_BYTES >> 20)));
}
bytes
}
None => {
if let Some(loaded) = s.doc()?.rasters.get(path) {
+16 -246
View File
@@ -1,7 +1,6 @@
//! Layers: LAYER (programmatic sub-ids, -LAYER prompts), layer tools (LAYMCUR, LAYISO, LAYOFF, LAYFRZ…).
mod prompts;
mod state_prompts;
use cadcraft_color::Color;
use cadcraft_doc::{Layer, Lineweight};
@@ -56,9 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("layon", "Turn All Layers On", |s, _| all_layers(s, |l| l.on = true)),
CommandSpec::new("laythw", "Thaw All Layers", |s, _| all_layers(s, |l| l.frozen = false)),
CommandSpec::new("layerp", "Previous Layer", run_layerp).menu(&["Format", "Layer Tools", "Previous Layer"]),
CommandSpec::new("layerstate.save", "Save Layer State", run_state_save)
.menu(&["Format", "Layer States Manager..."])
.params("{name, mask? (properties restoring sets: 1 on, 2 frozen, 4 locked, 8 plot, 16 new viewport freeze, 32 color, 64 linetype, 128 lineweight, 256 plot style, 1024 transparency; default all)}"),
CommandSpec::new("layerstate.save", "Save Layer State", run_state_save).menu(&["Format", "Layer States Manager..."]).params("{name}"),
CommandSpec::new("layerstate.restore", "Restore Layer State", run_state_restore).params("{name}"),
CommandSpec::new("layerstate.list", "List Layer States", run_state_list).params("{} → states").noundo(),
CommandSpec::new("layerstate.delete", "Delete Layer State", run_state_delete).params("{name}"),
@@ -403,108 +400,31 @@ fn all_layers(s: &mut Session, f: fn(&mut Layer)) -> Result<Value> {
}
fn run_state_save(s: &mut Session, p: &Value) -> Result<Value> {
use cadcraft_doc::LayerState as S;
let name = str_param(p, "name").ok_or_else(|| bad("layerstate.save", "`name` is required"))?.to_string();
// As -LAYER stAte Save and layerstate.rename take names: none empty, over 255 characters, with a
// control character or with one AutoCAD 2024 refuses (measured for Save).
if !valid_name(&name) {
return Err(bad("layerstate.save", "invalid name"));
}
// The properties restoring sets; bit 512, which no property toggles, is always set, as AutoCAD
// 2024 saves it (measured: On alone is 513).
let mask = match p.get("mask") {
None | Some(Value::Null) => S::ALL,
Some(v) => {
let m = v.as_u64().filter(|m| m & !u64::from(S::ALL) == 0);
m.and_then(|m| u32::try_from(m).ok()).ok_or_else(|| bad("layerstate.save", "`mask` must be a sum of layer state bits (0 to 2047)"))? | 512
}
};
let d = s.doc_mut()?;
let layers = d.layers.clone();
let current = d.header.str("CLAYER", "0");
// Replace the state Restore and Delete reach (the same spelling, else another case), so a
// drawing keeps one state per name: AutoCAD 2024 finds states without regard to case. Its
// -LAYER stAte Save and layerstate-save refuse `s1` after `S1` (measured), as the command line
// here does; this command replaces, as it does a state of the same spelling. When a file holds
// both `S1` and `s1`, only the one spelled so is replaced.
if let Some(i) = state_index(d, &name) {
d.layer_states.remove(i);
}
d.layer_states.push(S { mask, ..S::new(name, layers, current) });
d.layer_states.retain(|st| st.name != name);
d.layer_states.push(cadcraft_doc::LayerState { name, layers });
ok()
}
/// The saved state called `name`: the one spelled so, else the first whose name differs only in
/// case. AutoCAD 2024 finds layer states without regard to case (measured: Restore, Edit, Name
/// and Delete of `s1` reach `S1`); case is compared as for layers and view snapshots.
pub(super) fn state_index(d: &cadcraft_doc::Drawing, name: &str) -> Option<usize> {
d.layer_states.iter().position(|st| st.name == name).or_else(|| d.layer_states.iter().position(|st| st.name.eq_ignore_ascii_case(name)))
}
fn run_state_restore(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("layerstate.restore", "`name` is required"))?;
let d = s.doc_mut()?;
let st = state_index(d, name).and_then(|i| d.layer_states.get(i)).cloned().ok_or_else(|| bad("layerstate.restore", "no such layer state"))?;
restore_state(d, &st);
let st = d.layer_states.iter().find(|st| st.name == name).cloned().ok_or_else(|| bad("layerstate.restore", "no such layer state"))?;
restore_layers(d, st.layers);
ok()
}
/// Restore a saved layer state as AutoCAD 2024 does (measured): first the current layer it
/// names, when the drawing has it and the restore doesn't leave it frozen, then on each drawing
/// layer the state names (without regard to case) the properties its mask covers. The current
/// layer is never frozen; other properties (descriptions, names) stay as they are.
pub(crate) fn restore_state(d: &mut cadcraft_doc::Drawing, st: &cadcraft_doc::LayerState) {
use cadcraft_doc::LayerState as S;
// A frozen layer only thaws with Frozen in the mask and an entry of its own: without one
// AutoCAD 2024 keeps the current layer (measured).
let thaws = |l: &Layer| st.mask & S::FROZEN != 0 && st.layers.iter().any(|saved| saved.name.eq_ignore_ascii_case(&l.name));
if let Some(l) = d.layer(&st.current).filter(|l| !l.frozen || thaws(l)) {
let name = l.name.clone();
d.header.set_str("CLAYER", &name);
}
let current = d.header.str("CLAYER", "0");
let index = layer_index(d);
let has = |bit: u32| st.mask & bit != 0;
for saved in &st.layers {
let Some(l) = index.get(&saved.name.to_ascii_lowercase()).and_then(|&i| d.layers.get_mut(i)) else { continue };
if has(S::ON) {
l.on = saved.on;
}
if has(S::FROZEN) {
l.frozen = saved.frozen && !l.name.eq_ignore_ascii_case(&current);
}
if has(S::LOCKED) {
l.locked = saved.locked;
}
if has(S::PLOT) {
l.plot = saved.plot;
}
if has(S::VP_FREEZE_NEW) {
l.vp_freeze_new = saved.vp_freeze_new;
}
if has(S::COLOR) {
l.color = saved.color;
}
if has(S::LINETYPE) {
l.linetype.clone_from(&saved.linetype);
}
if has(S::LINEWEIGHT) {
l.lineweight = saved.lineweight;
}
if has(S::PLOT_STYLE) {
l.plot_style.clone_from(&saved.plot_style);
}
if has(S::TRANSPARENCY) {
l.transparency = saved.transparency;
}
}
}
/// Put the saved layers back over the drawing's layers of the same name (without regard to case);
/// saved layers the drawing no longer has are skipped. Both lists can come from a file, so the
/// drawing's layers are looked up in an index rather than scanned per saved layer.
pub(crate) fn restore_layers(d: &mut cadcraft_doc::Drawing, saved: Vec<Layer>) {
let index = layer_index(d);
let mut index: std::collections::HashMap<String, usize> = std::collections::HashMap::with_capacity(d.layers.len());
for (i, l) in d.layers.iter().enumerate() {
// The first of names that differ only in case, as `Drawing::layer_mut` finds it.
index.entry(l.name.to_ascii_lowercase()).or_insert(i);
}
for layer in saved {
if let Some(l) = index.get(&layer.name.to_ascii_lowercase()).and_then(|&i| d.layers.get_mut(i)) {
*l = layer;
@@ -512,16 +432,6 @@ pub(crate) fn restore_layers(d: &mut cadcraft_doc::Drawing, saved: Vec<Layer>) {
}
}
/// The drawing's layers by lower-case name: the first of names that differ only in case, as
/// `Drawing::layer_mut` finds it.
fn layer_index(d: &cadcraft_doc::Drawing) -> std::collections::HashMap<String, usize> {
let mut index = std::collections::HashMap::with_capacity(d.layers.len());
for (i, l) in d.layers.iter().enumerate() {
index.entry(l.name.to_ascii_lowercase()).or_insert(i);
}
index
}
fn run_state_list(s: &mut Session, _p: &Value) -> Result<Value> {
let d = s.doc()?;
let states: Vec<Value> = d.layer_states.iter().map(|st| json!({ "name": st.name, "layers": st.layers.len() })).collect();
@@ -536,8 +446,10 @@ fn run_state_list(s: &mut Session, _p: &Value) -> Result<Value> {
fn run_state_delete(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("layerstate.delete", "`name` is required"))?;
let d = s.doc_mut()?;
let i = state_index(d, name).ok_or_else(|| bad("layerstate.delete", "no such layer state"))?;
d.layer_states.remove(i);
if !d.layer_states.iter().any(|st| st.name == name) {
return Err(bad("layerstate.delete", "no such layer state"));
}
d.layer_states.retain(|st| st.name != name);
ok()
}
@@ -548,12 +460,10 @@ fn run_state_rename(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("layerstate.rename", "invalid name"));
}
let d = s.doc_mut()?;
// A name in another case counts, the state's own too (AutoCAD 2024 refuses `S1` to `s1`,
// measured).
if d.layer_states.iter().any(|st| st.name.eq_ignore_ascii_case(&to)) {
if d.layer_states.iter().any(|st| st.name == to) {
return Err(bad("layerstate.rename", format!("layer state `{to}` already exists")));
}
let st = state_index(d, from).and_then(|i| d.layer_states.get_mut(i)).ok_or_else(|| bad("layerstate.rename", "no such layer state"))?;
let st = d.layer_states.iter_mut().find(|st| st.name == from).ok_or_else(|| bad("layerstate.rename", "no such layer state"))?;
st.name = to;
ok()
}
@@ -606,146 +516,6 @@ mod tests {
assert!(used.contains(&true) && used.contains(&false));
}
/// Restoring follows AutoCAD 2024 (measured with -LAYER stAte and states written into a DXF):
/// the current layer first, then only the properties the mask covers; the current layer stays
/// thawed; a current layer that is empty or gone leaves the current layer as it is.
#[test]
fn layer_state_restore_follows_the_mask_and_current_layer() {
use cadcraft_color::Color;
use cadcraft_doc::LayerState;
let mut s = Session::new();
s.execute("layer.new", &json!({ "name": "A", "color": 1, "current": true })).unwrap();
s.execute("layer.new", &json!({ "name": "B" })).unwrap();
s.execute("layerstate.save", &json!({ "name": "all" })).unwrap();
let saved = s.doc().unwrap().layer_states[0].clone();
assert_eq!((saved.mask, saved.current.as_str()), (LayerState::ALL, "A"));
// Only On: A's colour stays green, B comes back on (AutoCAD's S7, mask 513).
let d = s.doc_mut().unwrap();
d.layer_states.push(LayerState { name: "on".into(), mask: LayerState::ON | 512, ..saved.clone() });
s.execute("layer.set", &json!({ "name": "A", "color": 3 })).unwrap();
s.execute("layer.set", &json!({ "name": "B", "on": false, "locked": true })).unwrap();
s.execute("layer.current", &json!({ "name": "B" })).unwrap();
s.execute("layerstate.restore", &json!({ "name": "on" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "A");
let (a, b) = (d.layer("A").unwrap(), d.layer("B").unwrap());
assert_eq!((a.color, b.on, b.locked), (Color::Index(3), true, true));
// Every property.
s.execute("layerstate.restore", &json!({ "name": "all" })).unwrap();
let d = s.doc().unwrap();
assert_eq!((d.layer("A").unwrap().color, d.layer("B").unwrap().locked), (Color::Index(1), false));
// A state that freezes B with no current layer of its own (or one that is gone), restored
// with B current: B stays current and thawed; A is turned off.
for current in ["", "NOSUCH"] {
let mut frozen = s.doc().unwrap().layers.clone();
for l in &mut frozen {
l.frozen = l.name == "B";
l.on = l.name != "A";
}
s.doc_mut().unwrap().layer_states.push(LayerState::new(format!("f{current}"), frozen.clone(), current));
s.execute("layer.current", &json!({ "name": "B" })).unwrap();
s.execute("layerstate.restore", &json!({ "name": format!("f{current}") })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "B", "{current:?}");
assert!(!d.layer("B").unwrap().frozen && !d.layer("A").unwrap().on, "{current:?}");
// Naming A current, it becomes current and B freezes.
s.doc_mut().unwrap().layer_states.push(LayerState::new("fA", frozen, "A"));
s.execute("layerstate.restore", &json!({ "name": "fA" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "A");
assert!(d.layer("B").unwrap().frozen);
s.doc_mut().unwrap().layer_states.retain(|st| st.name != "fA");
s.execute("layerstate.restore", &json!({ "name": "all" })).unwrap();
}
// A current layer the state's mask leaves frozen doesn't become current (AutoCAD's S9: On
// only, current B; restored with A current and B frozen).
let mut on_only = s.doc().unwrap().layer_states[0].clone();
(on_only.name, on_only.mask, on_only.current) = ("S9".into(), LayerState::ON | 512, "B".into());
s.doc_mut().unwrap().layer_states.push(on_only);
s.execute("layer.current", &json!({ "name": "A" })).unwrap();
s.execute("layer.set", &json!({ "name": "B", "frozen": true })).unwrap();
s.execute("layerstate.restore", &json!({ "name": "S9" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "A");
assert!(d.layer("B").unwrap().frozen);
// With Frozen in the mask B is thawed and made current.
let mut thaw = s.doc().unwrap().layer_states[0].clone();
(thaw.name, thaw.current) = ("thaw".into(), "B".into());
s.doc_mut().unwrap().layer_states.push(thaw);
s.execute("layerstate.restore", &json!({ "name": "thaw" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "B");
assert!(!d.layer("B").unwrap().frozen);
// Frozen in the mask, but no entry for B (a state written elsewhere): nothing would thaw
// B, so A stays current and B frozen (AutoCAD 2024, measured).
let mut no_entry = s.doc().unwrap().layer_states[0].clone();
(no_entry.name, no_entry.current) = ("no entry".into(), "B".into());
no_entry.layers.retain(|l| l.name != "B");
s.doc_mut().unwrap().layer_states.push(no_entry);
s.execute("layer.current", &json!({ "name": "A" })).unwrap();
s.execute("layer.set", &json!({ "name": "B", "frozen": true })).unwrap();
s.execute("layerstate.restore", &json!({ "name": "no entry" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "A");
assert!(d.layer("B").unwrap().frozen);
// An entry spelled in another case is B's (layer names ignore case, as the restore of the
// properties does): B is thawed and made current.
let mut other_case = s.doc().unwrap().layer_states[0].clone();
(other_case.name, other_case.current) = ("other case".into(), "B".into());
for l in other_case.layers.iter_mut().filter(|l| l.name == "B") {
l.name = "b".into();
}
s.doc_mut().unwrap().layer_states.push(other_case);
s.execute("layerstate.restore", &json!({ "name": "other case" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "B");
assert!(!d.layer("B").unwrap().frozen);
// What a state doesn't hold stays: the description.
s.execute("layer.set", &json!({ "name": "A", "description": "kept" })).unwrap();
s.execute("layerstate.restore", &json!({ "name": "all" })).unwrap();
assert_eq!(s.doc().unwrap().layer("A").unwrap().description, "kept");
}
/// Plotting, freezing in new viewports, linetype, lineweight, plot style and transparency each
/// come back under their own mask bit only: a state of one bit restores that property and
/// leaves the other five as they are.
#[test]
fn layer_state_restores_each_property_under_its_own_bit_only() {
use cadcraft_doc::{Drawing, LayerState as S, Lineweight};
let mut s = Session::new();
s.execute("layer.new", &json!({ "name": "A" })).unwrap();
s.execute("layerstate.save", &json!({ "name": "all" })).unwrap();
let saved = s.doc().unwrap().layer_states[0].clone();
let props = |d: &Drawing| {
let l = d.layer("A").unwrap();
(l.plot, l.vp_freeze_new, l.linetype.clone(), l.lineweight, l.plot_style.clone(), l.transparency)
};
let change = |d: &mut Drawing| {
let l = d.layer_mut("A").unwrap();
(l.plot, l.vp_freeze_new, l.linetype, l.lineweight, l.plot_style, l.transparency) =
(false, true, "DASHED".into(), Lineweight::from_dxf(50), "Thick".into(), 40);
};
let before = props(s.doc().unwrap());
change(s.doc_mut().unwrap());
let after = props(s.doc().unwrap());
for bit in [S::PLOT, S::VP_FREEZE_NEW, S::LINETYPE, S::LINEWEIGHT, S::PLOT_STYLE, S::TRANSPARENCY] {
let name = format!("b{bit}");
s.doc_mut().unwrap().layer_states.push(S { name: name.clone(), mask: bit | 512, ..saved.clone() });
change(s.doc_mut().unwrap());
s.execute("layerstate.restore", &json!({ "name": name })).unwrap();
let mut want = after.clone();
match bit {
S::PLOT => want.0 = before.0,
S::VP_FREEZE_NEW => want.1 = before.1,
S::LINETYPE => want.2.clone_from(&before.2),
S::LINEWEIGHT => want.3 = before.3,
S::PLOT_STYLE => want.4.clone_from(&before.4),
_ => want.5 = before.5,
}
assert_eq!(props(s.doc().unwrap()), want, "mask {bit}");
}
}
#[test]
fn rejected_layer_set_changes_nothing() {
let mut s = Session::new();
+7 -20
View File
@@ -8,7 +8,6 @@ use serde_json::{Value, json};
use super::super::find_command;
use super::super::qselect::wildcard;
use super::state_prompts;
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
const OPTIONS: &[&str] = &[
@@ -35,9 +34,9 @@ const OPTIONS: &[&str] = &[
];
/// Keyword-only: spaces separate inputs.
pub(super) const KW: Accept = Accept { point: false, number: false, text: false, select: false, enter: true };
const KW: Accept = Accept { point: false, number: false, text: false, select: false, enter: true };
/// A name or value: Space ends the input, as it does in AutoCAD scripts.
pub(super) const NAME: Accept = Accept { number: true, ..Accept::TEXT };
const NAME: Accept = Accept { number: true, ..Accept::TEXT };
/// A per-layer change applied to a list of layer names.
#[derive(Clone, Debug)]
@@ -112,8 +111,6 @@ enum Stage {
Layers(Change),
/// Turning the current layer off asks first.
ConfirmOff(Vec<String>),
/// stAte and its options.
State(state_prompts::Stage),
}
#[derive(Default)]
@@ -126,19 +123,19 @@ fn current_layer(s: &Session) -> String {
}
/// Run a layer command's body directly: the running command records the single undo step.
pub(super) fn call(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
fn call(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
(spec.run)(s, p)
}
pub(super) fn message(e: &EngineError) -> String {
fn message(e: &EngineError) -> String {
match e {
EngineError::BadParams { msg, .. } => msg.clone(),
other => other.to_string(),
}
}
pub(super) fn retry(msg: impl Into<String>) -> EngineError {
fn retry(msg: impl Into<String>) -> EngineError {
EngineError::Other(msg.into())
}
@@ -191,9 +188,8 @@ impl LayerM {
"LOck" => Stage::Layers(Change::Lock),
"Unlock" => Stage::Layers(Change::Unlock),
"Description" => Stage::Description,
"stAte" => Stage::State(state_prompts::Stage::Option),
other => {
// MATerial, rEconcile: report and stay at the option prompt.
// MATerial, stAte, rEconcile: report and stay at the option prompt.
s.echo(format!("-LAYER {other} is not available yet."));
Stage::Option
}
@@ -266,7 +262,7 @@ impl LayerM {
Ok(Step::Continue)
};
match stage {
Stage::Option | Stage::State(_) => Ok(Step::Continue),
Stage::Option => Ok(Step::Continue),
Stage::List => {
self.list(s, text.as_deref().unwrap_or("*"));
Ok(Step::Continue)
@@ -438,18 +434,9 @@ impl Interactive for LayerM {
if enter_is_current { p.default(cur) } else { p }
}
Stage::ConfirmOff(_) => Prompt::new(format!("Really want layer \"{cur}\" (the CURRENT layer) off?"), KW).kw(&["Yes", "No"]).default("N"),
Stage::State(st) => st.prompt(),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if let Stage::State(st) = &mut self.stage
&& !matches!(i, Input::Cancel)
{
if !st.input(s, &i)? {
self.stage = Stage::Option;
}
return Ok(Step::Continue);
}
match (&self.stage, &i) {
(_, Input::Cancel) => Ok(Step::Cancel),
(Stage::Option, Input::Enter) => Ok(Step::Done),
@@ -1,256 +0,0 @@
//! -LAYER stAte: save, restore, edit, rename, delete and list the drawing's layer states, with
//! AutoCAD 2024's prompts and messages (measured). Save, Restore, Name and Delete run the
//! `layerstate.*` commands; Edit changes the state's mask in place.
use cadcraft_doc::LayerState as LS;
use serde_json::{Value, json};
use super::prompts::{KW, NAME, call, message, retry};
use super::{state_index, valid_name};
use crate::{Input, Prompt, Result, Session};
/// The options after stAte. Import and EXport (layer state files) are not available yet.
const OPTIONS: &[&str] = &["?", "Save", "Restore", "Edit", "Name", "Delete", "Import", "EXport"];
/// "Enter states to change": each keyword, the name AutoCAD 2024 lists it by and its mask bit, in
/// AutoCAD's order.
const TOGGLES: [(&str, &str, u32); 10] = [
("On", "On", LS::ON),
("Frozen", "Frozen", LS::FROZEN),
("Lock", "Lock", LS::LOCKED),
("Plot", "Plot", LS::PLOT),
("Newvpfreeze", "Newvpfreeze", LS::VP_FREEZE_NEW),
("Color", "Color", LS::COLOR),
("lineType", "lineType", LS::LINETYPE),
("lineWeight", "lineWeight", LS::LINEWEIGHT),
("TRansparency", "Transparency", LS::TRANSPARENCY),
("plotStyle", "plotStyle", LS::PLOT_STYLE),
];
/// The options that ask for a saved state's name.
#[derive(Clone, Copy, Debug)]
pub(super) enum Pick {
Restore,
Edit,
Name,
Delete,
}
impl Pick {
fn verb(self) -> &'static str {
match self {
Pick::Restore => "restore",
Pick::Edit => "edit",
Pick::Name => "rename",
Pick::Delete => "delete",
}
}
}
#[derive(Clone, Debug, Default)]
pub(super) enum Stage {
#[default]
Option,
/// Save: the new state's name.
SaveName,
/// Restore, Edit, Name or Delete: the saved state's name.
Pick(Pick),
/// Name: the new name of the state called so.
RenameTo(String),
/// "Enter states to change" for the state `name`: one Save makes on Enter, or one Edit
/// changes (`edit`).
Toggles { name: String, mask: u32, edit: bool },
}
impl Stage {
pub(super) fn prompt(&self) -> Prompt {
match self {
Stage::Option => Prompt::new("Enter an option", KW).kw(OPTIONS),
Stage::SaveName | Stage::RenameTo(_) => Prompt::new("Enter new layer state name", NAME),
Stage::Pick(p) => Prompt::new(format!("Enter name of layer state to {}", p.verb()), NAME).kw(&["?"]),
Stage::Toggles { .. } => Prompt::new("Enter states to change", KW).kw(&TOGGLES.map(|t| t.0)),
}
}
/// One input. `Ok(false)`: back to -LAYER's options. An invalid input leaves the stage as it
/// is, so the prompt is asked again.
pub(super) fn input(&mut self, s: &mut Session, i: &Input) -> Result<bool> {
let text = match i {
Input::Text(t) | Input::Keyword(t) => Some(t.trim().to_string()).filter(|t| !t.is_empty()),
_ => None,
};
let next = match std::mem::take(self) {
Stage::Option => match i {
Input::Enter => return Ok(false),
Input::Keyword(k) => option(s, k),
_ => return Err(retry("Invalid option keyword.")),
},
Stage::SaveName => match text {
None => Stage::Option,
Some(n) => save_name(s, n),
},
Stage::Pick(p) => match (i, text) {
(Input::Keyword(k), _) if k == "?" => {
list(s);
Stage::Pick(p)
}
(_, None) => Stage::Option,
(_, Some(n)) => pick(s, p, &n),
},
Stage::RenameTo(from) => {
if let Some(to) = text {
rename(s, &from, &to);
}
Stage::Option
}
Stage::Toggles { name, mut mask, edit } => match i {
Input::Keyword(k) => {
if let Some(&(_, _, bit)) = TOGGLES.iter().find(|t| t.0 == k) {
mask ^= bit;
}
show(s, mask);
Stage::Toggles { name, mask, edit }
}
Input::Enter => {
finish(s, &name, mask, edit);
Stage::Option
}
_ => {
*self = Stage::Toggles { name, mask, edit };
return Err(retry("Invalid option keyword."));
}
},
};
*self = next;
Ok(true)
}
}
fn option(s: &mut Session, k: &str) -> Stage {
match k {
"?" => {
list(s);
Stage::Option
}
"Save" => Stage::SaveName,
"Restore" => Stage::Pick(Pick::Restore),
"Edit" => Stage::Pick(Pick::Edit),
"Name" => Stage::Pick(Pick::Name),
"Delete" => Stage::Pick(Pick::Delete),
other => {
s.echo(format!("-LAYER stAte {other} is not available yet."));
Stage::Option
}
}
}
/// Whether a saved state has the name `n` in any case.
fn taken(s: &Session, n: &str) -> bool {
s.doc().is_ok_and(|d| d.layer_states.iter().any(|st| st.name.eq_ignore_ascii_case(n)))
}
/// Save's name: refused (asked again) when it has a character AutoCAD 2024 refuses (the layer
/// name ones, measured one by one), is longer than 255 characters (measured 256), or is a saved
/// state's name in any case (measured `s1` after `S1`).
fn save_name(s: &mut Session, n: String) -> Stage {
if !valid_name(&n) {
s.echo(format!("\"{n}\" is an invalid layer state name."));
return Stage::SaveName;
}
if taken(s, &n) {
s.echo(format!("Layer state \"{n}\" already exists."));
return Stage::SaveName;
}
let mask = s.settings.layer_state_mask;
show(s, mask);
Stage::Toggles { name: n, mask, edit: false }
}
fn pick(s: &mut Session, p: Pick, n: &str) -> Stage {
let found = s.doc().ok().and_then(|d| state_index(d, n).and_then(|i| d.layer_states.get(i)).map(|st| (st.name.clone(), st.mask)));
let Some((name, mask)) = found else {
s.echo("Unknown layer state name.");
return Stage::Pick(p);
};
match p {
Pick::Restore => {
run(s, "layerstate.restore", &json!({ "name": name }));
Stage::Option
}
Pick::Delete => {
run(s, "layerstate.delete", &json!({ "name": name }));
Stage::Option
}
Pick::Edit => {
show(s, mask);
Stage::Toggles { name, mask, edit: true }
}
Pick::Name => Stage::RenameTo(name),
}
}
/// Name's new name. A name some state has in any case, the state's own too, is refused with
/// AutoCAD 2024's two lines (measured `S2` onto `S2`, `S1` onto `s1`). A name with a character
/// AutoCAD refuses leaves the state as it is with no message, as AutoCAD does (measured `a,b`,
/// `a<b`); AutoCAD renames to a name starting with "*" as an anonymous `*A1`, and CADCraft leaves
/// that state as it is too.
fn rename(s: &mut Session, from: &str, to: &str) {
if taken(s, to) {
s.echo("Layer state could not be renamed.");
s.echo(format!("{to} already exists."));
} else if valid_name(to) {
run(s, "layerstate.rename", &json!({ "from": from, "to": to }));
}
}
/// Enter at "Enter states to change": Save makes the state with this mask and keeps the toggles
/// for the next Save; Edit sets the state's mask and keeps the bits no toggle reaches (AutoCAD's
/// 65536 after a restore). Edit leaves the next Save's toggles alone (measured).
fn finish(s: &mut Session, name: &str, mask: u32, edit: bool) {
if !edit {
if run(s, "layerstate.save", &json!({ "name": name, "mask": mask & LS::ALL })) {
s.settings.layer_state_mask = mask & LS::ALL;
}
return;
}
// Only a changed mask touches the drawing.
let Ok(d) = s.doc() else { return };
let Some(i) = state_index(d, name).filter(|&i| d.layer_states.get(i).is_some_and(|st| st.mask != mask)) else { return };
if let Ok(d) = s.doc_mut()
&& let Some(st) = d.layer_states.get_mut(i)
{
st.mask = mask;
}
}
/// Run a `layerstate.*` command, reporting a refusal; `true` when it ran.
fn run(s: &mut Session, id: &str, p: &Value) -> bool {
match call(s, id, p) {
Ok(_) => true,
Err(e) => {
s.echo(message(&e));
false
}
}
}
/// The toggles as AutoCAD 2024 lists them before "Enter states to change".
fn show(s: &mut Session, mask: u32) {
s.echo("States");
for (_, label, bit) in TOGGLES {
s.echo(format!("{label:<20}{}", if mask & bit != 0 { "Yes" } else { "No" }));
}
}
/// `?`: every saved state by name without regard to case, as AutoCAD 2024 lists them (measured:
/// `S2`, `b`, `S1` saved in that order list as `b`, `S1`, `S2`; a name starting with "*", its
/// `*A1`, is listed too).
fn list(s: &mut Session) {
let mut names: Vec<String> = s.doc().map(|d| d.layer_states.iter().map(|st| st.name.clone()).collect()).unwrap_or_default();
names.sort_by_cached_key(|n| n.to_ascii_lowercase());
s.echo("Layer state");
s.echo("-".repeat(29));
for n in names {
s.echo(n);
}
}
+2 -2
View File
@@ -101,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("rename", "Rename...", run_rename)
.menu(&["Format", "Rename..."])
.alias(&["ren", "-rename"])
.params("{table: layer|linetype|style|dimstyle|block|mleaderstyle|tablestyle|view|ucs|vport, from, to}")
.params("{table: layer|linetype|style|dimstyle|block|mleaderstyle|tablestyle|view|ucs, from, to}")
.interactive(|_| Ok(Box::new(rename::RenameM::default()))),
]
}
@@ -995,7 +995,7 @@ fn run_rename(s: &mut Session, p: &Value) -> Result<Value> {
}
"block" => rename::block(s, &from, &to)?,
"mleaderstyle" | "multileaderstyle" => rename::simple(s, "mleaderstyle", &from, &to)?,
"tablestyle" | "view" | "ucs" | "vport" => rename::simple(s, &table, &from, &to)?,
"tablestyle" | "view" | "ucs" => rename::simple(s, &table, &from, &to)?,
"style" | "textstyle" => {
run_style_rename(s, &json!({ "from": from, "to": to }))?;
}
+16 -81
View File
@@ -93,8 +93,6 @@ pub(super) fn simple(s: &mut Session, table: &str, from: &str, to: &str) -> Resu
"tablestyle" => d.table_styles.iter_mut().map(|t| &mut t.name).collect(),
"view" => d.views.iter_mut().map(|t| &mut t.name).collect(),
"ucs" => d.ucss.iter_mut().map(|t| &mut t.name).collect(),
// A saved viewport configuration, every tile of it; never the one shown (`*Active`).
"vport" => d.vports.iter_mut().filter(|v| !v.is_active()).map(|t| &mut t.name).collect(),
_ => return Err(bad("rename", "unsupported table")),
};
if !to.eq_ignore_ascii_case(from) && names.iter().any(|n| n.eq_ignore_ascii_case(&to)) {
@@ -136,47 +134,35 @@ const TYPES: &[(&str, Option<&str>, &str)] = &[
("Plotstyle", None, "plot style"),
("textStyle", Some("style"), "text style"),
("Tablestyle", Some("tablestyle"), "table style"),
("Ucs", Some("ucs"), "ucs"),
("Ucs", Some("ucs"), "UCS"),
("VIew", Some("view"), "view"),
("VPort", Some("vport"), "viewport configuration"),
("VPort", None, "viewport configuration"),
];
/// The noun in "Cannot find …" and "Invalid … name.": AutoCAD 2024 writes "UCS" there, "ucs" in
/// its prompts and in "A ucs named … already exists." (measured).
fn title(noun: &str) -> &str {
if noun == "ucs" { "UCS" } else { noun }
}
/// Keyword-only: spaces separate inputs.
const KW: Accept = Accept { point: false, number: false, text: false, select: false, enter: true };
/// A name: Space ends the input.
const NAME: Accept = Accept { number: true, ..Accept::TEXT };
fn any_named<'a>(mut names: impl Iterator<Item = &'a String>, name: &str) -> Option<String> {
names.find(|n| n.eq_ignore_ascii_case(name)).cloned()
fn any_named<'a>(mut names: impl Iterator<Item = &'a String>, name: &str) -> bool {
names.any(|n| n.eq_ignore_ascii_case(name))
}
/// The name as the drawing spells it of the `table` entry named `name` (without regard to case).
fn stored(d: &Drawing, table: &str, name: &str) -> Option<String> {
fn exists(d: &Drawing, table: &str, name: &str) -> bool {
match table {
"block" => d.block(name).map(|t| t.name.clone()),
"layer" => d.layer(name).map(|t| t.name.clone()),
"linetype" => d.linetype(name).map(|t| t.name.clone()),
"style" => d.text_style(name).map(|t| t.name.clone()),
"dimstyle" => d.dim_style(name).map(|t| t.name.clone()),
"block" => d.block(name).is_some(),
"layer" => d.layer(name).is_some(),
"linetype" => d.linetype(name).is_some(),
"style" => d.text_style(name).is_some(),
"dimstyle" => d.dim_style(name).is_some(),
"mleaderstyle" => any_named(d.mleader_styles.iter().map(|t| &t.name), name),
"tablestyle" => any_named(d.table_styles.iter().map(|t| &t.name), name),
"view" => any_named(d.views.iter().map(|t| &t.name), name),
"ucs" => any_named(d.ucss.iter().map(|t| &t.name), name),
"vport" => any_named(d.vports.iter().filter(|v| !v.is_active()).map(|t| &t.name), name),
_ => Some(name.to_string()),
_ => true,
}
}
fn exists(d: &Drawing, table: &str, name: &str) -> bool {
stored(d, table, name).is_some()
}
#[derive(Default)]
enum Stage {
#[default]
@@ -213,15 +199,6 @@ impl Interactive for RenameM {
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
// No new name is an invalid one (AutoCAD 2024, measured for layers, blocks, views and
// viewport configurations).
if i == Input::Enter
&& let Stage::New(t, _) = &self.stage
&& let Some((_, Some(_), noun)) = TYPES.get(*t)
{
s.echo(format!("Invalid {} name.", title(noun)));
return Ok(Step::Done);
}
if matches!(i, Input::Cancel | Input::Enter) {
return Ok(if i == Input::Cancel { Step::Cancel } else { Step::Done });
}
@@ -240,41 +217,12 @@ impl Interactive for RenameM {
self.stage = Stage::Old(t);
return Ok(Step::Continue);
};
// AutoCAD 2024 ends -RENAME on an old name it won't rename (measured): "Invalid … name."
// for a viewport configuration or block whose name starts with "*" (*Active,
// *Model_Space, an anonymous block's *U0) and for linetypes ByLayer and ByBlock;
// "Cannot rename …" and "*Invalid*" for layer 0 and linetype Continuous.
let invalid = match *table {
Some("vport" | "block") => name.starts_with('*'),
Some("linetype") => name.eq_ignore_ascii_case("bylayer") || name.eq_ignore_ascii_case("byblock"),
_ => false,
};
if invalid {
s.echo(format!("Invalid {} name.", title(noun)));
return Ok(Step::Done);
if let Some(table) = table
&& !exists(s.doc()?, table, &name)
{
self.stage = Stage::Old(t);
return Err(EngineError::Other(format!("No {noun} named \"{name}\".")));
}
let fixed = match *table {
Some("layer") => name == "0",
Some("linetype") => name.eq_ignore_ascii_case("continuous"),
_ => false,
};
if fixed {
s.echo(format!("Cannot rename {} \"{name}\".", title(noun)));
s.echo("*Invalid*");
return Ok(Step::Done);
}
// The old name as the drawing spells it: a new name in another case than that is a
// rename, even when it is the old name as typed (AutoCAD 2024, measured).
let name = match table {
Some(table) => match stored(s.doc()?, table, &name) {
Some(n) => n,
None => {
s.echo(format!("Cannot find {} \"{name}\".", title(noun)));
return Ok(Step::Done);
}
},
None => name,
};
self.stage = Stage::New(t, name);
Ok(Step::Continue)
}
@@ -287,19 +235,6 @@ impl Interactive for RenameM {
s.echo(format!("Renaming a {noun} is not available yet."));
return Ok(Step::Done);
};
// AutoCAD 2024's messages, each ending the command (measured).
if !valid_name(&name) {
s.echo(format!("Invalid {} name.", title(noun)));
return Ok(Step::Done);
}
if !name.eq_ignore_ascii_case(&old) && exists(s.doc()?, table, &name) {
s.echo(format!("A {noun} named \"{name}\" already exists."));
s.echo("*Invalid*");
return Ok(Step::Done);
}
if name == old {
return Ok(Step::Done);
}
match super::run_rename(s, &json!({ "table": table, "from": old, "to": name })) {
Ok(_) => Ok(Step::Done),
Err(e) => {
+1 -1
View File
@@ -138,7 +138,7 @@ fn save(s: &mut Session, name: &str, window: Option<Bounds2>, snapshot: bool) ->
let layer_state = snapshot.then(|| {
let state = snapshot_name(name);
d.layer_states.retain(|l| !l.name.eq_ignore_ascii_case(&state));
d.layer_states.push(LayerState::new(state.clone(), d.layers.clone(), ""));
d.layer_states.push(LayerState { name: state.clone(), layers: d.layers.clone() });
state
});
if let Some(old) = &replaced {
+11 -6
View File
@@ -139,6 +139,9 @@ pub struct LispState {
/// Interpreter steps all synchronous callbacks have run, nested ones included. A callback's
/// allowance counts what ran since it started, so the callbacks it calls spend its steps.
pub(crate) callback_used: u64,
/// Work synchronous callbacks did inside the running step, already counted in `callback_used`:
/// the step is charged it without charging the enclosing callback a second time.
pub(crate) callback_work: u64,
/// The `callback_used` value the callback running now (and so every one it calls) must not
/// pass: the lowest of its own and its callers' allowances.
pub(crate) callback_ceiling: Option<u64>,
@@ -383,6 +386,14 @@ impl Session {
let uid = run.uid;
self.lisp_flush(&mut env, false);
self.lisp_env_put(uid, env);
// The work the slice did, which one step can take far past the slice. After a panic
// `used` is still the previous slice's; the run ends with the error anyway.
run.steps = run.steps.saturating_add(run.machine.used);
if run.blocking && run.steps > BLOCKING_CAP && matches!(outcome, Outcome::Wait(_)) {
self.lisp.run = Some(run);
self.lisp_error(LispError::quit(format!("routine stopped after {BLOCKING_CAP} steps")));
return;
}
match outcome {
Outcome::Done(v) => {
self.lisp.run = Some(run);
@@ -395,13 +406,7 @@ impl Session {
return;
}
Outcome::Wait(Need::Yield) => {
run.steps = run.steps.saturating_add(SLICE);
if run.blocking {
if run.steps > BLOCKING_CAP {
self.lisp.run = Some(run);
self.lisp_error(LispError::quit(format!("routine stopped after {BLOCKING_CAP} steps")));
return;
}
self.lisp.run = Some(run);
continue;
}
+41 -8
View File
@@ -175,17 +175,19 @@ pub struct Machine {
stack: Vec<Frame>,
state: State,
need: Option<Need>,
/// Steps the last [`Machine::run`] took, with the work done inside them.
pub(crate) used: u64,
}
impl Machine {
/// A machine evaluating `forms` in turn.
pub fn forms(forms: Vec<Value>) -> Machine {
Machine { stack: vec![Frame::Forms { rest: forms.into_iter().rev().collect() }], state: State::Ret(Value::Nil), need: None }
Machine { stack: vec![Frame::Forms { rest: forms.into_iter().rev().collect() }], state: State::Ret(Value::Nil), need: None, used: 0 }
}
/// A machine calling `f` with `args`.
pub fn calling(f: Value, args: Vec<Value>) -> Machine {
Machine { stack: Vec::new(), state: State::Call(f, args), need: None }
Machine { stack: Vec::new(), state: State::Call(f, args), need: None, used: 0 }
}
/// Give the value a [`Need`] waited for, and carry on.
@@ -193,12 +195,31 @@ impl Machine {
self.state = State::Ret(v);
}
/// Run until done, waiting, or `budget` steps.
/// Run until done, waiting, or `budget` steps. A step that walks a long list (`length`) or
/// runs a synchronous callback counts that work too, so one slice stays short.
pub fn run(&mut self, ctx: &mut Ctx<'_>, budget: u64) -> Outcome {
let mut n = 0u64;
let outcome = self.run_counted(ctx, budget, &mut n);
// The last step's work too, so nothing is left for the next run.
self.used = n.saturating_add(Machine::take_step_work(ctx));
outcome
}
/// The work the last step did besides itself: the lists it walked, which count against a
/// callback's allowance too, and the callbacks it ran, which were counted there as they ran.
fn take_step_work(ctx: &mut Ctx<'_>) -> u64 {
let walked = super::value::take_work();
let callbacks = std::mem::take(&mut ctx.s.lisp.callback_work);
if ctx.depth > 0 {
ctx.s.lisp.callback_used = ctx.s.lisp.callback_used.saturating_add(walked);
}
walked.saturating_add(callbacks)
}
fn run_counted(&mut self, ctx: &mut Ctx<'_>, budget: u64, n: &mut u64) -> Outcome {
loop {
n += 1;
if n > budget {
*n = n.saturating_add(1).saturating_add(Machine::take_step_work(ctx));
if *n > budget {
return Outcome::Wait(Need::Yield);
}
// Charge a callback's step as it runs, so callbacks it calls see what it already spent.
@@ -651,6 +672,10 @@ impl Ctx<'_> {
return Ok(v);
}
let cap = self.s.lisp.limits.callback_steps;
// Work the caller queued before this call (its list walks, earlier callbacks of the same
// step) is not this callback's: set it aside and hand it back with this callback's.
let pending = super::value::take_work();
let pending_callbacks = std::mem::take(&mut self.s.lisp.callback_work);
let start = self.s.lisp.callback_used;
// This callback may run until `callback_used` reaches `ceiling`: `cap` steps from now, or
// sooner where a caller's allowance ends, so callbacks nested in callbacks share one
@@ -658,13 +683,20 @@ impl Ctx<'_> {
let outer = self.s.lisp.callback_ceiling;
let ceiling = start.saturating_add(cap).min(outer.unwrap_or(u64::MAX));
self.s.lisp.callback_ceiling = Some(ceiling);
let r = self.drive_callback(f, args, ceiling);
let mut spent: u64 = 0;
let r = self.drive_callback(f, args, ceiling, &mut spent);
self.s.lisp.callback_ceiling = outer;
super::value::charge_work(pending);
// Its steps, nested callbacks' included, are work done inside the caller's one step: they
// count against the caller's slice and every enclosing callback's. They are in
// `callback_used` already, so they reach the caller apart from its list walks.
self.s.lisp.callback_work = pending_callbacks.saturating_add(spent);
r
}
/// Run callback `f` in slices until it finishes or `callback_used` reaches `ceiling`.
fn drive_callback(&mut self, f: &Value, args: Vec<Value>, ceiling: u64) -> Result<Value, LispError> {
/// Run callback `f` in slices until it finishes or `callback_used` reaches `ceiling`, adding
/// the work each slice did to `spent`.
fn drive_callback(&mut self, f: &Value, args: Vec<Value>, ceiling: u64, spent: &mut u64) -> Result<Value, LispError> {
let cap = self.s.lisp.limits.callback_steps;
let mut m = Machine::calling(f.clone(), args);
let mut sub = Ctx { s: &mut *self.s, env: &mut *self.env, depth: self.depth + 1 };
@@ -680,6 +712,7 @@ impl Ctx<'_> {
}
let slice = remaining.min(SYNC_SLICE);
let outcome = m.run(&mut sub, slice);
*spent = spent.saturating_add(m.used);
match outcome {
// The steps were charged as they ran; finishing past the shared allowance is a failure too.
Outcome::Done(_) if sub.s.lisp.callback_used > ceiling => {
+106
View File
@@ -247,6 +247,112 @@ fn synchronous_callback_loop_is_an_error_not_a_hang() {
assert_eq!(ok(&mut s, "(vl-sort '(3 1 2) '<)"), "(1 2 3)");
}
/// A step that walks a long list counts its work: one `length` of 32768 cells is past a 1000-step
/// slice, so the slice yields after it.
#[test]
fn walking_a_long_list_counts_against_the_slice() {
use super::eval::{Ctx, Machine, Need, Outcome};
let _heavy = super::value::HEAVY_CELLS.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let mut env = super::Env::default();
let mut ctx = Ctx { s: &mut s, env: &mut env, depth: 0 };
// Built before the measured run, so only the `length` is counted.
let mut build = Machine::forms(super::read::read_all("(setq l '(1)) (repeat 15 (setq l (append l l)))").unwrap());
assert!(matches!(build.run(&mut ctx, u64::MAX), Outcome::Done(_)));
let mut m = Machine::forms(super::read::read_all("(length l)").unwrap());
// Counted as one step, the walk left the few steps of `(length l)` well inside the slice.
assert!(matches!(m.run(&mut ctx, 1_000), Outcome::Wait(Need::Yield)), "the walk was not charged");
assert!(m.used > 32_768, "{}", m.used);
match m.run(&mut ctx, u64::MAX) {
Outcome::Done(v) => assert_eq!(to_text(&v, true), "32768"),
_ => panic!("the length did not finish"),
}
assert_eq!(super::value::take_work(), 0, "nothing is left for the next run");
}
/// A routine is charged the work its slice did, not the slice's length: one `length` of 2^19
/// cells is far past a 400000-step slice.
#[test]
fn a_routine_is_charged_the_work_of_its_slice() {
let _heavy = super::value::HEAVY_CELLS.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
ok(&mut s, "(setq l '(1)) (repeat 19 (setq l (append l l))) nil");
let r = s.lisp_eval("(length l) (repeat 10 (setq x 1))", false, false, Vec::new()).unwrap();
assert!(r.is_none(), "the routine gave the interface a frame");
assert!(s.lisp_busy());
let steps = s.lisp.run.as_ref().map(|r| r.steps).unwrap_or(0);
assert!(steps >= 1 << 19, "{steps}");
for _ in 0..100 {
if !s.lisp_busy() {
break;
}
s.lisp_tick();
}
assert!(!s.lisp_running());
ok(&mut s, "(setq l nil)");
}
/// A run's last step walking a long list is charged to that run, not left for the next one: here
/// it fails after the walk (a list of numbers isn't a list of strings), so no step follows it.
#[test]
fn the_last_steps_list_walk_is_charged_to_its_run() {
let _heavy = super::value::HEAVY_CELLS.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let mut env = super::Env::default();
env.globals.insert(super::value::Sym::new("L"), Value::list(vec![Value::Int(1); 100_000]));
let mut m = super::eval::Machine::forms(super::read::read_all("(acad_strlsort l)").unwrap());
let mut ctx = super::eval::Ctx { s: &mut s, env: &mut env, depth: 0 };
assert!(matches!(m.run(&mut ctx, u64::MAX), super::eval::Outcome::Error(_)));
assert!(m.used > 100_000, "{}", m.used);
assert_eq!(super::value::take_work(), 0, "nothing is left for the next run");
}
/// Nested callbacks share one cap: an inner endless callback retried by an outer one stops.
#[test]
fn nested_callback_steps_count_against_the_outer_callback() {
let mut s = session();
s.lisp.limits.callback_steps = 10_000;
// Each level retried the endless level inside it with a fresh cap: 10000^3 steps, a hang.
let code = "(defun g (a b) (while t)) \
(defun f (a b) (while t (vl-catch-all-apply 'vl-sort (list '(1 2) 'g)))) \
(defun h (a b) (while t (vl-catch-all-apply 'vl-sort (list '(1 2) 'f)))) \
(vl-sort '(1 2) 'h)";
assert_eq!(eval(&mut s, code), Err("callback stopped after 10000 steps".into()));
// A callback's own steps count once, however many slices it runs in: three slices do three
// times the work of one.
let counts: Vec<u64> = [400_000, 1_200_000]
.into_iter()
.map(|cap| {
s.lisp.limits.callback_steps = cap;
ok(&mut s, "(setq n 0)");
assert!(eval(&mut s, "(vl-remove-if '(lambda (x) (while t (setq n (1+ n)))) '(1))").is_err());
ok(&mut s, "n").parse().unwrap()
})
.collect();
assert!(counts[1] * 10 >= counts[0] * 29, "{counts:?}");
}
/// The callback cap holds for each callback: a sort's comparisons together take more steps than
/// it, and all their work still reaches the enclosing run.
#[test]
fn each_callback_has_its_own_cap_and_its_work_reaches_the_caller() {
let mut s = session();
s.lisp.limits.callback_steps = 1_000;
let mut env = super::Env::default();
env.globals.insert(super::value::Sym::new("L"), Value::list((0..300).rev().map(Value::Int)));
let mut m = super::eval::Machine::forms(super::read::read_all("(vl-sort l (function (lambda (a b) (< a b))))").unwrap());
let mut ctx = super::eval::Ctx { s: &mut s, env: &mut env, depth: 0 };
let v = match m.run(&mut ctx, u64::MAX) {
super::eval::Outcome::Done(v) => v,
super::eval::Outcome::Error(e) => panic!("the sort failed: {e:?}"),
super::eval::Outcome::Wait(_) => panic!("the sort waited"),
};
assert_eq!(to_text(&v, true), to_text(&Value::list((0..300).map(Value::Int)), true));
// Over a thousand comparisons of several steps each, together well past the cap.
assert!(m.used > 3_000, "{}", m.used);
assert_eq!(super::value::take_work(), 0, "nothing is left for the next run");
}
/// A zero-step callback limit prevents even the first callback side effect.
#[test]
fn a_zero_callback_budget_does_not_run_the_callback() {
+17 -1
View File
@@ -64,6 +64,8 @@ thread_local! {
static STRING_BYTES: Cell<(u64, u64)> = const { Cell::new((0, STRING_BUDGET)) };
/// The running slice's cap on live cons cells.
static CELL_LIMIT: Cell<usize> = const { Cell::new(MAX_CELLS) };
/// Work done inside the current machine step: list cells walked, steps of synchronous callbacks.
static WORK: Cell<u64> = const { Cell::new(0) };
}
/// Start a slice of a run on this thread: it fails when more than `limit` cells are alive.
@@ -76,6 +78,16 @@ pub fn check_cells() -> Result<(), LispError> {
if live_cells() > CELL_LIMIT.with(Cell::get) { Err(LispError::quit("out of memory: too many list cells")) } else { Ok(()) }
}
/// Count `n` units of work done inside one machine step ([`super::eval::Machine::run`] charges them as steps).
pub fn charge_work(n: u64) {
WORK.with(|c| c.set(c.get().saturating_add(n)));
}
/// The work counted since the last call.
pub fn take_work() -> u64 {
WORK.with(|c| c.replace(0))
}
/// Start a slice of a run on this thread: it has made `used` bytes of its `budget`.
pub fn set_string_budget(used: u64, budget: u64) {
STRING_BYTES.with(|c| c.set((used, budget)));
@@ -262,7 +274,10 @@ impl Value {
loop {
match v {
Value::Nil => return true,
Value::Cons(c) => v = c.cdr.clone(),
Value::Cons(c) => {
charge_work(1);
v = c.cdr.clone();
}
_ => return false,
}
}
@@ -318,6 +333,7 @@ impl Iterator for ListIter {
fn next(&mut self) -> Option<Value> {
match std::mem::take(&mut self.next) {
Value::Cons(c) => {
charge_work(1);
self.next = c.cdr.clone();
Some(c.car.clone())
}
+1 -2
View File
@@ -31,7 +31,7 @@ impl Accept {
/// [Truecolor/COlorbook] <BYLAYER>:". A prompt asking for something else besides its keywords has
/// it: "Enter block name or [?]:", "Specify insertion base point or [Basepoint/…]:". Read from
/// AutoCAD's command line over measured runs, where no prompt was written both ways.
const NO_OR: &[&str] = &[
const NO_OR: [&str; 28] = [
"Bring to front",
"Calculate rectangle dimensions based on",
"Choose mode for selected object conversion",
@@ -50,7 +50,6 @@ const NO_OR: &[&str] = &[
"Enter option",
"Enter polyline linetype generation option",
"Enter property to change",
"Enter states to change",
"Enter the type of array",
"Enter type of unused objects to purge",
"Enter viewport arrangement",
-5
View File
@@ -27,10 +27,6 @@ pub struct Settings {
pub measureinit: bool,
/// -VIEW sEttings > Layer snapshot: named views save the layer settings with them.
pub view_layer_snapshot: bool,
/// -LAYER stAte Save: the properties a new layer state restores (its mask), as the last Save
/// left them. AutoCAD 2024 keeps these toggles in the registry from one Save to the next
/// (measured); Edit doesn't change them.
pub layer_state_mask: u32,
pub dynmode: bool,
/// DYNDIGRIP: which dimensions grip dimensional input shows while a grip is stretched (bits:
/// 1 resulting length, 2 length change, 4 absolute angle, 8 angle change, 16 radius); read
@@ -152,7 +148,6 @@ impl Default for Settings {
zoomfactor: 60,
measureinit: false,
view_layer_snapshot: true,
layer_state_mask: cadcraft_doc::LayerState::ALL,
dynmode: true,
dyndigrip: 31,
dyndivis: 1,
+36
View File
@@ -329,3 +329,39 @@ fn auditctl_generates_adt_report_file() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_handle_in_the_reserved_band_is_not_repaired_on_every_audit() {
// A file object above HANDLE_LIMIT keeps its handle, and the seed deliberately does not move
// past it (#913). AUDIT must not report that policy as an error its own repair never fixes.
let band = Handle(cadcraft_engine::doc::HANDLE_LIMIT);
let mut d = Drawing::new_imperial();
d.space_mut(&Space::Model).unwrap().push(Entity { handle: band, common: Common::default(), kind: line((0.0, 0.0), (1.0, 0.0)) });
d.handseed = band.0;
for _ in 0..3 {
let r = cadcraft_engine::audit::check(&d);
assert!(r.issues.iter().all(|i| i.kind != "handseed"), "{}", r.message());
}
let mut repaired = d.clone();
let r = cadcraft_engine::audit::repair(&mut repaired);
assert!(r.iter().all(|i| i.kind != "handseed"), "{r:?}");
assert_eq!(repaired.handseed, band.0, "the seed moved past the file's own handle");
}
#[test]
fn an_ordinary_handle_behind_a_reserved_band_one_is_still_repaired() {
// The largest handle is in the reserved band, which the seed deliberately does not follow.
// An ordinary handle above the seed must still be found behind it: it is the one the seed
// has to move past, and skipping the check would leave AUDIT reporting a clean drawing.
let band = Handle(cadcraft_engine::doc::HANDLE_LIMIT);
let mut d = Drawing::new_imperial();
let store = d.space_mut(&Space::Model).unwrap();
store.push(Entity { handle: Handle(20), common: Common::default(), kind: line((0.0, 0.0), (1.0, 0.0)) });
store.push(Entity { handle: band, common: Common::default(), kind: line((2.0, 0.0), (3.0, 0.0)) });
d.handseed = 10;
let r = cadcraft_engine::audit::repair(&mut d);
assert!(r.iter().any(|i| i.kind == "handseed" && i.message.contains("(14)")), "the ordinary handle was hidden: {r:?}");
assert_eq!(d.handseed, 21, "the seed was not moved past the ordinary handle");
let r = cadcraft_engine::audit::repair(&mut d.clone());
assert!(r.iter().all(|i| i.kind != "handseed"), "the repair does not stick: {r:?}");
}
+45
View File
@@ -142,6 +142,51 @@ fn bad_input_is_refused_and_changes_nothing() {
assert_eq!(listed(&mut s), json!([]));
}
/// `data` longer than the largest image file encodes to is refused before it is decoded.
#[test]
fn oversized_data_is_refused_before_decoding() {
hooks();
const LIMIT: u64 = 256 << 20;
let mut s = Session::new();
// Not base64 at all: only the check before decoding tells it is too long ("not valid base64"
// otherwise), and nothing is decoded.
let too_long = "!".repeat(usize::try_from(LIMIT.div_ceil(3) * 4 + 1).unwrap());
let e = s.execute("imageattach", &json!({ "path": "a.png", "data": too_long })).unwrap_err().to_string();
assert!(e.contains("`data` is larger than 256 MB"), "{e}");
// Line breaks don't count: base64 wrapped as MIME writes it is taken.
let wrapped: String = base64_encode(&png()).as_bytes().chunks(76).map(|c| format!("{}\r\n", String::from_utf8_lossy(c))).collect();
s.execute("imageattach", &json!({ "path": "wrapped.png", "data": wrapped })).unwrap();
s.execute("undo", &json!({})).unwrap();
// The longest text allowed, holding one byte more than the limit, is refused once decoded.
let groups = usize::try_from(LIMIT / 3).unwrap();
let one_over = format!("{}AAA=", "AAAA".repeat(groups));
assert_eq!(u64::try_from(one_over.len()).unwrap(), LIMIT.div_ceil(3) * 4, "as long as the text for the limit itself");
let e = s.execute("imageattach", &json!({ "path": "a.png", "data": one_over })).unwrap_err().to_string();
assert!(e.contains("`data` is larger than 256 MB"), "{e}");
assert!(images(&s).is_empty());
}
/// A relative path in an unsaved drawing has nothing to be relative to, and the error says so.
#[test]
fn a_relative_path_in_an_unsaved_drawing_says_what_to_do() {
hooks();
let mut s = Session::new();
let e = s.execute("imageattach", &json!({ "path": "missing.png" })).unwrap_err().to_string();
assert!(e.contains("save the drawing first, or give a full path"), "{e}");
let dir = folder("unsaved");
let full = dir.join("missing.png");
let e = s.execute("imageattach", &json!({ "path": full.to_string_lossy() })).unwrap_err().to_string();
assert!(e.contains("file not found") && !e.contains("save the drawing"), "{e}");
// A full Windows path, read as relative elsewhere, is a full path all the same.
for windows in [r"C:\nowhere\a.png", "D:/nowhere/a.png", r"\\server\maps\a.png"] {
let e = s.execute("imageattach", &json!({ "path": windows })).unwrap_err().to_string();
assert!(e.contains("file not found") && !e.contains("save the drawing"), "{windows}: {e}");
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_image_among_many_objects_keeps_its_pixels() {
// More objects than one build task takes: the display list is built in parts and joined,
-202
View File
@@ -1,202 +0,0 @@
//! The Key point option of a base point: ARRAYRECT, ARRAYPOLAR and ARRAYEDIT (Base point and
//! REPlace) take the source objects' key point (an end point, midpoint, centre…) nearest the
//! picked point as the base point; the JSON forms take `keyPoint`.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{ArrayKind, ArrayParams, EntityKind, Handle};
use cadcraft_engine::geom::Vec2;
use serde_json::json;
fn source_line(s: &mut Session) -> String {
let r = s.execute("line", &json!({"points": [[0, 0], [2, 1]]})).unwrap();
r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string()
}
fn handle(v: &serde_json::Value) -> Handle {
Handle::parse_hex(v["handle"].as_str().unwrap()).unwrap()
}
/// The array's insertion point (its base point) and parameters.
fn array(s: &Session, h: Handle) -> (Vec2, ArrayParams) {
let d = s.doc().unwrap();
let e = d.entity(h).unwrap();
let EntityKind::Insert(i) = &e.kind else { panic!("not an array") };
(i.insert.xy(), d.array_params(e).unwrap())
}
fn only_array(s: &Session) -> Handle {
let d = s.doc().unwrap();
let arrays: Vec<Handle> = d.model.iter().filter(|e| d.array_params(e).is_some()).map(|e| e.handle).collect();
assert_eq!(arrays.len(), 1);
arrays[0]
}
fn typed(s: &mut Session, inputs: &[&str]) {
for t in inputs {
s.cmdline(t).unwrap();
}
}
#[test]
fn arrayrect_and_arraypolar_take_a_key_point_as_the_base_point() {
let mut s = Session::new();
let l = source_line(&mut s);
let r = s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "colSpacing": 5, "keyPoint": [1.9, 1.05]})).unwrap();
assert!(array(&s, handle(&r)).0.near(Vec2::new(2.0, 1.0), 1e-9));
let mut s = Session::new();
let l = source_line(&mut s);
let r = s.execute("arraypolar", &json!({"handles": [l], "center": [-10, 0], "count": 4, "keyPoint": [1.1, 0.4]})).unwrap();
assert!(array(&s, handle(&r)).0.near(Vec2::new(1.0, 0.5), 1e-9), "the line's midpoint");
}
#[test]
fn typed_key_points_at_arrayrect_and_arraypolar() {
let mut s = Session::new();
source_line(&mut s);
typed(&mut s, &["arrayrect", "l", "", "b", "k", "1.9,0.95", "x"]);
assert!(array(&s, only_array(&s)).0.near(Vec2::new(2.0, 1.0), 1e-9));
// Enter at the key point prompt goes back to the base point prompt.
let mut s = Session::new();
source_line(&mut s);
typed(&mut s, &["arraypolar", "l", "", "b", "k"]);
assert!(s.current_prompt().unwrap().message.contains("key point"));
typed(&mut s, &[""]);
assert!(s.current_prompt().unwrap().message.contains("base point"));
typed(&mut s, &["k", "0.1,0.1", "-10,0", "x"]);
assert!(array(&s, only_array(&s)).0.near(Vec2::new(0.0, 0.0), 1e-9));
}
#[test]
fn arrayedit_moves_the_base_point_to_a_key_point_of_an_item() {
let mut s = Session::new();
let l = source_line(&mut s);
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
// Near the start of the third item: the base point goes to (10, 0), the items stay.
s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": [10.2, 0.05]})).unwrap();
let (at, p) = array(&s, h);
assert!(at.near(Vec2::new(10.0, 0.0), 1e-9), "{at:?}");
assert!(matches!(p.kind, ArrayKind::Rect(r) if r.cols == 3 && r.col_spacing == 5.0));
let items = s.execute("explode", &json!({"handles": [h.hex()]})).unwrap();
assert!(items.to_string().len() > 2);
let d = s.doc().unwrap();
let mut starts: Vec<(i64, i64)> = d
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(l) => Some(((l.a.x * 10.0).round() as i64, (l.a.y * 10.0).round() as i64)),
_ => None,
})
.collect();
starts.sort();
assert_eq!(starts, [(0, 0), (50, 0), (100, 0)]);
// Not on an item: refused.
let mut s = Session::new();
let l = source_line(&mut s);
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
assert!(s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": [3.5, 40]})).is_err());
assert!(array(&s, h).0.near(Vec2::ZERO, 1e-9));
// Typed: Base point, Key point, a point on the second item near its end.
s.set_selection(vec![h]);
typed(&mut s, &["arrayedit", "b", "k", "6.9,0.9", "x"]);
assert!(array(&s, h).0.near(Vec2::new(7.0, 1.0), 1e-9));
}
#[test]
fn replacement_objects_take_a_key_point_as_their_base_point() {
let mut s = Session::new();
let l = source_line(&mut s);
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
let c = s.execute("circle", &json!({"center": [50, 50], "radius": 1})).unwrap()["handle"].clone();
// The circle's right quadrant is the base point: on item 1 (at x = 5) its centre is at x = 4.
s.execute("arrayedit", &json!({"handle": h.hex(), "replace": {"handles": [c], "keyPoint": [51.2, 50.1], "items": [[1, 0, 0]]}})).unwrap();
s.execute("explode", &json!({"handles": [h.hex()]})).unwrap();
let d = s.doc().unwrap();
// The replaced item stays a reference to the replacement block.
let centres: Vec<Vec2> = d
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Insert(i) => d.block(&i.block).map(|b| (i.transform(b.base.xy()), b)),
_ => None,
})
.flat_map(|(m, b)| {
b.entities
.iter()
.filter_map(move |e| match &e.kind {
EntityKind::Circle(c) => Some(m.apply(c.center.xy())),
_ => None,
})
.collect::<Vec<_>>()
})
.collect();
assert!(centres.iter().any(|c| c.near(Vec2::new(4.0, 0.0), 1e-9)), "{centres:?}");
}
#[test]
fn hostile_key_points_never_panic() {
let mut s = Session::new();
let l = source_line(&mut s);
for kp in [json!(["a", 1]), json!([1e308, -1e308]), json!([]), json!("x"), json!(null)] {
let _ = s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "keyPoint": kp}));
let _ = s.execute("arraypolar", &json!({"handles": [l], "center": [5, 5], "count": 3, "keyPoint": kp}));
}
let mut s = Session::new();
let l = source_line(&mut s);
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
for kp in [json!([1e308, 1e308]), json!([-1e308, 0]), json!(["x"]), json!([0.5, 0.25])] {
let _ = s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": kp}));
let _ = s.execute("arrayedit", &json!({"handle": h.hex(), "replace": {"handles": [], "keyPoint": kp, "items": [[0, 0, 0]]}}));
}
// Typed key points far away or on nothing are refused without leaving the command broken.
s.set_selection(vec![h]);
typed(&mut s, &["arrayedit", "b", "k"]);
assert!(s.cmdline("1e300,1e300").is_err() || s.running.is_some());
s.cancel();
}
/// A `keyPoint` that is there but isn't a point is refused, not taken as no key point (which
/// would make the array at another base point).
#[test]
fn a_key_point_that_is_not_a_point_is_refused() {
let mut s = Session::new();
let l = source_line(&mut s);
assert!(s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "keyPoint": ["bad", 1]})).is_err());
assert!(s.execute("arraypolar", &json!({"handles": [l], "center": [-10, 0], "count": 3, "keyPoint": "x"})).is_err());
assert!(s.doc().unwrap().model.iter().all(|e| s.doc().unwrap().array_params(e).is_none()), "no array made");
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
assert!(s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": [1]})).is_err());
let c = s.execute("circle", &json!({"center": [50, 50], "radius": 1})).unwrap()["handle"].clone();
assert!(s.execute("arrayedit", &json!({"handle": h.hex(), "replace": {"handles": [c], "keyPoint": {}, "items": [[1, 0, 0]]}})).is_err());
}
/// More objects than the key point search takes are refused rather than searched in part, which
/// could miss the nearest key point.
#[test]
fn a_key_point_of_too_many_objects_is_refused() {
let mut s = Session::new();
// 10,001 lines; the last one ends nearest the key point.
let pts: Vec<[f64; 2]> = (0..10_002).map(|i| [f64::from(i), 0.0]).collect();
let r = s.execute("line", &json!({ "points": pts })).unwrap();
let hs: Vec<String> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
assert_eq!(hs.len(), 10_001, "{r}");
let e = s.execute("arraypolar", &json!({"handles": hs, "center": [0, -50], "count": 2, "keyPoint": [10_001.2, 0]})).unwrap_err();
assert!(e.to_string().contains("10000"), "{e}");
}
/// ARRAYEDIT with a new base point (`base` or `keyPoint`) and a polar `center` in one call puts the
/// centre where asked: the base point moves the array's insertion point, so the centre is read in
/// the array's placement after that move.
#[test]
fn arrayedit_center_with_a_new_base_point_lands_where_asked() {
for (key, at) in [("base", json!([2, 1])), ("keyPoint", json!([1.95, 0.99]))] {
let mut s = Session::new();
let l = source_line(&mut s);
let h = handle(&s.execute("arraypolar", &json!({"handles": [l], "center": [-10, 0], "count": 4, "base": [0, 0]})).unwrap());
s.execute("arrayedit", &json!({"handle": h.hex(), key: at, "center": [5, 0]})).unwrap();
let (ins, p) = array(&s, h);
let ArrayKind::Polar(k) = p.kind else { panic!("not polar") };
assert!(ins.near(Vec2::new(2.0, 1.0), 1e-9), "{key}: {ins:?}");
// The centre is kept relative to the insertion point.
assert!((ins + k.center).near(Vec2::new(5.0, 0.0), 1e-9), "{key}: centre at {:?}", ins + k.center);
}
}
+4 -43
View File
@@ -83,22 +83,14 @@ fn dash_attedit_one_at_a_time_edits_the_selected_attributes() {
let mut s = with_block();
let h = handle(&insert(&mut s, 100.0, json!({"T": "abc"})));
type_lines(&mut s, &["-attedit", "y", "", "T", "", "105,0", ""]);
assert!(s.prompt_text().contains("[Value/Position/Height/Angle/Style/Layer/Color/Next] <N>"), "{}", s.prompt_text());
// Edit Position, Height, Angle, and Style
type_lines(&mut s, &["p", "10,20", "h", "2.5", "a", "45", "s", "Standard"]);
// Edit Value: change and replace
assert!(s.prompt_text().contains("[Value/Layer/Color/Next] <N>"), "{}", s.prompt_text());
// Unsupported options say so and keep the prompt.
s.cmdline("p").unwrap();
assert!(s.log.iter().any(|l| l.contains("Position is not available yet")), "{:?}", s.log);
type_lines(&mut s, &["v", "c", "b", "B", "v", "r", "replaced value", "n"]);
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(value(&s, h, "T"), "replaced value");
assert_eq!(value(&s, h, "U"), "u");
let EntityKind::Insert(ins) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") };
let att = ins.attribs.iter().find(|a| a.tag == "T").unwrap();
assert!((att.text.insert.x - 10.0).abs() < 1e-6);
assert!((att.text.insert.y - 20.0).abs() < 1e-6);
assert!((att.text.height - 2.5).abs() < 1e-6);
assert!((att.text.rotation.to_degrees() - 45.0).abs() < 1e-4);
assert_eq!(att.text.style, "Standard");
}
#[test]
@@ -117,34 +109,3 @@ fn attribute_tags_match_in_any_case_and_unknown_tags_are_reported() {
let r = s.execute("attedit", &json!({"handle": h.hex(), "values": {"T": "four"}})).unwrap();
assert_eq!(r, json!({"changed": 1}));
}
/// -ATTEDIT Position moves an aligned or fit attribute without losing its baseline: both of its
/// points move by the same offset (setting both to the picked point would leave no direction or
/// length to fit the text between).
#[test]
fn dash_attedit_position_keeps_an_aligned_attributes_baseline() {
use cadcraft_doc::HAlign;
use cadcraft_geom::Vec3;
for halign in [HAlign::Aligned, HAlign::Fit] {
let mut s = with_block();
let h = handle(&insert(&mut s, 100.0, json!({"T": "abc"})));
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let EntityKind::Insert(i) = &mut e.kind {
for a in i.attribs.iter_mut().filter(|a| a.tag == "T") {
a.text.halign = halign;
a.text.insert = Vec3::new(100.0, 1.0, 0.0);
a.text.align_pt = Some(Vec3::new(104.0, 1.0, 0.0));
}
}
})
.unwrap();
type_lines(&mut s, &["-attedit", "y", "", "T", "", "105,0", "", "p", "10,20", "n"]);
assert!(s.running.is_none(), "{}", s.prompt_text());
let EntityKind::Insert(ins) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") };
let t = &ins.attribs.iter().find(|a| a.tag == "T").unwrap().text;
assert!(t.insert.xy().near(cadcraft_geom::Vec2::new(10.0, 20.0), 1e-9), "{halign:?}: {:?}", t.insert);
assert!(t.align_pt.is_some_and(|p| p.xy().near(cadcraft_geom::Vec2::new(14.0, 20.0), 1e-9)), "{halign:?}: {:?}", t.align_pt);
}
}
+1 -1
View File
@@ -38,7 +38,7 @@ fn dash_attedit_sets_layer_and_colour_of_one_attribute() {
for t in ["-attedit", "y", "", "T", "", "105,0", ""] {
s.cmdline(t).unwrap();
}
assert!(s.prompt_text().contains("[Value/Position/Height/Angle/Style/Layer/Color/Next] <N>"), "{}", s.prompt_text());
assert!(s.prompt_text().contains("[Value/Layer/Color/Next] <N>"), "{}", s.prompt_text());
s.cmdline("l").unwrap();
assert!(s.prompt_text().contains("Enter new layer name <0>"), "{}", s.prompt_text());
// An unknown layer is refused and asked again.
@@ -1,247 +0,0 @@
//! -LAYER stAte: AutoCAD 2024's layer state prompts and messages (measured with accoreconsole on a
//! drawing with layers A, red, and B), and the `layerstate.*` commands they run.
use cadcraft_engine::doc::LayerState;
use cadcraft_engine::{Input, Session};
use serde_json::json;
const LABELS: [&str; 10] = ["On", "Frozen", "Lock", "Plot", "Newvpfreeze", "Color", "lineType", "lineWeight", "Transparency", "plotStyle"];
/// The toggles AutoCAD lists before "Enter states to change", with `no` the ones set to No.
fn table(no: &[&str]) -> Vec<String> {
let mut v = vec!["States".to_string()];
v.extend(LABELS.iter().map(|l| format!("{l:<20}{}", if no.contains(l) { "No" } else { "Yes" })));
v
}
/// Layers A (red) and B; the current layer stays 0.
fn drawing() -> Session {
let mut s = Session::new();
s.script("-LAYER N A,B C 1 A\n\n").unwrap();
s
}
/// Run `script` to its end and return what it wrote besides the commands' names and -LAYER's
/// "Current layer" line.
fn run(s: &mut Session, script: &str) -> Vec<String> {
let at = s.log.len();
s.script(script).unwrap();
assert!(s.running.is_none(), "{script:?} ends at: {}", s.prompt_text());
s.log[at..].iter().filter(|l| !l.starts_with("Command: ") && !l.starts_with("Current layer:")).cloned().collect()
}
fn states(s: &Session) -> Vec<(String, u32)> {
s.doc().unwrap().layer_states.iter().map(|st| (st.name.clone(), st.mask)).collect()
}
fn state(name: &str, mask: u32) -> (String, u32) {
(name.to_string(), mask)
}
#[test]
fn save_asks_the_states_and_remembers_them_for_the_next_save() {
let mut s = drawing();
// Each toggle lists the states again; On off is AutoCAD's 2046.
let out = run(&mut s, "-LAYER A S S6 ON\n\n\n\nLINE 0,0 1,0\n\n");
assert_eq!(out, [table(&[]), table(&["On"])].concat());
assert_eq!(states(&s), [state("S6", 2046)]);
assert_eq!(s.doc().unwrap().model.len(), 1, "the next command runs");
// The next Save starts from the toggles the last one left: On alone is 513, then every
// toggle once more is 2046 (AutoCAD's S7 and S8).
let out = run(&mut s, "-LAYER A S S7 ON F L P N C T W TR S\n\n\n\n");
assert_eq!(out[..11], table(&["On"]));
assert_eq!(
out[out.len() - 11..],
table(&["Frozen", "Lock", "Plot", "Newvpfreeze", "Color", "lineType", "lineWeight", "Transparency", "plotStyle"])
);
run(&mut s, "-LAYER A S S8 ON F L P N C T W TR S\n\n\n\n");
run(&mut s, "-LAYER A S S9 ON\n\n\n\n");
assert_eq!(states(&s)[1..], [state("S7", 513), state("S8", 2046), state("S9", LayerState::ALL)]);
// Edit lists and changes the state's own mask (found in any case), not the next Save's
// toggles (AutoCAD: Edit S1 to 2015, then S2 is 2047).
let out = run(&mut s, "-LAYER A E s6 ON C\n\n\n\n");
assert_eq!(out, [table(&["On"]), table(&[]), table(&["Color"])].concat());
run(&mut s, "-LAYER A S S10\n\n\n\n");
assert_eq!(states(&s)[0], state("S6", 2015));
assert_eq!(states(&s)[4], state("S10", LayerState::ALL));
// Each -LAYER is one undo step.
s.undo().unwrap();
assert_eq!(states(&s).len(), 4);
s.undo().unwrap();
assert_eq!(states(&s)[0], state("S6", 2046));
// A state from AutoCAD after a restore (mask 67583 = 2047 + 65536) named as AutoCAD names a
// state renamed to "*X": `?` lists it, and Edit keeps the bit no toggle reaches.
s.doc_mut().unwrap().layer_states.push(LayerState { name: "*A1".into(), mask: 67583, ..LayerState::default() });
assert_eq!(
run(
&mut s,
"-LAYER A ?
"
)[2],
"*A1"
);
run(
&mut s,
"-LAYER A E *a1 C
",
);
assert_eq!(states(&s)[4], state("*A1", 67583 - 32));
}
#[test]
fn names_follow_autocads_rules_and_messages() {
let mut s = drawing();
run(&mut s, "-LAYER A S S1\n\n\n\n");
// A saved name in another case is refused and asked again.
let out = run(&mut s, "-LAYER A S s1 S2\n\n\n\n");
assert_eq!(out, [vec!["Layer state \"s1\" already exists.".to_string()], table(&[])].concat());
// The layer name characters, and more than 255 characters, are refused; Enter goes back.
let long = "y".repeat(256);
let out = run(&mut s, &format!("-LAYER A S *X a<b a,b {long}\n\n\n\n"));
assert_eq!(
out,
[
"\"*X\" is an invalid layer state name.",
"\"a<b\" is an invalid layer state name.",
"\"a,b\" is an invalid layer state name.",
&format!("\"{long}\" is an invalid layer state name.")
]
);
run(&mut s, &format!("-LAYER A S {}\n\n\n\n", "x".repeat(255)));
assert_eq!(states(&s).len(), 3);
run(&mut s, &format!("-LAYER A D {}\n\n\n", "x".repeat(255)));
// `?` lists by name without regard to case.
run(&mut s, "-LAYER A S b\n\n\n\n");
let list = ["Layer state", "-----------------------------", "b", "S1", "S2"];
assert_eq!(run(&mut s, "-LAYER A ?\n\n\n"), list);
// Each name prompt lists on `?`, says an unknown name and asks again, and Enter goes back.
let out = run(&mut s, "-LAYER A R ? NOSUCH\n\nE NOSUCH\n\nN NOSUCH\n\nD NOSUCH\n\n\n\n");
assert_eq!(out[..5], list);
assert_eq!(out[5..], ["Unknown layer state name."; 4]);
// Unknown options, Import and EXport.
let out = run(&mut s, "-LAYER A XYZ I EX\n\n\n");
assert_eq!(out, ["Invalid option keyword.", "-LAYER stAte Import is not available yet.", "-LAYER stAte EXport is not available yet."]);
let out = run(&mut s, "-LAYER A S T1 XYZ\n\n\n\n");
assert_eq!(out, [table(&[]), vec!["Invalid option keyword.".to_string()]].concat());
assert_eq!(states(&s).len(), 4, "T1 is saved after the invalid toggle");
run(&mut s, "-LAYER A D T1\n\n\n");
// Name: a name some state has in any case, the state's own too, is refused with two lines.
assert_eq!(run(&mut s, "-LAYER A N S1 S2\n\n\n"), ["Layer state could not be renamed.", "S2 already exists."]);
assert_eq!(run(&mut s, "-LAYER A N S1 s1\n\n\n"), ["Layer state could not be renamed.", "s1 already exists."]);
// A name with a refused character leaves the state as it is, with no message; Enter too.
assert!(run(&mut s, "-LAYER A N S1 a,b\n\n\n").is_empty());
assert!(run(&mut s, "-LAYER A N S1\n\n\n\n").is_empty());
assert_eq!(states(&s).iter().map(|st| st.0.as_str()).collect::<Vec<_>>(), ["S1", "S2", "b"]);
// The old name in another case.
assert!(run(&mut s, "-LAYER A N s1 S9\n\n\n").is_empty());
assert_eq!(states(&s).iter().map(|st| st.0.as_str()).collect::<Vec<_>>(), ["S9", "S2", "b"]);
assert!(run(&mut s, "-LAYER A D s9\n\n\n").is_empty());
assert_eq!(states(&s).iter().map(|st| st.0.as_str()).collect::<Vec<_>>(), ["S2", "b"]);
}
#[test]
fn esc_drops_the_state_being_saved_and_undo_takes_back_name_and_delete() {
let mut s = drawing();
run(
&mut s,
"-LAYER A S S1
",
);
// Esc at the toggles: that state isn't saved and the next Save's toggles stay as they were;
// what the same -LAYER did before Esc stays, as for the other -LAYER options.
s.script(
"-LAYER A S S2
S S3 C ON
",
)
.unwrap();
// AutoCAD 2024 asks for the toggles without "or" before them.
assert_eq!(
s.current_prompt().unwrap().display(),
"Enter states to change [On/Frozen/Lock/Plot/Newvpfreeze/Color/lineType/lineWeight/TRansparency/plotStyle]:"
);
s.input(Input::Cancel).unwrap();
assert!(s.running.is_none());
assert_eq!(states(&s), [state("S1", LayerState::ALL), state("S2", LayerState::ALL)]);
assert_eq!(s.settings.layer_state_mask, LayerState::ALL);
// Name and Delete are one undo step each, like Save.
run(
&mut s,
"-LAYER A N S1 S9
",
);
run(
&mut s,
"-LAYER A D S2
",
);
assert_eq!(states(&s), [state("S9", LayerState::ALL)]);
s.undo().unwrap();
assert_eq!(states(&s), [state("S9", LayerState::ALL), state("S2", LayerState::ALL)]);
s.undo().unwrap();
assert_eq!(states(&s), [state("S1", LayerState::ALL), state("S2", LayerState::ALL)]);
}
#[test]
fn restore_finds_the_state_in_any_case() {
let mut s = drawing();
run(&mut s, "-LAYER A S S1\n\n\n\n");
run(&mut s, "-LAYER C 3 A M C\n\n");
let d = s.doc().unwrap();
assert_eq!((d.layer("A").unwrap().color, d.header.str("CLAYER", "0")), (cadcraft_color::Color::Index(3), "C".to_string()));
assert!(run(&mut s, "-LAYER A R s1\n\n\n").is_empty());
let d = s.doc().unwrap();
assert_eq!((d.layer("A").unwrap().color, d.header.str("CLAYER", "0")), (cadcraft_color::Color::Index(1), "0".to_string()));
}
#[test]
fn json_layer_states_take_a_mask_and_find_names_in_any_case() {
let mut s = drawing();
s.execute("layerstate.save", &json!({ "name": "M" })).unwrap();
s.execute("layerstate.save", &json!({ "name": "On", "mask": LayerState::ON })).unwrap();
for bad in [json!(4096), json!(-1), json!(1.5), json!("1")] {
assert!(s.execute("layerstate.save", &json!({ "name": "X", "mask": bad })).is_err(), "{bad}");
}
assert_eq!(states(&s), [state("M", LayerState::ALL), state("On", 513)]);
// Restore, Rename and Delete find a name in another case; a name another state has in any
// case is refused, the state's own in another case too.
s.execute("layer.set", &json!({ "name": "A", "color": "3" })).unwrap();
s.execute("layerstate.restore", &json!({ "name": "m" })).unwrap();
assert_eq!(s.doc().unwrap().layer("A").unwrap().color, cadcraft_color::Color::Index(1));
assert!(s.execute("layerstate.rename", &json!({ "from": "m", "to": "ON" })).is_err());
assert!(s.execute("layerstate.rename", &json!({ "from": "m", "to": "m" })).is_err());
s.execute("layerstate.rename", &json!({ "from": "m", "to": "M2" })).unwrap();
s.execute("layerstate.delete", &json!({ "name": "on" })).unwrap();
assert_eq!(states(&s), [state("M2", LayerState::ALL)]);
// A name -LAYER stAte Save refuses is refused here too, and nothing is saved.
let long = "x".repeat(256);
for name in ["", " ", "a<b", "a\nb", long.as_str()] {
assert!(s.execute("layerstate.save", &json!({ "name": name })).is_err(), "{name:?}");
}
assert_eq!(states(&s), [state("M2", LayerState::ALL)]);
// Save onto a name another state has in another case replaces that state, as one spelled the
// same: AutoCAD 2024 keeps one state per name in any case.
s.execute("layerstate.save", &json!({ "name": "m2", "mask": LayerState::ON })).unwrap();
assert_eq!(states(&s), [state("m2", 513)]);
// Names that differ only in case (CADCraft's own record keeps the second of them, which AutoCAD
// 2024 doesn't see): Save and Delete take the one spelled so, though the other comes first, and
// leave the other.
s.doc_mut().unwrap().layer_states.insert(0, LayerState::new("M2", Vec::new(), ""));
s.execute("layerstate.save", &json!({ "name": "m2", "mask": LayerState::ON | LayerState::FROZEN })).unwrap();
assert_eq!(states(&s), [state("M2", LayerState::ALL), state("m2", 515)]);
s.execute("layerstate.delete", &json!({ "name": "m2" })).unwrap();
assert_eq!(states(&s), [state("M2", LayerState::ALL)]);
}
-2
View File
@@ -4,7 +4,6 @@ mod annotate_options;
mod annotative;
mod arc_ctrl_direction;
mod array_commands;
mod array_key_point;
mod assoc_array;
mod attdef_command;
mod attdisp_attsync;
@@ -79,7 +78,6 @@ mod join_close;
mod json_param_validation;
mod layer_cmdline;
mod layer_merge_delete;
mod layer_state_cmdline;
mod layoff_repeat;
mod layout_prompts;
mod leader_command;
+7 -129
View File
@@ -76,135 +76,13 @@ fn rename_prompts_type_old_and_new_name() {
assert!(d.block("Pump").is_some() && d.layer("New").is_some() && d.layer("Old").is_none(), "{:?}", s.log);
assert_eq!(insert_targets(d), ["Assy", "Pump", "Pump", "Pump"]);
assert_eq!(d.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(), 1);
// A type CADCraft lacks reads both names and reports.
let n = s.log.len();
s.script("-RENAME M a b\nLINE 0,0 2,0\n\n").unwrap();
// An unknown old name re-prompts; a type CADCraft lacks reads both names and reports.
s.script("-RENAME LA Missing\nNew\nNewer\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert!(s.log[n..].iter().any(|l| l.contains("Renaming a material is not available yet.")), "{:?}", &s.log[n..]);
assert!(s.doc().unwrap().layer("Newer").is_some());
let n = s.log.len();
s.script("-RENAME VP a b\nLINE 0,0 2,0\n\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert!(s.log[n..].iter().any(|l| l.contains("not available yet")), "{:?}", &s.log[n..]);
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(), 2);
}
/// What `script` adds to the log; the command has ended.
fn said(s: &mut Session, script: &str) -> Vec<String> {
let n = s.log.len();
s.script(script).unwrap();
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
s.log[n..].to_vec()
}
fn says(log: &[String], text: &str) -> bool {
log.iter().any(|l| l.contains(text))
}
#[test]
fn rename_ends_on_a_name_it_cannot_take_with_autocads_messages() {
// AutoCAD 2024 (accoreconsole, measured, the same for blocks, dimension styles, layers,
// linetypes, text styles, UCSs and views): `Cannot find layer "X".` for an old name that
// doesn't exist, `A layer named "X" already exists.` and `*Invalid*` for a new name that does,
// `Invalid layer name.` for one it can't take; each ends the command.
let mut s = drawing();
for name in ["A1", "A2"] {
s.execute("layer.new", &json!({ "name": name })).unwrap();
}
let log = said(&mut s, "-RENAME LA NOSUCH\nLINE 0,0 3,0\n\n");
assert!(says(&log, "Cannot find layer \"NOSUCH\"."), "{log:?}");
// The command ended there: the next input started LINE.
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(), 1);
let log = said(&mut s, "-RENAME LA A1 A2\n");
assert!(says(&log, "A layer named \"A2\" already exists.") && says(&log, "*Invalid*"), "{log:?}");
let log = said(&mut s, "-RENAME LA A1 X<Y\n");
assert!(says(&log, "Invalid layer name."), "{log:?}");
// No new name at all is an invalid one too.
s.cmdline("-RENAME LA A1").unwrap();
let n = s.log.len();
s.cmdline("").unwrap();
assert!(s.running.is_none() && says(&s.log[n..], "Invalid layer name."), "{:?}", &s.log[n..]);
assert!(s.doc().unwrap().layer("A1").is_some());
said(&mut s, "-RENAME LA A1 B1\n");
assert!(s.doc().unwrap().layer("B1").is_some() && s.doc().unwrap().layer("A1").is_none());
// The old name in another case than stored, and the new name as typed: a rename to that case
// (AutoCAD 2024, measured: LAY1 typed lay1, new name lay1, gives lay1).
said(&mut s, "-RENAME LA b1 b1\n");
assert!(s.doc().unwrap().layers.iter().any(|l| l.name == "b1"));
// Old names AutoCAD 2024 won't rename (measured), each ending the command before the new name.
let lines = |s: &Session| s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
for (script, message) in [
("-RENAME LA 0\n", "Cannot rename layer \"0\"."),
("-RENAME LT continuous\n", "Cannot rename linetype \"continuous\"."),
("-RENAME LT ByLayer\n", "Invalid linetype name."),
("-RENAME LT byblock\n", "Invalid linetype name."),
("-RENAME LT CONTINUOUS\n", "Cannot rename linetype \"CONTINUOUS\"."),
("-RENAME B *Model_Space\n", "Invalid block name."),
("-RENAME B *U1\n", "Invalid block name."),
] {
let n = lines(&s);
let log = said(&mut s, &format!("{script}LINE 0,0 4,0\n\n"));
assert!(says(&log, message), "{script}: {log:?}");
assert_eq!(says(&log, "*Invalid*"), message.starts_with("Cannot"), "{script}: {log:?}");
assert_eq!(lines(&s), n + 1, "{script}: the next input starts a command");
}
// A UCS is "ucs" in the prompts and in "A ucs named", "UCS" in the other two.
for name in ["U1", "U2"] {
let ucs = cadcraft_engine::doc::Ucs { name: name.into(), origin: Default::default(), x_axis: Default::default(), y_axis: Default::default() };
s.doc_mut().unwrap().ucss.push(ucs);
}
s.cmdline("-RENAME U").unwrap();
assert!(s.prompt_text().contains("Enter old ucs name"), "{}", s.prompt_text());
s.cancel();
assert!(says(&said(&mut s, "-RENAME U NOSUCH\n"), "Cannot find UCS \"NOSUCH\"."));
assert!(says(&said(&mut s, "-RENAME U U1 U2\n"), "A ucs named \"U2\" already exists."));
assert!(says(&said(&mut s, "-RENAME U U1 X<Y\n"), "Invalid UCS name."));
}
#[test]
fn rename_takes_a_saved_viewport_configuration() {
// AutoCAD 2024 (measured): -RENAME VPort renames a saved configuration, every tile of it, old
// name in any case, and to another case of its own name; "*ACTIVE" (old or new), names with
// characters AutoCAD refuses and names already used are refused as for the other types.
let mut s = Session::new();
s.execute("-vports", &json!({ "option": "2", "arrangement": "vertical" })).unwrap();
s.execute("-vports", &json!({ "option": "save", "name": "CFG1" })).unwrap();
s.execute("-vports", &json!({ "option": "save", "name": "CFG3" })).unwrap();
let names = |s: &Session| -> Vec<(String, usize)> { s.doc().unwrap().vports.iter().map(|v| (v.name.clone(), v.tiles.len())).collect() };
said(&mut s, "-RENAME VP cfg1 CFG2\n");
assert_eq!(names(&s), [("*Active".to_string(), 2), ("CFG2".to_string(), 2), ("CFG3".to_string(), 2)]);
for (script, message) in [
// A refused old name ends the command before the new name is asked.
("-RENAME VP NOSUCH\n", "Cannot find viewport configuration \"NOSUCH\"."),
("-RENAME VP *ACTIVE\n", "Invalid viewport configuration name."),
("-RENAME VP CFG2 *ACTIVE\n", "Invalid viewport configuration name."),
("-RENAME VP CFG2 A<B\n", "Invalid viewport configuration name."),
("-RENAME VP CFG2 CFG3\n", "A viewport configuration named \"CFG3\" already exists."),
] {
let log = said(&mut s, script);
assert!(says(&log, message), "{script}: {log:?}");
// "*Invalid*" follows a name already used only.
assert_eq!(says(&log, "*Invalid*"), message.ends_with("already exists."), "{script}: {log:?}");
}
// No new name at all is an invalid one too (measured: CFG1, then Enter).
s.cmdline("-RENAME VP CFG2").unwrap();
let n = s.log.len();
s.cmdline("").unwrap();
assert!(s.running.is_none() && says(&s.log[n..], "Invalid viewport configuration name."), "{:?}", &s.log[n..]);
assert_eq!(names(&s), [("*Active".to_string(), 2), ("CFG2".to_string(), 2), ("CFG3".to_string(), 2)]);
said(&mut s, "-RENAME VP CFG2 cfg2\n");
assert_eq!(names(&s), [("*Active".to_string(), 2), ("cfg2".to_string(), 2), ("CFG3".to_string(), 2)]);
// The new name is compared with the stored one, not with the old name as typed (measured:
// CFG1 typed cfg1 to cfg1 gives cfg1; typed cfg1 to CFG1 changes nothing).
said(&mut s, "-RENAME VP CFG2 CFG2\n");
assert_eq!(names(&s)[1].0, "CFG2");
said(&mut s, "-RENAME VP cfg2 CFG2\n");
assert_eq!(names(&s)[1].0, "CFG2");
said(&mut s, "-RENAME VP cfg2 cfg2\n");
assert_eq!(names(&s)[1].0, "cfg2");
// The JSON form too, which never takes the configuration shown, and refuses a name already
// used (in any case) or with a character AutoCAD refuses, as for the other tables.
s.execute("rename", &json!({ "table": "vport", "from": "CFG3", "to": "Pair" })).unwrap();
assert_eq!(names(&s)[2].0, "Pair");
for to in ["Shown", "CFG2", "A<B"] {
let from = if to == "Shown" { "*Active" } else { "Pair" };
assert!(s.execute("rename", &json!({ "table": "vport", "from": from, "to": to })).is_err(), "{from} to {to}");
}
s.execute("rename", &json!({ "table": "vport", "from": "pair", "to": "PAIR" })).unwrap();
assert_eq!(names(&s), [("*Active".to_string(), 2), ("cfg2".to_string(), 2), ("PAIR".to_string(), 2)]);
}
+19 -6
View File
@@ -56,11 +56,17 @@ pub struct ShxGlyph {
pub advance: Vec2,
}
/// Glyphs cached per font, keyed by (shape, vertical).
type GlyphCache = HashMap<(u16, bool), Option<Arc<ShxGlyph>>>;
/// Glyphs cached per font, keyed by (shape, vertical), and their points in all.
#[derive(Default)]
struct GlyphCache {
glyphs: HashMap<(u16, bool), Option<Arc<ShxGlyph>>>,
points: usize,
}
/// Most glyphs cached per font (a big font has thousands; text uses a few hundred).
const MAX_CACHED_GLYPHS: usize = 16_384;
/// Most points cached per font (16 MB; a glyph may hold thousands of points).
const MAX_CACHED_POINTS: usize = 1 << 20;
/// A parsed SHX file.
pub struct ShxFont {
@@ -203,15 +209,22 @@ impl ShxFont {
}
let vertical = vertical && self.dual;
let key = (number, vertical);
if let Some(g) = self.cache.read().unwrap_or_else(PoisonError::into_inner).get(&key) {
if let Some(g) = self.cache.read().unwrap_or_else(PoisonError::into_inner).glyphs.get(&key) {
return g.clone();
}
let g = program::outline(self, number, vertical).ok().map(Arc::new);
let points = g.as_ref().map_or(0, |g| g.strokes.iter().map(Vec::len).sum::<usize>());
let mut c = self.cache.write().unwrap_or_else(PoisonError::into_inner);
if c.len() >= MAX_CACHED_GLYPHS {
c.clear();
// Another thread may have outlined it in the meantime: its points are counted already.
if let Some(g) = c.glyphs.get(&key) {
return g.clone();
}
c.insert(key, g.clone());
if c.glyphs.len() >= MAX_CACHED_GLYPHS || c.points.saturating_add(points) > MAX_CACHED_POINTS {
c.glyphs.clear();
c.points = 0;
}
c.points = c.points.saturating_add(points);
c.glyphs.insert(key, g.clone());
g
}
}
+16
View File
@@ -309,6 +309,22 @@ fn hostile_files_never_panic() {
assert!(compile("").is_err());
}
#[test]
fn the_glyph_cache_is_bounded_by_points() {
// Hostile: every glyph at the point bound, so 16,384 cached glyphs would hold 2 GB.
let mut src = format!("*2,1,HUNDRED\n{}0\n*3,3,V\n011,019,0\n", "7,3,".repeat(100));
for n in 10..=200 {
src.push_str(&format!("*{n},1,HEAVY\n{}0\n", "7,2,".repeat(40)));
}
let f = font(&src);
for n in 10..=200 {
assert!(f.glyph(n, false).is_some());
}
let c = f.cache.read().unwrap();
let cached: usize = c.glyphs.values().flatten().map(|g| g.strokes.iter().map(Vec::len).sum::<usize>()).sum();
assert!(cached <= MAX_CACHED_POINTS && cached == c.points, "{cached}");
}
/// Register a compiled test font under `name` (each test its own names: the table is shared).
fn reg(name: &str, src: &str) {
register(name, &compile(src).unwrap()).unwrap();
-294
View File
@@ -1,294 +0,0 @@
//! Saved layer states as AutoCAD keeps them: the LAYER table's extension dictionary holds an
//! `ACAD_LAYERSTATES` dictionary of one XRECORD per state. Measured in AutoCAD 2024 (DXFOUT of
//! states saved with -LAYER stAte), an XRECORD holds `280 1`, the mask (91), a text (301: empty
//! as -LAYER saves it; AutoCAD keeps one a file holds through restore and DXFOUT), `290 0` and
//! the current layer's name (302), then for each layer its LAYER handle (330),
//! flags (90: 1 off, 2 frozen, 4 locked, 8 plotted, 16 frozen in new viewports), colour index
//! (62), lineweight (370), for a layer of an xref 93 (0 for a newly attached one; a file can hold
//! 1, whose meaning isn't measured), LTYPE handle (331), plot style (in a drawing of colour-dependent
//! plot styles the name `Color_N` in group 1, N its colour index; of named ones the handle of its
//! placeholder object in group 390), transparency (440: 0 opaque, else `0x02000000 | alpha`) and,
//! for a true colour, 92 (`0xC2RRGGBB`).
//!
//! States AutoCAD's dictionary can't hold stay in CADCraft's own record (`CADCRAFT_LAYERSTATES`):
//! the view layer snapshots (`*VIEW name`), and a name that repeats an earlier one in another
//! case: AutoCAD 2024 opens the entries `S` and `s` of one dictionary as one state, named as the
//! first entry and holding the last one's record (measured), and so does the reader here.
use std::collections::{HashMap, HashSet};
use cadcraft_color::{Color, Rgb};
use cadcraft_doc::{Layer, LayerState, Lineweight};
use craft_dxf::Tag;
use crate::dxf_ext::{transparency_from_dxf, transparency_to_dxf};
/// The key of the states dictionary in the LAYER table's extension dictionary.
pub(crate) const KEY: &str = "ACAD_LAYERSTATES";
/// The prefix of a true colour in group 92.
const TRUE_COLOR: u32 = 0xC200_0000;
/// The bytes of layers the states of one file may copy (CWE-400). Each entry of a state is a copy
/// of the drawing's layer, its names and description included, so without a bound a small file
/// naming one layer with a long description in a great many entries would take gigabytes.
pub(crate) const MAX_COPIED_BYTES: usize = 256 << 20;
/// Which of `states` go into AutoCAD's dictionary (the others into CADCraft's record).
pub(crate) fn in_acad(states: &[LayerState]) -> Vec<bool> {
let mut seen: HashSet<String> = HashSet::with_capacity(states.len());
states.iter().map(|st| !st.name.trim().is_empty() && !st.name.starts_with('*') && seen.insert(st.name.to_lowercase())).collect()
}
/// The states CADCraft's own record keeps (those [`in_acad`] leaves out).
pub(crate) fn own(states: &[LayerState]) -> Vec<LayerState> {
states.iter().zip(in_acad(states)).filter(|(_, acad)| !acad).map(|(st, _)| st.clone()).collect()
}
/// Handles of the objects that hold the drawing's states in AutoCAD's form.
#[derive(Default)]
pub(crate) struct Plan {
/// The LAYER table, which owns the extension dictionary.
pub table: String,
/// The LAYER table's extension dictionary.
pub xdict: String,
/// The `ACAD_LAYERSTATES` dictionary.
dict: String,
/// (index in the drawing's states, XRECORD handle).
records: Vec<(usize, String)>,
}
impl Plan {
pub fn new(states: &[LayerState], mut handle: impl FnMut() -> String) -> Self {
let acad = in_acad(states);
if !acad.contains(&true) {
return Plan::default();
}
let xdict = handle();
let dict = handle();
let records = acad.iter().enumerate().filter(|(_, a)| **a).map(|(i, _)| (i, handle())).collect();
Plan { table: String::new(), xdict, dict, records }
}
pub fn is_empty(&self) -> bool {
self.records.is_empty()
}
}
/// What the state objects need from the rest of the file.
pub(crate) struct Refs<'a> {
/// Upper-case layer name → LAYER record handle.
pub layers: &'a HashMap<String, String>,
/// Upper-case linetype name → LTYPE record handle.
pub ltypes: &'a HashMap<String, String>,
/// Upper-case plot style name → its placeholder object's handle.
pub pstyles: &'a HashMap<String, String>,
/// Plot styles by colour (`$PSTYLEMODE` 1): the plot style name is `Color_N`.
pub colour_dependent: bool,
}
/// The objects of plan `p`: the extension dictionary, the `ACAD_LAYERSTATES` dictionary and one
/// XRECORD per state. Layers the drawing no longer has are left out of a state (AutoCAD names
/// layers by handle).
pub(crate) fn objects(p: &Plan, states: &[LayerState], refs: &Refs) -> Vec<Tag> {
let mut t = Vec::new();
if p.is_empty() {
return t;
}
t.extend([Tag::s(0, "DICTIONARY"), Tag::s(5, &p.xdict), Tag::s(330, &p.table), Tag::s(100, "AcDbDictionary"), Tag::i(280, 1), Tag::i(281, 1)]);
t.extend([Tag::s(3, KEY), Tag::s(360, &p.dict)]);
t.extend([Tag::s(0, "DICTIONARY"), Tag::s(5, &p.dict), Tag::s(102, "{ACAD_REACTORS"), Tag::s(330, &p.xdict), Tag::s(102, "}")]);
t.extend([Tag::s(330, &p.xdict), Tag::s(100, "AcDbDictionary"), Tag::i(281, 1)]);
let planned = || p.records.iter().filter_map(|(i, h)| Some((states.get(*i)?, h)));
for (st, h) in planned() {
t.extend([Tag::s(3, &st.name), Tag::s(350, h)]);
}
for (st, h) in planned() {
t.extend([Tag::s(0, "XRECORD"), Tag::s(5, h), Tag::s(102, "{ACAD_REACTORS"), Tag::s(330, &p.dict), Tag::s(102, "}"), Tag::s(330, &p.dict)]);
t.extend([Tag::s(100, "AcDbXrecord"), Tag::i(280, 1), Tag::i(91, i64::from(st.mask)), Tag::s(301, &st.description), Tag::i(290, 0)]);
t.push(Tag::s(302, &st.current));
for l in &st.layers {
if let Some(lh) = refs.layers.get(&l.name.to_ascii_uppercase()) {
layer(&mut t, l, lh, refs);
}
}
}
t
}
/// One layer of a state's XRECORD.
fn layer(t: &mut Vec<Tag>, l: &Layer, handle: &str, refs: &Refs) {
let flags = i64::from(!l.on) | i64::from(l.frozen) << 1 | i64::from(l.locked) << 2 | i64::from(l.plot) << 3 | i64::from(l.vp_freeze_new) << 4;
let aci = match l.color {
Color::True(rgb) => i64::from(cadcraft_color::nearest_aci(rgb)),
c => i64::from(c.to_aci()).clamp(1, 255),
};
t.extend([Tag::s(330, handle), Tag::i(90, flags), Tag::i(62, aci), Tag::i(370, i64::from(l.lineweight.to_dxf()))]);
if crate::dxf_xref::dependent(&l.name) {
t.push(Tag::i(93, 0));
}
// A linetype the drawing no longer has: Continuous, which every drawing has.
if let Some(lt) = refs.ltypes.get(&l.linetype.to_ascii_uppercase()).or_else(|| refs.ltypes.get("CONTINUOUS")) {
t.push(Tag::s(331, lt));
}
if refs.colour_dependent {
t.push(Tag::s(1, format!("Color_{aci}")));
} else if let Some(ps) = refs.pstyles.get(&l.plot_style.trim().to_ascii_uppercase()).or_else(|| refs.pstyles.get("NORMAL")) {
t.push(Tag::s(390, ps));
}
t.push(Tag::i(440, if l.transparency == 0 { 0 } else { transparency_to_dxf(l.transparency) }));
if let Color::True(rgb) = l.color {
t.push(Tag::i(92, i64::from(i32::from_be_bytes((TRUE_COLOR | rgb.to_u32()).to_be_bytes()))));
}
}
/// What a state's handles name in the drawing being read.
pub(crate) struct Lookup<'a> {
/// The drawing's layer a LAYER handle names: a state's layer starts as a copy of it (what the
/// state doesn't hold, such as the description, is the drawing's).
pub layer: &'a dyn Fn(&str) -> Option<Layer>,
/// The linetype an LTYPE handle names.
pub ltype: &'a dyn Fn(&str) -> Option<String>,
/// The plot style a placeholder handle names.
pub pstyle: &'a dyn Fn(&str) -> Option<String>,
/// Plot styles by colour: group 1 (`Color_N`) says nothing the layer's colour doesn't.
pub colour_dependent: bool,
}
/// The state `name` from its XRECORD's groups. A layer whose record is gone (AutoCAD keeps a
/// purged layer's entry, measured) is skipped. A layer named in two entries is in the state once,
/// the later entry's groups over the earlier one's, as restoring both in turn did: AutoCAD 2024
/// restores the later one (measured with entries that each set every property). Each copy of a
/// layer is charged to `budget`, the file's [`MAX_COPIED_BYTES`]; once it is spent, the entries
/// left are left out.
pub(crate) fn read(name: &str, tags: &[Tag], lookup: &Lookup, budget: &mut usize) -> LayerState {
let mut st = LayerState { name: name.to_string(), ..LayerState::default() };
// The data follows the subclass marker (an XRECORD without one holds none).
let start = tags.iter().position(|t| t.code == 100 && t.str().trim() == "AcDbXrecord").map_or(tags.len(), |i| i + 1);
let body = tags.get(start..).unwrap_or_default();
let first = body.iter().position(|t| t.code == 330).unwrap_or(body.len());
for t in body.get(..first).unwrap_or_default() {
match t.code {
91 => st.mask = t.str().trim().parse::<u32>().unwrap_or(LayerState::ALL),
301 => st.description = t.str(),
302 => st.current = t.str(),
_ => {}
}
}
let rest = body.get(first..).unwrap_or_default();
// The index in the state of each layer by its LAYER handle.
let mut index: HashMap<String, usize> = HashMap::new();
let mut at = 0;
while let Some(group) = rest.get(at..) {
let Some(head) = group.first() else { break };
let len = group.iter().skip(1).position(|t| t.code == 330).map_or(group.len(), |n| n + 1);
at += len;
let groups = group.get(1..len).unwrap_or_default();
let key = head.str().trim().to_ascii_uppercase();
if let Some(slot) = index.get(&key).and_then(|&i| st.layers.get_mut(i)) {
entry(slot, groups, lookup);
} else if let Some(mut l) = (lookup.layer)(&head.str()) {
let Some(left) = budget.checked_sub(cost(&l)) else { break };
*budget = left;
entry(&mut l, groups, lookup);
index.insert(key, st.layers.len());
st.layers.push(l);
}
}
st
}
/// The bytes a copy of layer `l` takes.
fn cost(l: &Layer) -> usize {
std::mem::size_of::<Layer>() + l.name.len() + l.linetype.len() + l.description.len() + l.plot_style.len()
}
/// A layer's properties from the groups after its handle.
fn entry(l: &mut Layer, groups: &[Tag], lookup: &Lookup) {
let int = |t: &Tag| t.str().trim().parse::<i64>().ok();
let mut true_color = None;
for t in groups {
match t.code {
90 => {
if let Some(f) = int(t) {
(l.on, l.frozen, l.locked, l.plot, l.vp_freeze_new) = (f & 1 == 0, f & 2 != 0, f & 4 != 0, f & 8 != 0, f & 16 != 0);
}
}
62 => {
if let Some(c) = int(t).map(i64::abs).and_then(|c| u8::try_from(c).ok()).filter(|c| *c >= 1) {
l.color = Color::Index(c);
}
}
92 => true_color = int(t).and_then(|v| u32::try_from(v & 0xFFFF_FFFF).ok()).filter(|v| v & 0xFF00_0000 == TRUE_COLOR),
370 => {
if let Some(w) = int(t).and_then(|w| i16::try_from(w).ok()) {
l.lineweight = Lineweight::from_dxf(w);
}
}
331 => {
if let Some(lt) = (lookup.ltype)(&t.str()) {
l.linetype = lt;
}
}
390 => {
if let Some(ps) = (lookup.pstyle)(&t.str()) {
l.plot_style = ps;
}
}
1 if !lookup.colour_dependent => l.plot_style = t.str(),
440 => {
if let Some(v) = int(t) {
l.transparency = transparency_from_dxf(v).unwrap_or(0);
}
}
_ => {}
}
}
if let Some(v) = true_color {
l.color = Color::True(Rgb::from_u32(v & 0x00FF_FFFF));
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A state's XRECORD groups with an entry per (layer handle, colour index).
fn tags(entries: &[(&str, i64)]) -> Vec<Tag> {
let mut t = vec![Tag::s(100, "AcDbXrecord"), Tag::i(280, 1), Tag::i(91, 2047), Tag::s(302, "0")];
for (h, aci) in entries {
t.extend([Tag::s(330, *h), Tag::i(90, 8)]);
// 0: no colour group.
if *aci != 0 {
t.push(Tag::i(62, *aci));
}
}
t
}
#[test]
fn a_layer_named_twice_takes_its_last_entry_and_copies_stop_at_the_budget() {
let layer = |h: &str| match h {
"A1" => Some(Layer::new("A")),
"B1" => Some(Layer::new("B")),
_ => None,
};
let none = |_: &str| None::<String>;
let lookup = Lookup { layer: &layer, ltype: &none, pstyle: &none, colour_dependent: true };
let colours = |st: &LayerState| st.layers.iter().map(|l| (l.name.clone(), l.color)).collect::<Vec<_>>();
// AutoCAD 2024 restores the last of two entries of one layer (measured: green, then blue,
// restores blue); it stays in the first one's place. A later entry without a colour keeps
// the earlier one's, as restoring both in turn did.
let mut budget = MAX_COPIED_BYTES;
let st = read("S", &tags(&[("A1", 3), ("B1", 2), ("A1", 5), ("B1", 0)]), &lookup, &mut budget);
assert_eq!(colours(&st), [("A".to_string(), Color::Index(5)), ("B".to_string(), Color::Index(2))]);
// Each new copy is charged (a repeated entry copies nothing); past the budget the rest of
// the entries, and of the file's states, are left out.
let one = cost(&Layer::new("A"));
let mut budget = one;
let st = read("S", &tags(&[("A1", 3), ("A1", 4), ("B1", 5)]), &lookup, &mut budget);
assert_eq!((colours(&st), budget), (vec![("A".to_string(), Color::Index(4))], 0));
let st = read("T", &tags(&[("B1", 2)]), &lookup, &mut budget);
assert!(st.layers.is_empty());
}
}
+55 -83
View File
@@ -36,11 +36,10 @@ const MODELLED_KEYS: &[&str] = &[
"ACAD_IMAGE_VARS",
];
/// Extension dictionary entries not kept raw: dimension associativity and the LAYER table's layer
/// states (CADCraft reads and rewrites them), draw order and annotation scale contexts (written
/// from their own models by the changes that model them; stale copies would contradict the
/// drawing).
const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_LAYERSTATES", "ACAD_SORTENTS", "ACDBCONTEXTDATAMANAGER"];
/// Extension dictionary entries not kept raw: dimension associativity (CADCraft reads and
/// rewrites it), draw order and annotation scale contexts (written from their own models by the
/// changes that model them; stale copies would contradict the drawing).
const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_SORTENTS", "ACDBCONTEXTDATAMANAGER"];
/// Applications whose xdata CADCraft reads and writes itself. `ACAD` holds dimension overrides
/// (DSTYLE) on dimensions and dimension styles; elsewhere it is kept.
@@ -990,7 +989,20 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
let root = objects.first().filter(|(k, _, _)| is_dictionary(k)).map(|(_, s, _)| *s);
let root_keys: HashSet<String> =
objects.iter().find(|(_, s, _)| Some(*s) == root).map(|(_, _, t)| entries(t).into_iter().map(|(k, _)| up(&k)).collect()).unwrap_or_default();
let (mut attached, merged) = kept_dictionaries(f, &xd, &recs, tags);
// Extension dictionaries that go on a written record (one without its own).
let mut block = String::new();
let mut attached: HashSet<String> = HashSet::new();
for r in &recs {
if r.kind == "BLOCK" {
block = up(&val(body(r), 2).unwrap_or_default());
}
if let Some(x) = extra_for(f, &xd, r, body(r), &block)
&& let Some(xd) = x.xdict
&& head(body(r)).xdict.is_none()
{
attached.insert(xd.hex());
}
}
for (_, t) in planned.values().flatten() {
let x = head(t.get(1..).unwrap_or(&[])).handle.and_then(|h| handle(&h)).and_then(|h| entity_extra(f, &xd, h));
attached.extend(x.and_then(|x| x.xdict).map(Handle::hex));
@@ -1038,7 +1050,7 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
if nod.contains(&owner) {
break dict_entries.get(&cur).is_some_and(|k| !root_keys.contains(&up(k))) && root.is_some();
}
if attached.contains(&cur) || merged.contains_key(&cur) {
if attached.contains(&cur) {
break true;
}
break unknown.contains(&owner) && written.contains(&owner);
@@ -1050,19 +1062,11 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
alive_memo
});
// New handles for the written kept objects, above every written handle and the seed.
let mut next = seed(tags).max(max_handle(tags).saturating_add(1));
let mut fresh = Fresh::new(tags);
let mut alive: HashMap<String, String> = HashMap::new();
for o in f.objects.iter().filter(|o| alive_memo.get(&o.handle.hex()) == Some(&true)) {
alive.insert(o.handle.hex(), format!("{next:X}"));
next = next.saturating_add(1);
alive.insert(o.handle.hex(), format!("{:X}", fresh.take()));
}
// A merged dictionary is not written: what pointed at it points at the written one.
for (kept, own) in &merged {
if let Some(h) = alive.get_mut(kept) {
h.clone_from(own);
}
}
let merged_into: HashMap<String, &ForeignObject> = merged.iter().filter_map(|(kept, own)| Some((own.clone(), *objs.get(kept)?))).collect();
let entities: HashSet<String> = all_entities(d).map(|e| e.handle.hex()).filter(|h| written.contains(h)).collect();
let map = Map { f, alive, raw: objs.keys().cloned().collect(), roles, entities };
let mut out: Vec<Tag> = Vec::with_capacity(tags.len() + f.objects.iter().map(|o| o.tags.len() + 1).sum::<usize>());
@@ -1076,7 +1080,7 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
continue;
}
if r.kind == "ENDSEC" && r.sec == "OBJECTS" {
for o in f.objects.iter().filter(|o| map.alive.contains_key(&o.handle.hex()) && !merged.contains_key(&o.handle.hex())) {
for o in f.objects.iter().filter(|o| map.alive.contains_key(&o.handle.hex())) {
let number = is_proxy(&o.kind).then(|| renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str()))))).flatten();
match number {
Some(n) => {
@@ -1100,15 +1104,11 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
}
out.extend(tags.get(r.start).cloned());
let x = extra_for(f, &xd, r, b, &block);
let joined = joined_into(&merged_into, b);
if x.is_none() && Some(r.start) != root && joined.is_none() {
if x.is_none() && Some(r.start) != root {
out.extend(b.iter().cloned());
continue;
}
record(&map, r, b, x.as_deref(), None, Some(r.start) == root, &mut out);
if let Some(kept) = joined {
join_entries(&map, b, kept, &mut out);
}
}
add_appids(&mut out);
let top = max_handle(&out).saturating_add(1);
@@ -1120,32 +1120,6 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
*tags = out;
}
/// Kept extension dictionaries of written records: those that go on a record without its own,
/// and those whose entries join the one the writer gave a table (the LAYER table's, holding the
/// layer states) as kept dictionary → the written one.
fn kept_dictionaries(f: &Foreign, xd: &XdataOf, recs: &[Rec], tags: &[Tag]) -> (HashSet<String>, HashMap<String, String>) {
let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]);
let mut block = String::new();
let mut attached: HashSet<String> = HashSet::new();
let mut merged: HashMap<String, String> = HashMap::new();
for r in recs {
if r.kind == "BLOCK" {
block = up(&val(body(r), 2).unwrap_or_default());
}
let Some(kept) = extra_for(f, xd, r, body(r), &block).and_then(|x| x.xdict) else { continue };
match head(body(r)).xdict {
None => {
attached.insert(kept.hex());
}
Some(own) if r.sec == "TABLES" => {
merged.insert(kept.hex(), own);
}
Some(_) => {}
}
}
(attached, merged)
}
/// Complete source tables keep positional identities even when names repeat.
fn proxy_class_number(f: &Foreign, numbers: &HashMap<String, i64>, old: Option<i64>) -> Option<i64> {
if f.complete_class_table {
@@ -1377,37 +1351,6 @@ fn record(map: &Map, r: &Rec, b: &[Tag], x: Option<&ForeignExtra>, unknown: Opti
}
}
/// The kept dictionary whose entries join written dictionary `b`, if any.
fn joined_into<'a>(merged_into: &HashMap<String, &'a ForeignObject>, b: &[Tag]) -> Option<&'a ForeignObject> {
if merged_into.is_empty() {
return None;
}
head(b).handle.and_then(|h| merged_into.get(&h).copied())
}
/// The entries of kept dictionary `kept` that written dictionary `b` doesn't have (by key, without
/// regard to case), appended to it with their handles remapped; entries whose object is gone are
/// left out.
fn join_entries(map: &Map, b: &[Tag], kept: &ForeignObject, out: &mut Vec<Tag>) {
let has = |key: &str| b.iter().any(|t| t.code == 3 && up(&t.str()) == up(key));
let mut key: Option<&str> = None;
for t in kept.tags.iter().take_while(|t| t.code < 1000) {
match t.code {
3 => key = Some(t.value.as_str()),
350 | 360 => {
if let Some(k) = key.take()
&& !has(k)
&& let Some(h) = map.get(&t.value).filter(|h| h != "0")
{
out.push(Tag::s(3, k));
out.push(Tag::s(t.code, h));
}
}
_ => {}
}
}
}
/// Kept xdata of applications the record doesn't already carry, handles remapped.
fn xdata(map: &Map, x: &ForeignExtra, own: &HashSet<String>, out: &mut Vec<Tag>) {
let mut skip = false;
@@ -1445,19 +1388,18 @@ fn add_appids(out: &mut Vec<Tag>) {
return;
}
// New handles above the seed, which is then moved past them.
let mut next = seed(out).max(max_handle(out).saturating_add(1));
let mut fresh = Fresh::new(out);
let mut add = Vec::new();
for app in &missing {
add.extend([
Tag::s(0, "APPID"),
Tag::s(5, format!("{next:X}")),
Tag::s(5, format!("{:X}", fresh.take())),
Tag::s(330, table_h.clone()),
Tag::s(100, "AcDbSymbolTableRecord"),
Tag::s(100, "AcDbRegAppTableRecord"),
Tag::s(2, (*app).clone()),
Tag::i(70, 0),
]);
next = next.saturating_add(1);
}
let end_at = end.start;
if let Some(count) = out.get_mut(t.start + 1..t.end).and_then(|b| b.iter_mut().find(|x| x.code == 70)) {
@@ -1476,6 +1418,36 @@ fn seed(tags: &[Tag]) -> u64 {
seed_index(tags).and_then(|i| tags.get(i)).and_then(|t| Handle::parse_hex(&t.str())).map_or(0, |h| h.0)
}
/// New handles for records added to written tags: above the seed and every handle written, and
/// never one a record already holds. A file may hold the top handle (#913): then counting on from
/// it would give every added record that same handle, so past the top of the range the numbering
/// goes on in the reserved band above [`cadcraft_doc::HANDLE_LIMIT`], skipping the handles there.
struct Fresh {
next: u64,
used: HashSet<u64>,
}
impl Fresh {
fn new(tags: &[Tag]) -> Self {
let used: HashSet<u64> =
tags.iter().filter(|t| t.code == 5 || t.code == 105).filter_map(|t| Handle::parse_hex(&t.str())).map(|h| h.0).collect();
let above = used.iter().max().map_or(0, |h| h.checked_add(1).unwrap_or(cadcraft_doc::HANDLE_LIMIT));
Fresh { next: seed(tags).max(above), used }
}
/// The next free handle. Each handle skipped is one a record holds, so the walk is bounded
/// by their count (and handle 0, which means "none").
fn take(&mut self) -> u64 {
for _ in 0..self.used.len().saturating_add(2) {
let h = self.next;
self.next = h.checked_add(1).unwrap_or(cadcraft_doc::HANDLE_LIMIT);
if h != 0 && self.used.insert(h) {
return h;
}
}
self.next
}
}
/// The largest handle of a record (groups 5 and 105).
fn max_handle(tags: &[Tag]) -> u64 {
tags.iter().filter(|t| t.code == 5 || t.code == 105).filter_map(|t| Handle::parse_hex(&t.str())).map(|h| h.0).max().unwrap_or(0)
+32 -4
View File
@@ -102,11 +102,36 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result<Drawing> {
// its $HANDSEED can be lower than its handles, and entities made while reading (the faces of
// a polygon mesh) would otherwise get handles that records further on still have. A file
// CADCraft wrote names its own next handle, above which its rebuilt records are numbered
// (#495), so it is left to that.
// (#495), so for it only the entity records are reserved. Handles in the reserved band are
// reserved for allocation rather than followed (#913): a handle-less entity read before the
// section that names one is placed would otherwise be given it and replace the record (#1276).
let ours = secs.iter().any(|s| s.name == "OBJECTS" && s.tags.iter().any(|t| t.code == 3 && t.str() == crate::dxf_ext::HANDSEED_KEY));
for t in secs.iter().filter(|_| !ours).flat_map(|s| s.tags.iter()).filter(|t| t.code == 5 || t.code == 105) {
if let Some(h) = Handle::parse_hex(t.str().trim()) {
d.bump_handseed(h);
if ours {
// Its table and object records are numbered above its seed and rebuilt on save (#495),
// so only its entities are reserved. Reading is section by section: an entity that has
// no handle, or repeats one within its section, gets a fresh handle, and that must not
// be one an entity of a later section still names. `BLOCK` and `ENDBLK` are structural
// records, not entities, and are left out so they don't move the saved seed.
for (kind, tags) in secs.iter().filter(|s| s.name == "BLOCKS" || s.name == "ENTITIES").flat_map(|s| records(&s.tags)) {
if matches!(kind.as_str(), "BLOCK" | "ENDBLK") {
continue;
}
if let Some(h) = tags.iter().find(|t| t.code == 5).and_then(|t| Handle::parse_hex(t.str().trim())) {
d.bump_handseed(h);
d.reserve_handle(h);
}
}
} else {
for s in &secs {
let entity_section = s.name == "BLOCKS" || s.name == "ENTITIES";
for t in s.tags.iter().filter(|t| t.code == 5 || t.code == 105) {
if let Some(h) = Handle::parse_hex(t.str().trim()) {
d.bump_handseed(h);
if entity_section {
d.reserve_handle(h);
}
}
}
}
}
let mut skipped = std::collections::BTreeMap::new();
@@ -148,6 +173,9 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result<Drawing> {
crate::dxf_raw::read(&secs, &mut d);
crate::dxf_clip::read(&mut d);
d.skipped_records = skipped;
// Every record is placed now, and an object holding a reserved handle keeps it from new
// objects by itself. Kept, the set would be copied with every undo step of the drawing.
d.reserved_handles.clear();
Ok(d)
}
+1
View File
@@ -55,6 +55,7 @@ pub(super) fn parse_entities(
}
if let Some((c, mut k)) = kindent {
let h = match handle {
// A file's handles keep their identity, however high they are (#913, #939).
Some(h) => {
d.bump_handseed(h);
h
+5 -96
View File
@@ -8,14 +8,10 @@ use super::{Drawing, EntityKind, Group, Handle, HashMap, MLeaderStyle, PageSetup
pub(super) struct Objects {
/// Dictionary entry handle (upper case) → entry name.
names: HashMap<String, String>,
/// (dictionary handle, entry handle), both upper case, in the order the dictionaries list them.
entry_order: Vec<(String, String)>,
/// SCALE objects (the annotation scale list), in file order.
scales: Vec<cadcraft_doc::AnnoScale>,
/// XRECORD handle (upper case) → its groups.
xrecords: HashMap<String, Vec<Tag>>,
/// XRECORD handles in file order.
xrecord_order: Vec<String>,
/// TABLESTYLE objects: (handle, groups).
table_styles: Vec<(String, Vec<Tag>)>,
/// DIMASSOC objects.
@@ -54,11 +50,7 @@ impl Objects {
if let Some(n) = name.take()
&& self.names.len() < MAX_OBJECTS
{
let entry = t.str().trim().to_ascii_uppercase();
if self.entry_order.len() < MAX_OBJECTS {
self.entry_order.push((h.clone(), entry.clone()));
}
self.names.insert(entry, n);
self.names.insert(t.str().trim().to_ascii_uppercase(), n);
}
}
_ => {}
@@ -66,9 +58,7 @@ impl Objects {
}
}
"XRECORD" if self.xrecords.len() < MAX_OBJECTS => {
if self.xrecords.insert(h.clone(), tags.to_vec()).is_none() {
self.xrecord_order.push(h);
}
self.xrecords.insert(h, tags.to_vec());
}
"TABLESTYLE" if self.table_styles.len() < MAX_OBJECTS => self.table_styles.push((h, tags.to_vec())),
"DIMASSOC" if self.dimassocs.len() < MAX_OBJECTS => self.dimassocs.push(tags.to_vec()),
@@ -90,65 +80,6 @@ impl Objects {
}
}
/// The layer states of the LAYER table's `ACAD_LAYERSTATES` dictionary (its XRECORDs, in file
/// order), read with the drawing's layers and linetypes. Entries whose names differ only in case
/// are one state, as AutoCAD 2024 opens them (measured with `S` and `s` in both orders): named as
/// the first of them in the dictionary, holding the last one's record, where the first of their
/// records comes in the file.
fn acad_layer_states(&self, d: &Drawing, rx: &Rx) -> Vec<cadcraft_doc::LayerState> {
let dicts: std::collections::HashSet<&str> =
self.names.iter().filter(|(_, n)| n.eq_ignore_ascii_case(crate::dxf_layer_states::KEY)).map(|(h, _)| h.as_str()).collect();
if dicts.is_empty() {
return Vec::new();
}
let mut by_name: HashMap<String, &cadcraft_doc::Layer> = HashMap::with_capacity(d.layers.len());
for l in &d.layers {
by_name.entry(l.name.to_ascii_lowercase()).or_insert(l);
}
let layer_of =
|h: &str| rx.layers.get(&h.trim().to_ascii_uppercase()).and_then(|n| by_name.get(&n.to_ascii_lowercase())).map(|l| (*l).clone());
let ltype_of = |h: &str| rx.ltypes.get(&h.trim().to_ascii_uppercase()).cloned();
let pstyle_of = |h: &str| rx.pstyles.get(&h.trim().to_ascii_uppercase()).cloned();
let lookup = crate::dxf_layer_states::Lookup {
layer: &layer_of,
ltype: &ltype_of,
pstyle: &pstyle_of,
colour_dependent: d.header.i64("PSTYLEMODE", 1) != 0,
};
let ours = |tags: &[Tag]| owner(tags).is_some_and(|o| dicts.contains(o.as_str()));
// By lower-case name: the first entry's name and the last entry's record, in dictionary order.
let mut first: HashMap<String, &String> = HashMap::new();
let mut last: HashMap<String, &Vec<Tag>> = HashMap::new();
for (dict, h) in &self.entry_order {
if dicts.contains(dict.as_str())
&& let (Some(name), Some(tags)) = (self.names.get(h), self.xrecords.get(h))
&& ours(tags)
{
first.entry(name.to_ascii_lowercase()).or_insert(name);
last.insert(name.to_ascii_lowercase(), tags);
}
}
let mut out = Vec::new();
let mut taken = std::collections::HashSet::new();
let mut budget = crate::dxf_layer_states::MAX_COPIED_BYTES;
for h in &self.xrecord_order {
let (Some(tags), Some(name)) = (self.xrecords.get(h), self.names.get(h)) else { continue };
if out.len() >= crate::dxf_ext::MAX_LAYER_STATES {
break;
}
if !ours(tags) {
continue;
}
let key = name.to_ascii_lowercase();
if taken.insert(key.clone()) {
let name = first.get(&key).copied().unwrap_or(name);
let tags = last.get(&key).copied().unwrap_or(tags);
out.push(crate::dxf_layer_states::read(name, tags, &lookup, &mut budget));
}
}
out
}
/// The text of the CADCraft XRECORD stored under `key` in a dictionary (its 1/3 strings).
pub(super) fn xrecord_text(&self, key: &str) -> Option<String> {
let h = self.names.iter().find(|(_, n)| n.as_str() == key).map(|(h, _)| h)?;
@@ -277,18 +208,10 @@ impl Objects {
if let Some(p) = self.xrecord_text(crate::dxf_ext::ANNOTATION_KEY).and_then(|t| crate::dxf_ext::parse_anno(&t)) {
crate::dxf_ext::apply_anno(d, p);
}
// Saved layer states: AutoCAD's, then those of CADCraft's own record (a file of an
// earlier version keeps them all there) that AutoCAD's doesn't hold.
let mut states = self.acad_layer_states(d, rx);
if let Some(own) = self.xrecord_text(crate::dxf_ext::LAYER_STATES_KEY).and_then(|t| crate::dxf_ext::parse_layer_states(&t)) {
let mut names: std::collections::HashSet<String> = states.iter().map(|s| s.name.clone()).collect();
for st in own {
if states.len() < crate::dxf_ext::MAX_LAYER_STATES && names.insert(st.name.clone()) {
states.push(st);
}
}
// Saved layer states.
if let Some(states) = self.xrecord_text(crate::dxf_ext::LAYER_STATES_KEY).and_then(|t| crate::dxf_ext::parse_layer_states(&t)) {
d.layer_states = states;
}
d.layer_states = states;
// The drawing's plot style tables.
if let Some(tables) = self.xrecord_text(crate::dxf_ext::PLOT_STYLES_KEY).and_then(|t| crate::dxf_ext::parse_plot_styles(&t)) {
d.plot_style_tables = tables;
@@ -308,20 +231,6 @@ impl Objects {
}
}
/// An object's owner (its first group 330 outside a `102` group), upper case.
fn owner(tags: &[Tag]) -> Option<String> {
let mut inside = false;
for t in tags {
match t.code {
102 => inside = t.str().trim().starts_with('{'),
330 if !inside => return Some(t.str().trim().to_ascii_uppercase()),
100 => return None,
_ => {}
}
}
None
}
/// Page setup from a LAYOUT object's AcDbPlotSettings fields (sizes and margins in mm).
pub(super) fn page_setup(t: &T) -> PageSetup {
let mut p = PageSetup::default();
+34 -5
View File
@@ -3,7 +3,7 @@
//! the newer DIMSTYLE groups, and from 2007 in UTF-8 text (the caller picks the text encoding) and
//! MULTILEADER entities (older files get LEADER + MTEXT).
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use cadcraft_color::Color;
use cadcraft_doc::{
@@ -39,6 +39,9 @@ use sections::tags_for;
struct W {
t: Vec<Tag>,
next: u64,
/// Handles the drawing's objects already hold: structural records skip them, so writing a
/// file whose own handles sit near the top of the range never repeats a handle (#913).
used: HashSet<u64>,
/// Upper-case plot style name → its `ACDBPLACEHOLDER` handle (group 390 of layers and objects).
pstyles: HashMap<String, String>,
/// Upper-case layer name → its LAYER table record handle (group 331/341 of viewports).
@@ -48,6 +51,21 @@ struct W {
reactors: HashMap<Handle, Vec<String>>,
}
/// Where the writer's own records (tables, objects, dictionaries) start numbering: above every
/// object handle and the drawing's seed, with headroom for handles the drawing allocates next.
fn structural_start(d: &Drawing) -> u64 {
let highest = entity_handles(d).max().unwrap_or(0);
d.handseed.max(0x100).max(highest.saturating_add(1)).saturating_add(0x1000)
}
/// Every handle an object holds, plus the drawing's next one.
fn entity_handles(d: &Drawing) -> impl Iterator<Item = u64> + '_ {
let model = d.model.iter().map(|e| e.handle.0);
let layouts = d.layouts.iter().flat_map(|l| l.entities.iter()).map(|e| e.handle.0);
let blocks = d.blocks.values().flat_map(|b| b.entities.iter()).map(|e| e.handle.0);
model.chain(layouts).chain(blocks).chain(std::iter::once(d.handseed))
}
impl W {
fn s(&mut self, c: i32, v: impl Into<String>) {
self.t.push(Tag::s(c, v));
@@ -71,10 +89,20 @@ impl W {
format!("{:X}", self.next_handle())
}
/// A new handle for a record the drawing doesn't hold (as [`W::h`]).
///
/// Skips every handle in use, so a file object carrying a handle above the seed (the
/// reserved band) is not handed out again, and wraps into that band if the writer runs off
/// the top of the range. Each handle skipped is one in use, so the walk is bounded by their
/// count.
fn next_handle(&mut self) -> u64 {
let h = self.next;
self.next = self.next.saturating_add(1);
h
for _ in 0..self.used.len().saturating_add(1) {
let h = self.next;
self.next = h.checked_add(1).unwrap_or(cadcraft_doc::HANDLE_LIMIT);
if self.used.insert(h) {
return h;
}
}
self.next
}
/// A `102 {NAME` … `102 }` group of handles.
fn group(&mut self, name: &str, code: i32, handles: &[&str]) {
@@ -152,7 +180,8 @@ fn bridge_markers(tags: &mut [Tag]) {
pub fn entity_groups(d: &Drawing, e: &Entity) -> (String, Vec<Tag>) {
let mut w = W {
t: Vec::new(),
next: d.handseed.max(0x100).saturating_add(0x1000),
next: structural_start(d),
used: entity_handles(d).collect(),
pstyles: HashMap::new(),
layers: HashMap::new(),
reactors: HashMap::new(),
+8 -1
View File
@@ -16,7 +16,14 @@ pub(super) fn annotative_xdata(w: &mut W) {
/// Override (`ACAD` DSTYLE) and associativity (`CADCRAFT` ASSOC) xdata of a dimension.
pub(super) fn dim_xdata(w: &mut W, dm: &Dimension, cx: &Ctx) {
let mut ov = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new() };
let mut ov = W {
t: Vec::new(),
next: 0,
used: std::collections::HashSet::new(),
pstyles: HashMap::new(),
layers: HashMap::new(),
reactors: HashMap::new(),
};
let mut sah = false;
for (k, v) in &dm.overrides {
let Some(field) = DimStyle::field_name(k) else { continue };
-2
View File
@@ -58,8 +58,6 @@ pub(super) struct Ctx {
pub(super) frozen_341: bool,
/// MTEXT columns as the legacy groups 75..79 even from R2018 (the groups AutoLISP lists).
pub(super) legacy_columns: bool,
/// Saved layer states in AutoCAD's form (the LAYER table's extension dictionary).
pub(super) layer_states: crate::dxf_layer_states::Plan,
}
impl Ctx {
-8
View File
@@ -143,18 +143,10 @@ pub(super) fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) {
}
pub(super) fn table_head(w: &mut W, name: &str, count: usize) -> String {
table_head_x(w, name, count, None)
}
/// A table's head, with its extension dictionary `xdict` when it has one.
pub(super) fn table_head_x(w: &mut W, name: &str, count: usize, xdict: Option<&str>) -> String {
let h = w.h();
w.s(0, "TABLE");
w.s(2, name);
w.s(5, h.clone());
if let Some(x) = xdict {
w.group("ACAD_XDICTIONARY", 360, &[x]);
}
w.s(330, "0");
w.s(100, "AcDbSymbolTable");
w.i(70, count as i64);
+17 -36
View File
@@ -4,12 +4,13 @@ use super::common::annotative_xdata;
use super::ctx::{AssocObj, Ctx};
use super::entity::{entity, hatch_reactors};
use super::header::{code_page, header_vars};
use super::layout::{paper_views, record_head, sheet_first, table_head, table_head_x, vport_table};
use super::layout::{paper_views, record_head, sheet_first, table_head, vport_table};
use super::objects::{cadcraft_fonts_name, group_obj, mleader_style_obj, scale_list, table_style_obj};
use super::{
Block, Color, DimStyle, DimVal, Drawing, Entity, EntityKind, EntityStore, Group, HVal, Handle, HashMap, Layout, MLeaderStyle, PageSetup, Space,
TableStyle, Tag, Vec2, Vec3, Version, W, dxf_ext,
Block, Color, DimStyle, DimVal, Drawing, Entity, EntityKind, EntityStore, Group, HVal, Handle, HashMap, HashSet, Layout, MLeaderStyle, PageSetup,
Space, TableStyle, Tag, Vec2, Vec3, Version, W, dxf_ext,
};
use super::{entity_handles, structural_start};
struct TableWritePlan<'a> {
d: &'a Drawing,
@@ -68,7 +69,7 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
}
}
w.s(0, "ENDTAB");
write_layer_table(w, d, &mut cx.layer_states);
write_layer_table(w, d);
// STYLE. Linetype shapes from a shape file that isn't a text style get an unnamed shape
// style record (70 bit 1) naming the file.
let mut shape_files: Vec<String> = Vec::new();
@@ -185,12 +186,8 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
ltype_handles
}
/// The LAYER table; when the drawing has layer states AutoCAD can hold, the table's extension
/// dictionary holds them (written with the objects, [`crate::dxf_layer_states`]).
fn write_layer_table(w: &mut W, d: &Drawing, states: &mut crate::dxf_layer_states::Plan) {
let xdict = (!states.is_empty()).then(|| states.xdict.clone());
let th = table_head_x(w, "LAYER", d.layers.len(), xdict.as_deref());
states.table.clone_from(&th);
fn write_layer_table(w: &mut W, d: &Drawing) {
let th = table_head(w, "LAYER", d.layers.len());
for l in &d.layers {
let lh = record_head(w, "LAYER", &th, "AcDbLayerTableRecord");
w.layers.insert(l.name.to_ascii_uppercase(), lh);
@@ -249,7 +246,7 @@ fn write_dimstyles(w: &mut W, d: &Drawing, cx: &mut Ctx, version: Version) {
w.i(70, 0);
let v = serde_json::to_value(s).unwrap_or_default();
let defaults = serde_json::to_value(DimStyle::default()).unwrap_or_default();
let mut newer = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new() };
let mut newer = W { t: Vec::new(), next: 0, used: HashSet::new(), pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new() };
for (field, code, kind) in dxf_ext::DIM_CODES {
let Some(enc) = v.get(*field).and_then(|x| cx.encode(*kind, x)) else { continue };
// DIMPOST is written even when empty: a reader that defaults a missing one to "<>"
@@ -753,16 +750,6 @@ fn write_objects(w: &mut W, plan: ObjectWritePlan<'_>) {
write_root_group_objects(w, &plan, &groups, &group_owner, &written, &mleader_dict);
write_style_objects(w, &plan, &mleader_dict, &mleader_handles);
write_named_objects(w, &plan);
let layer_states = {
let refs = crate::dxf_layer_states::Refs {
layers: &w.layers,
ltypes: &plan.cx.ltypes,
pstyles: &w.pstyles,
colour_dependent: plan.d.header.i64("PSTYLEMODE", 1) != 0,
};
crate::dxf_layer_states::objects(&plan.cx.layer_states, &plan.d.layer_states, &refs)
};
w.t.extend(layer_states);
write_associative_objects(w, plan.cx);
write_layout_objects(w, &plan);
// Raster image definitions.
@@ -930,7 +917,8 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
// Structural handles start above every entity handle.
let mut w = W {
t: Vec::new(),
next: d.handseed.max(0x100).saturating_add(0x1000),
next: structural_start(d),
used: entity_handles(d).collect(),
pstyles: HashMap::new(),
layers: HashMap::new(),
reactors: hatch_reactors(d),
@@ -993,9 +981,7 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
if let Some(chunks) = dxf_ext::constraint_chunks(&d.constraints, &d.parametric) {
xrecords.push((dxf_ext::CONSTRAINTS_KEY, w.h(), chunks));
}
// Saved layer states: AutoCAD's dictionary holds those it can, CADCraft's record the others.
cx.layer_states = crate::dxf_layer_states::Plan::new(&d.layer_states, || w.h());
if let Some(chunks) = dxf_ext::layer_state_chunks(&crate::dxf_layer_states::own(&d.layer_states)) {
if let Some(chunks) = dxf_ext::layer_state_chunks(&d.layer_states) {
xrecords.push((dxf_ext::LAYER_STATES_KEY, w.h(), chunks));
}
if let Some(chunks) = dxf_ext::plot_style_chunks(&d.plot_style_tables) {
@@ -1007,19 +993,14 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
// The annotation scale list: the ACAD_SCALELIST dictionary of SCALE objects.
let scale_dict = w.h();
let scales: Vec<(&cadcraft_doc::AnnoScale, String)> = d.scales.iter().filter(|s| s.is_valid()).map(|s| (s, w.h())).collect();
// Plot style names used by layers and objects (Normal always), each a placeholder object; in
// a drawing of named plot styles also those of the layers of saved layer states, which name
// theirs by placeholder.
// Plot style names used by layers and objects (Normal always), each a placeholder object.
let pstyle_dict = w.h();
let mut pstyle_names: Vec<String> = vec![cadcraft_doc::NORMAL_STYLE.to_string()];
let mut seen: std::collections::HashSet<String> = pstyle_names.iter().map(|n| n.to_ascii_uppercase()).collect();
let named_styles = d.header.i64("PSTYLEMODE", 1) == 0;
let in_states = d.layer_states.iter().filter(|_| named_styles).flat_map(|s| s.layers.iter());
let named = d.layers.iter().chain(in_states).map(|l| l.plot_style.as_str()).chain(every.iter().map(|e| e.common.plot_style.as_str()));
let named = d.layers.iter().map(|l| l.plot_style.as_str()).chain(every.iter().map(|e| e.common.plot_style.as_str()));
for n in named {
let n = n.trim();
let logical = n.is_empty() || n.eq_ignore_ascii_case("bylayer") || n.eq_ignore_ascii_case("byblock");
if !logical && pstyle_names.len() < dxf_ext::MAX_PLOT_STYLE_NAMES && seen.insert(n.to_ascii_uppercase()) {
if !logical && pstyle_names.len() < dxf_ext::MAX_PLOT_STYLE_NAMES && !pstyle_names.iter().any(|x| x.eq_ignore_ascii_case(n)) {
pstyle_names.push(n.to_string());
}
}
@@ -1114,11 +1095,11 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
for (n, h, b) in &user_blocks {
block(&mut w, (n, &b.description), h, b.base, if b.anonymous { 1 } else { 0 }, &mut b.entities.iter().map(|e| e.as_ref()), false);
}
// Generated geometry entities (dimension, arrowhead and table blocks) need handles.
// Generated geometry entities (dimension, arrowhead and table blocks) need handles; take
// them from the writer's allocator, which skips the drawing's own handles.
for (_, _, ents) in dim_defs.iter_mut().chain(arrow_defs.iter_mut()).chain(table_defs.iter_mut()) {
for e in ents.iter_mut().filter(|e| e.handle.0 == 0) {
e.handle = Handle(w.next);
w.next = w.next.saturating_add(1);
e.handle = Handle(w.next_handle());
}
}
for (n, h, ents) in &dim_defs {
-1
View File
@@ -9,7 +9,6 @@ mod dxf_raw;
mod dxf_clip;
mod dxf_ext;
mod dxf_image;
mod dxf_layer_states;
mod dxf_mleader;
mod dxf_read;
mod dxf_table;
+122 -16
View File
@@ -17,7 +17,7 @@ use std::collections::BTreeMap;
use cadcraft_color::Color;
use cadcraft_doc::{Circle, Common, Drawing, Ellipse, EntityKind, Layer, Line, LwPolyline, Space};
use cadcraft_geom::{Mat3, PolyVertex, Spline, Vec2, Vec3};
use cadcraft_geom::{Mat3, PolyVertex, Spline, Vec2, Vec3, bulge_to_arc};
use crate::{IoError, Result};
@@ -70,6 +70,8 @@ struct Parser {
verts_left: usize,
/// What was left out, by kind ([`LeftOut`]).
left_out: BTreeMap<LeftOut, usize>,
/// Shapes left out because their coordinates or extents overflow: invalid, not unsupported.
too_large: usize,
}
/// Drawn content the reader leaves out, named in the drawing's read note.
@@ -105,16 +107,23 @@ impl Parser {
elements: 0,
verts_left: MAX_TOTAL_VERTS,
left_out: BTreeMap::new(),
too_large: 0,
}
}
/// The read note on what was left out, if anything was.
fn note(&self) -> Option<String> {
if self.left_out.is_empty() {
return None;
/// The read notes on what was left out: what isn't read yet, then what is invalid.
fn notes(&self) -> Vec<String> {
let mut notes = Vec::new();
if !self.left_out.is_empty() {
let list: Vec<String> = self.left_out.iter().map(|(k, n)| k.describe(*n)).collect();
notes.push(format!("SVG: CADCraft doesn't read these yet, so they were left out: {}", list.join(", ")));
}
let list: Vec<String> = self.left_out.iter().map(|(k, n)| k.describe(*n)).collect();
Some(format!("SVG: CADCraft doesn't read these yet, so they were left out: {}", list.join(", ")))
match self.too_large {
0 => {}
1 => notes.push("SVG: 1 shape was left out as invalid: its coordinates or size are too large to represent".into()),
n => notes.push(format!("SVG: {n} shapes were left out as invalid: their coordinates or size are too large to represent")),
}
notes
}
fn parse(&mut self, text: &str) -> Result<()> {
@@ -150,7 +159,7 @@ impl Parser {
};
self.left_out.insert(kind, count);
}
self.drawing.read_notes.extend(self.note());
self.drawing.read_notes.extend(self.notes());
Ok(())
}
@@ -218,12 +227,18 @@ impl Parser {
}
// Charge the vertices this entity retains against the shared document budget, so repeated
// flattened arcs/curves cannot amplify a compact path into unbounded geometry (CWE-400).
// A shape left out below was generated all the same, so it is charged too.
let verts = match &kind {
EntityKind::LwPolyline(p) => p.vertices.len(),
EntityKind::Spline(s) => s.control.len(),
_ => 1,
};
self.verts_left = self.verts_left.checked_sub(verts).ok_or_else(|| IoError::Format("SVG: too much generated geometry".into()))?;
// Finite numbers can still overflow through transforms and relative steps (`l1e308 0` twice).
if !finite(&kind) {
self.too_large += 1;
return Ok(());
}
let common = Common { layer: self.layer.clone(), ..Common::default() };
self.drawing.add(&Space::Model, common, kind).map(|_| ()).map_err(parse_err)
}
@@ -231,7 +246,10 @@ impl Parser {
/// A circle or ellipse through a transform. A circle stays a `CIRCLE` under rotations,
/// uniform scales and reflections; anything else becomes an `ELLIPSE` holding the axes
/// of the transformed shape — a linear map sends the unit circle to an ellipse whose
/// semi-axes are the square roots of the eigenvalues of `A·Aᵀ`.
/// semi-axes are the square roots of the eigenvalues of `A·Aᵀ`. With `B = [bx by]` the
/// ellipse is `center + B·(cos t, sin t)`; `B·Bᵀ` lives in the drawing plane, so its leading
/// eigenvector is the major axis's direction. `major` is that axis from the centre, as
/// [`Ellipse::major`] is everywhere else.
fn add_rounded(&mut self, center_user: Vec2, rx: f64, ry: f64) -> Result<()> {
let center = self.map(center_user);
let bx = self.map_vec(Vec2::new(rx, 0.0));
@@ -253,18 +271,15 @@ impl Parser {
if s_max <= f64::EPSILON {
return Ok(());
}
let axis = if xy.abs() <= 1e-12 * trace.max(1.0) {
let axis = if xy.abs() <= 1e-12 * trace {
if yy > xx { Vec2::new(0.0, 1.0) } else { Vec2::new(1.0, 0.0) }
} else {
let v = Vec2::new(xy, l_max - xx);
let l = len(v);
if l <= f64::EPSILON {
return Ok(());
}
v / l
// |v| ≥ |xy| > 1e-12·trace ≥ 0 here, so the division is never by zero.
v / len(v)
};
let ratio = (l_min.max(0.0).sqrt() / s_max).clamp(1e-9, 1.0);
let major = center + axis * s_max;
let major = axis * s_max;
self.add(EntityKind::Ellipse(Ellipse { center: v3(center), major: v3(major), ratio, start: 0.0, end: std::f64::consts::TAU }))
}
@@ -380,6 +395,79 @@ impl Parser {
}
}
/// Every coordinate of an entity the reader makes is finite, and so are its extents: a finite
/// centre and radius can still reach past the largest number.
fn finite(kind: &EntityKind) -> bool {
match kind {
EntityKind::Line(l) => l.a.is_finite() && l.b.is_finite(),
EntityKind::Circle(c) => {
c.center.is_finite()
&& c.radius.is_finite()
&& cadcraft_geom::Circle::new(c.center.xy(), c.radius).bounds().corners().iter().all(|p| p.is_finite())
}
EntityKind::Ellipse(e) => {
// Half the box is `hypot` of the major axis and the minor axis (`ratio` times it, turned).
let (m, r) = (e.major.xy(), e.ratio);
e.center.is_finite() && e.major.is_finite() && e.ratio.is_finite() && box_finite(e.center.xy(), m.x.hypot(r * m.y), m.y.hypot(r * m.x))
}
EntityKind::LwPolyline(p) => p.vertices.iter().all(|v| v.p.is_finite() && v.bulge.is_finite()) && bulges_finite(p),
EntityKind::Spline(s) => s.control.iter().all(|p| p.is_finite()),
// The SVG reader doesn't make these.
EntityKind::Point(_)
| EntityKind::Arc(_)
| EntityKind::Polyline3d(_)
| EntityKind::Helix(_)
| EntityKind::Ray(_)
| EntityKind::XLine(_)
| EntityKind::Text(_)
| EntityKind::MText(_)
| EntityKind::AttDef(_)
| EntityKind::Insert(_)
| EntityKind::Dimension(_)
| EntityKind::MLine(_)
| EntityKind::Leader(_)
| EntityKind::MLeader(_)
| EntityKind::Hatch(_)
| EntityKind::Solid(_)
| EntityKind::Trace(_)
| EntityKind::Face3d(_)
| EntityKind::PolyfaceMesh(_)
| EntityKind::Region(_)
| EntityKind::Viewport(_)
| EntityKind::Image(_)
| EntityKind::Wipeout(_)
| EntityKind::Table(_)
| EntityKind::Tolerance(_)
| EntityKind::Unknown(_) => true,
}
}
/// The box `centre ± (hx, hy)` is finite.
fn box_finite(c: Vec2, hx: f64, hy: f64) -> bool {
[c.x - hx, c.x + hx, c.y - hy, c.y + hy].iter().all(|v| v.is_finite())
}
/// Every arc segment of the polyline (a bulge between finite vertices) has a finite centre and
/// radius, and the quadrant points it passes through are finite.
fn bulges_finite(p: &LwPolyline) -> bool {
let n = p.vertices.len();
p.vertices.iter().enumerate().all(|(i, v)| {
let next = if i + 1 < n {
p.vertices.get(i + 1)
} else if p.closed {
p.vertices.first()
} else {
None
};
let Some((arc, _)) = next.and_then(|w| bulge_to_arc(v.p, w.p, v.bulge)) else { return true };
arc.center.is_finite()
&& arc.radius.is_finite()
&& (0..4)
.map(|k| f64::from(k) * std::f64::consts::FRAC_PI_2)
.all(|a| !arc.contains_angle(a) || Vec2::polar(arc.center, arc.radius, a).is_finite())
})
}
/// One `M …` run of a `d` attribute.
struct Subpath {
start: Vec2,
@@ -471,4 +559,22 @@ mod tests {
assert_eq!(arc_of("M10 10 a20 20 0 1 0 20 20"), (true, false, spaced.2));
assert!(arc_of("M10 10 a20 20 0 10-20 20").0);
}
#[test]
fn extents_past_the_largest_number_are_not_finite() {
let ellipse = |c: Vec2, major: Vec2| EntityKind::Ellipse(Ellipse { center: v3(c), major: v3(major), ratio: 1.0, start: 0.0, end: 0.0 });
assert!(!finite(&ellipse(Vec2::new(1e308, 0.0), Vec2::new(1e308, 0.0))));
assert!(finite(&ellipse(Vec2::new(5e307, 0.0), Vec2::new(5e307, 0.0))));
// Turned, its box is wider than its axis: `centre ± major` is finite, the box isn't.
assert!(!finite(&ellipse(Vec2::new(6e307, 0.0), Vec2::new(9e307, 9e307))));
assert!(finite(&ellipse(Vec2::ZERO, Vec2::new(9e307, 9e307))));
// Half circles between the same finite points: bulging up passes 1.8e308, down doesn't.
let half = |bulge: f64| {
let (a, b) = (Vec2::new(0.0, 1.5e308), Vec2::new(1e308, 1.5e308));
let vertices = vec![PolyVertex::with_bulge(a, bulge), PolyVertex::new(b)];
EntityKind::LwPolyline(LwPolyline { vertices, closed: false, const_width: 0.0, elevation: 0.0, plinegen: false })
};
assert!(!finite(&half(-1.0)));
assert!(finite(&half(1.0)));
}
}
+122 -18
View File
@@ -1856,24 +1856,22 @@ fn layer_states_roundtrip_next_to_constraints() {
description: "walls \\ hidden".into(),
..Layer::default()
});
d.layer_states.push(LayerState::new("Plot", d.layers.clone(), "Wände"));
d.layer_states.push(LayerState { name: "Plot".into(), layers: d.layers.clone() });
let mut off = d.layers.clone();
for l in &mut off {
(l.on, l.frozen, l.locked, l.plot) = (false, true, true, false);
}
d.layer_states.push(LayerState::new("All off", off, ""));
d.layer_states.push(LayerState { name: "All off".into(), layers: off });
let text = write_dxf(&d);
// AutoCAD's dictionary holds both states; CADCraft's record isn't needed.
assert!(text.contains("ACAD_LAYERSTATES") && !text.contains("CADCRAFT_LAYERSTATES"));
assert!(text.contains("CADCRAFT_LAYERSTATES"));
let back = read_dxf(text.as_bytes()).unwrap();
assert_eq!(back.layer_states, d.layer_states);
assert_eq!(back.constraints, constraints);
assert_eq!(roundtrip(&back).layer_states, d.layer_states);
#[cfg(not(target_arch = "wasm32"))]
assert_eq!(read(&write(&d, "x.dwg").unwrap(), "x.dwg").unwrap().layer_states, d.layer_states);
// Drawings without saved layer states carry neither.
let none = write_dxf(&Drawing::new_imperial());
assert!(!none.contains("CADCRAFT_LAYERSTATES") && !none.contains("ACAD_LAYERSTATES"));
// Drawings without saved layer states carry no record.
assert!(!write_dxf(&Drawing::new_imperial()).contains("CADCRAFT_LAYERSTATES"));
}
fn table_sample() -> Table {
@@ -2917,12 +2915,75 @@ fn svg_shapes_become_entities_in_millimetres() {
let c = first(&d, |k| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None });
assert!((c.radius - 2.0).abs() < 1e-9 && (c.center.x - 10.0).abs() < 1e-9 && (c.center.y - 5.0).abs() < 1e-9, "{c:?}");
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
let major = Vec2::new(e.major.x - e.center.x, e.major.y - e.center.y);
let major = Vec2::new(e.major.x, e.major.y);
assert!((major.len() - 4.0).abs() < 1e-9 && (e.ratio - 0.5).abs() < 1e-9, "{e:?}");
let l = first(&d, |k| if let EntityKind::Line(l) = k { Some(l.clone()) } else { None });
assert!((l.a.y - 10.0).abs() < 1e-9 && (l.b.y).abs() < 1e-9, "{l:?}");
}
#[test]
fn svg_ellipse_major_axis_is_relative_to_its_centre() {
// Away from the origin: the major axis was stored as the absolute point centre + axis.
let svg = format!("{SVG_PAGE}<ellipse cx=\"15\" cy=\"2\" rx=\"2\" ry=\"1\"/><circle cx=\"15\" cy=\"2\" r=\"1\"/></svg>");
let d = read(svg.as_bytes(), "ellipse.svg").unwrap();
assert_eq!(kinds(&d), ["Ellipse", "Circle"]);
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
assert!((e.center - Vec3::new(15.0, 8.0, 0.0)).len() < 1e-9, "{e:?}");
assert!((e.major.x.abs() - 2.0).abs() < 1e-9 && e.major.y.abs() < 1e-9 && e.major.z == 0.0, "{e:?}");
assert!((e.ratio - 0.5).abs() < 1e-9, "{e:?}");
let c = first(&d, |k| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None });
assert!((c.center - Vec3::new(15.0, 8.0, 0.0)).len() < 1e-9 && (c.radius - 1.0).abs() < 1e-9, "{c:?}");
}
#[test]
fn svg_rotated_ellipse_keeps_its_turn() {
// The page maps SVG (x, y) to (x, 10 - y); undo that, then rotate by -30°, to get back to the ellipse's own frame.
let svg = format!("{SVG_PAGE}<ellipse cx=\"0\" cy=\"0\" rx=\"20\" ry=\"10\" transform=\"rotate(30)\"/></svg>");
let d = read(svg.as_bytes(), "rotated.svg").unwrap();
assert_eq!(kinds(&d), ["Ellipse"]);
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
let major = Vec2::new(e.major.x, e.major.y);
assert!((major.len() - 20.0).abs() < 1e-9 && (e.ratio - 0.5).abs() < 1e-9, "{e:?}");
let (s, c) = 30f64.to_radians().sin_cos();
let want = Vec2::new(20.0 * c, -20.0 * s);
assert!((major - want).len() < 1e-9 || (major + want).len() < 1e-9, "{e:?}");
let (ux, uy) = (e.center.x + major.x, 10.0 - (e.center.y + major.y));
let (x, y) = (c * ux + s * uy, -s * ux + c * uy);
assert!(((x / 20.0).powi(2) + (y / 10.0).powi(2) - 1.0).abs() < 1e-9, "{e:?}");
}
#[test]
fn svg_sheared_circle_has_the_axes_of_its_image() {
// matrix(1 0 1 1 0 0) is B = [[1, 1], [0, 1]]; the page then flips Y at one millimetre per unit.
let svg = format!("{SVG_PAGE}<circle r=\"1\" transform=\"matrix(1 0 1 1 0 0)\"/></svg>");
let d = read(svg.as_bytes(), "sheared.svg").unwrap();
assert_eq!(kinds(&d), ["Ellipse"]);
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
let major = Vec2::new(e.major.x, e.major.y);
let s_max = ((3.0 + 5f64.sqrt()) / 2.0).sqrt();
let s_min = ((3.0 - 5f64.sqrt()) / 2.0).sqrt();
assert!((major.len() - s_max).abs() < 1e-9 * s_max, "{e:?}");
assert!((e.ratio - s_min / s_max).abs() < 1e-9, "{e:?}");
let (ux, uy) = (major.x, -major.y);
let pre = Vec2::new(ux - uy, uy);
assert!((pre.len() - 1.0).abs() < 1e-9, "B⁻¹·major = {pre:?}, {e:?}");
assert!(major.x.abs() > 1e-3 && major.y.abs() > 1e-3, "{e:?}");
}
#[test]
fn svg_tiny_sheared_circle_has_the_axes_of_its_image() {
// Columns (1, 0.5)·1e-6 and (1, -0.5)·1e-6: far from orthogonal, though their dot product is tiny.
let svg = format!("{SVG_PAGE}<circle r=\"1\" transform=\"matrix(1e-6 0.5e-6 1e-6 -0.5e-6 0 0)\"/></svg>");
let d = read(svg.as_bytes(), "tiny.svg").unwrap();
assert_eq!(kinds(&d), ["Ellipse"]);
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
let major = Vec2::new(e.major.x, e.major.y);
assert!(major.y.abs() <= 1e-9 * major.x.abs(), "{e:?}");
let want = 2f64.sqrt() * 1e-6;
assert!((major.len() - want).abs() < 1e-9 * want, "{e:?}");
assert!((e.ratio - 0.5).abs() < 1e-9, "{e:?}");
}
#[test]
fn svg_path_lines_curves_and_arcs() {
let svg = format!("{SVG_PAGE}<path d=\"M1 1 L5 1 C6 1 7 2 8 3\"/><path d=\"M0 0 A5 5 0 0 1 10 0 Z\"/></svg>");
@@ -3139,6 +3200,59 @@ fn svg_hostile_input_errors_without_panicking() {
assert!(deep.is_err(), "200 nested groups are refused, not walked");
}
#[test]
fn svg_coordinates_that_overflow_are_left_out() {
// Every number is finite; relative steps and transforms overflow them to infinity or NaN.
let svg = format!(
"{SVG_PAGE}<path d=\"M1e308 0 l1e308 0\"/><rect x=\"1e308\" width=\"1e308\" height=\"1\"/>\
<g transform=\"scale(1e308)\"><line x1=\"1e308\" y1=\"0\" x2=\"1\" y2=\"1\"/><circle r=\"1e308\"/></g>\
<g transform=\"scale(1e308,1)\"><ellipse rx=\"1e308\" ry=\"1\"/><path d=\"M0 0 C1e308 0 1 1 2 2\"/></g>\
<line x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"/></svg>"
);
let d = read(svg.as_bytes(), "huge.svg").unwrap();
assert_eq!(kinds(&d), ["Line"]);
assert_eq!(d.read_notes, ["SVG: 6 shapes were left out as invalid: their coordinates or size are too large to represent"]);
}
#[test]
fn svg_shapes_whose_extents_overflow_are_left_out() {
// A finite centre and radius whose sum overflows; the same scale on smaller values stays
// representable.
let svg = format!("{SVG_PAGE}<g transform=\"scale(1e308)\"><circle cx=\"1\" cy=\"0\" r=\"1\"/><circle cx=\"0.5\" cy=\"0\" r=\"0.5\"/></g></svg>");
let d = read(svg.as_bytes(), "huge.svg").unwrap();
assert_eq!(kinds(&d), ["Circle"]);
let c = first(&d, |k| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None });
assert!((c.radius - 5e307).abs() < 1e293, "{}", c.radius);
assert_eq!(d.read_notes, ["SVG: 1 shape was left out as invalid: its coordinates or size are too large to represent"]);
}
/// A shape too large to represent is invalid, not something CADCraft doesn't read yet: it gets a
/// note of its own.
#[test]
fn svg_too_large_shapes_are_noted_apart_from_unread_content() {
let svg = format!("{SVG_PAGE}<text x=\"0\" y=\"5\">one</text><path d=\"M1e308 0 l1e308 0\"/><line x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"/></svg>");
let d = read(svg.as_bytes(), "huge.svg").unwrap();
assert_eq!(kinds(&d), ["Line"]);
assert_eq!(
d.read_notes,
[
"SVG: CADCraft doesn't read these yet, so they were left out: 1 text",
"SVG: 1 shape was left out as invalid: its coordinates or size are too large to represent"
]
);
}
#[test]
fn svg_shapes_left_out_still_count_against_the_vertex_budget() {
// Each arc flattens to 10,000 chords under the non-uniform scale, and the doubled translation
// overflows to infinity, so each is left out; 820 of them make more than the 8,000,000 vertices
// a file may generate.
let arcs = "A1e9 1e9 0 0 1 2e9 0 A1e9 1e9 0 0 1 0 0 ".repeat(410);
let svg = format!("{SVG_PAGE}<g transform=\"translate(1e308 0) translate(1e308 0) scale(2 1)\"><path d=\"M0 0 {arcs}\"/></g></svg>");
let err = read(svg.as_bytes(), "huge.svg").err().map(|e| e.to_string()).unwrap_or_default();
assert!(err.contains("SVG: too much generated geometry"), "{err}");
}
#[test]
fn svg_no_geometry_yields_an_empty_drawing() {
let svg = format!("{SVG_PAGE}</svg>");
@@ -3715,13 +3829,3 @@ fn solid_hatch_keeps_angle_scale_and_double_flag() {
assert!(f("41").is_some_and(|s| (s - 2.0).abs() < 1e-12), "{h:?}");
assert_eq!(group(h, "77"), Some("0"), "{h:?}");
}
/// A layer state of CADCraft's own record from before states had a mask, a current layer and a
/// description (its JSON holds only the name and the layers) restores every property and names no
/// current layer.
#[test]
fn a_layer_state_saved_before_masks_restores_everything() {
let states = crate::dxf_ext::parse_layer_states(r#"{"version":1,"states":[{"name":"S","layers":[]}]}"#).unwrap();
let got: Vec<(&str, u32, &str, &str)> = states.iter().map(|s| (s.name.as_str(), s.mask, s.current.as_str(), s.description.as_str())).collect();
assert_eq!(got, [("S", LayerState::ALL, "", "")]);
}
+360
View File
@@ -0,0 +1,360 @@
//! A hostile or damaged file can name a handle at the top of the range: an object's own handle,
//! or its `$HANDSEED`. A file's handles keep their identity, so a new object must take a free
//! handle instead of replacing the file's own object (#913).
#![cfg(not(target_arch = "wasm32"))]
use cadcraft_doc::{Common, DimKind, Dimension, Drawing, Entity, EntityKind, Handle, Line, Space};
use cadcraft_geom::Vec3;
const TOP: &str = "FFFFFFFFFFFFFFFF";
const NEAR_TOP: &str = "FFFFFFFFFFFEFFFF";
fn read(text: &str) -> Drawing {
cadcraft_io::read_dxf(text.as_bytes()).unwrap()
}
fn line(x: f64, y: f64) -> EntityKind {
EntityKind::Line(Line { a: Vec3::new(x, y, 0.0), b: Vec3::new(x + 1.0, y, 0.0) })
}
/// One line, with `entity_handle` when given, under a `$HANDSEED` of `seed`.
fn dxf(entity_handle: Option<&str>, seed: &str) -> String {
let handle = entity_handle.map(|h| format!("5\n{h}\n")).unwrap_or_default();
format!(
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n{seed}\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n0\nLINE\n{handle}8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n0.0\n31\n0.0\n0\nENDSEC\n0\nEOF\n"
)
}
fn distinct(d: &Drawing) -> Vec<Handle> {
d.model.iter().map(|e| e.handle).collect()
}
#[test]
fn an_object_at_the_top_of_the_handle_range_is_not_replaced_by_a_new_one() {
let mut d = read(&dxf(Some(TOP), TOP));
assert_eq!(d.model.len(), 1);
// The file's handle is its own; the new object takes a free handle below it.
assert!(d.entity(Handle::parse_hex(TOP).unwrap()).is_some(), "the file's handle was renumbered");
d.add(&Space::Model, Common::default(), line(10.0, 10.0)).unwrap();
assert_eq!(d.model.len(), 2, "the file's line was replaced by the new one");
let handles = distinct(&d);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 0.0)), "the file's line is gone");
}
#[test]
fn a_seed_at_the_top_of_the_handle_range_cannot_be_followed_twice() {
let mut d = read(&dxf(None, TOP));
let a = d.add(&Space::Model, Common::default(), line(0.0, 10.0)).unwrap();
let b = d.add(&Space::Model, Common::default(), line(0.0, 20.0)).unwrap();
assert_ne!(a, b, "two objects were given the same handle");
assert_eq!(d.model.len(), 3, "the second line replaced the first");
}
#[test]
fn an_ordinary_high_handle_keeps_its_identity() {
// Far below the top of the range a file's handles are its own: they stay as they are.
let h = "FFFFFFFF";
let mut d = read(&dxf(Some(h), h));
assert!(d.entity(Handle::parse_hex(h).unwrap()).is_some(), "the file's handle was renumbered");
let n = d.add(&Space::Model, Common::default(), line(0.0, 5.0)).unwrap();
assert!(n.0 > Handle::parse_hex(h).unwrap().0, "a new handle below the file's own");
}
#[test]
fn a_handle_just_below_the_top_survives_a_save() {
// Main keeps a file's handles exactly as written, even near the top of the range: handles
// are how other objects and other programs refer to an entity (#939's round-trip tests).
let mut d = read(&dxf(Some(NEAR_TOP), NEAR_TOP));
let n = d.add(&Space::Model, Common::default(), line(0.0, 5.0)).unwrap();
let bytes = cadcraft_io::write(&d, "near-top.dxf").unwrap();
let r = cadcraft_io::read_dxf(&bytes).unwrap();
assert!(r.entity(Handle::parse_hex(NEAR_TOP).unwrap()).is_some(), "the file's handle did not survive the save");
assert!(r.entity(n).is_some(), "the new handle did not survive the save");
}
#[test]
fn nine_objects_drawn_after_a_saturated_seed_save_and_reopen_distinct() {
// The nine-entity case from #2237: a saturated $HANDSEED, ordinary entity handles. Drawing
// after the load gives every object its own handle, and a save/reopen keeps them apart.
let mut d = read(&dxf(None, TOP));
for i in 0..9 {
d.add(&Space::Model, Common::default(), line(f64::from(i), 40.0)).unwrap();
}
let bytes = cadcraft_io::write(&d, "nine.dxf").unwrap();
let r = cadcraft_io::read_dxf(&bytes).unwrap();
assert_eq!(r.model.len(), 10, "the file's line and the nine drawn ones");
let handles = distinct(&r);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "repeated handles on reopen: {handles:?}");
}
/// The first handle in the reserved band above [`HANDLE_LIMIT`].
const BAND: &str = "FFFFFFFF00000000";
#[test]
fn a_seed_in_the_reserved_band_does_not_hand_out_the_files_handle() {
// #913's remaining case: a file says its next handle is FFFFFFFF00000000 and an object holds
// that handle. Following the seed once would hand the object's handle to the new object, and
// `EntityStore` would replace the file's line.
let mut d = read(&dxf(Some(BAND), BAND));
assert_eq!(d.model.len(), 1);
let n = d.add(&Space::Model, Common::default(), line(10.0, 10.0)).unwrap();
assert_ne!(n, Handle::parse_hex(BAND).unwrap(), "the new object took the file object's handle");
assert_eq!(d.model.len(), 2, "the file's line was replaced");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 0.0)), "the file's line is gone");
let bytes = cadcraft_io::write(&d, "band-seed.dxf").unwrap();
let r = cadcraft_io::read_dxf(&bytes).unwrap();
let handles = distinct(&r);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "repeated handles on reopen: {handles:?}");
assert_eq!(r.model.len(), 2, "a line did not survive the save");
}
#[test]
fn a_save_does_not_give_a_structural_record_an_objects_handle() {
// The writer numbers its own records from `seed + 0x1000`; with the seed at the bottom of the
// reserved band that lands on the file's own handle. The file must keep one record per handle.
let object = "FFFFFFFF00001000";
let d = read(&dxf(Some(object), "FFFFFFFEFFFFFFFF"));
let bytes = cadcraft_io::write(&d, "band-structural.dxf").unwrap();
let tags = craft_dxf::parse(&bytes).unwrap();
// Record handles start with the TABLES section; before it the HEADER's `$HANDSEED` is the
// next free handle, not a record's.
let after_header = tags.iter().position(|t| t.code == 2 && t.str() == "TABLES").unwrap();
let written: Vec<String> = tags[after_header..].iter().filter(|t| t.code == 5 || t.code == 105).map(|t| t.str().to_string()).collect();
let unique: std::collections::HashSet<&String> = written.iter().collect();
assert_eq!(unique.len(), written.len(), "the save repeats a handle: {written:?}");
assert_eq!(written.iter().filter(|h| h.as_str() == object).count(), 1, "the object's handle was not written exactly once");
let r = cadcraft_io::read_dxf(&bytes).unwrap();
assert!(r.entity(Handle::parse_hex(object).unwrap()).is_some(), "the file's object is gone");
}
/// A CADCraft-marked file with a handle-less block entity and an `ENTITIES` record that names
/// the handle the reader would give it. The marker means the reader skips the handle pre-scan,
/// so the two sections must still reserve against each other.
fn marked_file_with_handle_less_block_entity() -> String {
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n1000\n0\nENDSEC\n\
0\nSECTION\n2\nBLOCKS\n\
0\nBLOCK\n8\n0\n2\n*MODEL_SPACE\n70\n0\n10\n0.0\n20\n0.0\n30\n0.0\n3\n*MODEL_SPACE\n1\n\n\
0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n0.0\n31\n0.0\n\
0\nENDBLK\n8\n0\n\
0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n\
0\nLINE\n5\n100\n8\n0\n10\n10.0\n20\n0.0\n30\n0.0\n11\n11.0\n21\n0.0\n31\n0.0\n\
0\nENDSEC\n\
0\nSECTION\n2\nOBJECTS\n\
0\nXRECORD\n5\n300\n100\nAcDbXrecord\n3\nCADCRAFT_HANDSEED\n1\n1000\n\
0\nENDSEC\n0\nEOF\n"
.to_string()
}
#[test]
fn a_marked_files_sections_reserve_handles_against_each_other() {
// The block entity has no handle of its own, so the reader gives it one; a later ENTITIES
// record must not be given the same handle, or one entity silently replaces the other.
let d = read(&marked_file_with_handle_less_block_entity());
assert_eq!(d.model.len(), 2, "one entity replaced the other");
let handles = distinct(&d);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 0.0)), "the block entity is gone");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 10.0)), "the ENTITIES line is gone");
}
/// A file whose BLOCKS holds a handle-less model-space entity and whose ENTITIES names the
/// last handle below the reserved band and the first handle in it. With `marked` the file names
/// CADCraft's own seed record, which narrows the reader's handle pre-scan to the entity sections.
fn file_with_reserved_band_entities(marked: bool) -> String {
let below = format!("{:X}", cadcraft_doc::HANDLE_LIMIT - 1);
let band = format!("{:X}", cadcraft_doc::HANDLE_LIMIT);
let objects = if marked {
"0\nSECTION\n2\nOBJECTS\n\
0\nXRECORD\n5\n300\n100\nAcDbXrecord\n3\nCADCRAFT_HANDSEED\n1\n1000\n\
0\nENDSEC\n"
} else {
""
};
format!(
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n1000\n0\nENDSEC\n\
0\nSECTION\n2\nBLOCKS\n\
0\nBLOCK\n8\n0\n2\n*MODEL_SPACE\n70\n0\n10\n0.0\n20\n0.0\n30\n0.0\n3\n*MODEL_SPACE\n1\n\n\
0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n0.0\n31\n0.0\n\
0\nENDBLK\n8\n0\n\
0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n\
0\nLINE\n5\n{below}\n8\n0\n10\n10.0\n20\n0.0\n30\n0.0\n11\n11.0\n21\n0.0\n31\n0.0\n\
0\nLINE\n5\n{band}\n8\n0\n10\n20.0\n20\n0.0\n30\n0.0\n11\n21.0\n21\n0.0\n31\n0.0\n\
0\nENDSEC\n{objects}0\nEOF\n"
)
}
/// All three lines survive with their own handles: the handle-less block entity could not take
/// the reserved-band handle of the file's own ENTITIES record.
fn assert_three_lines_survive(d: &Drawing) {
assert_eq!(d.model.len(), 3, "one entity replaced another");
let handles = distinct(d);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 0.0)), "the block entity is gone");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 10.0)), "the line below the band is gone");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 20.0)), "the line in the band is gone");
// The band's explicit handle stays with the record that names it.
let band = Handle(cadcraft_doc::HANDLE_LIMIT);
let owner = d.model.iter().find(|e| e.handle == band).expect("the band handle was renumbered");
assert!(matches!(&owner.kind, EntityKind::Line(l) if l.a.x == 20.0), "the band handle moved to another line");
// The handle just below the band is the file's too, and it stays with its own record.
let below = Handle(cadcraft_doc::HANDLE_LIMIT - 1);
let owner = d.model.iter().find(|e| e.handle == below).expect("the below-band handle was renumbered");
assert!(matches!(&owner.kind, EntityKind::Line(l) if l.a.x == 10.0), "the below-band handle moved to another line");
}
#[test]
fn reserved_band_handles_in_entities_are_not_handed_to_a_handle_less_block_entity() {
// The handle below the reserved band is the file's, so the reader's next handle is the first
// handle in the band, which an ENTITIES record already owns. The seed cannot follow it
// (#913), so the handle is reserved for allocation instead: the handle-less model-space
// block entity must not take it and replace the file's line.
assert_three_lines_survive(&read(&file_with_reserved_band_entities(true)));
}
#[test]
fn reserved_band_handles_are_reserved_without_the_cadcraft_seed_record() {
// The same reservation holds when the pre-scan reads every section's handles: a handle in
// the band is the file's own there too, and still must not be given away.
assert_three_lines_survive(&read(&file_with_reserved_band_entities(false)));
}
#[test]
fn reservations_end_with_the_read_and_placed_objects_still_keep_their_handles() {
// The reservations only bridge the gap until a record is placed; a drawing does not carry
// them on (every undo step copies the drawing). The placed objects keep new ones off.
let mut d = read(&file_with_reserved_band_entities(true));
assert!(d.reserved_handles.is_empty(), "the reader's reservations outlived the read");
for i in 0..3 {
d.add(&Space::Model, Common::default(), line(f64::from(i), 50.0)).unwrap();
}
assert_eq!(d.model.len(), 6, "a new object replaced one of the file's");
assert_three_lines_survive_among(&d);
}
fn assert_three_lines_survive_among(d: &Drawing) {
let band = Handle(cadcraft_doc::HANDLE_LIMIT);
assert!(d.model.iter().any(|e| e.handle == band && matches!(&e.kind, EntityKind::Line(l) if l.a.x == 20.0)), "the band line lost its handle");
let handles = distinct(d);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}");
}
#[test]
fn generated_geometry_never_takes_a_handle_an_object_holds() {
// The drawing's own handles sit in the reserved band and the seed is at the top of the
// range, so the writer's structural numbering wraps into the band. Every other band handle
// is taken, so without a check the generated dimension block's entities land on an occupied
// one: the saved file would repeat a handle.
let mut d = Drawing::new_imperial();
d.handseed = u64::MAX - 1;
{
let model = d.space_mut(&Space::Model).unwrap();
for i in 0..200u64 {
let handle = Handle(cadcraft_doc::HANDLE_LIMIT + 1 + 2 * i);
model.push(Entity { handle, common: Common::default(), kind: line(i as f64, 0.0) });
}
model.push(Entity {
handle: Handle(0x200),
common: Common::default(),
kind: EntityKind::Dimension(Dimension {
kind: DimKind::Linear { rotation: 0.0 },
defpt: Vec3::new(0.0, 1.0, 0.0),
text_mid: Vec3::new(1.0, 1.0, 0.0),
p13: Vec3::ZERO,
p14: Vec3::new(2.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 2.0,
text_rotation: 0.0,
user_text_pos: false,
block: None,
insertion_point: Vec3::ZERO,
overrides: serde_json::Map::new(),
assoc: Vec::new(),
marks: Default::default(),
}),
});
}
let bytes = cadcraft_io::write(&d, "generated.dxf").unwrap();
let tags = craft_dxf::parse(&bytes).unwrap();
let after_header = tags.iter().position(|t| t.code == 2 && t.str() == "TABLES").unwrap();
let written: Vec<String> = tags[after_header..].iter().filter(|t| t.code == 5 || t.code == 105).map(|t| t.str().to_string()).collect();
let unique: std::collections::HashSet<&String> = written.iter().collect();
assert_eq!(unique.len(), written.len(), "the save repeats a handle");
}
/// A line at the top handle with another application's xdata, and that application's object kept
/// from the file: a dictionary in the named object dictionary holding an XRECORD.
fn top_line_with_kept_objects() -> String {
let groups: &[(i32, &str)] = &[
(0, "SECTION"),
(2, "ENTITIES"),
(0, "LINE"),
(5, TOP),
(8, "0"),
(10, "0"),
(20, "0"),
(11, "10"),
(21, "0"),
(1001, "OTHER_APP"),
(1000, "tagged"),
(0, "ENDSEC"),
(0, "SECTION"),
(2, "OBJECTS"),
(0, "DICTIONARY"),
(5, "C"),
(330, "0"),
(100, "AcDbDictionary"),
(3, "OTHER_APP"),
(350, "50"),
(0, "DICTIONARY"),
(5, "50"),
(330, "C"),
(100, "AcDbDictionary"),
(281, "1"),
(3, "DATA"),
(360, "51"),
(0, "XRECORD"),
(5, "51"),
(330, "50"),
(100, "AcDbXrecord"),
(280, "1"),
(1, "kept"),
(0, "ENDSEC"),
(0, "EOF"),
];
groups.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect()
}
#[test]
fn records_added_on_save_after_the_top_handle_take_free_handles() {
// The writer adds the kept objects (and any application id the xdata needs) after its own
// records, numbered above the largest handle written. That is the file's line at the top of
// the range: counting on from it would give every added record the line's handle.
let d = read(&top_line_with_kept_objects());
let bytes = cadcraft_io::write(&d, "kept-top.dxf").unwrap();
let text = String::from_utf8_lossy(&bytes);
assert!(text.contains("\nkept"), "the kept XRECORD was not written");
let tags = craft_dxf::parse(&bytes).unwrap();
let after_header = tags.iter().position(|t| t.code == 2 && t.str() == "TABLES").unwrap();
let written: Vec<String> = tags[after_header..].iter().filter(|t| t.code == 5 || t.code == 105).map(|t| t.str().to_string()).collect();
let unique: std::collections::HashSet<&String> = written.iter().collect();
assert_eq!(unique.len(), written.len(), "the save repeats a handle: {written:?}");
assert_eq!(written.iter().filter(|h| h.as_str() == TOP).count(), 1, "the line's handle was not written exactly once");
let r = read(&String::from_utf8_lossy(&bytes));
assert!(r.entity(Handle::parse_hex(TOP).unwrap()).is_some(), "the file's line is gone");
}
-451
View File
@@ -1,451 +0,0 @@
//! Saved layer states in AutoCAD's form: the LAYER table's extension dictionary holds an
//! `ACAD_LAYERSTATES` dictionary of one XRECORD per state. The groups below are copied from
//! AutoCAD 2024's own DXFOUT of states saved with -LAYER stAte on a self-built drawing.
use cadcraft_color::{Color, Rgb};
use cadcraft_doc::{Drawing, Layer, LayerState, Lineweight};
use cadcraft_io::{read, write_dxf};
/// `(code, value)` pairs of a DXF, trimmed.
fn pairs(dxf: &str) -> Vec<(String, String)> {
let lines: Vec<&str> = dxf.lines().collect();
lines.chunks(2).filter_map(|c| Some((c.first()?.trim().to_string(), c.get(1)?.trim().to_string()))).collect()
}
fn join(p: &[(String, String)]) -> String {
p.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect()
}
fn g(c: &str, v: &str) -> (String, String) {
(c.to_string(), v.to_string())
}
/// The records of a DXF: (type, groups after the `0`).
fn records(p: &[(String, String)]) -> Vec<(String, Vec<(String, String)>)> {
let mut out: Vec<(String, Vec<(String, String)>)> = Vec::new();
for (c, v) in p {
if c == "0" {
out.push((v.clone(), Vec::new()));
} else if let Some(last) = out.last_mut() {
last.1.push((c.clone(), v.clone()));
}
}
out
}
fn value<'a>(groups: &'a [(String, String)], code: &str) -> Option<&'a str> {
groups.iter().find(|(c, _)| c == code).map(|(_, v)| v.as_str())
}
/// The handle of table record `kind` named `name`.
fn record_handle(p: &[(String, String)], kind: &str, name: &str) -> String {
let recs = records(p);
let (_, groups) = recs.iter().find(|(k, gs)| k == kind && value(gs, "2").is_some_and(|n| n.eq_ignore_ascii_case(name))).unwrap();
value(groups, "5").unwrap().to_string()
}
/// A handle above every handle of the file, plus `k`.
fn fresh(p: &[(String, String)], k: u64) -> String {
let top = p.iter().filter(|(c, _)| c == "5" || c == "105").filter_map(|(_, v)| u64::from_str_radix(v, 16).ok()).max().unwrap();
format!("{:X}", top + 0x100 + k)
}
/// `dxf` with the LAYER table given extension dictionary `xdict` and `objects` added at the end
/// of OBJECTS.
fn inject(dxf: &str, xdict: &str, objects: Vec<(String, String)>) -> String {
let mut p = pairs(dxf);
let table = p.iter().enumerate().position(|(i, (c, v))| c == "0" && v == "TABLE" && p.get(i + 1).is_some_and(|n| n.1 == "LAYER")).unwrap();
let at = table + p[table..].iter().position(|(c, _)| c == "5").unwrap() + 1;
p.splice(at..at, [g("102", "{ACAD_XDICTIONARY"), g("360", xdict), g("102", "}")]);
let objs = p.iter().position(|(c, v)| c == "2" && v == "OBJECTS").unwrap();
let end = objs + p[objs..].iter().position(|(c, v)| c == "0" && v == "ENDSEC").unwrap();
p.splice(end..end, objects);
join(&p)
}
/// Layers A (red) and B, and the DASHED linetype.
fn drawing() -> Drawing {
let mut d = Drawing::new_metric();
d.layers.push(Layer { color: Color::Index(1), ..Layer::new("A") });
d.layers.push(Layer::new("B"));
d.linetypes.push(cadcraft_doc::library::standard_linetypes().into_iter().find(|l| l.name == "DASHED").unwrap());
d
}
/// State S2 as AutoCAD 2024 wrote it after -LAYER: A true colour 10,20,30 (nearest index 168),
/// 50% transparent, 0.35 mm, DASHED, not plotted; B locked and frozen in new viewports. Then the
/// entry of a layer purged since (AutoCAD keeps it, pointing at handles that are gone).
fn s2(p: &[(String, String)], rec: &str, dict: &str) -> Vec<(String, String)> {
let (a, b, zero) = (record_handle(p, "LAYER", "A"), record_handle(p, "LAYER", "B"), record_handle(p, "LAYER", "0"));
let (cont, dashed) = (record_handle(p, "LTYPE", "Continuous"), record_handle(p, "LTYPE", "DASHED"));
let gone = fresh(p, 0x50);
let mut v =
vec![g("0", "XRECORD"), g("5", rec), g("102", "{ACAD_REACTORS"), g("330", dict), g("102", "}"), g("330", dict), g("100", "AcDbXrecord")];
v.extend([g("280", "1"), g("91", "2047"), g("301", ""), g("290", "0"), g("302", "0")]);
for (h, flags, aci, lw, lt, ps, tr) in [
(b.as_str(), "28", "7", "-3", cont.as_str(), "Color_7", "0"),
(a.as_str(), "0", "168", "35", dashed.as_str(), "Color_168", "33554559"),
(zero.as_str(), "8", "7", "-3", cont.as_str(), "Color_7", "0"),
(gone.as_str(), "8", "7", "-3", gone.as_str(), "Color_7", "0"),
] {
v.extend([g("330", h), g("90", flags), g("62", aci), g("370", lw), g("331", lt), g("1", ps), g("440", tr)]);
if h == a {
v.push(g("92", "-1039526882"));
}
}
v
}
/// State S7, saved with only On and restored once (AutoCAD then sets bit 65536), current layer A.
fn s7(p: &[(String, String)], rec: &str, dict: &str) -> Vec<(String, String)> {
let (a, b) = (record_handle(p, "LAYER", "A"), record_handle(p, "LAYER", "B"));
let cont = record_handle(p, "LTYPE", "Continuous");
let mut v =
vec![g("0", "XRECORD"), g("5", rec), g("102", "{ACAD_REACTORS"), g("330", dict), g("102", "}"), g("330", dict), g("100", "AcDbXrecord")];
v.extend([g("280", "1"), g("91", "66049"), g("301", "only on"), g("290", "0"), g("302", "A")]);
for (h, aci) in [(b.as_str(), "7"), (a.as_str(), "1")] {
v.extend([g("330", h), g("90", "8"), g("62", aci), g("370", "-3"), g("331", &cont), g("1", &format!("Color_{aci}")), g("440", "0")]);
}
v
}
/// The extension dictionary of the LAYER table and the states dictionary, with `extra` entries in
/// the extension dictionary.
fn dictionaries(p: &[(String, String)], x: &str, y: &str, states: &[(&str, &str)], extra: &[(&str, &str)]) -> Vec<(String, String)> {
let table = {
let recs = records(p);
let (_, gs) = recs.iter().find(|(k, gs)| k == "TABLE" && value(gs, "2") == Some("LAYER")).unwrap();
value(gs, "5").unwrap().to_string()
};
let mut v = vec![g("0", "DICTIONARY"), g("5", x), g("330", &table), g("100", "AcDbDictionary"), g("280", "1"), g("281", "1")];
for (k, h) in extra.iter().copied().chain([("ACAD_LAYERSTATES", y)]) {
v.extend([g("3", k), g("360", h)]);
}
v.extend([
g("0", "DICTIONARY"),
g("5", y),
g("102", "{ACAD_REACTORS"),
g("330", x),
g("102", "}"),
g("330", x),
g("100", "AcDbDictionary"),
g("281", "1"),
]);
for (name, h) in states {
v.extend([g("3", name), g("350", h)]);
}
v
}
fn autocad_file() -> String {
let base = write_dxf(&drawing());
let p = pairs(&base);
let h = |k| fresh(&p, k);
let (x, y, r2, r7) = (h(1), h(2), h(3), h(4));
let mut objects = dictionaries(&p, &x, &y, &[("S2", &r2), ("S7", &r7)], &[]);
objects.extend(s2(&p, &r2, &y));
objects.extend(s7(&p, &r7, &y));
inject(&base, &x, objects)
}
#[test]
fn reads_the_layer_states_autocad_writes() {
let d = read(autocad_file().as_bytes(), "acad.dxf").unwrap();
let names: Vec<&str> = d.layer_states.iter().map(|s| s.name.as_str()).collect();
assert_eq!(names, ["S2", "S7"]);
let s2 = &d.layer_states[0];
assert_eq!((s2.mask, s2.current.as_str(), s2.description.as_str()), (2047, "0", ""));
// The purged layer's entry is skipped.
let layers: Vec<&str> = s2.layers.iter().map(|l| l.name.as_str()).collect();
assert_eq!(layers, ["B", "A", "0"]);
let a = &s2.layers[1];
assert_eq!(a.color, Color::True(Rgb(10, 20, 30)));
assert_eq!((a.transparency, a.lineweight, a.linetype.as_str()), (50, Lineweight::from_dxf(35), "DASHED"));
assert!(a.on && !a.frozen && !a.locked && !a.plot && !a.vp_freeze_new);
// A colour-dependent drawing: the plot style stays the layer's ("Color_168" is its colour's).
assert_eq!(a.plot_style, "Normal");
let b = &s2.layers[0];
assert!(b.on && !b.frozen && b.locked && b.plot && b.vp_freeze_new, "{b:?}");
assert_eq!((b.color, b.linetype.as_str(), b.transparency), (Color::Index(7), "Continuous", 0));
let s7 = &d.layer_states[1];
assert_eq!((s7.mask, s7.current.as_str(), s7.description.as_str()), (66049, "A", "only on"));
assert_eq!(s7.layers.iter().find(|l| l.name == "A").unwrap().color, Color::Index(1));
}
#[test]
fn autocads_layer_states_are_written_back_in_its_form() {
let d = read(autocad_file().as_bytes(), "acad.dxf").unwrap();
let text = write_dxf(&d);
let p = pairs(&text);
// One states dictionary, in the LAYER table's extension dictionary, and no CADCraft copy.
assert_eq!(p.iter().filter(|(c, v)| c == "3" && v == "ACAD_LAYERSTATES").count(), 1);
assert!(!text.contains("CADCRAFT_LAYERSTATES"));
let recs = records(&p);
let (_, table) = recs.iter().find(|(k, gs)| k == "TABLE" && value(gs, "2") == Some("LAYER")).unwrap();
let x = table.windows(2).find(|w| w[0] == g("102", "{ACAD_XDICTIONARY")).map(|w| w[1].1.clone()).unwrap();
let (_, xd) = recs.iter().find(|(k, gs)| k == "DICTIONARY" && value(gs, "5") == Some(x.as_str())).unwrap();
assert_eq!(value(xd, "330"), value(table, "5"));
let back = read(text.as_bytes(), "back.dxf").unwrap();
assert_eq!(back.layer_states, d.layer_states);
// The XRECORD of S2 as AutoCAD writes it: B, then A.
let (a_h, b_h) = (record_handle(&p, "LAYER", "A"), record_handle(&p, "LAYER", "B"));
let (_, rec) = recs.iter().find(|(k, gs)| k == "XRECORD" && gs.contains(&g("91", "2047"))).unwrap();
let head = rec.iter().position(|(c, _)| c == "280").unwrap();
assert_eq!(rec[head..head + 5], [("280", "1"), ("91", "2047"), ("301", ""), ("290", "0"), ("302", "0")].map(|(c, v)| g(c, v)));
let cont = record_handle(&p, "LTYPE", "Continuous");
let b = [("330", b_h.as_str()), ("90", "28"), ("62", "7"), ("370", "-3"), ("331", &cont), ("1", "Color_7"), ("440", "0")];
assert_eq!(rec[head + 5..head + 12], b.map(|(c, v)| g(c, v)));
let from = rec.iter().position(|(c, v)| c == "330" && *v == a_h).unwrap();
let a: Vec<(String, String)> = rec[from..from + 9].to_vec();
let dashed = record_handle(&p, "LTYPE", "DASHED");
let want = [
("330", a_h.as_str()),
("90", "0"),
("62", "168"),
("370", "35"),
("331", &dashed),
("1", "Color_168"),
("440", "33554559"),
("92", "-1039526882"),
];
assert_eq!(a[..8], want.map(|(c, v)| g(c, v)), "{a:?}");
#[cfg(not(target_arch = "wasm32"))]
{
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
assert_eq!(read(&dwg, "x.dwg").unwrap().layer_states, d.layer_states);
}
}
#[test]
fn layer_filters_next_to_the_states_are_kept() {
// The LAYER table's extension dictionary of a drawing with layer filters holds them next to
// the states (ACAD_LAYERFILTERS, ACLYDICTIONARY): they stay, in the dictionary CADCraft writes.
let base = write_dxf(&drawing());
let p = pairs(&base);
let h = |k| fresh(&p, k);
let (x, y, r2, f, fr, gone) = (h(1), h(2), h(3), h(4), h(5), h(6));
// Two entries whose objects the file doesn't have (a handle of nothing, and a null one): they
// aren't written into the table's dictionary.
let extra = [("ACAD_LAYERFILTERS", f.as_str()), ("OTHER_GONE", gone.as_str()), ("OTHER_NULL", "0")];
let mut objects = dictionaries(&p, &x, &y, &[("S2", &r2)], &extra);
objects.extend(s2(&p, &r2, &y));
objects.extend([g("0", "DICTIONARY"), g("5", &f), g("102", "{ACAD_REACTORS"), g("330", &x), g("102", "}"), g("330", &x)]);
objects.extend([g("100", "AcDbDictionary"), g("281", "1"), g("3", "Walls"), g("350", &fr)]);
objects.extend([g("0", "XRECORD"), g("5", &fr), g("102", "{ACAD_REACTORS"), g("330", &f), g("102", "}"), g("330", &f), g("100", "AcDbXrecord")]);
objects.extend([g("280", "1"), g("1", "A*")]);
let file = inject(&base, &x, objects);
let mut text = file;
for round in 0..2 {
let d = read(text.as_bytes(), "f.dxf").unwrap();
assert_eq!(d.layer_states.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["S2"], "round {round}");
text = write_dxf(&d);
let p = pairs(&text);
let recs = records(&p);
let (_, table) = recs.iter().find(|(k, gs)| k == "TABLE" && value(gs, "2") == Some("LAYER")).unwrap();
let xdicts: Vec<String> = table.windows(2).filter(|w| w[0] == g("102", "{ACAD_XDICTIONARY")).map(|w| w[1].1.clone()).collect();
assert_eq!(xdicts.len(), 1, "round {round}");
let xd = &xdicts[0];
let (_, dict) = recs.iter().find(|(k, gs)| k == "DICTIONARY" && value(gs, "5") == Some(xd.as_str())).unwrap();
let keys: Vec<&str> = dict.iter().filter(|(c, _)| c == "3").map(|(_, v)| v.as_str()).collect();
assert_eq!(keys, ["ACAD_LAYERSTATES", "ACAD_LAYERFILTERS"], "round {round}");
// The filters dictionary is owned by the written one, and so is its filter by it.
let fh = dict.windows(2).find(|w| w[0] == g("3", "ACAD_LAYERFILTERS")).map(|w| w[1].1.clone()).unwrap();
let (_, fd) = recs.iter().find(|(k, gs)| k == "DICTIONARY" && value(gs, "5") == Some(fh.as_str())).unwrap();
let owner = fd.iter().filter(|(c, _)| c == "330").map(|(_, v)| v.as_str()).collect::<Vec<_>>();
assert_eq!(owner, [xd.as_str(), xd.as_str()], "round {round}: reactor and owner");
let walls = value(fd, "350").unwrap();
let (_, wr) = recs.iter().find(|(k, gs)| k == "XRECORD" && value(gs, "5") == Some(walls)).unwrap();
assert!(wr.contains(&g("330", &fh)) && wr.contains(&g("1", "A*")), "round {round}");
// The kept dictionary itself is not written a second time.
assert_eq!(recs.iter().filter(|(k, gs)| k == "DICTIONARY" && gs.iter().any(|(c, v)| c == "3" && v == "ACAD_LAYERFILTERS")).count(), 1);
}
// With every state deleted the filters stay, in the table's own dictionary, and AutoCAD's states
// don't come back.
let mut d = read(text.as_bytes(), "f.dxf").unwrap();
d.layer_states.clear();
let text = write_dxf(&d);
assert!(!text.contains("ACAD_LAYERSTATES"));
let p = pairs(&text);
let recs = records(&p);
let (_, table) = recs.iter().find(|(k, gs)| k == "TABLE" && value(gs, "2") == Some("LAYER")).unwrap();
let xd = table.windows(2).find(|w| w[0] == g("102", "{ACAD_XDICTIONARY")).map(|w| w[1].1.clone()).unwrap();
let (_, dict) = recs.iter().find(|(k, gs)| k == "DICTIONARY" && value(gs, "5") == Some(xd.as_str())).unwrap();
assert_eq!(dict.iter().filter(|(c, _)| c == "3").map(|(_, v)| v.as_str()).collect::<Vec<_>>(), ["ACAD_LAYERFILTERS"]);
assert!(read(text.as_bytes(), "g.dxf").unwrap().layer_states.is_empty());
}
#[test]
fn entries_whose_names_differ_only_in_case_open_as_one_state() {
// AutoCAD 2024 opens the entries `S` and `s` of one ACAD_LAYERSTATES dictionary as one state:
// named as the first entry in the dictionary and holding the last entry's record (measured with
// the records in one file order and the entries in both dictionary orders, so the first entry's
// record came first in the file once and last once). Here S2's record (mask 2047) comes first in
// the file, then state T's, then S7's (66049); the merged state stays where S2's record is.
let base = write_dxf(&drawing());
let p = pairs(&base);
let h = |k| fresh(&p, k);
let (x, y, r2, r7, rt) = (h(1), h(2), h(3), h(4), h(5));
let states = |d: &Drawing| d.layer_states.iter().map(|s| (s.name.clone(), s.mask)).collect::<Vec<_>>();
for (pair, name, mask) in [([("S", r2.as_str()), ("s", r7.as_str())], "S", 66049), ([("s", r7.as_str()), ("S", r2.as_str())], "s", 2047)] {
let entries = [pair[0], ("T", rt.as_str()), pair[1]];
let mut objects = dictionaries(&p, &x, &y, &entries, &[]);
objects.extend(s2(&p, &r2, &y));
objects.extend(s7(&p, &rt, &y));
objects.extend(s7(&p, &r7, &y));
let d = read(inject(&base, &x, objects).as_bytes(), "case.dxf").unwrap();
let want = [(name.to_string(), mask), ("T".to_string(), 66049)];
assert_eq!(states(&d), want, "{entries:?}");
// Written back, they are the states AutoCAD opened.
let back = read(write_dxf(&d).as_bytes(), "back.dxf").unwrap();
assert_eq!(states(&back), want, "{entries:?}");
}
// A record the dictionary lists as `s` but another object owns isn't a state, and doesn't stand
// in for S's record either.
let mut objects = dictionaries(&p, &x, &y, &[("S", r2.as_str()), ("s", r7.as_str())], &[]);
objects.extend(s2(&p, &r2, &y));
objects.extend(s7(&p, &r7, &x));
let d = read(inject(&base, &x, objects).as_bytes(), "stray.dxf").unwrap();
assert_eq!(states(&d), [("S".to_string(), 2047)]);
}
#[test]
fn view_snapshots_and_names_twice_in_another_case_stay_in_cadcrafts_record() {
let mut d = drawing();
for name in ["Plan", "*VIEW Front", "PLAN", "Wände", "WÄNDE", "", " "] {
d.layer_states.push(LayerState::new(name, d.layers.clone(), "A"));
}
let text = write_dxf(&d);
let p = pairs(&text);
let recs = records(&p);
let (_, states) =
recs.iter().find(|(k, gs)| k == "DICTIONARY" && gs.contains(&g("281", "1")) && gs.iter().any(|(c, v)| c == "3" && v == "Plan")).unwrap();
// (The DXF writes "ä" as \U+00E4.)
let keys: Vec<String> = states.iter().filter(|(c, _)| c == "3").map(|(_, v)| v.replace("\\U+00E4", "ä")).collect();
assert_eq!(keys, ["Plan", "Wände"], "AutoCAD's dictionary holds the first of each name");
assert!(text.contains("CADCRAFT_LAYERSTATES"));
let back = read(text.as_bytes(), "v.dxf").unwrap();
// AutoCAD's states first, then CADCraft's own.
// (A blank name can't be a key of AutoCAD's dictionary: those stay in CADCraft's record too.)
let want: Vec<LayerState> = [0, 3, 1, 2, 4, 5, 6].iter().map(|&i| d.layer_states[i].clone()).collect();
assert_eq!(back.layer_states, want);
#[cfg(not(target_arch = "wasm32"))]
{
let dwg = cadcraft_io::write(&d, "v.dwg").unwrap();
assert_eq!(read(&dwg, "v.dwg").unwrap().layer_states, want);
}
}
#[test]
fn a_layer_of_an_xref_gets_group_93() {
// AutoCAD 2024 writes 93 (0 for a newly attached xref) after the lineweight of an xref's layer
// only (measured with a self-built xref).
let mut d = drawing();
d.layers.push(Layer::new("XR|L1"));
d.layer_states.push(LayerState::new("X", d.layers.clone(), "0"));
let p = pairs(&write_dxf(&d));
let recs = records(&p);
let (_, rec) = recs.iter().find(|(k, gs)| k == "XRECORD" && gs.contains(&g("91", "2047"))).unwrap();
let start = rec.iter().position(|(c, _)| c == "302").unwrap() + 1;
let mut with_93 = Vec::new();
let mut layer = String::new();
for (i, (c, v)) in rec.iter().enumerate().skip(start) {
match c.as_str() {
"330" => layer.clone_from(v),
"93" => {
assert_eq!((v.as_str(), rec[i - 1].0.as_str(), rec[i + 1].0.as_str()), ("0", "370", "331"));
with_93.push(layer.clone());
}
_ => {}
}
}
assert_eq!(with_93, [record_handle(&p, "LAYER", "XR|L1")]);
}
#[test]
fn named_plot_styles_are_written_by_placeholder() {
// In a drawing of named plot styles AutoCAD 2024 writes a layer's plot style as group 390, the
// handle of the style's placeholder object (measured); CADCraft reads it back by that handle.
let mut d = drawing();
d.header.set_i64("PSTYLEMODE", 0);
let a = d.layers.iter().position(|l| l.name == "A").unwrap();
d.layers[a].plot_style = "Thick".into();
d.layer_states.push(LayerState::new("N", d.layers.clone(), "0"));
// No layer uses Thick any more: its placeholder is written for the state.
d.layers[a].plot_style = "Normal".into();
let text = write_dxf(&d);
let p = pairs(&text);
let recs = records(&p);
let (_, names) = recs.iter().find(|(k, _)| k == "ACDBDICTIONARYWDFLT").unwrap();
let thick = names.windows(2).find(|w| w[0] == g("3", "Thick")).map(|w| w[1].1.clone()).unwrap();
let (_, rec) = recs.iter().find(|(k, gs)| k == "XRECORD" && gs.contains(&g("91", "2047"))).unwrap();
assert!(rec.contains(&g("390", &thick)) && !rec.iter().any(|(c, _)| c == "1"), "{rec:?}");
let back = read(text.as_bytes(), "n.dxf").unwrap();
assert_eq!(back.layer_states[0].layers.iter().find(|l| l.name == "A").unwrap().plot_style, "Thick");
assert_eq!(back.layer_states, d.layer_states);
#[cfg(not(target_arch = "wasm32"))]
{
let dwg = cadcraft_io::write(&d, "n.dwg").unwrap();
assert_eq!(read(&dwg, "n.dwg").unwrap().layer_states, d.layer_states);
}
}
#[test]
fn a_state_in_both_records_is_read_from_autocads() {
// A file of an earlier CADCraft keeps its states in CADCraft's record; AutoCAD then saves a state
// of the same name in its own dictionary: AutoCAD's is the one read.
let mut d = drawing();
d.layer_states.push(LayerState::new("S", d.layers.clone(), "A"));
d.layer_states.push(LayerState::new("*VIEW S", d.layers.clone(), "B"));
let text = write_dxf(&d);
assert!(text.contains("*VIEW S"));
let text = text.replace("*VIEW S", "S");
let back = read(text.as_bytes(), "both.dxf").unwrap();
assert_eq!(back.layer_states.iter().map(|s| (s.name.as_str(), s.current.as_str())).collect::<Vec<_>>(), [("S", "A")]);
}
#[test]
fn states_past_the_limit_are_left_out_and_the_rest_come_in_file_order() {
// A hostile file with one state more than the reader keeps (100 000): the last one in the file
// is left out, and the others come in file order, here the reverse of their names' order.
const LIMIT: u64 = 100_000;
let base = write_dxf(&drawing());
let p = pairs(&base);
let first = u64::from_str_radix(&fresh(&p, 0), 16).unwrap();
let h = |k: u64| format!("{:X}", first + k);
let (x, y) = (h(1), h(2));
let names: Vec<String> = (0..=LIMIT).map(|i| format!("S{:06}", LIMIT + 1 - i)).collect();
let records: Vec<String> = (0..=LIMIT).map(|i| h(3 + i)).collect();
let entries: Vec<(&str, &str)> = names.iter().map(String::as_str).zip(records.iter().map(String::as_str)).collect();
let mut objects = dictionaries(&p, &x, &y, &entries, &[]);
for r in &records {
objects.extend([g("0", "XRECORD"), g("5", r), g("330", &y), g("100", "AcDbXrecord")]);
objects.extend([g("280", "1"), g("91", "2047"), g("301", ""), g("290", "0"), g("302", "0")]);
}
let d = read(inject(&base, &x, objects).as_bytes(), "many.dxf").unwrap();
let names: Vec<&str> = d.layer_states.iter().map(|s| s.name.as_str()).collect();
assert_eq!(names.len(), 100_000);
assert_eq!((names.first().copied(), names.get(1).copied(), names.last().copied()), (Some("S100001"), Some("S100000"), Some("S000002")));
}
#[test]
fn a_record_twice_in_a_file_is_one_state() {
// A damaged file can hold an object twice under one handle: one state.
let base = write_dxf(&drawing());
let p = pairs(&base);
let h = |k| fresh(&p, k);
let (x, y, r7) = (h(1), h(2), h(4));
let mut objects = dictionaries(&p, &x, &y, &[("S7", &r7)], &[]);
objects.extend(s7(&p, &r7, &y));
objects.extend(s7(&p, &r7, &y));
let d = read(inject(&base, &x, objects).as_bytes(), "twice.dxf").unwrap();
assert_eq!(d.layer_states.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["S7"]);
}
#[test]
fn group_92_without_the_true_colour_prefix_is_not_a_true_colour() {
// AutoCAD 2024 writes 92 only for a true colour, 0xC2RRGGBB (measured); a value with another
// high byte (not seen from AutoCAD) leaves the colour index of group 62.
let text = autocad_file().replace("92\n-1039526882", "92\n-1023410175");
let d = read(text.as_bytes(), "c3.dxf").unwrap();
assert_eq!(d.layer_states[0].layers.iter().find(|l| l.name == "A").unwrap().color, Color::Index(168));
}
-1
View File
@@ -32,7 +32,6 @@ mod groups_roundtrip;
mod hatch_assoc_roundtrip;
mod hatch_pattern_def;
mod helix_roundtrip;
mod layer_states_acad;
mod layout_limits_roundtrip;
mod layout_paper_units;
mod layout_plot_window;
+1 -1
View File
@@ -185,7 +185,7 @@ pub(super) fn layer_states() -> Case {
layer.on = false;
layer.locked = true;
}
drawing.layer_states.push(LayerState::new("Saved", layers, "0"));
drawing.layer_states.push(LayerState { name: "Saved".into(), layers });
Case { name: "drawing/layer-state".into(), drawing }
}
@@ -26,7 +26,6 @@ fn preserves_or_refuses(path: &str, binary: bool) {
}
#[test]
#[ignore = "Confirmed DXF data loss: exhausted generated handles produce a successful save that reopens with no model entities"]
fn dxf_exhausted_handles_are_preserved_or_refused() {
for binary in [false, true] {
preserves_or_refuses("memory.dxf", binary);
+5 -15
View File
@@ -492,16 +492,11 @@ const OBJECTS: &str = "
330 61
100 AcDbXrecord
280 1
91 2047
91 0
301 Plan
290 0
302 0
330 11
90 8
8 WALLS
90 0
62 1
370 -3
1 Normal
440 0
0 DICTIONARY
5 63
330 10
@@ -808,19 +803,14 @@ fn ucs_layer_states_and_block_descriptions_are_kept() {
assert_eq!((u.origin.x, u.origin.y, u.origin.z), (1.0, 2.0, 3.0));
assert_eq!((u.x_axis.y, u.y_axis.x), (1.0, -1.0));
assert_eq!(d.block("DOOR").map(|b| b.description.as_str()), Some("A door leaf"));
let states: Vec<(&str, Vec<&str>)> =
d.layer_states.iter().map(|s| (s.name.as_str(), s.layers.iter().map(|l| l.name.as_str()).collect())).collect();
assert_eq!(states, [("Plan", vec!["WALLS"])]);
for o in [&a, &b] {
// Layer states live in the LAYER table's extension dictionary, each layer named by its
// handle (as AutoCAD 2024 writes them; CADCraft reads and rewrites them).
// Layer states live in the LAYER table's extension dictionary.
let table = o.of("TABLE").into_iter().find(|t| s(t, 2) == "LAYER").expect("LAYER table");
let [xd] = group(table, "ACAD_XDICTIONARY").try_into().expect("LAYER table extension dictionary");
let (_, dict) = o.handle(&xd).expect("dictionary");
let (_, states) = o.entry(dict, "ACAD_LAYERSTATES").expect("ACAD_LAYERSTATES");
let (_, plan) = o.entry(states, "Plan").expect("layer state Plan");
let layers = plan.iter().skip_while(|t| t.code != 302).filter(|t| t.code == 330).map(Tag::str).collect::<Vec<_>>();
assert_eq!((s(plan, 301), layers), ("Plan".into(), vec![h(o.named("LAYER", "WALLS"))]));
assert_eq!((s(plan, 301), s(plan, 8)), ("Plan".into(), "WALLS".into()));
}
}
@@ -16,8 +16,8 @@ fn import(transform: &str) -> (f64, f64) {
_ => None,
})
.unwrap();
let (dx, dy) = (e.major.x - e.center.x, e.major.y - e.center.y);
(dy.atan2(dx), e.ratio)
// `major` is the axis from the centre (#2821).
(e.major.y.atan2(e.major.x), e.ratio)
}
/// Major-axis angle and ratio of the image of the ellipse under the 2x2 map `[a c; b d]`, with