Compare commits

..
Author SHA1 Message Date
Tanish Manku d7df84316f Merge #3288: SCALE Reference Points/Copy and grip scaling of heights 2026-11-24 22:02:14 -07:00
Tanish Manku 0d4b100209 Merge pull request #3471 from storytold/stack/n4
Land #3235, #3382, #2808: dynamic block stretch of wipeouts, arcs and hatches; TRIM/EXTEND part highlight; EXTRIM
2026-11-24 22:01:30 -07:00
vantruong-dang 23e5688a6f fix(cmd): mark SCALE Reference new-length prompt with distance() 2026-11-25 11:26:15 +07:00
vantruong-dang faba6b7e1e Merge remote-tracking branch 'origin/main' into fix/scale-reference-points
# Conflicts:
#	crates/ui-egui/src/cmdline.rs
2026-11-25 11:26:04 +07:00
Tanish Manku 33d46f3a00 Merge #2808: EXTRIM: trim everything crossing one cutting edge on the side picked 2026-11-24 21:16:52 -07:00
Tanish Manku a992e3198b Merge #3382: TRIM highlights only the piece a click removes, EXTEND what it adds (fixes #1118) 2026-11-24 21:16:32 -07:00
Tanish Manku 993388ca8c Merge #3235: Dynamic blocks: a stretch moves wipeouts, arcs and associative hatches as AutoCAD does 2026-11-24 21:16:30 -07:00
Tanish Manku 966d12819b Merge pull request #3470 from storytold/stack/n3
Land #3373, #3290, #3105: download docs, paste spreadsheet text as a TABLE, Tamil
2026-11-24 21:12:49 -07:00
Tanish Manku b11e2a94ac Merge pull request #3469 from storytold/docs/parity-batch-1125
Parity docs: rows updated for what merged from 2026-11-21 to 2026-11-25
2026-11-24 21:12:44 -07:00
Tanish Manku 510b7da798 Parity docs: qualify the plot-settings and existing-tab claims 2026-11-24 20:53:03 -07:00
okereke-dev 49ac1b1d30 EXTRIM: keep the Chinese menu row, which chinese_menus_and_commands_are_fully_translated requires 2026-11-24 22:47:35 -05:00
2ez4gcxandClaude Opus 5.5 3f805561d6 Dynamic blocks: a stretch moves the right end of a flipped arc
A stretch picks which ends of an arc move by testing the dynamic
block's arc ends against its frame (0 its start, 1 its end), but a
mirror swaps an arc's start and end (Arc::transform). In a reference
flipped by a flip action, the copy's start is the block's end, so a
later stretch moved the wrong end and distorted the arc.

The stretch now maps the indices to the copy's when the copy is
mirrored from the block: by the flips the reference already has (an
odd number of flipped flip actions holding the object; a repeated
selection counts once and a reflection line of no length mirrors
nothing, as the flip action itself does) and by mirrors queued for it
earlier in the same change. Unmirrored arcs keep their indices.

Tests: a flipped door arc stretched by Width (flipped, not flipped,
held twice, two flip actions, a reflection line of no length), and a
lookup that flips and stretches in one change, with the flip action
before or after the stretch, and back.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 10:46:10 +07:00
okereke-dev c7e6b10f42 EXTRIM: find each stretch on the object itself, report one it can't find (review on #2808)
A large arc's flattened outline strays from the arc by up to a millionth of its radius, more
than the tolerance next to a short edge, so a stretch's pick could miss every piece and the
object was still counted as trimmed through. The pick is now brought onto the object's exact
lines and arcs and the pieces are measured exactly; a stretch still not found counts the object
as uncut. The menu entry moves to Additional Tools, and the es/zh rows go (feature PRs add
English only).
2026-11-24 22:38:00 -05:00
Tanish Manku 408927c8a8 Merge #3105: Add Tamil (ta) to the interface languages; pasted table cells keep backslashes and braces as text 2026-11-24 20:32:18 -07:00
Tanish Manku feec896112 Merge #3290: feat(table): paste Excel TSV as native TABLE using craft-csv 2026-11-24 20:31:30 -07:00
Tanish Manku 52bb384e13 Merge #3373: docs: align CADCraft downloads with published packages 2026-11-24 20:31:29 -07:00
Tanish Manku abacc4c360 Parity docs: rows updated for what merged from 2026-11-21 to 2026-11-25 2026-11-24 20:29:53 -07:00
okereke-dev e1766b2191 Merge remote-tracking branch 'upstream/main' into feat/extrim 2026-11-24 22:28:22 -05:00
okereke-dev 3c7427d2bb TRIM preview: refresh after a fence point is taken back, and cap the Fence preview
The rollover highlight's cache key now counts the running command's answers, so Undo at the
fence prompt redraws the preview without the cursor moving. A Fence or Crossing preview works
out at most 64 picks; past that it shows no part highlight, and the fence still trims them all.
2026-11-24 22:27:54 -05:00
Tanish Manku 6e48d4b250 Merge pull request #3467 from storytold/stack/u11
Land #3231, #3394, #3457: Dynamic Input Tab cycle, Array window, lone user alias opens its dialog
2026-11-24 20:24:01 -07:00
okereke-dev f8fe736221 Merge remote-tracking branch 'upstream/main' into feat/trim-preview
# Conflicts:
#	crates/engine/src/cmd/modify.rs
#	crates/engine/src/guard.rs
#	crates/engine/src/prompt.rs
#	crates/engine/src/session/interactive.rs
2026-11-24 22:20:54 -05:00
vantruong-dang b8818c78b1 Merge remote-tracking branch 'origin/main' into feat/paste-table-tsv
# Conflicts:
#	crates/engine/src/session/interactive.rs
#	crates/ui-egui/src/clipboard.rs
#	crates/ui-egui/src/menus.rs
2026-11-25 10:14:06 +07:00
Tanish Manku 51b07ec42a Merge pull request #3419 from storytold/land/3375
Land #3375: PDFIMPORT imports a PDF page as editable lines, polylines, solid hatches and text
2026-11-24 20:05:00 -07:00
Tanish Manku 4e1ebc79c2 User alias lookup: a key stored with a capital outside ASCII matches a name typed in lower case 2026-11-24 20:04:41 -07:00
vantruong-dang cd5620a75d Merge remote-tracking branch 'origin/main' into fix/scale-reference-points
# Conflicts:
#	crates/engine/src/cmd/modify.rs
2026-11-25 10:02:17 +07:00
Tanish Manku c973274a23 Merge pull request #3466 from storytold/stack/n2
Land #3460, #3461, #3462, #3453: held paste follow-ups, constant attribute values, tapered-corner test
2026-11-24 19:59:59 -07:00
Tanish Manku 2a4dc14672 Merge #3457: a lone user alias of a UI command opens its dialog; landing fixes (alias lookup past ASCII capitals, Array window id without a lint allow) 2026-11-24 19:29:40 -07:00
Tanish Manku a254ed5bd5 Merge #3394: feat(ui): live Array dialog for ARRAYRECT and ARRAYPOLAR 2026-11-24 19:29:17 -07:00
Tanish Manku 9b8e4f257c Merge #3231: Dynamic Input: Tab cycles back to the first box and keeps the second value (#3201) 2026-11-24 19:29:15 -07:00
Tanish Manku 91ba1b8cc5 Merge #3453: Wide polylines: mitre the corners instead of leaving notches (#3443) 2026-11-24 19:27:39 -07:00
Tanish Manku 138acd3149 Merge #3462: A block reference draws its constant attribute values (#3413) 2026-11-24 19:27:37 -07:00
Tanish Manku 839036bcff Merge #3461: Input to the running command drops a held paste (follow-up to #3366, builds on #3460) 2026-11-24 19:27:35 -07:00
Tanish Manku c048120a0f Merge #3460: A held paste stays with the drawing that asked for it (follow-up to #3366) 2026-11-24 19:27:33 -07:00
Tanish Manku fc1b63a792 PDF import: fill-only text before fill-and-stroke text no longer doubles the stroked text 2026-11-24 19:27:21 -07:00
Tanish Manku bd520db235 Merge #3375 again: the eight review fixes, and main 2026-11-24 19:27:03 -07:00
moandClaude Fable 5.2 7ee382fb06 fix(doc): the extents of constant values follow ATTMODE, as their drawing does
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 21:23:55 -05:00
C00kieMonsta 2236c14802 PDF import: give hatch loops main's new boundary_flags field
A loop the importer builds has no DXF boundary path flags of its own,
so it takes None, as the proxy-graphics loops on main do.
2026-11-25 01:49:03 +00:00
C00kieMonsta d7088aab34 Merge main into feat/pdf-import
main gave HatchLoop a boundary_flags field, so the gate's merge build
no longer compiles the PDF importer's loops.
2026-11-25 01:48:22 +00:00
C00kieMonsta 6a98857ffa PDF import: compute a contour's signed area relative to its first vertex
At coordinates near 2^29 the cross products of absolute coordinates
round away a unit of area, so a unit square there had zero area and its
nonzero fill was dropped. The products are now taken relative to the
contour's first vertex.
2026-11-25 01:33:22 +00:00
C00kieMonsta 2873092eae PDF import: place even-odd contours that don't meet by their own boundary
An even-odd loop's depth was counted at a point nudged just inside its
longest edge. A hole drawn closer to that edge than the nudge held the
point, so the outer loop counted as nested and neither loop was saved
with the outer flag. When no two contours meet, each is now placed by
the middle of its longest edge, as nonzero fills already are; crossing
contours keep the nudged point.
2026-11-25 01:32:44 +00:00
C00kieMonsta 3655ded652 PDF import: read a clip as a rectangle only from one subpath
rect_of joined the points of every subpath, so two open segments that
reached the four corners of a box were read as that box, and a stroke
through it was kept. A rectangle must now be one subpath. A clip whose
subpaths each lie on one line encloses no area and clips everything;
any other clip of several subpaths is still reported as not applied.
2026-11-25 01:31:45 +00:00
C00kieMonsta 958ce153d2 PDF import: measure a text run's baseline from its first glyph
A glyph joined a run when it lay within 0.1 em of the previous glyph's
baseline, so text that climbed a little each glyph stayed one run and
was placed on the first glyph's baseline. The offset across the baseline
is now measured from where the run starts; the gap along it is still
measured from the previous glyph.
2026-11-25 01:30:32 +00:00
C00kieMonsta a248c59fa4 PDF import: leave out text inside a clip with no area
Two clips that only touch intersect in a rectangle with no area. Shapes
under it were already left out, but a glyph whose middle lay on the
shared edge passed the inclusive range test and was imported. Text now
needs a clip with area as well.
2026-11-25 01:29:48 +00:00
C00kieMonsta 2aa669fad9 PDF import: match a text's stroke replay glyph by glyph, not by its last run
Render mode 2 fills a whole Tj or TJ and then draws it again for its
stroke. A TJ that split into two runs arrived as fill A, fill B, stroke
A, stroke B, and the one remembered text matched neither stroke, so both
words were imported twice. The same record also dropped a later fill of
the same text in another colour.

The glyphs filled since the last shape, image or stroke are now queued,
and only a stroke glyph that repeats the next queued one is skipped.
Fills are never matched against each other.
2026-11-25 01:28:51 +00:00
2ez4gcxandClaude Opus 5.5 e49207546c Merge main into fix/dynblock-stretch-wipeout
Main moved the action loop into ActionRun (#3424). The frame test for
wipeouts and arcs moves into ActionRun::stretch; a polar stretch still
moves a wipeout or an arc whole, as it did, now that move_entity reads a
stored list for them (tested). Main's array helpers and the hatch outline
code sit side by side.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 08:27:50 +07:00
C00kieMonsta 13b956c166 PDF import: convert to US survey units (INSUNITS 21 to 24)
Survey feet, inches, yards and miles fell through to the millimetre
case, so a page imported into a drawing in survey feet came in 304.8
times too large. A survey foot is 1200/3937 m.
2026-11-25 01:26:59 +00:00
moandClaude Fable 5.2 4be3a25b42 fix(doc): a constant value the reference has an attribute for does not count in its extents
Such a reference draws its attribute and not the definition's value, but
the extents still added the value's box. The cache of block bounds now
keeps each constant value by tag, and a reference leaves out the ones it
carries an attribute for.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 19:51:26 -05:00
Dylan M. Taylor 7e95cfc864 packaging(linux): support co-installable nightly packages (#3450)
Linux nightly packaging by @dylanmtaylor, with the per-app Nightly flavor commits stacked on his branch.

Co-authored-by: Dylan M. Taylor <[email protected]>
2026-11-24 18:38:19 -06:00
kc8a 2ecf474da8 feat(ui): live Array dialog for ARRAYRECT and ARRAYPOLAR
Bind an Array window to the running rectangular/polar array commands: fields apply live in both directions while the command-line prompts and canvas preview stay active.
The polar window exposes Items, Angle between, Fill angle, Rows and Levels; the centre must be specified before OK commits.
The preview stays visible while the pointer is over the window.
2026-11-25 00:25:59 +00:00
Ray bda2f3db3d Dynamic Input: Tab wraps around to the first box and keeps the second value (#3201)
Tab after the second value now locks it (when typed) and moves back to the
first box, so the typed length or X can be changed; Tab there moves on to the
second box again. Typing and Backspace in the first box edit only the first
value, keeping the separator, the second value and its lock.

Escape, history recall, a picked option or a click could clear or replace the
command line while the first-box record stayed set, so retyping the same text
later reactivated the first box without Tab and put the next digit into the
first value (40<90 then 1 became 401<90).

Turning Dynamic Input off (F12) with the first box active left the record set
too, so Backspace then erased from the first value (40<90 became 4<90). The
record now goes whenever the Dynamic Input boxes are not on screen.

With the first value erased after Tab locked the second one (40<90 to <90),
the canvas now holds the locked angle (or Y) too, so the preview and a click
use the pointer distance along 90 degrees instead of the free pointer.

Escape and a click that used up the typed entry left the second value's lock
set, so retyping the same text (40<90) locked the angle without Tab. Both now
drop the lock as well as the first-box record.

A separator typed in the first box that switches the format is refused when
the second value does not read in the new format (40<N to a comma would give
40,N, which reads as nothing and hid both boxes); the entry and the first box
stay as they were.

A click at a prompt is now taken when the button goes down, and that path
also uses up the typed entry; it drops the lock and the first-box record the
same way, so a click there does not leave 40<90 locked for the next retype.
2026-11-24 17:16:38 -07:00
moandClaude Fable 5.2 b9821b2b03 fix(doc): constant values in extents: one cache for both kinds of reference, upright text
The bounds of a block's contents are cached by name and depth for block
references and for dimensions that use the block. Only a block reference
draws constant attribute values, so with one cached box the reference's
extents depended on which of the two measured the block first. The cache
now keeps the geometry and the constant values apart.

A constant value whose definition matches the layout's orientation is
drawn upright, and is now measured that way too.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 19:12:02 -05:00
moandClaude Fable 5.2 8bc673130f fix(ui-egui): input to the running command drops a held paste
A paste asked for while another command runs waits for the system
clipboard before it takes over. Input given in that time (a coordinate
typed or picked for LINE) answered the running command's prompt, and
the paste then cancelled that command anyway. The session now counts
the inputs it is given, a held paste remembers the count, and it is
dropped when input arrived before the clipboard was read.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 18:34:43 -05:00
moandClaude Opus 5.5 4f58d51241 fix(render): a block reference draws its constant attribute values (#3413)
Constant attribute definitions are not copied into a reference as
attributes; their value is drawn from the definition with the block.
The renderer skipped every attribute definition while drawing a
reference's contents, so constant values never showed on screen, in
plots or in exports, and the reference's extents left them out.

A constant definition inside a referenced block now draws its value
(multiline as multiline text) with the definition's properties and the
reference's transform, inside each array copy and under XCLIP like the
rest of the block. ATTMODE applies as for other attributes: 0 hides it,
1 hides an invisible one, 2 shows it. Variable definitions still draw
nothing from the block. A reference that carries an attribute with the
same tag draws that attribute only, not both.

The reference's extents add the box of each visible constant value, so
ZOOM Extents and selection by box agree with what is drawn. Hit testing
of a reference already reads the rendered geometry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 18:29:41 -05:00
moandClaude Fable 5.2 e2eedc1918 fix(ui-egui): a held paste stays with the drawing that asked for it
A paste asked for from a menu or the command line waits for the system
clipboard for up to half a second. If another drawing became the shown
one in that time (a file read in the background finished opening), the
held paste ran there. It now remembers its drawing and is dropped, with
a line in the command history, when another one is shown.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 18:16:54 -05:00
Tanish Manku 2ce75fcb03 Merge pull request #3456 from storytold/stack/n1
Land #3444, #3446, #3431, #3151, #3152, #2972, #3453, #2977, #2969, #3097, #2903, #3445: spline prompts, DIMSPACE, image limits, mitred wide polylines, DIMASSOC, mirror hatch, selection
2026-11-24 15:55:39 -07:00
Tanish Manku 63a5a321dd Merge #3366 again: the author's fix and test for a paste bound to another key 2026-11-24 15:32:25 -07:00
Tanish Manku 94b1174806 Merge main (after #3454, #3455); a block's image is hit on the outline of what it shows 2026-11-24 15:32:15 -07:00
Tanish Manku d538a468e4 Merge pull request #3455 from storytold/stack/u10
Land #3368, #3390, #3399, #3405, #3392, #3411, #3366: Thai PDF text, layout plot settings, Polish strings, dimension inline editor, table cell text, ATTDIA, system clipboard paste
2026-11-24 15:31:19 -07:00
Jarek Jastrzębski a13cbdc883 Command line: a lone user alias of a UI command opens its dialog
A user alias typed alone routes as its command in the interface, so an
alias of HATCH (KR) opens the Hatch dialog as HATCH does, also when typed
with the Greek layout active (ΚΡ). With more on the line (KR P ANSI31)
it goes to the engine as before, which runs the command with those inputs.
2026-11-24 23:26:32 +01:00
Tanish Manku f80dbb461a Merge pull request #3454 from storytold/stack/p1
Land #3425, #3426, #3095, #3435, #3439, #3437: hatch edge, dependency prune, tilt check, proxy graphics follow-ups, kept dimensions
2026-11-24 15:23:27 -07:00
Tanish Manku c1f771d5cd Merge pull request #3424 from storytold/stack/b1
Land #963, #993, #1752 (with #1030, #1098, #1699, #1723): dynamic block references rotate, flip, array, scale, align and look up
2026-11-24 15:04:29 -07:00
moandClaude Fable 5.2 57c1d36fc0 fix(ui-egui): a paste bound to another key reads the system clipboard first
The shortcut loop ran every paste command as already read, but only the
ones from this frame's clipboard events are. A paste command the user
bound to a key of its own fired from the key press with nothing read, so
it pasted what this window held. It is now held like a menu paste.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 17:04:19 -05:00
Franz Ferdinand Tritschel 7210d1d4ef Review: the tapered-corner test tapers its first segment
The test gave each segment a constant width, so a miter from an offset of the centre line would also have passed. The first segment now widens from 2 to 4, and the corner must reach (11, -2.1), where the edges meet, not (11, -2).
2026-11-24 22:48:09 +01:00
Tanish Manku d71f2b9584 Crossing selection: a block's image is tested by what it shows, not by its unclipped corners 2026-11-24 14:36:50 -07:00
Tanish Manku 8d3e176aa8 Merge #3445: Select block references by drawn geometry in crossing windows 2026-11-24 14:36:33 -07:00
Tanish Manku 5d8bfff1d4 Merge #2903: Select: a blank MTEXT is picked inside its box (fixes #2810) 2026-11-24 14:36:31 -07:00
Tanish Manku f16fb24b40 Merge #3097: Options: turn off the update check at start 2026-11-24 14:36:29 -07:00
Tanish Manku 59e7a0b178 Merge #2969: fix(engine): preserve hatch direction when mirroring 2026-11-24 14:36:27 -07:00
Tanish Manku df624b7a49 Merge #2977: fix(engine): respect DIMASSOC1 for new dimensions 2026-11-24 14:36:25 -07:00
Tanish Manku fc09368b69 Merge #3453: Wide polylines: mitre the corners instead of leaving notches (#3443) 2026-11-24 14:36:23 -07:00
Tanish Manku 5b4bbd933c Merge #2972: test: make non-Unicode filename fixtures portable on macOS 2026-11-24 14:36:21 -07:00
Tanish Manku 6deb10f4a8 Merge #3152: Images: IMAGEATTACH refuses a wrongly typed at, scale, rotation or name 2026-11-24 14:36:19 -07:00
Tanish Manku b2c35cd100 Merge #3151: Images: loaders start a file only while its largest size still fits the loaded-image limit 2026-11-24 14:36:17 -07:00
Tanish Manku 137c8e8a08 Merge #3431: Use dimension text height for DIMSPACE Auto 2026-11-24 14:36:15 -07:00
Tanish Manku 7f5750dc1f Merge #3446: SPLINE: handle Method and Object at the CV first-point prompt 2026-11-24 14:36:14 -07:00
Tanish Manku ef59bd8251 Merge #3444: SPLINE: ask again when the CV degree is fractional 2026-11-24 14:36:12 -07:00
Tanish Manku fe5b66d163 Paste: a paste command fired by a user-bound key asks for the system clipboard, like the menu 2026-11-24 14:35:51 -07:00
Tanish Manku 6d5bc58b72 Merge #3366: Edit > Paste and typed PASTECLIP read the system clipboard, like Ctrl+V (#3320) 2026-11-24 14:35:31 -07:00
Tanish Manku 603852d47e Merge #3411: INSERT: ATTDIA and the Edit Attributes dialog (repair of #2376) 2026-11-24 14:35:28 -07:00
Tanish Manku c35d323fe9 Merge #3392: DXF: preserve table cell text in 2007 and later saves 2026-11-24 14:35:26 -07:00
Tanish Manku 4ab5a56dc6 Merge #3405: Dynamic dimension inline editor: claim pointer drag, select text on open, commit on focus loss 2026-11-24 14:35:24 -07:00
Tanish Manku 4562fcbc44 Merge #3399: i18n(pl): translate the 218 strings added since #218 2026-11-24 14:35:23 -07:00
Tanish Manku 7cb911dbd4 Merge #3390: Save: every layout keeps its plot settings, the Model layout included 2026-11-24 14:35:21 -07:00
Tanish Manku d1fa21d798 Merge #3368: PDF text: Thai sara am reads after its tone mark (น้ำ, not นำ้); builds on #3090 (#2899) 2026-11-24 14:35:19 -07:00
Tanish Manku 6db635aadb Merge #3437: keep proxy graphics on their layers when the layer table changes (#3094) 2026-11-24 14:34:57 -07:00
Tanish Manku a6995acce4 Merge #3439: draw kept dimensions from their *D block and keep it on save (#3438) 2026-11-24 14:34:17 -07:00
Tanish Manku 21d295d671 Landing fixes: the two new tests join the tests/it binary; the POLYLINE caller of tilted() passes a closure 2026-11-24 14:33:56 -07:00
Tanish Manku 71527f87a7 Merge #3435: fix(doc): proxy graphics fill as a trait, ellipses under uneven matrices, size group after the marker (#2697 follow-ups) 2026-11-24 14:33:41 -07:00
Tanish Manku a329b3963a Merge #3095: fix(io): skip sampling arcs for the tilt check when the extrusion is on the Z axis 2026-11-24 14:33:40 -07:00
Tanish Manku 787d4e70b8 Merge #3426: DXF/DWG: prune kept ACDBASSOCDEPENDENCY objects whose target handle is unmapped 2026-11-24 14:33:40 -07:00
Tanish Manku f3959d65f9 Merge #3425: DXF/DWG: elliptic HATCH boundary edges deduplicate the shared start vertex 2026-11-24 14:33:39 -07:00
Tanish Manku 8fb4d81338 Merge #1752 again: the six review fixes (array budget, alignment grips, frozen layers) 2026-11-24 14:28:29 -07:00
Franz Ferdinand Tritschel 4370e61c17 Wide polylines: mitre the corners instead of leaving notches (#3443)
Each segment's band was built with that segment's own normal, so a wide
polyline showed a notch at every vertex. Each vertex now gets a corner on
the outer side of the turn: the two outer edges are extended until they
meet, or bevelled past the miter limit plot style joins already use.
Tapered segments meet where their own edges do; closed polylines get the
corner at their first vertex; repeated vertices don't stop it; straight
runs get nothing extra.

Wide polylines with a linetype (wide.rs) follow after #2487.
2026-11-24 22:20:40 +01:00
STE1200andClaude Opus 5.5 9f245800ee DXF/DWG: classify unknown assoc actions once
The prune guard parsed a dependency owner's action list again for each
dependency in each pass. finish now collects the handles of the kept
actions of unknown shape once, beside the handles they reference, and
the guard tests the owner against that set. The exemption is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 21:09:35 +01:00
moandClaude Fable 5.2 2ecbc112cc style: wrap the two changed lines as rustfmt asks
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 13:57:53 -05:00
mo 09eb871e38 Merge main into pdf-thai-order
# Conflicts:
#	crates/io/tests/pdf_text.rs
2026-11-24 13:49:35 -05:00
moandClaude Fable 5.2 dc143302ee fix(ui-egui): the command line's recent commands offer a paste the same way
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 13:49:14 -05:00
mo 0f62df0b35 Merge main into paste-os-clipboard
# Conflicts:
#	apps/cadcraft/src/native_menu.rs
2026-11-24 13:48:55 -05:00
moandClaude Fable 5.2 08b68e8c51 fix(macos): the menu bar offers Paste when the system clipboard may hold objects
The native menu bar refreshed enablement with the command's own check,
so Edit > Paste stayed disabled there until something was copied in this
window. It now asks clipboard::offered, like the in-window menus and the
context menu.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 13:48:45 -05:00
Yohanes Yuen afb53d5357 Fix block ray and clipped image crossing selection 2026-11-25 01:15:21 +08:00
Cody VogtandClaude Opus 5.5 ced6984630 Alignment grips: targets stay on a ray and off layers frozen in the viewport
The alignment search projected the cursor onto a ray as if it were an
xline, so a point behind the ray's base could be the target; behind it the
base is now the nearest point. It also passed no frozen layers, so an object
on a layer frozen in the active MSPACE viewport (not drawn there) could be
aligned with; `nearest_with_direction` now takes the viewport's frozen
layers, as the osnap search does.

Review of #3424 (CodeRabbit).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 10:46:32 -06:00
Cody VogtandClaude Opus 5.5 522ed59680 Dynamic blocks: an XY distance past the number range is refused; a polar end grip snaps its angle
With a tiny reference scale a finite typed XY distance became infinite in
block units and was stored, so the saved end point couldn't be read back as
the parameter's points. The distance and the end point must now be finite.

Dragging a polar parameter's end grip applied the distance value set but not
the angle one: the angle now snaps to its value set as typing it does, and
goes where it is dragged when the set has no limits.

Review of #3424 (CodeRabbit).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 10:36:37 -06:00
Cody VogtandClaude Opus 5.5 c862f8ac09 Dynamic blocks: the array budget is taken before offsets are kept; a repeated hatch follows its own outline
The arrays' copies were counted only after every selected object's offsets
had been cloned, so one array of 99,999 offsets over 1,000 objects held
nearly 100 million offsets before it was refused. `keep_array` now takes
each object's share of `MAX_ARRAY` before its offsets are kept.

A repeated associative hatch kept the first copy's outline handle, so
`refill_hatches` put every repeat's boundary back on the first square. Each
arrayed object's copies get their handles first, by place in the array
(in the same order as before, so the handles are unchanged), and a
repeated hatch's loop names the copy of its outline at the same place.

Review of #3424 (CodeRabbit).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 10:30:30 -06:00
Walter Haslbeck de1fb50043 proxy layers: the same marker on another layer is a conflict 2026-11-24 17:07:40 +01:00
Walter Haslbeck ebda56eab5 proxy graphics: fill hatches stay out of picking and snaps; three-point tests on their own 2026-11-24 17:07:38 +01:00
Walter Haslbeck 8c2852fd2d Snaps: dimensions inside blocks reach their block; the block moves with group 12 as drawn 2026-11-24 16:11:26 +01:00
Walter Haslbeck 4c7b64d37b proxy layers: indices above 65,535 resolve through the file's table 2026-11-24 16:11:24 +01:00
Walter Haslbeck 85e0fca6b4 proxy graphics: a circle or arc seen edge-on draws as the line it covers 2026-11-24 16:11:22 +01:00
Walter Haslbeck ec31dad772 proxy layers: a kept layer isn't a conflict; name indices around ones above 65,535 2026-11-24 14:59:34 +01:00
Walter Haslbeck 72f0dddc81 proxy graphics: fit three-point chunks in their own plane, collinearity relative to the triangle 2026-11-24 14:59:28 +01:00
Walter Haslbeck a4b15ec5f1 Kept dimensions: place the block reference at its base point, ByBlock transparency and plot style; snaps follow it 2026-11-24 14:59:21 +01:00
bic98andOpenAI Codex 1a0363905b SPLINE: handle Method and Object at the CV first-point prompt
Co-authored-by: OpenAI Codex <[email protected]>
2026-11-24 22:04:03 +09:00
Yohanes Yuen 15d2a63b45 Use block geometry for crossing selection 2026-11-24 20:36:48 +08:00
bic98andOpenAI Codex 877ce87557 SPLINE: ask again when the CV degree is fractional
Co-authored-by: OpenAI Codex <[email protected]>
2026-11-24 21:32:04 +09:00
Walter Haslbeck f33fa1ee0f proxy layers: name indices by the record's own graphics; read only the declared size
Review: a proxy copied from another drawing was remapped against the wrong
table; its indices are now named by its own decoded graphics (decoded again
with marker names), the file's table only as fallback. Only the 310 groups
holding the declared size are read and rewritten; names are looked up once.
2026-11-24 12:21:09 +01:00
Walter Haslbeck 80470c03e3 proxy graphics: axes through the linear part only; fill under a filled ellipse
Review: a tiny scale under a large translation lost the circle's axes to
cancellation; a filled circle that becomes an ellipse lost its fill.
2026-11-24 12:21:08 +01:00
Walter Haslbeck 3ac368c013 Kept dimensions reference their *D block instead of copying it
Review: copying block contents into the graphics multiplied nested
dimensions exponentially, missed nested pictures and the block's draw
order. One reference to the block lets the renderer's depth and size
limits, nesting and SORTENTS apply as for any block reference. PURGE keeps
the block a kept dimension names; picking uses the drawn block.
2026-11-24 12:08:09 +01:00
Walter Haslbeck f297806c43 fix: draw kept dimensions from their *D block and keep it on save (#3438, #1161)
A LARGE_RADIAL_DIMENSION or ARC_DIMENSION CADCraft keeps as read draws the
*D block its AcDbDimension part names, as AutoCAD does; without one, the
proxy graphics in its AcDbEntity part (the decoder learns POLYLINE_WITH_NORMAL,
chunk 32). Saving counts that block as used, so it is written and AutoCAD
reads the dimension again. cadcraft-cli no longer counts unknown entities
that draw graphics as not drawn.
2026-11-24 10:23:30 +01:00
Walter Haslbeck a4aa6cfa68 fix: keep proxy graphics on their layers when the layer table changes (#3094)
Proxy graphics name layers by their index in the file's LAYER table.
- Layers proxy graphics draw on count as used for PURGE and layer.delete,
  as in AutoCAD.
- Drawing::proxy_layers keeps the file's layer order under current names;
  saving turns each ATTRIBUTE_LAYER index into the written table's, so
  purging a layer before them no longer moves the graphics (AutoCAD itself
  saves the old indices).
- RENAME, LAYMRG and LAYDEL update the decoded graphics and that list.
- A LAYER or LTYPE record without a handle or name keeps its place in the
  index lists, so the records after it don't shift (review of #3423).
2026-11-24 09:25:46 +01:00
NewsBaba fb2f25d346 Merge branch 'storytold:main' into main 2026-11-24 12:51:50 +05:30
STE1200andClaude Opus 5.5 10a493d24c DXF/DWG: rewrite assoc action lists with non-owned dependencies
acadrust writes each AcDbAssocAction dependency entry as group 360
(owned) or 330 (not owned). The list rewrite accepted only 360 entries,
so an action with a 330 entry kept a stale count and a null entry after
a dependency was pruned. The rewrite now accepts both codes, keeps each
surviving entry's code, keeps input-null entries, and drops only
entries whose object is gone.

A dependency is no longer pruned when an action of unknown header
shape owns it or names it in any group 330 or 360, so that action's
count and list stay consistent. The prune loop runs until nothing
changes instead of at most 64 passes, and the cascade finds owners
through owner_of, so a null-owner body goes with its pruned hard owner
and stays while another live object holds it.

Tests: assoc_dependency_prune gains a mixed 330/360 list, a null-owner
body with one and with two hard owners, an unknown action header, and
an unknown action that lists a dependency of a known action by 330.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 08:06:12 +01:00
Walter Haslbeck bc6e0010eb fix(doc): proxy graphics: fill as a trait, ellipses under uneven matrices, size after the marker
Follow-ups to #2697 from the review in #3423:
- ATTRIBUTE_FILL is an AcGiFillType trait (1 always, 2 never) in force
  until the next one, for polygons and circles; a filled shape keeps its
  outline. Before, a 2 turned fill on, and only for the next polygon.
- A circle or arc under a matrix that scales its plane unevenly is an
  ellipse or elliptical arc; 3-point chunks are fitted in their plane.
- The size group is the first 92/160 after the AcDbProxyEntity marker.
- Only what the 310 groups hold is reserved, not the size claimed.
2026-11-24 08:05:57 +01:00
cloutier a888218786 fix(engine): use dimension text height for DIMSPACE Auto (#3429) 2026-11-23 22:36:37 -05:00
code-compliant 2017653a14 Correct the ATTDIA default in the system variable table comment 2026-11-24 11:26:49 +08:00
code-compliant d759668ff6 INSERT: a point does not answer an attribute prompt; ATTDIA defaults to 1
A canvas click reaches INSERT as Input::Point while the attribute prompts wait. The Attribs arm treated any non-text input as the default and advanced, so the dialog closed and the first attribute took its default. Ignore Input::Point and keep prompting, as Verify does; Enter still keeps the default.

Set ATTDIA's session default to 1, AutoCAD 2026's initial value, and update tests that assumed 0 to set it explicitly. Add tests for a point at the plain command line and a canvas click with the dialog open.
2026-11-24 11:16:51 +08:00
Jon Breen 661d0776a3 Keep saved pixel paper units on kept plot settings
The inherited-unit repair for group 72 now applies only to saved inch or
millimeter values (0 or 1). A layout saved in pixels (2) keeps 2 when its
units are unchanged, including after a device-only edit; an explicit unit
edit still writes its unit.
2026-11-23 20:31:49 -06:00
Zhan Zhancheng 1d28c3ef32 ui-egui: prevent inline dimcon Enter/Escape from leaking to command line 2026-11-24 09:08:41 +08:00
Zhan Zhancheng 34777543d9 ui-egui: guard inline dimcon edit across drawings and LISP prompts 2026-11-24 08:00:12 +08:00
Jon Breen 0611bad380 Review: Model flag on kept plot settings; shade groups only where the version defines them
write_plot_settings takes the layout's model flag and passes it to the baseline
call. Kept group 70 always has bit 1024 set for Model and cleared for paper
layouts. Plot groups 76 to 78 are written from AC1018 and 333 from AC1021, and
333 only when the object it names is saved.
2026-11-23 15:50:38 -06:00
Jarek Jastrzębski 08dfe1ed8d i18n(pl): translate the 218 strings added upstream
Dimension Style Manager (lines and arrowheads, text, fit, primary and
alternate units, tolerances), Blocks palette and block libraries, icon
sizes and a few prompts. translation_gaps reports nothing missing for pl.
Terms follow the existing catalog: linia pomocnicza / wymiarowa, grot,
odnośnik, rodzaj linii, grubość linii, LUW.
2026-11-23 22:49:40 +01:00
STE1200andLetta Code 99a83201b5 DXF/DWG: prune kept ACDBASSOCDEPENDENCY objects whose target handle is unmapped
When dxf_raw::finish remaps handles on kept associative objects, a
dangling dependentOnObject pointer (group 330 inside the
AcDbAssocDependency subclass) was rewritten to "0" while the dependency
remained active and stayed listed in its owning ACDBASSOCACTION 360
dependency list.

dxf_raw::finish now drops any kept AcDbAssocDependency whose non-null
dependentOnObject handle does not resolve to a written object/entity
(along with kept objects owned only by it), while leaving originally
unbound dependencies (330 = 0 in the input) untouched. In Map::object,
AcDbAssocAction filters dropped handles out of its 360 dependency list
and updates its 90 dependency count.

Tests: assoc_dependency_prune::{orphaned_assoc_dependency_is_pruned_along_with_action_entry_and_body,originally_unbound_assoc_dependency_with_null_target_is_kept}.

👾 Generated with [Letta Code](https://letta.com)

Co-Authored-By: Letta Code <[email protected]>
2026-11-23 22:19:37 +01:00
STE1200andLetta Code 008d538e28 DXF/DWG: elliptic HATCH boundary edges deduplicate the shared start vertex
When dxf_read::hatch converts an edge-based HATCH boundary loop into a
HatchLoop polyline, line_edge, circular_edge, and spline_edge each skip
the incoming first vertex when it coincides with the previous end vertex
(last.p.near(point, 1e-9)). elliptic_edge did not, emitting consecutive
duplicate vertices whenever an elliptic edge met a neighbouring edge.

elliptic_edge now applies the same skip check as spline_edge (after
reversing points for !ccw).

Tests: hatch_elliptic_edge_dedup::{ccw,cw}_elliptic_edge_does_not_duplicate_shared_start_vertex.

👾 Generated with [Letta Code](https://letta.com)

Co-Authored-By: Letta Code <[email protected]>
2026-11-23 22:19:33 +01:00
Jon Breen ff0e4173d3 Review: inherited paper units follow a changed MEASUREMENT
A layout that inherits its paper units wrote back the file's group 72 after
MEASUREMENT changed, so it reopened with the old unit. Group 72 is now
rewritten when it no longer matches the unit the drawing applies.
2026-11-23 15:14:16 -06:00
Jon Breen 94d9e3542f Save: every layout keeps its plot settings, the Model layout included
See the pull request description for the cause, the change and the tests.
2026-11-23 15:14:16 -06:00
Tanish Manku e2cd875560 Merge #1752: Dynamic blocks: base point and alignment parameters; lookups of angles, flips, XY and positions 2026-11-23 12:50:36 -07:00
Tanish Manku b418e68372 Merge #993: Block reference grips: none on locked or invisible attributes; a moved multiline attribute moves its text 2026-11-23 12:50:24 -07:00
Tanish Manku d1a4809b2b Merge #963: Dynamic blocks: a stretch or move carries a multiline attribute's text along 2026-11-23 12:50:18 -07:00
Tanish Manku 6cc7e0c881 Parity documents stay as on main: the rows PDFIMPORT moves are named in the pull request 2026-11-23 12:36:31 -07:00
Tanish Manku f7f409b2b0 Merge #3375: PDFIMPORT: a page of a PDF imports as editable lines, polylines, solid hatches and text 2026-11-23 12:36:20 -07:00
code-compliant df5063f5cd INSERT: a cancel handler's command never takes the person's dialog origin
Session::start_from recorded the incoming origin and command number, then
cancelled the running command. Cancellation can abort a paused LISP routine
and run its *error* handler; a handler that starts a command records that
command's Program origin through its own Session::start_from. The new
command's factory then ran after that cancellation, and the INSERT and
MINSERT factories read the overwritten field, so a person's '-INSERT T …
replacing a waiting routine was taken for a program's and ATTDIA 1 opened
no dialog.

The origin and number are now recorded after the cancellation, so they
describe this start and the factory sees the origin this command was
started with; a handler's own commands keep their Program origin. The
handler's command also keeps its own number, which the dialog identity and
the Blocks palette's placing test use.

Regression tests replace (command "LINE" "0,0" pause), whose *error*
handler starts LINE, with a person's '-INSERT or '-MINSERT under ATTDIA 1:
both fail before the change (command_origin Program, no attribute entry),
in the engine and in the UI harness, and the handler's LINE is still drawn
as the program's. The UI test comment that called a fresh OK an old
confirmation now says what the test does.
2026-11-23 22:26:26 +08:00
Jon Breen 3c70690990 Review: covered table cells write empty values in DXF 2007 and later
A covered cell that still held text wrote it into the typed and formatted
values. The modern value block is now empty for covered cells; the legacy
groups are unchanged. The test keeps text in a covered cell.
2026-11-23 08:20:59 -06:00
Zhan Zhancheng b23eaa591c Dynamic dimension inline editor: claim pointer drag, select text on open, commit on focus loss 2026-11-23 21:18:42 +08:00
code-compliant b244b59ec2 INSERT: a LISP token that replaces a running command never opens the dialog
A command a routine started was the program's only through
Session::start_programmatic, which (command …) uses for a start at Command:.
A token it feeds while a command runs takes the typed-input path instead
(Session::typed → typed_token), and that path called Session::start, which
records Origin::Person outside a script. With ATTDIA 1, the INSERT that
(command "LINE" "0,0" "'-INSERT" …) starts to replace LINE asked for the Edit
Attributes dialog, which the routine could never answer. MINSERT, COMMAND-S
and VL-CMDF reach the same path.

Session::lisp_drive now marks its slice as program input (Session::program_input,
saved and restored around the slice, a panic in it included), and Session::start
records Origin::Program for a command it starts then, as it does in a script. A
person typing the same tokens at the command line still gets the dialog.
2026-11-23 20:42:26 +08:00
code-compliant d3419d156a INSERT: only a command a person started opens the Edit Attributes dialog
A script's flag was the only origin INSERT consulted, and only Session::script
set it. A LISP (command "-INSERT" …) — in a LISP file, APPLOAD, or
engine.execute {"command":"lisp"} — started INSERT outside a script, so a
routine that ended before the first attribute answer left ATTDIA 1 to open a
dialog it could never answer; a routine resumed after a yield had the same gap.

Commands now record who started them for their whole life
(Session::command_origin(): a person at the command line or from a menu,
toolbar or palette, or a program), and INSERT opens the dialog only for a
person's command. Session::start_programmatic marks an AutoLISP (command …)
start, and Session::start takes a script's commands as the program's, so the
scripted INSERT still asks at the command line. A typed or menu INSERT keeps
the dialog.
2026-11-23 20:42:26 +08:00
code-compliant 21cd284434 Edit Attributes: a confirmation for the old dialog never finishes its replacement
One drained control batch can cancel the dialog's command and start another
INSERT of the same block before the next frame. The draft filter gave the
replacement its own defaults, but the window, its fields and OK kept the same
ids, and a click or Enter queued for the old dialog (ui.click and ui.key wait
in the app's synthetic input, one pointer event a frame) confirmed the
replacement with defaults nobody had seen.

The window and every widget in it now carry the drawing and command they
belong to, so a press on the old OK never ends on the new one and no focus or
keyboard state carries over; input queued before a dialog appeared is dropped
instead of handed to its replacement; and no answer is taken on the frame a
new owner's dialog first draws.
2026-11-23 20:42:19 +08:00
code-compliant ed012ca376 INSERT: a command a script starts never opens the Edit Attributes dialog
INSERT copied ATTDIA into the command without asking who started it. A
script that ends before the first attribute answer leaves INSERT waiting,
so a scripted -INSERT with ATTDIA 1 exposed the Edit Attributes dialog,
which a script cannot answer.

InsertM now records whether a script started it (Session::script_running)
for its whole life, and ATTDIA opens the dialog only for a command the
user started. A typed INSERT with ATTDIA 1 still asks in the dialog.
2026-11-23 20:42:04 +08:00
code-compliant 5b00e36200 Edit Attributes: a dialog draft belongs to the drawing and command that asked for it
The dialog kept its draft by block name and row count alone. A cancel
through the control channel runs before the dialog frame, so a second
INSERT of the same block could reach its attribute prompts in the same
drained batch and then inherit the cancelled draft; OK, or a queued
confirmation, submitted those values to the new command. A redefined block
with the same name and row count got values meant for other tags.

Session::attribute_entry now stamps each entry with the active drawing's
uid and the command's number in Session::commands_started, and the dialog
shows its draft only while both still match. A replacement command starts
from its own defaults, so a confirmation left over from the old dialog can
only submit what the new one shows.
2026-11-23 20:42:04 +08:00
NewsBaba ca1cdfb91b Merge branch 'storytold:main' into main 2026-11-23 16:10:34 +05:30
code-compliant bd7b7b77b0 Merge main into pr/insert-attrib-modes
Main gained ATTREQ, Preset and Verify prompts (#2535) while this branch was
open, so what is new here is ATTDIA and the Edit Attributes dialog: the
setting and its SETVAR registration, Session::attribute_entry and its guard
hook, the dialog, and the tests. Main's prompt flow is kept as it is: every
attribute value at the command line (or in the dialog), then the Verify
attributes asked again.

INSERT counts its attribute answers per definition (`asked`) instead of by
tag, as main still does: a block with two definitions of one tag stopped
asking until the map grew, which it never did. The duplicate-tag test fails
without it.

docs/gaps.md and docs/ui-parity.md keep main's rows; the affected rows are
named in the pull request instead.
2026-11-23 13:21:47 +08:00
Jon Breen 807085159d DXF: preserve table cell text in 2007 and later saves
Write modern table cell value blocks and keep merged anchors
content-bearing. Read formatted cell text when typed text is absent.
2026-11-22 17:15:42 -06:00
okereke-dev bb53e4e77d TRIM/EXTEND: preview every piece a Fence or a Crossing window will change while it is drawn
While a fence (Fence, or Quick mode's two-point fence) or a crossing window is drawn, every
piece it will remove (EXTEND: every stretch it will add) is highlighted with the same band as a
single pick.

- trimextend.rs: fence() and crossing() are split into fence_work()/crossing_work(), which find
  what they cut, and run_picks(). picks_preview() works the same run out without changing the
  drawing: each object at its picks in turn, against edges that include what the run has already
  made of other objects (Overlay), so the preview follows a fence whose trims change each
  other's edges.
- modify/trim.rs: trim_kind() and extend_kind() trim or extend a shape; edge_segments_over()
  gathers edges with an Overlay in place of the objects it names.
- Interactive::highlight_all / Session::highlight_all; the canvas draws it in place of the
  object under the cursor.

Tests: a fence highlighting both lines it crosses, the drawing untouched; a fence through a grid
and a circle removing exactly the highlighted length; Quick mode's two-point fence and a crossing
window; an EXTEND fence adding exactly what it highlighted.
2026-11-22 09:24:28 -05:00
okereke-dev af33469ec4 TRIM/EXTEND highlight: a wide see-through band under the part a click changes
The rollover look alone (a thin dashed line over the object itself) was hard to see on part of
an object.
2026-11-22 09:14:38 -05:00
okereke-dev e6a486b767 TRIM highlight: skip the kept outline's segments whose box is out of reach (CodeRabbit on #3382)
The coverage test in uncovered() now works out each segment's box and piece ends once and
passes over a segment whose box is farther than the tolerance from the point before measuring
its distance. Same result, less work on long polylines and finely flattened curves.
2026-11-22 09:08:30 -05:00
okereke-devandMarco Arnulfo 09351655b4 TRIM highlights only the piece a click removes, EXTEND what it adds (fixes #1118)
At TRIM's "Select object to trim" prompt the rollover highlight showed the whole object under
the cursor. It now shows only the piece a click there removes, and the whole object only when
Quick mode would erase it; EXTEND shows the stretch a click adds.

- modify/trim.rs: `trimmed` and `extended` work a trim or an extend out without changing the
  drawing; `trim` and `extend` apply them. The preview and the click share that code, so they
  can't disagree.
- prompt.rs, guard.rs, session: `Interactive::highlight` (under the panic guard) and
  `Session::highlight`: what the rollover highlight shows of the object under the cursor.
- trimextend.rs: TRIM/EXTEND's highlight is the object less the pieces a trim keeps (or the
  object as extended less the object), split where a piece ends, so it works the same for lines,
  arcs, circles, polylines, ellipses and splines. The edges of the object under the cursor are
  gathered once while the drawing and the edges stay the same.
- canvas: the highlighted part replaces the whole-object highlight, worked out again only when the
  object, the cursor, the zoom, the drawing or the prompt changes.

Tests: engine/tests/it/trim_highlight.rs (the piece between and past two edges, Quick-mode
erase, the drawing and undo untouched, the highlight matching what a click removes for seven
kinds of object, EXTEND, other prompts and locked layers, edges gathered again after a trim) and
a canvas test (the part is computed once while the cursor rests).

Follows the approach of #1126.

Co-authored-by: Marco Arnulfo <[email protected]>
2026-11-21 22:02:54 -05:00
C00kieMonsta 90d0942548 PDF import test: allow the interpreter's full nested-paint budget for a self-calling form 2026-11-21 22:28:56 +01:00
C00kieMonsta 186e465487 PDF import: fixes from review
- Fill tolerance follows the drawing unit, so arcs are sampled and fills
  split into triangles to the same accuracy in metres as in millimetres.
- Nonzero fills test containment from a point on each contour's edge, so
  an inner contour close to its parent's edge keeps the fill.
- A fill of two arc vertices (a disc) is kept.
- The same text drawn again after a shape or image is kept.
- A clip path that doubles back along an edge is not taken as a rectangle.
- PDF options that are not a JSON object are refused.
- The options window imports into the drawing it was opened for.
- The self-calling form test checks the outcome against a finite form.
2026-11-21 22:02:20 +01:00
C00kieMonsta c79fdde52d PDF import CLI test: format with rustfmt 2026-11-21 21:43:57 +01:00
C00kieMonsta d4fd0dd7a2 PDFIMPORT: a page of a PDF imports as editable lines, polylines, solid hatches and text
PDFIMPORT (File > Import PDF...) adds a chosen page to the current drawing,
with page, scale, insertion point, password and content options. OPEN and
IMPORT take a PDF too; OPEN reads its first page into a new metric drawing,
and cadcraft-cli convert writes it to DXF or DWG.

The mapping is adapted from PR #2787 (MIT OR Apache-2.0) onto craft-pdf's
interpreter. Nonzero fills whose contours don't cross keep their loops and
arcs; crossing contours are split into triangles so the filled area matches.
Content the import leaves out or approximates is named in the read notes,
and a page with no vector content is refused instead of opening empty.
2026-11-21 21:31:15 +01:00
Mex 7568e34248 docs: align CADCraft downloads with published packages 2026-11-21 20:08:01 +01:00
Vincent Cloutier a1b77015b6 Refresh MIRROR hatch direction against current main 2026-11-21 14:04:42 -05:00
Vincent Cloutier fbcebf3392 Refresh DIMASSOC mode handling against current main 2026-11-21 13:53:54 -05:00
moandClaude Sonnet 5.5 f581688caf fix(ui-egui): tie a held paste to its own clipboard request
A cancelled request's answer could complete a newer held paste, whose
own answer was then dropped. Each RequestPaste now has an identity kept
with the held command, and a Paste completes the command only when it
answers that request; otherwise it is a stale answer that pastes
nothing (its text still becomes the clipboard, being the system
clipboard's) and the command keeps waiting for its own answer or
deadline.

Where the window answers in the next frame or not at all (X11, Windows,
macOS), a request is answerable for that one frame, counted in frames,
so a paste with no answer falls back at once and a later Ctrl+V is never
taken for it. Only native Wayland, which reads asynchronously with a 3 s
budget, keeps the time bound, now 5 s. The app tells the interface which
case applies from the display handle.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-21 13:48:41 -05:00
moandClaude Sonnet 5.5 a91650376f fix(ui-egui): attribute each Paste to the paste request it answers
A typed UI command such as quickcalc left a held paste waiting, and the
one-second window for ignoring a late Paste could be consumed by a real
Ctrl+V or missed by a slow answer, so one request could paste twice.

Typed commands now drop a held paste before the UI-command branch. Each
RequestPaste is remembered for 3.5 s, the delivery budget egui-winit
gives its asynchronous Wayland read (elsewhere the answer arrives in the
next frame's input, and nothing arrives when the clipboard has no text).
A Paste is the answer to the oldest request still remembered, so one
whose command was escaped or gave up pastes nothing, while a Paste with
no request outstanding is an ordinary Ctrl+V. This replaces the time
window that swallowed a Paste.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-21 13:18:51 -05:00
moandClaude Sonnet 5.5 f24468f2a1 fix(ui-egui): a held paste is cancelled by Escape and runs once
A paste waiting for the system clipboard kept running after Escape, and
a wait that ran out in the same frame as the Paste event, or a Paste that
answered a request already given up on, started a second paste.

Escape (command line and cmdline.key) and starting any other command now
drop a held paste. A Paste event in the frame the wait expires completes
the held command instead of the timeout running it first. After a
timeout or a cancel of a request already sent to the window, one Paste
within one second is treated as that request's late answer and ignored;
a real Ctrl+V inside that second is swallowed once, and pressing it
again pastes.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-21 12:53:24 -05:00
moandClaude Opus 5.5 d3baf2e9e7 PDF text test: one glyph that shows sara aa in one word and sara am in another reads right in both
After the typed-order change of issue #2899, the sara aa glyph shows ำ in น้ำ and า in นา.
The PDF writer gives a glyph one ToUnicode entry, taken from its first use; krilla wraps a
later use with other text in its own /ActualText span. The test plots นา and น้ำ in one
drawing, in both orders, and reads the page glyph by glyph (ActualText where there is one,
else ToUnicode), which must give the typed words.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 12:52:00 -05:00
moandClaude Opus 5.5 1fa0a8b18c Complex text shaping: typed order never costs a character its own glyph in the text layer
The typed-order assignment of a cluster's characters to its glyphs could put a character
second on a glyph where the previous assignment gave every character a glyph of its own.
With น typed before the tone mark and then sara u, the shaper draws sara u before the
tone mark (FreeSerif shapes นุ้ as no, sara u, mai tho): the typed pass matched sara u to its
glyph, so the tone mark went with no and its own glyph showed nothing. Render and the PDF
writer keep a glyph's first character only, so the tone mark dropped out of the PDF text,
where the previous assignment kept all three, out of order.

glyph_chars now takes the typed assignment only when it leaves at least as many glyphs
showing a character as the plain one, and the plain one otherwise. น้ำ, ฐ with sara u as
one glyph and the Devanagari vowel sign before its consonant come out as before; the unit
test gains the unusual order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 12:52:00 -05:00
moandClaude Opus 5.5 5e01c3bb81 PDF text: Thai sara am reads after its tone mark, the glyphs of a shaped cluster show their characters in typed order
A TEXT or MTEXT with น้ำ plotted to PDF in a font such as FreeSerif or Garuda read
นำ้ in its text layer (the first part of issue #2899). The shaper splits sara am into
nikhahit and sara aa and draws the nikhahit before the tone mark. glyph_chars in
crates/fonts/src/complex.rs then gave sara am to the first glyph without a character of
its own, the nikhahit, so in drawing order, which is the order the PDF writes the glyphs
in, sara am came before the tone mark. Fonts that substitute the tone mark (Noto Sans
Thai raises it over the nikhahit) only read right because no glyph matched its own
character.

Within a cluster, own glyphs are now matched only in typed order, the other glyphs take
the remaining characters between them, and a character with no glyph of its own there
goes with the glyph before it, as a ligature's characters already go with the
ligature. In น้ำ the sara aa shows ำ after the tone mark and the nikhahit is drawn as an
outline; ฐ with sara u as one glyph still shows both. Where typed order would need a
character on a glyph before every glyph that shows one (a vowel sign drawn before its
consonant, as in Devanagari), the assignment stays as before: render and the PDF writer
take the first character of a glyph only, so moving a character onto another glyph
would drop it from the text. What is drawn does not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 12:27:58 -05:00
moandClaude Sonnet 5.5 2d95af7d7b fix(ui-egui): Edit > Paste and PASTECLIP read the system clipboard
Only Ctrl+V reached load_system_text, so a copy made in another CADCraft
window could not be pasted from the Edit menu, the context menu or by
typing PASTECLIP, PASTEBLOCK or PASTEORIG (issue #3320).

A paste started from a menu or typed on the command line is now held for
a frame while the window is asked for the system clipboard
(ViewportCommand::RequestPaste). The resulting Paste event goes through
the same path as Ctrl+V, so the newest of this window's clipboard and
the system's wins, and then the held command runs. If no text arrives
within half a second (the clipboard holds an image or nothing), or a text
field has the keyboard, the command runs at once with what this window
holds. The web build gets a Paste only from the browser's own gesture, so
it keeps its behaviour.

The paste items are offered while a drawing is open and nothing was
copied in this window, instead of being disabled; they report an empty
clipboard when it turns out to be empty. The engine is unchanged.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-21 12:20:10 -05:00
Cody Vogt b92da359bd Merge storytold/cadcraft main into feat/dynblock-params
# Conflicts:
#	crates/engine/src/snap.rs
2026-11-21 11:02:42 -06:00
vantruong-dang 7819b4b65a fix(ui-egui): separate pointer-box display from dyn_frame point completion 2026-11-21 19:02:26 +07:00
vantruong-dang 9efc5e3541 fix(ui-egui/cmdline): keep dyn_frame active for Prompt::distance prompts 2026-11-21 18:14:51 +07:00
vantruong-dang 1203f087d3 Merge remote-tracking branch 'origin/main' into fix/scale-reference-points
# Conflicts:
#	crates/ui-egui/src/cmdline.rs
2026-11-21 17:41:09 +07:00
vantruong-dang 7707d49b66 Merge remote-tracking branch 'origin/main' into feat/paste-table-tsv
# Conflicts:
#	Cargo.toml
2026-11-21 17:17:10 +07:00
okereke-dev fe7d82d2a5 Merge main into EXTRIM
- tests/it/main.rs: keep extend_polyline_end_choice next to extrim.
- file_access/commands.rs: extrim touches no file.
- Two tests follow TRIM keeping the object's handle on its first piece.
2026-11-20 18:41:05 -05:00
vantruong-dang ff88c83b50 fix(table): route start_paste_table through launch_interactive and drop dead shortcut_commands 2026-11-19 20:11:23 +07:00
vantruong-dang 28ab81b3a3 feat(table): paste Excel TSV as native TABLE using craft-csv 2026-11-19 17:25:59 +07:00
vantruong-dang 573488d5a3 fix(cmd): support SCALE Reference Points and Copy, disable pointer boxes on numeric prompts, and scale heights in grip SCALE 2026-11-19 16:47:55 +07:00
moandClaude Opus 5.5 5c4a7ce5ed Merge remote-tracking branch 'origin/main' into thai-shaper
crates/fonts/src/complex.rs takes main's pedantic-lint style (#2568) with
this branch's glyph_chars that gives a ligature glyph every character of
its cluster.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 20:17:00 -05:00
tirael 3554e906e6 Merge current main into startup update preference 2026-11-17 11:04:51 +01:00
2ez4gcxandClaude Opus 5.5 e3599da862 Dynamic blocks: a hatch vertex among too many boundary points matches none
The grid that finds which boundary point a hatch vertex sits on kept at
most 16 points per cell. When the point the vertex sat on was one of
those dropped, the vertex matched a kept point of another object, and
the loop followed a line the stretch had left behind.

Every point is kept now. A vertex with more than 16 points in its cell
and the eight around it matches none, and its loop keeps what it has:
it can't tell which object it sits on, and the cap still bounds the
work per vertex.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 14:05:43 +07:00
2ez4gcxandClaude Opus 5.5 8c143f8feb Dynamic blocks: stretch an arc by its ends; hatches follow their lines
An arc with one end inside a stretch frame moved whole. AutoCAD 2024
moves that end and keeps the arc's height over its chord: in its own
stretched copies of library blocks, 84 arcs whose ends moved apart kept
their height to 1.1e-14 of it.

An associative hatch whose loop is made of several lines didn't follow
them: only a loop of one closed polyline was filled again. A straight
loop whose every vertex is a line's end or a flat polyline's vertex of
its boundary objects (within a billionth of the largest coordinate) now
takes those points' new places. The points looked through are bounded.

A tilted arc, and an arc when the frame can't be tested, still move
whole.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 13:15:43 +07:00
2ez4gcxandClaude Opus 5.5 05cd8ac095 Dynamic blocks: a stretch moves a wipeout's points inside its frame
A stretch action moved a selected WIPEOUT whole even when only part of
its outline was inside the frame. AutoCAD 2024 moves only the outline's
points inside the frame, as it does for lines and polylines: in its own
stretched copies of a library block, 324 of a 521-point wipeout's points
moved by the distance's change and the other 197 stayed.

The points that move are tested where the dynamic block has them; the
repeated closing point moves with the first. A frame that can't be
tested point by point still moves the wipeout whole, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 12:10:50 +07:00
Cody VogtandClaude Opus 5.5 95aefd183d Tests: block references built in tests give the clip main added
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 17:27:37 -06:00
Cody VogtandClaude Opus 5.5 105930e79d Merge storytold/cadcraft main into feat/dynblock-params
prompt.rs: main's takes_block and this branch's angle field both stay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 16:43:46 -06:00
NewsBaba 23abe2ed43 ta: record the native-speaker review
Radhika and Mohan Raj reviewed CADCraft's Tamil interface in the running
app on 2026-11-14. ATTRIBUTION.md and docs/localization.md say so instead
of listing the newer rows as unreviewed.
2026-11-16 08:35:11 +05:30
NewsBaba ecc0578661 Merge storytold/cadcraft main into the Tamil branch
Main gained the Polish catalog, Greek rows, and Additional Tools in place
of Express Tools.

- crates/fonts/build.rs, crates/fonts/src/craft_fonts.rs: keep main's
  backticked names and the Tamil `Taml` web face.
- crates/ui-egui/src/i18n.rs: LANGUAGES holds 21 and Preference::ALL 22,
  with both Polish and Tamil.
- ta.tsv: Express Tools becomes Additional Tools (கூடுதல் கருவிகள்), the
  label every European catalog now translates.
2026-11-16 03:33:33 +05:30
KvasExpert edf0a52640 Merge branch 'main' into update-check-option 2026-11-15 09:46:59 +01:00
dotCooCoo 7c580ec8cc Images: IMAGEATTACH refuses a wrongly typed scale when width is given
placement read `scale` only when `width` was omitted, so a call with
both a valid `width` and `"scale": "big"` attached the image. `scale`
is now checked first; a valid `width` still takes precedence.
2026-11-13 21:06:28 -08:00
dotCooCoo f833ab96f5 Images: IMAGEATTACH refuses a wrongly typed at, scale, rotation or name
A value of the wrong type for `at`, `scale`, `rotation` or `name` was
taken as omitted, so `"scale": "big"` attached an image one drawing unit
wide and `"at": "nowhere"` put it at 0,0. Each is now refused with an
error. An omitted or null value still takes its default.
2026-11-13 20:45:26 -08:00
dotCooCoo 1f56cef64e fix(engine): image loaders start a file only while its largest size still fits the loaded-image limit
When a drawing opened, each image loader checked the decoded total against
the 2 GB limit before decoding and added the image's size only after, so up
to four images of up to 512 MB each could decode at once past the limit.

A loader now starts a file only while the images decoded so far, plus the
largest image each file being decoded can become, fit under the limit, and
otherwise waits for a file to finish. With no other file being decoded one
file always starts, so the total runs past the limit by one image at most,
as it does with a single loader. A file that fails to decode counts nothing.
2026-11-13 20:36:47 -08:00
NewsBaba aa3d4635df Add Tamil (ta) to the interface languages
ta.tsv has 1,507 rows: 1,505 labels and the two count templates (one|other).
It covers every key of the existing catalogs the code still uses and the five
marked strings no catalog has yet, so `cargo xtask i18n` reports nothing
missing for ta. 1,289 rows come from the Tamil CADCraft and shared catalogs
in storytold/craft-i18n, reviewed there by native speakers; the other 218 are
AI-assisted and not yet native-reviewed.

egui's bundled faces have no Tamil letters, so Tamil follows the Arabic path:
an installed Tamil font whose first face has every letter the catalog uses
(theme::tamil_font), or a craft-fonts Taml face, loaded in the Tamil
interface only; the web build keeps Taml faces. Without either the choice is
kept, the interface stays English and the language command says why, and the
picker reads "Tamil" wherever Tamil can't be drawn.

The Properties header's All | My control sized each half 35 px, so a Tamil
"All" ran into "My"; each half now fits its label, and English is unchanged.
2026-11-13 00:05:55 +05:30
tiraelandClaude Opus 5.5 a1964aa9c5 Options: turn off the update check at start
Options ▸ User Preferences gets "Check for updates when CADCraft starts"
(on by default, desktop only). Off, the startup check and its "Update and
Restart" prompt never run; Help ▸ Check for Updates… still checks. The
choice is the OPTIONS JSON key `checkUpdatesAtStart`, kept in the profile and
restored by Reset to Defaults, for people who manage updates themselves (an
offline machine, a package manager, a pinned version).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 10:28:41 +01:00
Walter Haslbeck ad596f1e41 fix(io): skip sampling arcs for the tilt check when the extrusion is on the Z axis
`tilted` took its points eagerly, so every bulged edge of every LWPOLYLINE and HATCH loop was
tessellated on read, also with extrusion +Z or -Z, where no point can move and the answer is
always "not tilted". It now takes the points as a closure and returns before gathering them
when the normal's x and y are exactly 0. For such a normal `Mat4::ocs` is the identity or
(-x, y, -z), so the result is the same as before.
2026-11-12 07:48:07 +01:00
moandClaude Opus 5.5 e09870949d fix(fonts): a Thai ligature keeps every character it stands for as text
A font may draw a consonant and its below vowel as one ligature glyph:
GNU FreeSerif's Thai liga lookup replaces tho than + sara u with a
single tailless form. glyph_chars gave each glyph of a cluster at most
one character, so the characters left over in the cluster were
dropped and sara u was missing from the shaped text records.

glyph_chars now returns the characters each glyph shows, and the
cluster's last glyph takes any that are left over. push_glyph records
one text glyph per character against the same outline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 17:19:38 -05:00
SBaksa 086bd8a865 Select: say why a blank MTEXT frame is upright, and when its insertion points keep it a snap candidate (#2810) 2026-11-12 00:24:17 +11:00
SBaksa 72f07e5cd1 Select: a blank MTEXT's frame follows layout orientation, and its insertion points keep it a snap candidate only when INS is on and within the aperture (#2810)
A top-level MTEXT with a non-zero AcadAnnoPO value is drawn upright, so its pick frame no longer turns with the stored rotation. Insertion points now keep a blank frame in the snap pool only when INS is enabled and the point is within the aperture circle, not just the square probe.
2026-11-12 00:05:58 +11:00
SBaksa cf9f3a7ea3 Select: a blank MTEXT's bounds stay what it draws, and only the insertion points snap offers keep it a snap candidate (#2810) 2026-11-11 20:33:58 +11:00
SBaksa 2697456c9c Select: a blank MTEXT frame is only scaled for blank text, and its snap check uses the drawn insertion point (#2810) 2026-11-11 18:39:38 +11:00
SBaksa a0ce65ef06 Select: a blank MLEADER text box also catches a crossing window; share the annotation scaling (#2810)
Blank MTEXT frames use cadcraft_doc::anno_scaled, is_blank_mtext no longer allocates, and
the crossing test accepts the frame. Out-of-reach blank frames no longer use up snap
candidate or intersection slots. Adds tests for each.
2026-11-11 15:04:12 +11:00
Vincent Cloutier 71f77aca60 Merge official main font-test correction into PR2969 2026-11-10 10:36:15 -05:00
Vincent Cloutier c6ee9801b6 Merge official main font-test correction into PR2977 2026-11-10 10:10:36 -05:00
Vincent Cloutier 73c5232360 Merge official main font-test correction into PR2972 2026-11-10 09:36:05 -05:00
Vincent Cloutier 0ef5093530 PR2969: document mirror fill policy and regression coverage 2026-11-09 16:04:33 -05:00
Vincent Cloutier 4f51d0c655 PR2977: document dimension associativity policy and tests 2026-11-09 15:57:12 -05:00
Vincent Cloutier 57e32b0cdd fix(engine): honor non-associative DIMASSOC mode 2026-11-09 13:32:08 -05:00
Vincent Cloutier fb9a833144 test: handle macOS rejection of non-Unicode filenames 2026-11-09 12:42:59 -05:00
Vincent Cloutier bb36fab20e fix(engine): retain hatch direction in mirror commands and previews 2026-11-09 12:11:19 -05:00
SBaksa 2ef9cf67cf Select: a blank MLEADER text is picked inside its box (#2810)
Share the blank MTEXT frame with multileader picking and extend the
candidate bounds used by both scans and the spatial index.
Cover empty and whitespace boxes and preserve normal text picking.
2026-11-09 13:08:36 +11:00
SBaksa f04ca5144e Size a blank MTEXT's pick box at the current annotation scale
An annotative blank MTEXT is picked in the box it draws at CANNOSCALE,
and not at all while that scale hides it, as its drawn bounds already are.
2026-11-08 14:03:57 +11:00
SBaksa 89817444f2 Select: a turned blank MTEXT is picked in its turned box (#2810)
A click on a blank MTEXT is tested in its box turned with the text, not the
axis-aligned box around it (the spatial index and windows keep the larger box).
One helper holds the frame geometry for both.
2026-11-08 11:16:01 +11:00
SBaksa bc7f41d538 Select: a blank MTEXT is picked inside its box (#2810)
A blank or whitespace-only MTEXT has no glyph strokes and empty drawn bounds, so
a click inside it, and the spatial index, missed it. It is now picked (and
window/crossing selected) in its width x text-height box, placed by its
attachment point and rotation.
2026-11-08 00:25:32 +11:00
okereke-devandClaude Opus 5.5 1a57b390e1 EXTRIM: exactly one cutting edge, from the JSON form and at the prompt (CodeRabbit on #2808)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 09:29:21 -05:00
okereke-devandClaude Opus 5.5 1a4f8d3844 EXTRIM: a set for the stretches already taken, so many crossings stay linear (CodeRabbit on #2808)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 09:14:57 -05:00
okereke-devandClaude Opus 5.5 a0b2d45f22 EXTRIM: closedness from the object, end and seam crossings as TRIM has them, bounded work (review on #2808)
- An object is closed when it is (a closed polyline, circle, full ellipse,
  closed spline), not when its ends happen to meet; a crossing at an open
  outline's end doesn't count (as in trim), and one at a closed outline's seam
  counts once. Preview and trim now agree on touching and ends-meeting cases.
- Each object's crossings with the edge and the trace are found once and
  bracketed by binary search; at most 10,000 stretches per call.
- trim's edge_segments looks up the given edges by handle instead of scanning
  the space for them.
- An arc's or elliptical arc's side is inside or outside its full circle or
  ellipse, as OFFSET has it; the trace limit counts joined points.
- TRACE_GAP, a Side enum, and tests for arcs, ellipses, splines, bulged
  polylines, two stretches, touching, ends meeting, the seam and the limits.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 09:00:58 -05:00
okereke-devandClaude Opus 5.5 07ae46cc74 EXTRIM: report objects a planned cut can't open instead of counting them as done (CodeRabbit on #2808)
A closed object the edge crosses only once can't be trimmed open: it's left
out of the preview and counted in `skipped.uncut`, as is any planned cut the
trim refuses, with a line in the message.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 23:23:38 -05:00
okereke-devandClaude Opus 5.5 2cdb5832b3 EXTRIM: tests for the object and trace limits (CodeRabbit on #2808)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 23:11:35 -05:00
okereke-devandClaude Opus 5.5 14779e26c0 EXTRIM: trim everything crossing one cutting edge on the side picked, with a live preview (#2802)
Pick a line, arc, circle, ellipse, polyline or spline, then the side. The edge
is traced a hair's breadth toward that side; every object the trace crosses
loses the stretch between its edge crossings there, trimmed at the stretch's
middle with the edge as the only cutting edge. Objects that don't cross, the
edge itself, blocks, hatches, text and locked layers stay (and are counted).
One undo step, a red preview band that follows the cursor, a JSON form, and
no zero-length pieces left behind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 22:58:24 -05:00
Cody Vogt e789f77ba9 Merge commit 'e28ebc6958feb5990178b0ea9d3b6230e3b4a25d' into HEAD 2026-11-03 22:52:41 -06:00
Cody Vogt e28ebc6958 Merge remote-tracking branch 'origin/feat/dynblock-array' into feat/dynblock-scale 2026-11-03 22:52:07 -06:00
Cody Vogt 72fafd2807 Merge branch 'main' of https://github.com/storytold/cadcraft into feat/dynblock-scale
# Conflicts:
#	crates/engine/src/session/interactive.rs
2026-11-03 22:52:06 -06:00
Cody Vogt 84c3243d23 Merge branch 'main' of https://github.com/storytold/cadcraft into HEAD
# Conflicts:
#	crates/engine/src/session/interactive.rs
2026-11-03 22:39:40 -06:00
Cody VogtandClaude Sonnet 5.5 4d872f87d0 Merge #1723's fixes into feat/dynblock-params
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-02 22:43:19 -06:00
Cody Vogt eb87758abf Merge commit '858e1146e78fbb0ff266777c85091f23eec283c1' into HEAD
# Conflicts:
#	crates/doc/src/dynblock.rs
2026-11-02 22:38:01 -06:00
Cody Vogt 7f3687f506 Merge commit 'bb32810f' into HEAD 2026-11-02 22:31:28 -06:00
Cody Vogt 797b83b413 Merge branch 'main' of https://github.com/storytold/cadcraft into HEAD
# Conflicts:
#	crates/doc/src/dynblock/apply.rs
2026-11-02 22:15:39 -06:00
Cody Vogt 858e1146e7 Merge branch 'main' of https://github.com/storytold/cadcraft into feat/dynblock-scale
# Conflicts:
#	crates/doc/src/dynblock/apply.rs
2026-11-02 22:14:03 -06:00
Cody VogtandClaude Sonnet 5.5 bb32810f3e Merge main into feat/dynblock-scale; the DWG scale action test matches the struct variant
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-02 22:07:10 -06:00
Cody VogtandClaude Sonnet 5.5 34d889619c Tests: the DWG scale action test matches the Scale struct variant
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-02 16:18:48 -06:00
Cody Vogt d11c7f36ca Merge branch 'main' of https://github.com/storytold/cadcraft into feat/dynblock-scale 2026-11-02 16:07:05 -06:00
Cody Vogt cec1d2b9da Merge commit 'f4fd603acf4449f8943b5860264421ad85c502c1' into HEAD 2026-11-02 16:03:28 -06:00
Cody Vogt f4fd603acf Merge remote-tracking branch 'origin/feat/dynblock-array' into feat/dynblock-scale
# Conflicts:
#	crates/doc/src/dynblock/apply.rs
2026-11-02 16:03:04 -06:00
Cody Vogt 2d5988c13f Merge branch 'main' of https://github.com/storytold/cadcraft into feat/dynblock-scale
# Conflicts:
#	crates/doc/src/dynblock/apply.rs
2026-11-02 15:51:45 -06:00
Cody Vogt a17af990c8 Merge branch 'main' of https://github.com/storytold/cadcraft into HEAD
# Conflicts:
#	crates/doc/src/dynblock/apply.rs
2026-11-02 15:48:05 -06:00
Cody Vogt 843ee072d8 Merge commit '8aea81d682f248b711acc6ad5ec3d940f840fe25' into HEAD 2026-11-02 05:07:23 -06:00
Cody Vogt 8aea81d682 Merge remote-tracking branch 'origin/feat/dynblock-array' into feat/dynblock-scale
# Conflicts:
#	crates/doc/src/dynblock/apply.rs
2026-11-02 05:07:00 -06:00
Cody Vogt 9df1e11656 Merge branch 'main' of https://github.com/storytold/cadcraft into feat/dynblock-scale
# Conflicts:
#	crates/doc/src/dynblock/apply.rs
2026-11-02 04:54:36 -06:00
Cody Vogt 8428fbb4e7 Merge branch 'main' of https://github.com/storytold/cadcraft into HEAD
# Conflicts:
#	crates/doc/src/dynblock/apply.rs
2026-11-02 04:52:05 -06:00
Cody VogtandClaude Sonnet 5.5 309c902329 Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-01 16:19:04 -06:00
Cody VogtandClaude Sonnet 5.5 2513204737 Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-01 16:17:43 -06:00
Cody VogtandClaude Sonnet 5.5 41d20af874 Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-01 16:17:39 -06:00
Cody Vogt c0005803e8 Merge commit '7050d6dc2d49214162e2d93c2de591db35af3472' into HEAD
# Conflicts:
#	docs/file-format-parity.md
#	docs/gaps.md
2026-10-31 09:01:03 -06:00
Cody Vogt 2c775694d4 Merge branch 'main' of https://github.com/storytold/cadcraft into HEAD
# Conflicts:
#	crates/engine/tests/it/main.rs
2026-10-31 09:00:27 -06:00
Cody Vogt 7050d6dc2d Merge branch 'main' of https://github.com/storytold/cadcraft into feat/dynblock-scale
# Conflicts:
#	crates/engine/tests/it/main.rs
2026-10-31 08:53:46 -06:00
Cody Vogt 9f7440ce94 Merge branch 'main' of https://github.com/storytold/cadcraft into feat/dynblock-scale
# Conflicts:
#	docs/file-format-parity.md
#	docs/gaps.md
2026-10-30 20:36:06 -06:00
Cody VogtandClaude Sonnet 5.5 5e8d4e7f39 Snap: gather_in takes the object to skip, like its siblings' argument lists
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-29 22:29:46 -06:00
Cody VogtandClaude Opus 5.5 db3e14f494 Tests: the base point, alignment and lookup tests join the io test binary
Upstream (#1989) builds each crate's tests as one binary; dynblock_params.rs moves into tests/it, and dynamic_grips.rs's new fixture path is one level deeper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:29:46 -06:00
Cody VogtandClaude Opus 5.5 241cc6a9d4 Docs: the dynamic block data row names the fixed-base rotate and scale limit
A rotate or scale action with a fixed base point still acts about where the
dynamic block has it after a base point parameter has moved the reference;
AutoCAD replays the whole history instead. The PR said so; the row now does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:29:46 -06:00
Cody VogtandClaude Opus 5.5 e265c5cadd Docs: the dynamic block data row lists base point, alignment and lookup changes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:29:46 -06:00
Cody VogtandClaude Opus 5.5 fc82a2f903 Dynamic blocks: base point and alignment parameters; lookups of angles, flips, XY distances and positions
- An action that moves a base point parameter moves the reference's insertion point with it and
  the block's objects and parameters back, as AutoCAD saves it.
- Alignment parameters: type read, a grip at the base point; dragged next to an object the
  reference moves onto it and turns along it, its right side toward the cursor (measured in AutoCAD).
- Lookup columns UpdatedAngle, UpdatedFlip, UpdatedDistanceX/Y, UpdatedX/Y (and polar distance
  and angle) set and read, including the reverse lookup; any changed parameter re-evaluates the
  lookups that read it.
- A distance of 0 is taken, as AutoCAD takes it.
- A first-time flip value is saved with its state after its points and the flip grip's record
  without a point; AutoCAD dropped the reference's dynamic properties otherwise.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:29:46 -06:00
Cody VogtandClaude Opus 5.5 dc55e72d49 Tests: scale and polar stretch tests join the io test binary; Scale's doc says diagonal
Upstream gathered each crate's integration tests into one binary (tests/it); the scale and polar
stretch tests move there. The scale action's doc now says an XY parameter scales by its diagonal,
as the code does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:29:06 -06:00
Cody VogtandClaude Opus 5.5 e74cac535b Docs: DWG save of drawings with scale actions needs #1725
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:29:06 -06:00
Cody VogtandClaude Opus 5.5 50060af67d Docs: the dynamic block data row lists scale and polar stretch actions
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:29:06 -06:00
Cody VogtandClaude Opus 5.5 fc8caca7b3 Dynamic blocks: polar stretch actions; scale by an XY parameter's diagonal
A polar stretch action turns its objects about the polar parameter's base by the change of its
angle and moves the vertices in its frame (and the objects it doesn't stretch) with the end, as
AutoCAD does; its rotate-only objects just turn. Parameters in its selection are carried.

A scale action driven by an XY parameter scales uniformly by the parameter's diagonal, as AutoCAD
does (the X-only and Y-only choices live only in DWG data that isn't read).

Stretch and move actions on polar and XY parameters were checked against AutoCAD: they already
match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:29:05 -06:00
Cody VogtandClaude Opus 5.5 b471e5974a Dynamic blocks: scale actions
A scale action scales its objects about its base point by how much the distance it follows grew
(an XY parameter's horizontal and vertical distances each on their own axis), as AutoCAD does,
carrying the parameters in its selection. Factors that would scale to nothing or overflow are
refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:28:14 -06:00
Cody VogtandClaude Opus 5.5 201b5688a4 Tests: the array and rotate/flip tests join the io and engine test binaries
Upstream (#1989) builds each crate's tests as one binary, tests/it/main.rs; these files moved with their fixture paths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:59 -06:00
Cody VogtandClaude Opus 5.5 e6fce40d6e Dynamic blocks: an angle just short of a full turn shows as 0, not 360
Custom angle properties were formatted to AUPREC decimals straight from
the value, so 359.7 degrees with no decimals showed as "360". They are now
rounded first and wrapped back into 0 to 360.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:59 -06:00
Cody VogtandClaude Opus 5.5 5721b77933 Docs: the dynamic block data row lists polar, XY and array changes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:59 -06:00
Cody VogtandClaude Opus 5.5 7cd5ef36dc Dynamic block grips: list XY corner parts as a drag takes them
blocks.reference.grips listed an XY parameter's corner grips as baseXEndY
and baseYEndX (serde's camelCase), but blocks.reference.grip takes
basex-endy and basey-endx, so a caller passing a listed grip back was
refused. The corners are now listed by the names a drag takes, and the
command's params doc names them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:59 -06:00
Cody VogtandClaude Opus 5.5 46acac72eb Dynamic blocks: array actions, polar and XY parameters
A dynamic block reference now repeats its arrayed objects as AutoCAD does:
along a linear or polar parameter one copy per whole column offset in its
distance, across an XY parameter a whole number of columns by rows (just the
object when either is short of one), following the parameter's base point.
Copies after the first carry AutoCAD's AcDbBlockArrayActionTag; without it
AutoCAD can't change the reference again ("Invalid input").

Polar parameters show Distance1 and Angle1, XY parameters X Distance1 and
Y Distance1, in Properties (editable, value sets applied; an XY distance
below its minimum is refused as AutoCAD refuses it), with square grips at
the base and end and an XY parameter's two other corners.

Checked against AutoCAD with a linear, a polar and an XY array block: copy
counts and positions match for each value tried, AutoCAD reads CADCraft's
saved values and geometry, and changes them again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:59 -06:00
Cody VogtandClaude Opus 5.5 4f671b7759 Dynamic blocks: an angle's tick marks are where its grip will be
The rotation grip is drawn where its grip object is, which can be off the
radius' end; its stops are now marked there too (the grip object's angle and
distance from the base added to each value), not at the radius' end.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:27 -06:00
Cody VogtandClaude Opus 5.5 eeb213dccd Dynamic blocks: a grip on a value list or increments marks its stops while dragged
A distance or angle whose values are a list, or go by an increment, stops
only at those values; while its grip is dragged, the preview marks each stop
with a short tick across the grip's travel (a few pixels, whatever the zoom),
as AutoCAD does. `dynblock::grip_stops` gives the stops: along a distance from
the point that stays, or from its midpoint, and round an angle's circle (a
full turn being no turn).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:27 -06:00
Cody VogtandClaude Sonnet 5.5 28d240ca67 Dynamic blocks: the actions' bookkeeping moves into ActionRun
main now denies cognitive_complexity over 30: apply() was at 35 with the
rotate and flip actions. The action loop becomes ActionRun, one method per
kind of action (rotate and flip, stretch and move), and the carrying of a
parameter by a stretch is shifted(). No change in what the actions do.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-29 22:27:14 -06:00
Cody VogtandClaude Opus 5.5 7f6033c0aa Dynamic blocks: a rotate or flip selection that repeats an object turns or mirrors it once
A repeated handle queued the transform twice: a flip mirrored the object back
while its value recorded the flip. Repeats are skipped, as the stretch and
move path does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:14 -06:00
Cody VogtandClaude Opus 5.5 ca56d0097e Prompt: the picker's doc stays on picker, the angle's on angle
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:14 -06:00
Cody VogtandClaude Opus 5.5 b19fa36396 Dynamic blocks: a flip value's state is written after both its points
A new flip value from a one-point record had its state (70) written before
the end point was added, between the two points.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:14 -06:00
Cody VogtandClaude Opus 5.5 cae6f75b4e Docs: the dynamic block data row says what can be changed now
It still said only visibility states and lookups could be changed and
that only stretch and lookup actions were read. Distances and positions
(stretch, move), angles (rotate) and flip states (flip) can be changed,
and their value records are saved.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 7f85a5473a Dynamic blocks: a value record takes its shape from its parameter
A flip record was told from another two-point record by a group 70 after
its points. A stray 70 on a linear or rotation record made its value a
flip (and ignored), and a flip record without its state was read as
plain points. The parameter the record is keyed by now decides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 74498ff4b0 Dynamic blocks: the rotation grip's Dynamic Input shows one angle box
At a rotation grip AutoCAD's Dynamic Input asks for the angle alone; CADCraft
showed a distance and an angle from the grip. A prompt can now say it asks for
an angle about its base (`Prompt::angle`), and a command can give the value
the cursor would give (`Interactive::live_value`, under the crash guard;
`Session::live_value`). The rotation grip does both, with the angle as
Properties will show it, and the canvas draws one box: what was typed, else
that live value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 98db1164ff Dynamic blocks: flipped text keeps its mirrored footprint, as AutoCAD draws it
A flip mirrors text and attributes but AutoCAD draws them readable (MIRRTEXT
0): the text keeps the mirrored footprint, so text that ran away from the
symbol still runs away from it on the other side. CADCraft mirrored only the
text's anchor, so flipped text ran back across the block. Text carried by an
action that mirrors now reads in whichever mirrored direction is nearer its
own, and swaps left and right justification when its footprint is reversed
along it (AutoCAD keeps the justification and moves the start back by the
text's width, which draws the same; it re-derives attributes from the block
when it next changes them), top and bottom when reversed across it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 84310182ca Dynamic blocks: the flip grip is a block arrow, as AutoCAD draws it
The flip grip was a narrow triangle; AutoCAD draws a block arrow, a short
shaft and a head about as wide as a square grip. Its shaft and head are filled
apart (the painter fills convex shapes) and outlined as one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 95f7f6687a Dynamic blocks: an angle parameter shows and is typed as the drawing measures angles
AutoCAD shows an angle parameter's value as it shows any angle: from ANGBASE,
clockwise when ANGDIR is 1. In a drawing measured clockwise from north it shows
an Angle1 of 0 as 90, and 0.5 rad as 61.35 (checked in AutoCAD). Properties and
typed values (blocks.reference.set, a value typed at the rotation grip) now
convert the same way; the stored value is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 e0fa2af3b0 Dynamic blocks: the rotation grip is where its grip object is, and a drag turns by the cursor's turn
AutoCAD draws a rotation parameter's grip where the block's grip object is,
which need not be the radius' end (a well-centre symbol has it a quarter turn
round), and turns it with the angle. CADCraft drew it at the radius' end. The
grip is now placed from its grip object, kept along and across the radius as
it turns (as the flip grip already was), and dragging it subtracts the grip's
offset from the radius, so the block turns by the cursor's turn instead of
jumping to the cursor's direction.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 6977a58a59 Dynamic blocks: rotation test compares with a plain bound, not an approximate TAU
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 ebeb263874 Dynamic blocks: rotation and flip grips, flip state after the points, tests
A rotation parameter's grip (a circle at the radius' end) turns the angle when
dragged (a typed number sets it, in degrees); a flip grip (an arrow across the
reflection line, placed from its grip object and turning with the line) flips
at a click. A flip value record keeps its state after its points, also in a
record CADCraft writes without a template. A synthetic Symbol fixture covers
reading, turning, flipping, grips and bad values. Also: #967's test
expectation counts positions from 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 ee0697955c Dynamic block references: rotation and flip parameters and their rotate and flip actions
Angle1 (degrees, as Properties shows them) turns the rotate action's objects
about its base point; Flip state1 mirrors the flip action's objects across
the current reflection line (text stays readable). Parameters in the
selection are carried along, attributes follow, the flip grip's record and
the history are written as AutoCAD writes them. Checked against AutoCAD's own
output for the same changes: value records, history and geometry match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 22:27:13 -06:00
Francesco BVandClaude Opus 5.5 d3ec8efe19 INSERT: ATTDIA defaults to 0, the command line, as in AutoCAD
AutoCAD's published system variable reference gives ATTDIA an initial
value of 0: a typed INSERT asks for attribute values at the command line,
which also keeps scripts and agents typing through the command line as
before. ATTDIA 1 still opens the Edit Attributes dialog. The dialog tests
set ATTDIA 1 themselves; a new check shows the default opens no dialog.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-29 10:37:59 +01:00
Cody VogtandClaude Opus 5.5 d35ee3ae71 Block reference grips: none on locked or invisible attributes; a moved multiline attribute moves its text
Every attribute of a block reference had a grip, also those locked in
position and invisible ones, which AutoCAD gives none. Dragging a multiline
attribute's grip moved its position but not its multiline text, so the grip
moved and the text stayed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 09:08:04 -06:00
Cody VogtandClaude Opus 5.5 b6cd6667ca Test: a stretched multiline attribute survives a save
The moved attribute's insertion and its multiline text's are checked
again after saving to DXF (in the drawing's version; R2000 DXF has no
multiline attributes) and reopening.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 09:06:23 -06:00
Cody VogtandClaude Opus 5.5 cc0e3c7add Dynamic blocks: a stretch or move carries a multiline attribute's text along
The reference's attribute moved with its definition, but a multiline
attribute's text (its embedded MTEXT) stayed behind; the grip preview drew it
as one line. Both landed before multiline attributes (#854) and couldn't use
them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 09:06:23 -06:00
Francesco BVandClaude Opus 5.5 0332836238 INSERT: Verify and Preset attributes, ATTREQ and ATTDIA with the Edit Attributes dialog (F17)
A typed or menu INSERT asks a Verify attribute's value twice and gives
Preset (and constant) attributes their defaults without asking. ATTREQ 0
gives every attribute its default; ATTDIA 1 (the default) asks for the
values in an Edit Attributes dialog, typed answers still working. Both are
user settings, as DWG keeps them in its header only before R2000. Answers
are counted per prompt, so two definitions with one tag no longer ask the
second for ever. The JSON form never asks.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-27 22:31:35 +01:00
181 changed files with 23971 additions and 866 deletions
+36
View File
@@ -89,3 +89,39 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted); 46 later rows: @V1dalTheAbidal with Claude Code (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the 46 later rows were read by their contributor, a native Greek speaker; independent native proofreading of the whole file pending |
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology chosen with a native speaker, full proofreading pending |
| `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) |
| `crates/ui-egui/src/i18n/ta.tsv` | @newsbaba24x7 (AI-assisted) | Original Tamil translations of CADCraft English strings, shared with storytold/craft-i18n `locales/ta/` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings; the 1,289 rows from craft-i18n reviewed there for language and terminology by native speakers, and the whole Tamil interface reviewed in the running app by native speakers Radhika and Mohan Raj (2026-11-14); no font assets added (Tamil comes from an installed font or the craft-fonts face) |
## PDF import
The CAD mapping and initial synthetic PDF tests are adapted from CADCraft contributor
@DuukDuul's [PR #2787](https://github.com/storytold/cadcraft/pull/2787), commit
`ec17f63f189d1dccf91357701f9bba243ca88dd5`, under MIT OR Apache-2.0. The mapping has
been changed for the current shared reader, bounded import, fill rules and diagnostics.
PDF test inputs in `crates/io/tests/it/pdf_import.rs`, `crates/io/src/pdf_read.rs`, and
`apps/cadcraft-cli/tests/it/pdf_import.rs` are generated from literal content streams or
CadCraft's own plotter. No customer documents are included.
Enabling `craft-pdf` interpretation uses the following unchanged dependency assets from
`craft-libs` revision `453b0da782ccef39be9a6dac8d27c80b553ef1cc`. Fonts remain in the
shared dependency. Their source and hashes are retained below; notices are in `NOTICE`.
| Asset | Author | Source | Licence | SHA-256 | Notes |
|---|---|---|---|---|---|
| `hayro-interpret 0.7.0 / assets/FoxitDingbats.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitDingbats.pfb | BSD-3-Clause | `845c752392b6c914fb989c75a08b7792b88f542d2499042ef2889f8c814a16ed` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixed.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixed.pfb | BSD-3-Clause | `b6c8fe53f134b8b6d4578cd2d544df4cee9624c4efa8d51a560fb40ea296101b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixedBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixedBold.pfb | BSD-3-Clause | `f1b7159702973f54fc86254ea38bcf3712b2a736eb3a0995751e9f4bb45ad603` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixedBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb | BSD-3-Clause | `8a000945843bd31add06aee63bf9fd41b7578b4f3242a4b7cd46349ad9d24d4d` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixedItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb | BSD-3-Clause | `5007faf8320fa1fcc08b8894b356ad976f60b992ba29ee5272578bbdebaf3876` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSans.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSans.pfb | BSD-3-Clause | `a02339e95d20db14cbdfc1c6baf359cd36a091d5434925c3a4040f60e1a1af9e` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSansBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSansBold.pfb | BSD-3-Clause | `7bdfa36de1d5757dcfaf8b8a4be95c6e41c40fa70dbed9d78bf979a7b9959054` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSansBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb | BSD-3-Clause | `555ce45924338e2e4b32821910221ce85da691fd59a9723c4c971a7c5627fc8b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSansItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSansItalic.pfb | BSD-3-Clause | `7751cbefeda351708dae8c4a88db043411bc39ab2ae2097685da845d4d16f307` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerif.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerif.pfb | BSD-3-Clause | `4f57d2b9d884af8f907bf22df6019b52d86cbf6214fdbd02b1ae05472a543f35` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerifBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerifBold.pfb | BSD-3-Clause | `0bdf4b04e964139818d51eda03d566ba999fc3ba2421b1c6c51f9dc969022e80` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerifBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb | BSD-3-Clause | `a406cac82583bf98175cb62c87ed5e95c45fbb34eece63a10b0a13e793cb2e10` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) |
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://github.com/storytold/pdfcraft/blob/a2ec27b4775f53c40cad3456936d9406611e3a8d/vendor/hayro-cmap/assets/cmaps.brotli | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged |
| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged |
Generated
+132 -6
View File
@@ -156,19 +156,34 @@ dependencies = [
"zerocopy",
]
[[package]]
name = "alloc-no-stdlib"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
[[package]]
name = "alloc-no-stdlib"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
[[package]]
name = "alloc-stdlib"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
dependencies = [
"alloc-no-stdlib 2.0.4",
]
[[package]]
name = "alloc-stdlib"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
dependencies = [
"alloc-no-stdlib",
"alloc-no-stdlib 3.0.0",
]
[[package]]
@@ -592,14 +607,35 @@ dependencies = [
"piper",
]
[[package]]
name = "brotli"
version = "8.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
dependencies = [
"alloc-no-stdlib 2.0.4",
"alloc-stdlib 0.2.4",
"brotli-decompressor 5.0.3",
]
[[package]]
name = "brotli-decompressor"
version = "5.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
dependencies = [
"alloc-no-stdlib 2.0.4",
"alloc-stdlib 0.2.4",
]
[[package]]
name = "brotli-decompressor"
version = "6.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
"alloc-no-stdlib 3.0.0",
"alloc-stdlib 0.3.0",
]
[[package]]
@@ -737,6 +773,7 @@ dependencies = [
"cadcraft-geom",
"cadcraft-io",
"cadcraft-render",
"craft-csv",
"craft-docpath",
"craft-dxf",
"craft-mime",
@@ -786,6 +823,8 @@ dependencies = [
"craft-pdf",
"craft-svg",
"image",
"kurbo",
"lyon_tessellation",
"miniz_oxide 0.9.1",
"serde",
"serde_json",
@@ -1189,6 +1228,14 @@ name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
[[package]]
name = "craft-csv"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-dds"
version = "0.1.0"
@@ -1322,7 +1369,7 @@ name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"brotli-decompressor",
"brotli-decompressor 6.3.2",
"chrono",
"craft-tiff",
"quick-xml 0.41.0",
@@ -1344,6 +1391,7 @@ name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"hayro-interpret",
"hayro-syntax",
"krilla",
"thiserror 2.0.21",
@@ -2487,11 +2535,39 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"brotli",
"hayro-postscript",
]
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
"hayro-syntax",
"kurbo",
"moxcms",
"phf 0.13.1",
"rustc-hash 2.1.3",
"siphasher",
"skrifa 0.47.0",
"smallvec",
"yoke",
]
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"fearless_simd",
"hayro-ccitt",
]
@@ -2504,13 +2580,21 @@ dependencies = [
"fearless_simd",
]
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"flate2",
"hayro-ccitt",
"hayro-jbig2",
"hayro-jpeg2000",
"memchr",
"rustc-hash 2.1.3",
"smallvec",
"stringprep",
@@ -3910,17 +3994,37 @@ dependencies = [
"phf_shared 0.11.3",
]
[[package]]
name = "phf"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
dependencies = [
"phf_macros 0.13.1",
"phf_shared 0.13.1",
]
[[package]]
name = "phf"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6"
dependencies = [
"phf_macros",
"phf_macros 0.14.0",
"phf_shared 0.14.0",
"serde",
]
[[package]]
name = "phf_generator"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
dependencies = [
"fastrand",
"phf_shared 0.13.1",
]
[[package]]
name = "phf_generator"
version = "0.14.0"
@@ -3931,13 +4035,26 @@ dependencies = [
"phf_shared 0.14.0",
]
[[package]]
name = "phf_macros"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
dependencies = [
"phf_generator 0.13.1",
"phf_shared 0.13.1",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "phf_macros"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085"
dependencies = [
"phf_generator",
"phf_generator 0.14.0",
"phf_shared 0.14.0",
"proc-macro2",
"quote",
@@ -3953,6 +4070,15 @@ dependencies = [
"siphasher",
]
[[package]]
name = "phf_shared"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"
dependencies = [
"siphasher",
]
[[package]]
name = "phf_shared"
version = "0.14.0"
+7
View File
@@ -39,6 +39,8 @@ craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-l
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
# Delimited text (CSV/TSV) parsing (shared Craft library).
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4.6.11"
clap_mangen = { version = "0.3.3", features = ["env"] }
@@ -48,6 +50,8 @@ thiserror = "2"
same-file = "1"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = { version = "1", features = ["float_roundtrip", "raw_value"] }
# Geometry types shared with the PDF interpreter.
kurbo = "0.13"
log = "0.4"
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
@@ -116,6 +120,9 @@ debug = 0
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# Keep the complete egui family and native event bridge on reviewed fork commits.
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+189
View File
@@ -172,3 +172,192 @@ Original src/avx2/fdct.rs opening notice
* Based on the x86 SIMD extension for IJG JPEG library
* Copyright (C) 1999-2006, MIYASAKA Masaru.
*/
PDF import dependency notices
=============================
The PDF import mapping and synthetic tests derive from CADCraft PR #2787,
commit ec17f63f189d1dccf91357701f9bba243ca88dd5 (MIT OR Apache-2.0).
Local adaptations retain the project licences.
Standard PDF font programs (PDFium, BSD-3-Clause)
// Copyright 2014 PDFium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
CMYK profile (CC0-1.0)
CC0 1.0 Universal
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator and
subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for the
purpose of contributing to a commons of creative, cultural and scientific
works ("Commons") that the public can reliably and without fear of later
claims of infringement build upon, modify, incorporate in other works, reuse
and redistribute as freely as possible in any form whatsoever and for any
purposes, including without limitation commercial purposes. These owners may
contribute to the Commons to promote the ideal of a free culture and the
further production of creative, cultural and scientific works, or to gain
reputation or greater distribution for their Work in part through the use and
efforts of others.
For these and/or other purposes and motivations, and without any expectation
of additional consideration or compensation, the person associating CC0 with a
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
and publicly distribute the Work under its terms, with knowledge of his or her
Copyright and Related Rights in the Work and the meaning and intended legal
effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not limited
to, the following:
i. the right to reproduce, adapt, distribute, perform, display, communicate,
and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or likeness
depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data in
a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation thereof,
including any amended or successor version of such directive); and
vii. other similar, equivalent or corresponding rights throughout the world
based on applicable law or treaty, and any national implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention of,
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
and Related Rights and associated claims and causes of action, whether now
known or unknown (including existing as well as future claims and causes of
action), in the Work (i) in all territories worldwide, (ii) for the maximum
duration provided by applicable law or treaty (including future time
extensions), (iii) in any current or future medium and for any number of
copies, and (iv) for any purpose whatsoever, including without limitation
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
the Waiver for the benefit of each member of the public at large and to the
detriment of Affirmer's heirs and successors, fully intending that such Waiver
shall not be subject to revocation, rescission, cancellation, termination, or
any other legal or equitable action to disrupt the quiet enjoyment of the Work
by the public as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason be
judged legally invalid or ineffective under applicable law, then the Waiver
shall be preserved to the maximum extent permitted taking into account
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
is so judged Affirmer hereby grants to each affected person a royalty-free,
non transferable, non sublicensable, non exclusive, irrevocable and
unconditional license to exercise Affirmer's Copyright and Related Rights in
the Work (i) in all territories worldwide, (ii) for the maximum duration
provided by applicable law or treaty (including future time extensions), (iii)
in any current or future medium and for any number of copies, and (iv) for any
purpose whatsoever, including without limitation commercial, advertising or
promotional purposes (the "License"). The License shall be deemed effective as
of the date CC0 was applied by Affirmer to the Work. Should any part of the
License for any reason be judged legally invalid or ineffective under
applicable law, such partial invalidity or ineffectiveness shall not
invalidate the remainder of the License, and in such case Affirmer hereby
affirms that he or she will not (i) exercise any of his or her remaining
Copyright and Related Rights in the Work or (ii) assert any associated claims
and causes of action with respect to the Work, in either case contrary to
Affirmer's express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or warranties
of any kind concerning the Work, express, implied, statutory or otherwise,
including without limitation warranties of title, merchantability, fitness
for a particular purpose, non infringement, or the absence of latent or
other defects, accuracy, or the present or absence of errors, whether or not
discoverable, all to the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without limitation
any person's Copyright and Related Rights in the Work. Further, Affirmer
disclaims responsibility for obtaining any necessary consents, permissions
or other rights required for any use of the Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to this
CC0 or use of the Work.
For more information, please see
http://creativecommons.org/publicdomain/zero/1.0/
PDF character maps: LICENSE.txt
Copyright 1990-2023 Adobe. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Neither the name of Adobe nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+9 -3
View File
@@ -118,7 +118,7 @@ numbers):
| Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF |
| Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit |
| Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror |
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski) and Georgian (ქართული), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski), Georgian (ქართული) and Tamil (தமிழ், with an installed Tamil font), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
| Automation | MCP server, JSON control channel, `cadcraft-cli` (info, convert, run, commands, mcp) |
## Quick start
@@ -344,7 +344,9 @@ See [ROADMAP.md](ROADMAP.md) for the stage, measured parity and the estimate of
|---|---|---|
| x64 (64-bit Intel/AMD) | `cadcraft-<ver>-windows-x64.msi` | `cadcraft-<ver>-windows-x64-portable.zip` |
| arm64 (Snapdragon and other ARM PCs) | `cadcraft-<ver>-windows-arm64.msi` | `cadcraft-<ver>-windows-arm64-portable.zip` |
| x86 (32-bit) | `cadcraft-<ver>-windows-x86.msi` | `cadcraft-<ver>-windows-x86-portable.zip` |
For 32-bit Windows, [CADCraft v0.18.0](https://github.com/storytold/cadcraft/releases/tag/v0.18.0)
was the last release with both an x86 MSI and portable ZIP.
Installers and executables are code-signed.
@@ -381,15 +383,19 @@ and web backend defaults are unchanged.
| Flatpak | `cadcraft-<ver>-linux-x86_64.flatpak` | `cadcraft-<ver>-linux-aarch64.flatpak` | Sandboxed; `flatpak install --user <file>` |
| Debian/Ubuntu | `cadcraft-<ver>-linux-x86_64.deb` | `cadcraft-<ver>-linux-aarch64.deb` | |
| Fedora/RHEL/openSUSE | `cadcraft-<ver>-linux-x86_64.rpm` | `cadcraft-<ver>-linux-aarch64.rpm` | |
| Arch Linux | `cadcraft-<ver>-linux-x86_64.pkg.tar.zst` | `cadcraft-<ver>-linux-aarch64.pkg.tar.zst` | |
| Tarball | `cadcraft-<ver>-linux-x86_64.tar.gz` | `cadcraft-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
RISC-V (riscv64): `cadcraft-<ver>-linux-riscv64.tar.gz`, cross-compiled; needs glibc 2.39 or newer (Ubuntu 24.04+, Debian 13+).
RISC-V (riscv64) packages are `cadcraft-<ver>-linux-riscv64.deb`,
`cadcraft-<ver>-linux-riscv64.rpm`, and `cadcraft-<ver>-linux-riscv64.tar.gz`. They are
cross-compiled and need glibc 2.39 or newer (Ubuntu 24.04+, Debian 13+).
### FreeBSD
| Build | File |
|---|---|
| x86_64 | `cadcraft-<ver>-freebsd-x86_64.tar.gz` |
| aarch64 (ARM64) | `cadcraft-<ver>-freebsd-aarch64.tar.gz` |
### Web (WebAssembly)
+6 -3
View File
@@ -2,7 +2,7 @@
**Stage: pre-alpha** · next: alpha, when the six rows of the [alpha gate](docs/roadmap.md#alpha-gate) pass (five fail today; the gate was revised on 2026-11-19 and its hours are not re-estimated yet)
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-20 · **Change:** minor (Upcoming updated for what merged on 2026-11-19 and 2026-11-20; previously major: alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-25 · **Change:** minor (Upcoming updated for what merged from 2026-11-21 to 2026-11-25; previously minor: Upcoming updated for what merged on 2026-11-19 and 2026-11-20; previously major: alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
CADCraft targets full parity with AutoCAD (2D drafting first, then annotation, layouts and
plotting, DWG, parametrics and 3D), plus what AutoCAD doesn't have: agent control over MCP, a
@@ -115,7 +115,7 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
- The open findings of the security audit (#1919–#1935): check each against the input limits that
landed on 2026-11-11, close what is fixed and fix the rest. A crafted handle that makes new entities
overwrite existing ones (#1921) is fixed by #1276.
- A saved file that crashes AutoCAD 2021 (#3303) and dimension text lost on save (#3299).
- A saved file that crashes AutoCAD 2021 (#3303); dimension text lost on save (#3299) was fixed on 2026-11-20.
- Crashes and hangs with a reproduction: the web build on a large DXF (#1603), a DWG with 3D content
(#2174), startup on older graphics hardware (#1724, #1631, #3222).
@@ -131,7 +131,7 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
- The prompt options that still say "not available yet" (gaps F1).
- Layouts print at scale on a system printer (#3216); the menu bar and panels can be restored since
#3308.
- 661 pull requests are open (2026-11-20; 714 the day before). About 230 were mergeable, passed CI and were small; they are
- 602 pull requests are open (2026-11-25; 661 on 2026-11-20). About 230 were mergeable, passed CI and were small; they are
reviewed and landed in this order, the longest-waiting authors first within a row.
**3. Lower priority: affects fewer people and nothing breaks without it.**
@@ -141,6 +141,8 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
but a file with 3D content must open safely (tier 1).
- Menu breadth against AutoCAD for Mac as a headline number.
Done from 2026-11-21 to 2026-11-25: PDFIMPORT, a PDF page as editable lines, polylines, solid hatches and text (#3375 in #3419); dynamic block references that rotate, flip, array, scale, stretch polar, align and look up, with their grips (#963, #993, #1030, #1098, #1699, #1723, #1752 in #3424; authoring is still open); the proxy graphics of other applications' objects drawn (#2697, #3435, #3437) and dimensions kept as read drawn from their `*D` block (#3439); saves that keep layout plot settings (#3233, #3386, #3390), DXF 2007+ table cell text (#3392), hatch boundary flags (#3389), fit text (#3391) and registered applications (#2918); the Array window for ARRAYRECT and ARRAYPOLAR (#3394); ATTDIA and the Edit Attributes dialog on INSERT (#3411) and constant attribute values drawn (#3462); Edit > Paste from the system clipboard (#3366, #3460, #3461; #3320 open); opening from Finder and quit prompts on macOS (#1347 in #3344, not yet run on a Mac); an already-open drawing selects its tab when opened from the interface (#899 in #3422; the control channel, MCP, scripts and LISP still open a second copy); Tab through every object snap candidate (#1673); the Write Block dialog for WBLOCK (#1778); Generate Boundary (#2804); mitred wide polylines (#3453; the extents leave out the mitre tip, #3443); DIMASSOC 1 (#2977); crossing selection of block references by what they draw (#3445); an option to turn off the update check (#3097).
Done on 2026-11-19 and 2026-11-20: the hostile-input fixes #1276, #2820, #2821 and #2765 (#3304, #3305), clicks while the mouse moves and right-click or Space as Enter (#3307), the interface reset (#3308), paper units (#3309), the UCS command (#3310), -ATTEDIT, -RENAME and -LAYER options (#3311), TRIM/EXTEND depth (#3312), dimension values kept on save (#3335), the stencil switch (#3336), a typed OPEN path (#3343) and double-click text editing (#3345).
Done before that: precision input (#379, #441, #60, #519), prompt options in TRIM/EXTEND,
@@ -170,6 +172,7 @@ REFEDIT (#818), XCLIP (#2354), dynamic block references (#838–#883), and the D
| Date | Change | Summary |
|---|---|---|
| 2026-11-25 | minor | Upcoming updated for the merges of 2026-11-21 to 2026-11-25 (PDF import, dynamic block reference actions, proxy graphics, what saves keep, Array window, ATTDIA, system clipboard paste, macOS opening from Finder, WBLOCK dialog, Generate Boundary); #3299 fixed; pull-request count 661 → 602; percentages and hours not re-scored |
| 2026-11-20 | minor | Upcoming updated for the merges of 2026-11-19 and 2026-11-20 (security stacks, input, interface reset, paper units, UCS, prompt options, TRIM/EXTEND, text editing in place); pull-request count 714 → 661; percentages and hours not re-scored |
| 2026-11-19 | major | Alpha gate revised from user reports (six rows, Windows first; block authoring, xref editing in place and exact curve geometry moved to beta); Upcoming re-ranked into three tiers: urgent (security, leaks, crashes, lost work), parity, lower priority; percentages and hours not re-scored |
| 2026-10-24 | minor | Re-audit against main 41d9b5e95: language table, CI gate and open-PR count re-checked against main 41d9b5e95 |
+2 -2
View File
@@ -26,12 +26,12 @@ fn with_formats(cell: &'static std::sync::OnceLock<String>, before: &str, list:
/// The drawing an input argument names.
fn read_help() -> &'static str {
static C: std::sync::OnceLock<String> = std::sync::OnceLock::new();
with_formats(&C, "The drawing to read ", Format::READ, "")
with_formats(&C, "The drawing to read ", Format::READ, ", or a PDF whose first page opens as editable vector content")
}
fn open_help() -> &'static str {
static C: std::sync::OnceLock<String> = std::sync::OnceLock::new();
with_formats(&C, "Drawings to open ", Format::READ, "")
with_formats(&C, "Drawings to open ", Format::READ, ", or PDFs (their first page)")
}
fn write_help() -> &'static str {
+1
View File
@@ -49,6 +49,7 @@ fn install_io() {
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
});
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
groups: cadcraft_io::entity_groups,
+4
View File
@@ -171,6 +171,10 @@ pub(crate) fn undrawn_message(d: &cadcraft_engine::doc::Drawing, path: &str) ->
ole = ole.saturating_add(1);
continue;
}
// One with proxy graphics draws them (#2697, #3438).
if !u.graphics.is_empty() {
continue;
}
let n = types.entry(u.dxf_type.as_str()).or_insert(0);
*n = n.saturating_add(1);
}
+1
View File
@@ -2,6 +2,7 @@ mod cli;
mod drafting_spacing;
mod help;
mod mcp_connect;
mod pdf_import;
mod skipped_records;
mod undrawn_entities;
mod usage;
+116
View File
@@ -0,0 +1,116 @@
//! A PDF page converted on the command line keeps its geometry and its fill rules through a DXF
//! or DWG save and reopen.
use std::process::{Command, Output};
use serde_json::Value;
const MM_PER_PT: f64 = 25.4 / 72.0;
/// A line, a nonzero fill of two nested squares wound the same way (all of it filled), an
/// even-odd fill of the same squares (the inner one a hole) and a nonzero fill of two
/// overlapping squares (split into triangles).
const CONTENT: &str = "1 0 0 RG 2 w 10 10 m 100 10 l S\n\
0 0 1 rg 200 200 m 300 200 l 300 300 l 200 300 l h 220 220 m 280 220 l 280 280 l 220 280 l h f\n\
0 1 0 rg 400 400 m 500 400 l 500 500 l 400 500 l h 420 420 m 480 420 l 480 480 l 420 480 l h f*\n\
1 0 1 rg 50 600 m 150 600 l 150 700 l 50 700 l h 100 650 m 200 650 l 200 750 l 100 750 l h f\n";
fn page(content: &str) -> Vec<u8> {
format!(
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R >> endobj\n\
4 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n\
trailer << /Root 1 0 R >>\n%%EOF\n",
content.len()
)
.into_bytes()
}
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A fresh scratch directory that is removed on drop, also when an assertion fails.
struct Scratch(std::path::PathBuf);
impl Scratch {
fn new(tag: &str) -> Self {
let dir = std::env::temp_dir().join(format!("cc-cli-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir(&dir).expect("create scratch dir");
Scratch(dir)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// The model space of `file` with each object's geometry.
fn inspect(file: &str) -> Value {
let out = cli(&["run", file, "--cmd", r#"drawing.inspect {"entities":true}"#]);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success(), "{file}: {}", String::from_utf8_lossy(&out.stderr));
serde_json::from_str(stdout.lines().last().unwrap_or_default()).unwrap_or_else(|e| panic!("{file}: {e}: {stdout}"))
}
fn inside(ring: &[(f64, f64)], (x, y): (f64, f64)) -> bool {
let mut odd = false;
for (i, &(ax, ay)) in ring.iter().enumerate() {
let (bx, by) = ring[(i + 1) % ring.len()];
if (ay > y) != (by > y) && x < (bx - ax) * (y - ay) / (by - ay) + ax {
odd = !odd;
}
}
odd
}
/// Whether a hatch covers the page point `at` (in PDF points), by odd parity as hatches are drawn.
fn filled(drawing: &Value, at: (f64, f64)) -> bool {
let at = (at.0 * MM_PER_PT, at.1 * MM_PER_PT);
let entities = drawing["entities"].as_array().cloned().unwrap_or_default();
entities.iter().filter(|e| e["type"] == "Hatch").any(|hatch| {
let loops = hatch["geometry"]["loops"].as_array().cloned().unwrap_or_default();
let rings = loops.iter().map(|l| {
l["vertices"]
.as_array()
.into_iter()
.flatten()
.map(|v| (v["p"]["x"].as_f64().unwrap_or(0.0), v["p"]["y"].as_f64().unwrap_or(0.0)))
.collect()
});
rings.filter(|ring: &Vec<(f64, f64)>| inside(ring, at)).count() % 2 == 1
})
}
#[test]
fn a_pdf_page_keeps_its_fills_through_dxf_and_dwg() {
let scratch = Scratch::new("pdf-import");
let pdf = scratch.0.join("plan.pdf");
std::fs::write(&pdf, page(CONTENT)).unwrap();
let pdf = pdf.to_str().unwrap().to_string();
let mut files = vec![pdf.clone()];
for ext in ["dxf", "dwg"] {
let out = scratch.0.join(format!("plan.{ext}"));
let out = out.to_str().unwrap().to_string();
let run = cli(&["convert", &pdf, &out]);
assert!(run.status.success(), "convert to {ext}: {}", String::from_utf8_lossy(&run.stderr));
files.push(out);
}
for file in &files {
let d = inspect(file);
assert_eq!(d["counts"]["Line"], 1, "{file}: {}", d["counts"]);
assert_eq!(d["counts"]["Hatch"], 3, "{file}: {}", d["counts"]);
assert!(filled(&d, (251.3, 247.7)), "{file}: the nonzero fill keeps its centre");
assert!(filled(&d, (210.2, 205.9)), "{file}: the nonzero fill keeps its rim");
assert!(!filled(&d, (451.3, 447.7)), "{file}: the even-odd fill keeps its hole");
assert!(filled(&d, (410.2, 405.9)), "{file}: the even-odd fill keeps its rim");
assert!(!filled(&d, (350.4, 351.7)), "{file}: nothing is filled between the shapes");
assert!(filled(&d, (125.3, 675.2)), "{file}: the overlap of the crossing squares stays filled");
assert!(filled(&d, (60.4, 610.3)) && filled(&d, (190.2, 740.1)), "{file}: both crossing squares stay filled");
assert!(!filled(&d, (60.4, 740.1)), "{file}: the corner beside the crossing squares stays empty");
}
}
+20 -1
View File
@@ -818,7 +818,8 @@ fn non_unicode_arguments() {
assert!(err.starts_with("error: invalid UTF-8 was detected"), "{err}");
}
/// An output name that isn't valid Unicode is written as given: only its extension picks the format.
/// An output name that isn't valid Unicode reaches the filesystem unchanged: only its extension
/// picks the format. Filesystems that reject the name must report their write error.
#[cfg(unix)]
#[test]
fn non_unicode_output_names() {
@@ -836,6 +837,18 @@ fn non_unicode_output_names() {
let code = cadcraft_cli::run(args, &mut out, &mut err);
(code, String::from_utf8_lossy(&err).into_owned())
};
// APFS rejects invalid UTF-8 names (EILSEQ), although Unix paths can represent them.
// Probe this scratch filesystem rather than assuming every macOS volume behaves alike.
let probe = latin1("probe");
let rejected_name: Option<String> = match std::fs::write(&probe, b"") {
Ok(()) => {
std::fs::remove_file(&probe).expect("remove filename probe");
None
}
#[cfg(target_os = "macos")]
Err(e) if e.raw_os_error() == Some(92) => Some(e.to_string()), // Darwin EILSEQ
Err(e) => panic!("unexpected filename probe error: {e}"),
};
let b = s.0.join("b.dxf");
let cases: [(Vec<OsString>, std::path::PathBuf); 3] = [
(vec!["sample".into(), "bracket".into(), latin1("dxf").into()], latin1("dxf")),
@@ -844,6 +857,12 @@ fn non_unicode_output_names() {
];
for (args, path) in cases {
let (code, err) = run(args.clone());
if let Some(ref filesystem_error) = rejected_name {
assert_eq!(code, 1, "{args:?}: {err}");
assert!(err.contains(filesystem_error), "{args:?}: {err}");
assert!(!path.exists(), "{path:?}");
continue;
}
assert_eq!(code, 0, "{args:?}: {err}");
assert!(path.exists(), "{path:?}");
assert!(std::fs::metadata(&path).expect("stat output").len() > 0, "{path:?}");
+1
View File
@@ -123,6 +123,7 @@ mod web {
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
});
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
groups: cadcraft_io::entity_groups,
+1 -1
View File
@@ -18,7 +18,7 @@ use web_sys::js_sys;
/// The hidden file input (one at a time; a cancelled pick leaves it until the next one).
const INPUT_ID: &str = "cadcraft_open_input";
/// What the picker offers: the formats OPEN reads, and the SHX fonts drawings name.
const ACCEPT: &str = ".dxf,.dwg,.shx";
const ACCEPT: &str = ".dxf,.dwg,.pdf,.shx";
/// Most files taken from one pick.
const MAX_PICKED: u32 = 64;
+13
View File
@@ -188,6 +188,7 @@ pub fn install_io() {
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
});
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
groups: cadcraft_io::entity_groups,
@@ -224,6 +225,7 @@ fn filters(pick: &Pick) -> Vec<(&'static str, Vec<&'static str>)> {
Pick::Open => vec![
(i18n::t("Drawings (DWG, DXF)"), vec!["dwg", "dxf", "dwt"]),
(i18n::t("SVG drawings (SVG, SVGZ)"), vec!["svg", "svgz"]),
(i18n::t("PDF files (PDF)"), vec!["pdf"]),
(i18n::t("All files"), vec!["*"]),
],
Pick::Save(name) => filters_for_save(name).iter().map(|(label, ext)| (i18n::t(label), vec![*ext])).collect(),
@@ -620,6 +622,17 @@ fn main() -> eframe::Result {
app.ui = ui;
}
app.set_system_cursor_default(vars.system_cursor == Switch::On);
// Native Wayland answers a clipboard request asynchronously; every other backend in the
// next frame (egui-winit).
#[cfg(all(unix, not(target_os = "macos")))]
{
use eframe::egui_wgpu::wgpu::rwh::{HasDisplayHandle, RawDisplayHandle};
if let Ok(display) = cc.display_handle() {
app.set_clipboard_late_answers(matches!(display.as_raw(), RawDisplayHandle::Wayland(_)));
}
}
#[cfg(any(not(unix), target_os = "macos"))]
app.set_clipboard_late_answers(false);
// macOS: CADCRAFT_NO_NATIVE_MENU=1 keeps the menus inside the window.
#[cfg(target_os = "macos")]
app.set_native_menus(vars.no_native_menu != Switch::On);
+2 -1
View File
@@ -148,7 +148,8 @@ impl NativeMenu {
if cmd == menus::RECENT_CLEAR {
continue;
}
let en = (typing && menus::edits_text(cmd)) || cadcraft_engine::find_command(cmd).is_none_or(|c| (c.enabled)(&app.session).is_ok());
let en = (typing && menus::edits_text(cmd))
|| cadcraft_engine::find_command(cmd).is_none_or(|c| cadcraft_ui_egui::clipboard::offered(&app.session, c));
item.set_enabled(en);
}
}
+3
View File
@@ -138,3 +138,6 @@ real_name = "Tyrel Haveman"
real_name = "Sladrian Pedroso"
display_name = "Sladrian Pedroso"
sync_github_name = false
[people.iHateStupidPeople]
sync_github_name = true
+246 -47
View File
@@ -22,7 +22,7 @@ use crate::{Drawing, Handle, RawTag};
mod apply;
mod grips;
mod reference;
pub use apply::{drag_grip, set_property};
pub use apply::{align_grip, drag_grip, grip_stops, set_property};
pub use grips::{DynGrip, GripPart, GripShape, grips};
pub use reference::{CustomProperty, Reference, Value, custom_properties, reference};
@@ -52,6 +52,13 @@ pub struct DynamicBlock {
/// the grips shown in them by object).
#[serde(skip)]
pub grip_objects: Vec<(i32, Handle)>,
/// Where each grip object is in the dynamic block, by graph id (a flip grip's place along its
/// reflection line).
#[serde(skip)]
pub grip_points: Vec<(i32, Vec3)>,
/// The block's base point (where a base point parameter is in the block).
#[serde(skip)]
pub base: Vec3,
}
/// One parameter: a property a reference to the block can change.
@@ -87,16 +94,41 @@ pub enum ParameterKind {
/// The value changes the end point (`false`) or both points from the midpoint (`true`).
from_midpoint: bool,
},
/// A distance and an angle from a base point.
Polar { base: Vec3, end: Vec3 },
/// Horizontal and vertical distances from a base point.
Xy { base: Vec3, end: Vec3 },
/// An angle about a base point.
Rotation { base: Vec3, end: Vec3 },
/// Aligns the reference with nearby geometry.
Alignment { base: Vec3, end: Vec3 },
/// Mirrors the objects about a reflection line.
Flip { base: Vec3, end: Vec3 },
/// A distance and an angle from a base point (Distance1, Angle1): the end point's distance
/// from the base and its direction (counterclockwise from the X axis of the block).
Polar {
base: Vec3,
end: Vec3,
label: String,
description: String,
angle_label: String,
angle_description: String,
values: ValueSet,
angle_values: ValueSet,
},
/// Horizontal and vertical distances from a base point (X Distance1, Y Distance1): how far
/// the end point is from the base along the block's X and Y axes.
Xy {
base: Vec3,
end: Vec3,
x_label: String,
y_label: String,
x_description: String,
y_description: String,
x_values: ValueSet,
y_values: ValueSet,
},
/// An angle about a base point (Angle1): the end point turns about the base. The angle is
/// measured from the direction the dynamic block has from base to end.
Rotation { base: Vec3, end: Vec3, label: String, description: String, values: ValueSet },
/// Aligns the reference with nearby geometry: dragged next to an object, its base point lands
/// on the object and the direction from base to end runs along it. `perpendicular` is the
/// parameter's type (perpendicular, else tangent); AutoCAD aligned both types the same way in
/// every case measured.
Alignment { base: Vec3, end: Vec3, perpendicular: bool },
/// Mirrors the objects about the reflection line from base to end (Flip state1); the names
/// of its two states, not flipped and flipped.
Flip { base: Vec3, end: Vec3, label: String, description: String, states: [String; 2] },
/// A position (Position1).
Point { at: Vec3, label: String, description: String },
/// Named sets of visible objects.
@@ -110,7 +142,9 @@ pub enum ParameterKind {
},
/// A named value chosen from a lookup table.
Lookup { at: Vec3, label: String, description: String },
/// Moves the block's base point.
/// The block's base point: the reference's insertion point is here, and an action that moves
/// it moves the reference's insertion point. `at` is where the block editor showed it; the
/// block itself has it at its base point (AutoCAD moves the block's objects to put it there).
BasePoint { at: Vec3 },
/// A parameter type not modelled yet.
Other { dxf_type: String },
@@ -122,11 +156,23 @@ impl ParameterKind {
match self {
ParameterKind::Linear { label, .. }
| ParameterKind::Point { label, .. }
| ParameterKind::Rotation { label, .. }
| ParameterKind::Flip { label, .. }
| ParameterKind::Visibility { label, .. }
| ParameterKind::Lookup { label, .. } => Some(label),
_ => None,
}
}
/// Every property name a reference shows for the parameter: a polar parameter's distance
/// and angle, an XY parameter's two distances, else its one label.
pub fn labels(&self) -> Vec<&str> {
match self {
ParameterKind::Polar { label, angle_label, .. } => vec![label, angle_label],
ParameterKind::Xy { x_label, y_label, .. } => vec![x_label, y_label],
other => other.label().into_iter().collect(),
}
}
}
/// One visibility state: its name and the objects shown in it (the parameter's other controlled
@@ -205,24 +251,46 @@ pub enum ActionKind {
angle_offset: f64,
},
/// A table: each row sets the listed parameter values together.
Lookup {
columns: Vec<LookupColumn>,
rows: Vec<Vec<String>>,
},
Lookup { columns: Vec<LookupColumn>, rows: Vec<Vec<String>> },
/// Moves the objects by the change of the parameter values it follows.
Move {
Move { multiplier: f64, angle_offset: f64 },
/// Scales the objects about its base point by how much the distance it follows grew (a linear
/// or polar parameter's distance, an XY parameter's diagonal). Its connections name what each
/// reads ("Scale", "XScale", "YScale").
Scale { base: ActionBase },
/// Turns the objects about its base point by the change of a rotation parameter's angle.
Rotate { base: ActionBase },
/// Mirrors the objects across a flip parameter's reflection line when its state changes.
Flip,
/// Repeats the objects as far as the parameter it follows reaches: along a distance (linear
/// or polar parameter) every `column` units, or in a grid of columns and rows across an XY
/// parameter's distances. The objects follow the parameter's base point.
Array { column: f64, row: f64 },
/// Follows a polar parameter: turns its objects about the parameter's base point by the change
/// of its angle, and moves the vertices inside `frame` of the objects listed (all of an object
/// not listed) along the parameter's new direction by the change of its distance. The
/// `rotate_only` objects (outside the selection) only turn.
PolarStretch {
frame: Vec<Vec2>,
#[serde(serialize_with = "hex_vertices")]
vertices: Vec<(Handle, Vec<i32>)>,
#[serde(serialize_with = "hexes")]
rotate_only: Vec<Handle>,
multiplier: f64,
angle_offset: f64,
},
Scale,
Rotate,
Flip,
Array,
PolarStretch,
/// An action type not modelled yet.
Other {
dxf_type: String,
},
Other { dxf_type: String },
}
/// Where an action that turns or scales its objects has its base point.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionBase {
/// It follows the parameter's base point, at `offset` from it; else it stays at `at`.
pub dependent: bool,
pub offset: Vec3,
pub at: Vec3,
}
/// A lookup table column: the parameter value it reads or sets.
@@ -383,7 +451,7 @@ pub fn is_dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -
/// [`dynamic_block`] with the drawing's [`ObjectIndex`] already built.
pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> Option<DynamicBlock> {
let xdict = block_xdict(d, name)?;
let mut out = DynamicBlock::default();
let mut out = DynamicBlock { base: d.block(name.trim()).map(|b| b.base).unwrap_or_default(), ..Default::default() };
for o in graph_members(&objects.0, xdict)? {
let secs = sections(&o.tags);
let node = Cursor::new(section(&secs, "AcDbEvalExpr")).int(90);
@@ -398,6 +466,7 @@ pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> O
} else {
if kind.ends_with("GRIP") {
out.grip_objects.push((node, o.handle));
out.grip_points.push((node, Cursor::new(section(&secs, "AcDbBlockGrip")).point(1010)));
}
out.other.push(o.kind.clone());
}
@@ -406,15 +475,21 @@ pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> O
}
/// A parameter's grip ids: after a two-point parameter's points, the grip count (170) and the
/// base and end grips (91); after a one-point parameter's point, its grip (93).
/// base and end grips (91), then an XY parameter's corner grips (base X and end Y, base Y and end
/// X); after a one-point parameter's point, its grip (93).
fn grip_ids(secs: &[(&str, &[RawTag])]) -> Vec<i32> {
let two = section(secs, "AcDbBlock2PtParameter");
if !two.is_empty() {
let mut c = Cursor::new(two);
c.point(1010);
c.point(1011);
let n = c.count(170).min(2);
return (0..n).map(|_| c.int(91)).collect();
let n = c.count(170).min(4);
let mut ids: Vec<i32> = (0..n).map(|_| c.int(91)).collect();
// Corner grips only an XY parameter has (the others write 0 for them).
while ids.len() > 2 && ids.last() == Some(&0) {
ids.pop();
}
return ids;
}
let mut c = Cursor::new(section(secs, "AcDbBlock1PtParameter"));
c.point(1010);
@@ -446,15 +521,49 @@ fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind {
ParameterKind::Lookup { at: one(), label: c.string(303), description: c.string(304) }
}
"BLOCKBASEPOINTPARAMETER" => ParameterKind::BasePoint { at: one() },
"BLOCKPOLARPARAMETER" | "BLOCKXYPARAMETER" | "BLOCKROTATIONPARAMETER" | "BLOCKALIGNMENTPARAMETER" | "BLOCKFLIPPARAMETER" => {
// Its name and description (305, 306), the base angle point (1011) and angle (140), then
// the value set.
"BLOCKROTATIONPARAMETER" => {
let (base, end) = two();
match kind {
"BLOCKPOLARPARAMETER" => ParameterKind::Polar { base, end },
"BLOCKXYPARAMETER" => ParameterKind::Xy { base, end },
"BLOCKROTATIONPARAMETER" => ParameterKind::Rotation { base, end },
"BLOCKALIGNMENTPARAMETER" => ParameterKind::Alignment { base, end },
_ => ParameterKind::Flip { base, end },
}
let mut c = Cursor::new(section(secs, "AcDbBlockRotationParameter"));
let (label, description) = (c.string(305), c.string(306));
ParameterKind::Rotation { base, end, label, description, values: value_set(&mut c) }
}
// Its name and description (305, 306) and its states' names (307 not flipped, 308 flipped).
"BLOCKFLIPPARAMETER" => {
let (base, end) = two();
let mut c = Cursor::new(section(secs, "AcDbBlockFlipParameter"));
let (label, description) = (c.string(305), c.string(306));
let states = [c.string(307), c.string(308)];
ParameterKind::Flip { base, end, label, description, states }
}
// The distance's name and description (305, 306), the angle's (307, 308), the label
// offset (140), then the distance's value set (309, 96, 141–144, 175) and the angle's
// (410, 97, 145–148, 176).
"BLOCKPOLARPARAMETER" => {
let (base, end) = two();
let mut c = Cursor::new(section(secs, "AcDbBlockPolarParameter"));
let (label, description, angle_label, angle_description) = (c.string(305), c.string(306), c.string(307), c.string(308));
let values = value_set_at(&mut c, [309, 96, 141, 175]);
let angle_values = value_set_at(&mut c, [410, 97, 145, 176]);
ParameterKind::Polar { base, end, label, description, angle_label, angle_description, values, angle_values }
}
// The vertical distance's name (305) before the horizontal's (306), then their
// descriptions (307, 308), label offsets (141, 140), the vertical value set (309, 97,
// 146–149, 176) and the horizontal one (410, 96, 142–145, 175).
"BLOCKXYPARAMETER" => {
let (base, end) = two();
let mut c = Cursor::new(section(secs, "AcDbBlockXYParameter"));
let (y_label, x_label, y_description, x_description) = (c.string(305), c.string(306), c.string(307), c.string(308));
let y_values = value_set_at(&mut c, [309, 97, 146, 176]);
let x_values = value_set_at(&mut c, [410, 96, 142, 175]);
ParameterKind::Xy { base, end, x_label, y_label, x_description, y_description, x_values, y_values }
}
// Its type (280): 1 perpendicular, 0 tangent.
"BLOCKALIGNMENTPARAMETER" => {
let (base, end) = two();
let perpendicular = Cursor::new(section(secs, "AcDbBlockAlignmentParameter")).int(280) != 0;
ParameterKind::Alignment { base, end, perpendicular }
}
other => ParameterKind::Other { dxf_type: other.to_string() },
}
@@ -463,11 +572,17 @@ fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind {
/// A value set after a parameter's name and description: description (307), flags (96),
/// minimum, maximum and increment (141–143), then the listed values (175 count, 144 each).
fn value_set(c: &mut Cursor) -> ValueSet {
c.next(307);
let flags = c.int(96);
let (minimum, maximum, increment) = (c.real(141), c.real(142), c.real(143));
let n = c.count(175);
let list = (0..n).filter_map(|_| c.next(144).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())).collect();
value_set_at(c, [307, 96, 141, 175])
}
/// A value set written with codes `[description, flags, minimum, count]`: the maximum and
/// increment follow the minimum's code, each listed value is the code after the increment's.
fn value_set_at(c: &mut Cursor, [description, flags, min, count]: [i32; 4]) -> ValueSet {
c.next(description);
let flags = c.int(flags);
let (minimum, maximum, increment) = (c.real(min), c.real(min + 1), c.real(min + 2));
let n = c.count(count);
let list = (0..n).filter_map(|_| c.next(min + 3).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())).collect();
ValueSet { flags, minimum, maximum, increment, list }
}
@@ -507,16 +622,56 @@ fn action(handle: Handle, node: i32, name: String, kind: &str, secs: &[(&str, &[
let (multiplier, angle_offset) = (c.real(140), c.real(141));
(two_connections(tags), ActionKind::Move { multiplier, angle_offset })
}
"BLOCKSCALEACTION" => (Vec::new(), ActionKind::Scale),
"BLOCKROTATEACTION" => (Vec::new(), ActionKind::Rotate),
"BLOCKFLIPACTION" => (Vec::new(), ActionKind::Flip),
"BLOCKARRAYACTION" => (Vec::new(), ActionKind::Array),
"BLOCKPOLARSTRETCHACTION" => (Vec::new(), ActionKind::PolarStretch),
// The base point's two connections (as a rotate action's), then the scale's three: the
// parameters (94-96) and what each reads (303-305, "Scale", "XScale", "YScale").
"BLOCKSCALEACTION" => {
let with_base = section(secs, "AcDbBlockActionWithBasePt");
let mut connections = two_connections(with_base);
let tags = section(secs, "AcDbBlockScaleAction");
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
connections.extend((0..3).map(|i| (first(94 + i).trim().parse().unwrap_or(0), first(303 + i))));
(connections, ActionKind::Scale { base: action_base(with_base) })
}
"BLOCKROTATEACTION" => {
let mut connections = two_connections(section(secs, "AcDbBlockActionWithBasePt"));
let mut c = Cursor::new(section(secs, "AcDbBlockRotationAction"));
connections.push((c.int(94), c.string(303)));
(connections, ActionKind::Rotate { base: action_base(section(secs, "AcDbBlockActionWithBasePt")) })
}
// Its four connections: the parameter (92-95) and the values it reads (301-304).
"BLOCKFLIPACTION" => {
let tags = section(secs, "AcDbBlockFlipAction");
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
let connections = (0..4).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
(connections, ActionKind::Flip)
}
// Its four connections (92-95 with 301-304, as a flip action's), then the row (140) and
// column (141) offsets.
"BLOCKARRAYACTION" => {
let tags = section(secs, "AcDbBlockArrayAction");
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
let connections = (0..4).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
let mut c = Cursor::new(tags);
let (row, column) = (c.real(140), c.real(141));
(connections, ActionKind::Array { column, row })
}
"BLOCKPOLARSTRETCHACTION" => polar_stretch(section(secs, "AcDbBlockPolarStretchAction")),
other => (Vec::new(), ActionKind::Other { dxf_type: other.to_string() }),
};
Action { node, handle, name, at, selection, connections, kind }
}
/// The base point of an action that has one: after its two connections (92/93, 301/302), the
/// offset from the parameter's base point (1011), whether it follows that point (280), and the
/// point it stays at when it doesn't (1012).
fn action_base(tags: &[RawTag]) -> ActionBase {
let mut c = Cursor::new(tags);
c.next(302);
let offset = c.point(1011);
let dependent = c.int(280) != 0;
ActionBase { dependent, offset, at: c.point(1012) }
}
/// Two connections: parameter ids (92, 93) and the values they read (301, 302). Writers order
/// these groups differently (92 93 301 302, or 92 301 93 302), so each is read on its own.
fn two_connections(tags: &[RawTag]) -> Vec<(i32, String)> {
@@ -551,6 +706,42 @@ fn stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) {
(connections, ActionKind::Stretch { frame, vertices, multiplier, angle_offset })
}
/// A polar stretch action: its six connections (92-97 with 301-306), the frame (73 count,
/// 1011/1021 points), the objects it only turns (72 count, 331 each), the objects whose vertices it
/// moves (74 count; each a 332 handle, a 75 count and 76 vertex indices), more vertex lists (78
/// count; each a 98 code, a 79 count and 76 indices), then the distance multiplier (141) and angle
/// offset (140).
fn polar_stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) {
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
let connections = (0..6).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
let mut c = Cursor::new(tags);
let n = c.count(73);
let frame = (0..n)
.map(|_| {
let x = c.real(1011);
Vec2::new(x, c.real(1021))
})
.collect();
let n = c.count(72);
let rotate_only = c.handles(331, n);
let objects = c.count(74);
let vertices = (0..objects)
.filter_map(|_| {
let h = c.handle(332)?;
let n = c.count(75);
Some((h, (0..n).map(|_| c.int(76)).collect()))
})
.collect();
for _ in 0..c.count(78) {
c.next(98);
for _ in 0..c.count(79) {
c.next(76);
}
}
let (multiplier, angle_offset) = (c.real(141), c.real(140));
(connections, ActionKind::PolarStretch { frame, vertices, rotate_only, multiplier, angle_offset })
}
/// A lookup table: rows (92) and columns (93), the cells row by row (302, after a 301 header),
/// then each column: unmatched name (303 then 305), parameter id (94), lookup flag (282) and the
/// parameter value it stands for (304).
@@ -598,5 +789,13 @@ mod tests {
let (_, ActionKind::Stretch { vertices, .. }) = stretch(&tags) else { panic!("a stretch action") };
let ints: usize = vertices.iter().map(|(_, v)| v.len()).sum();
assert!(ints <= 16 * tags.len() + 1024, "{ints}");
let mut tags = vec![tag(74, &n.to_string())];
tags.extend((0..n).flat_map(|_| [tag(332, "1F"), tag(75, &n.to_string())]));
tags.push(tag(78, &n.to_string()));
tags.extend((0..n).map(|_| tag(79, &n.to_string())));
let (_, ActionKind::PolarStretch { vertices, .. }) = polar_stretch(&tags) else { panic!("a polar stretch action") };
let ints: usize = vertices.iter().map(|(_, v)| v.len()).sum();
assert!(ints <= 16 * tags.len() + 1024, "{ints}");
}
}
File diff suppressed because it is too large Load Diff
+151 -3
View File
@@ -1,7 +1,11 @@
//! The grips of a dynamic block reference, as AutoCAD shows them on a selected reference: an
//! arrow at each end of a distance (linear parameter), a square at a position (point parameter)
//! and a down-pointing triangle for a list (visibility states, lookup values). Dragging an arrow
//! or square is [`super::drag_grip`]; a list grip offers its property's choices.
//! arrow at each end of a distance (linear parameter), a square at a position (point parameter),
//! a circle at the end of an angle (rotation parameter), a flip arrow across a reflection line
//! (flip parameter), a down-pointing triangle for a list (visibility states, lookup values) and a
//! pentagon pointing across the alignment direction at an alignment's base point (alignment
//! parameter; dragged next to an object it aligns the reference with it, [`super::align_grip`]).
//! Dragging an arrow, square or circle is [`super::drag_grip`]; a flip grip flips at a click; a
//! list grip offers its property's choices.
//!
//! With a visibility parameter, a state lists the grips shown in it; the others are hidden.
@@ -26,6 +30,13 @@ pub enum GripPart {
End,
/// A one-point parameter's point (a position, a visibility or lookup grip).
At,
/// An XY parameter's corner at the base's X and the end's Y (listed as `blocks.reference.grip`
/// takes it, as [`GripPart::name`] names it).
#[serde(rename = "basex-endy")]
BaseXEndY,
/// An XY parameter's corner at the end's X and the base's Y.
#[serde(rename = "basey-endx")]
BaseYEndX,
}
impl GripPart {
@@ -34,6 +45,8 @@ impl GripPart {
GripPart::Base => "base",
GripPart::End => "end",
GripPart::At => "at",
GripPart::BaseXEndY => "basex-endy",
GripPart::BaseYEndX => "basey-endx",
}
}
pub fn from_name(s: &str) -> Option<GripPart> {
@@ -41,11 +54,28 @@ impl GripPart {
"base" => Some(GripPart::Base),
"end" => Some(GripPart::End),
"at" => Some(GripPart::At),
"basex-endy" => Some(GripPart::BaseXEndY),
"basey-endx" => Some(GripPart::BaseYEndX),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::GripPart;
/// A grip is listed with the part name `blocks.reference.grip` takes back.
#[test]
fn listed_part_names_are_the_names_a_drag_takes() {
for p in [GripPart::Base, GripPart::End, GripPart::At, GripPart::BaseXEndY, GripPart::BaseYEndX] {
let listed = serde_json::to_value(p).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
assert_eq!(listed, p.name());
assert_eq!(GripPart::from_name(&listed), Some(p));
}
}
}
/// How a grip looks and what it does.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
@@ -56,6 +86,13 @@ pub enum GripShape {
Point,
/// A down-pointing triangle: click it for the property's choices.
List,
/// A circle at the end of an angle: drag it to turn the angle.
Rotation,
/// An arrow across a reflection line: click it to flip (its choices are the two states).
Flip,
/// A pentagon pointing to the left of an alignment's direction: drag it next to an object to
/// align the reference with it.
Alignment,
}
/// One grip of a dynamic block reference.
@@ -102,6 +139,15 @@ fn ends_used(m: &DynamicBlock, node: i32) -> Option<(bool, bool)> {
used
}
/// Where a grip object at `g` (from its parameter's base, in the dynamic block) is when the
/// parameter's line `home` (base to end, in the block) is now `now` from `base`: kept along and
/// across the line as it turns, moves or stretches. `home` and `now` aren't zero.
fn carried(g: Vec2, home: Vec2, base: Vec2, now: Vec2) -> Vec2 {
let (u0, u) = (home * (1.0 / home.len()), now * (1.0 / now.len()));
let (along, across) = (g.dot(u0) / home.len(), u0.x * g.y - u0.y * g.x);
base + now * along + u.perp() * across
}
fn point<S: serde::Serializer>(p: &Vec2, s: S) -> Result<S::Ok, S::Error> {
[p.x, p.y].serialize(s)
}
@@ -120,6 +166,7 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
};
// The grips the current visibility state shows (all of them without visibility states).
let objects: HashMap<i32, Handle> = m.grip_objects.iter().copied().collect();
let points: HashMap<i32, Vec3> = m.grip_points.iter().copied().collect();
let mut shown_in_state: Option<HashSet<Handle>> = None;
let mut visibility_node = None;
for p in &m.parameters {
@@ -171,6 +218,87 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
}
}
}
ParameterKind::Rotation { base: hb, end: he, label, .. } => {
let (b, e) = match r.values.get(&p.node) {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*hb, *he),
};
let id = grip(1);
let (home, now) = ((*he - *hb).xy(), (e - b).xy());
if shown(p.node, id) && home.len() > 1e-12 && now.len() > 1e-12 {
// The grip object's place (AutoCAD draws the circle there, not at the radius'
// end), turned and moved with the radius.
let at = carried(points.get(&id).copied().unwrap_or(*he).xy() - hb.xy(), home, b.xy(), now);
let at = Vec3::new(at.x, at.y, b.z);
let u = at - b;
let u = if u.len() > 1e-12 { u * (1.0 / u.len()) } else { Vec3::new(1.0, 0.0, 0.0) };
let (at, dir) = (world(at), toward(at, u));
out.push(DynGrip {
node: p.node,
part: GripPart::End,
shape: GripShape::Rotation,
at,
dir,
property: label.clone(),
choices: Vec::new(),
});
}
}
ParameterKind::Flip { base: hb, end: he, label, states, .. } => {
let (b, e, flipped) = match r.values.get(&p.node) {
Some(Value::Flip { base, end, flipped }) => (*base, *end, *flipped),
_ => (*hb, *he, false),
};
let id = grip(0);
let (home, now) = ((*he - *hb).xy(), (e - b).xy());
if shown(p.node, id) && home.len() > 1e-12 && now.len() > 1e-12 {
// The grip object's place, kept along and across the reflection line as the
// line turns or moves with other actions.
let g = points.get(&id).copied().unwrap_or(*hb).xy() - hb.xy();
let at = carried(g, home, b.xy(), now);
let u = now * (1.0 / now.len());
let across_dir = if flipped { -u.perp() } else { u.perp() };
let (at3, dir) = (Vec3::new(at.x, at.y, b.z), toward(Vec3::new(at.x, at.y, b.z), across_dir.to3(0.0)));
out.push(DynGrip {
node: p.node,
part: GripPart::Base,
shape: GripShape::Flip,
at: world(at3),
dir,
property: label.clone(),
choices: states.to_vec(),
});
}
}
// Squares at the base and the end (a polar parameter), and at the two other corners of
// the rectangle they span (an XY parameter), for the grips the parameter has; an end
// no action follows has none.
ParameterKind::Polar { base, end, label, .. } | ParameterKind::Xy { base, end, x_label: label, .. } => {
let (b, e) = match r.values.get(&p.node) {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*base, *end),
};
let used = ends_used(&m, p.node).map_or([true, true], |(base, end)| [base, end]);
let mut corners = vec![(0, GripPart::Base, b, used[0]), (1, GripPart::End, e, used[1])];
if matches!(p.kind, ParameterKind::Xy { .. }) {
let both = used[0] && used[1];
corners.push((2, GripPart::BaseXEndY, Vec3::new(b.x, e.y, b.z), both));
corners.push((3, GripPart::BaseYEndX, Vec3::new(e.x, b.y, b.z), both));
}
for (i, part, at, used) in corners {
if used && shown(p.node, grip(i)) {
out.push(DynGrip {
node: p.node,
part,
shape: GripShape::Point,
at: world(at),
dir: Vec2::ZERO,
property: label.clone(),
choices: Vec::new(),
});
}
}
}
ParameterKind::Point { at, label, .. } => {
let at = match r.values.get(&p.node) {
Some(Value::Point { at }) => *at,
@@ -189,6 +317,26 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
});
}
}
// At the base point, pointing to the left of the direction (as AutoCAD draws it).
ParameterKind::Alignment { base, end, .. } => {
let (b, e) = match r.values.get(&p.node) {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*base, *end),
};
let u = (e - b).xy();
if shown(p.node, grip(0)) && u.len() > 1e-12 {
let (at, dir) = (world(b), toward(b, u.perp().to3(0.0)));
out.push(DynGrip {
node: p.node,
part: GripPart::Base,
shape: GripShape::Alignment,
at,
dir,
property: String::new(),
choices: Vec::new(),
});
}
}
ParameterKind::Visibility { at, label, .. } | ParameterKind::Lookup { at, label, .. } => {
let Some(list) = choices.get(&label.to_ascii_uppercase()).filter(|c| !c.is_empty()) else { continue };
if shown(p.node, grip(0)) {
+106 -29
View File
@@ -29,6 +29,8 @@ pub enum Value {
Point { at: Vec3 },
/// A two-point parameter's points.
Points { base: Vec3, end: Vec3 },
/// A flip parameter's reflection line and whether it is flipped.
Flip { base: Vec3, end: Vec3, flipped: bool },
}
/// A dynamic block reference.
@@ -51,8 +53,8 @@ pub struct CustomProperty {
/// The values it may be set to, when it is a choice (visibility states, lookup values, a
/// distance's list).
pub choices: Vec<String>,
/// CADCraft can change it ([`super::set_property`]): a visibility state, a distance, a
/// position, or a lookup whose tables set only those.
/// CADCraft can change it ([`super::set_property`]): a visibility state, a distance, an angle,
/// a position, a flip state, or a lookup whose tables set only those.
pub editable: bool,
}
@@ -91,7 +93,9 @@ fn entries(objects: &HashMap<Handle, &ForeignObject>, dict: Handle) -> Vec<(Stri
out
}
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30).
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30); a flip
/// parameter's also has its state, a group 70 after its points (the header's `70 25`, `70 104`
/// come before them).
fn value(o: &ForeignObject) -> Option<Value> {
if let Some(t) = o.tags.iter().find(|t| t.code == 1) {
return Some(Value::Text { value: t.value.clone() });
@@ -100,7 +104,10 @@ fn value(o: &ForeignObject) -> Option<Value> {
o.tags.iter().filter(|t| t.code == code).nth(i).and_then(|t| t.value.trim().parse::<f64>().ok()).filter(|v| v.is_finite())
};
let point = |i: usize| Some(Vec3::new(num(10, i)?, num(20, i)?, num(30, i).unwrap_or(0.0)));
let first_point = o.tags.iter().position(|t| t.code == 10).unwrap_or(o.tags.len());
let state = o.tags.get(first_point..).unwrap_or_default().iter().rev().find(|t| t.code == 70).map(|t| t.value.trim() == "1");
match (point(0), point(1)) {
(Some(base), Some(end)) if state.is_some() => Some(Value::Flip { base, end, flipped: state == Some(true) }),
(Some(base), Some(end)) => Some(Value::Points { base, end }),
(Some(at), None) => Some(Value::Point { at }),
_ => None,
@@ -122,17 +129,52 @@ pub fn reference(d: &Drawing, insert: Handle) -> Option<Reference> {
let target = data.tags.iter().find(|t| t.code == 340).and_then(|t| Handle::parse_hex(&t.value))?;
let (kind, name) = d.foreign.targets.get(&target)?;
let definition = d.block(name).filter(|_| kind == "BLOCK_RECORD")?.name.clone();
dynamic_block(d, &definition)?;
let m = dynamic_block(d, &definition)?;
let mut values = BTreeMap::new();
let cache = entry(&objects, rep, "AppDataCache").and_then(|c| entry(&objects, c, "ACAD_ENHANCEDBLOCKDATA"));
for (key, h) in cache.map(|c| entries(&objects, c)).unwrap_or_default().into_iter().take(MAX_VALUES) {
if let (Ok(node), Some(v)) = (key.trim().parse::<i32>(), objects.get(&h).and_then(|o| value(o))) {
// The record's groups alone can't tell a flip from another two-point parameter (a stray
// 70, or a flip without its state): the parameter it belongs to decides.
let flip = m.parameters.iter().any(|p| p.node == node && matches!(p.kind, ParameterKind::Flip { .. }));
let v = match (flip, v) {
(false, Value::Flip { base, end, .. }) => Value::Points { base, end },
(true, Value::Points { base, end }) => Value::Flip { base, end, flipped: false },
(_, v) => v,
};
values.insert(node, v);
}
}
Some(Reference { definition, values })
}
/// An angle (radians) as Properties shows it: degrees with AUPREC decimals.
/// An angle parameter's value `a` (radians, counterclockwise) as the drawing shows angles: from
/// ANGBASE, clockwise when ANGDIR is 1 (AutoCAD shows a 0 angle as 90 in a drawing measured
/// clockwise from north, and 0.5 rad as 61.35).
pub(super) fn angle_shown(d: &Drawing, a: f64) -> f64 {
let base = d.header.f64("ANGBASE", 0.0);
let shown = if d.header.i64("ANGDIR", 0) == 1 { base - a } else { a - base };
shown.rem_euclid(std::f64::consts::TAU)
}
/// The value of an angle parameter shown (or typed) as `v` (radians): the inverse of
/// [`angle_shown`].
pub(super) fn angle_from_shown(d: &Drawing, v: f64) -> f64 {
let base = d.header.f64("ANGBASE", 0.0);
let a = if d.header.i64("ANGDIR", 0) == 1 { base - v } else { v + base };
a.rem_euclid(std::f64::consts::TAU)
}
fn angle_text(d: &Drawing, a: f64) -> String {
let prec = usize::try_from(d.header.i64("AUPREC", 0).clamp(0, 8)).unwrap_or(0);
// Rounded to the shown decimals first: an angle just short of a full turn shows as 0, not 360.
let step = 10f64.powi(i32::try_from(prec).unwrap_or(0));
let shown = (angle_shown(d, a).to_degrees() * step).round() / step;
let shown = if shown >= 360.0 { shown - 360.0 } else { shown };
format!("{:.prec$}", shown + 0.0)
}
/// A number as the drawing shows lengths (LUPREC decimals).
fn number(d: &Drawing, v: f64) -> String {
let prec = usize::try_from(d.header.i64("LUPREC", 4).clamp(0, 8)).unwrap_or(4);
@@ -156,26 +198,7 @@ struct Current<'a> {
impl Current<'_> {
/// Parameter `node`'s value of property `property`, as table cells write it.
fn property(&self, node: i32, property: &str) -> Option<String> {
let p = self.m.parameters.iter().find(|p| p.node == node)?;
let v = self.values.get(&node);
match (&p.kind, property.to_ascii_lowercase().as_str()) {
(ParameterKind::Visibility { states, .. }, "visibilitystate") => match v {
Some(Value::Text { value }) => Some(value.clone()),
_ => states.first().map(|s| s.name.clone()),
},
(ParameterKind::Linear { base, end, .. }, "updateddistance" | "distance") => {
let (b, e) = match v {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*base, *end),
};
Some(format!("{}", (e - b).len()))
}
(ParameterKind::Lookup { .. }, "lookupstring") => match v {
Some(Value::Text { value }) => Some(value.clone()),
_ => None,
},
_ => None,
}
super::apply::property_text(self.m, self.values, node, property)
}
/// Lookup parameter `node`'s value: the value every lookup table that sets it gives for the
@@ -239,6 +262,27 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
let choices = if values.is_list() { values.list.iter().map(|x| number(d, x * sx)).collect() } else { Vec::new() };
out.push(CustomProperty { name: label.clone(), value: number(d, (e - b).len() * sx), choices, editable: true });
}
// The distance from the base to the end, and the end's direction (AutoCAD measures it
// from the block's X axis, not from where the dynamic block has it).
ParameterKind::Polar { base: b, end: e, label, angle_label, values, .. } => {
let (b, e) = match v {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*b, *e),
};
let choices = if values.is_list() { values.list.iter().map(|x| number(d, x * sx)).collect() } else { Vec::new() };
out.push(CustomProperty { name: label.clone(), value: number(d, (e - b).len() * sx), choices, editable: true });
let a = (e - b).xy().angle().rem_euclid(std::f64::consts::TAU);
out.push(CustomProperty { name: angle_label.clone(), value: angle_text(d, a), choices: Vec::new(), editable: true });
}
// How far the end is from the base along X and along Y.
ParameterKind::Xy { base: b, end: e, x_label, y_label, .. } => {
let (b, e) = match v {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*b, *e),
};
out.push(CustomProperty { name: x_label.clone(), value: number(d, (e.x - b.x) * sx), choices: Vec::new(), editable: true });
out.push(CustomProperty { name: y_label.clone(), value: number(d, (e.y - b.y) * sy), choices: Vec::new(), editable: true });
}
ParameterKind::Point { at, label, .. } => {
let at = match v {
Some(Value::Point { at }) => *at,
@@ -247,6 +291,21 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
out.push(CustomProperty { name: format!("{label} X"), value: number(d, (at.x - base.x) * sx), choices: Vec::new(), editable: true });
out.push(CustomProperty { name: format!("{label} Y"), value: number(d, (at.y - base.y) * sy), choices: Vec::new(), editable: true });
}
ParameterKind::Rotation { base: hb, end: he, label, .. } => {
let (b, e) = match v {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*hb, *he),
};
let now = (e - b).xy();
let zero = (*he - *hb).xy();
let a = (now.y.atan2(now.x) - zero.y.atan2(zero.x)).rem_euclid(std::f64::consts::TAU);
out.push(CustomProperty { name: label.clone(), value: angle_text(d, a), choices: Vec::new(), editable: true });
}
ParameterKind::Flip { label, states, .. } => {
let flipped = matches!(v, Some(Value::Flip { flipped: true, .. }));
let value = states[usize::from(flipped)].clone();
out.push(CustomProperty { name: label.clone(), value, choices: states.to_vec(), editable: true });
}
ParameterKind::Visibility { label, states, .. } => {
let value = cur.property(p.node, "VisibilityState").unwrap_or_default();
out.push(CustomProperty { name: label.clone(), value, choices: states.iter().map(|s| s.name.clone()).collect(), editable: true });
@@ -263,7 +322,8 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
}
/// Whether every lookup table that sets lookup parameter `node` sets only what
/// [`super::set_property`] can apply with it: visibility states and distances.
/// [`super::set_property`] can apply with it: visibility states, distances, angles, positions and
/// flip states.
fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool {
let mut any = false;
for a in &m.actions {
@@ -272,12 +332,29 @@ fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool {
continue;
}
any = true;
if !columns
.iter()
.all(|c| matches!(c.property.to_ascii_lowercase().as_str(), "lookupstring" | "visibilitystate" | "updateddistance" | "distance"))
{
let settable = |c: &super::LookupColumn| {
m.parameters.iter().find(|p| p.node == c.node).is_some_and(|p| super::apply::column(&p.kind, &c.property).is_some())
};
if !columns.iter().all(settable) {
return false;
}
}
any
}
#[cfg(test)]
mod tests {
use super::angle_text;
use crate::Drawing;
#[test]
fn an_angle_just_short_of_a_full_turn_shows_as_zero() {
let mut d = Drawing::new_imperial();
d.header.set_i64("AUPREC", 0);
assert_eq!(angle_text(&d, 359.7f64.to_radians()), "0");
assert_eq!(angle_text(&d, 359.4f64.to_radians()), "359");
d.header.set_i64("AUPREC", 2);
assert_eq!(angle_text(&d, 359.996f64.to_radians()), "0.00");
assert_eq!(angle_text(&d, 90f64.to_radians()), "90.00");
}
}
+5 -3
View File
@@ -271,8 +271,10 @@ impl EntityKind {
EntityKind::Image(i) => vec![Prim::Point(i.insert.xy())],
EntityKind::Table(t) => vec![Prim::Point(t.insert.xy())],
EntityKind::Tolerance(t) => vec![Prim::Point(t.insert.xy())],
// What its proxy graphics draw, so a proxy can be picked and snapped to.
EntityKind::Unknown(u) => u.graphics.iter().flat_map(|g| g.kind.prims()).collect(),
// What its proxy graphics draw, so a proxy can be picked and snapped to. A filled
// shape's hatch is left out: its outline is drawn too, and the hatch's sides (72 for an
// ellipse) would offer snaps inside it.
EntityKind::Unknown(u) => u.graphics.iter().filter(|g| !matches!(g.kind, EntityKind::Hatch(_))).flat_map(|g| g.kind.prims()).collect(),
}
}
@@ -625,7 +627,7 @@ impl EntityKind {
EntityKind::Text(t) => vec![t.justify_point()],
EntityKind::MText(t) => vec![t.insert.xy()],
EntityKind::AttDef(a) => vec![a.text.justify_point()],
EntityKind::Insert(i) => std::iter::once(i.insert.xy()).chain(i.attribs.iter().map(|a| a.text.justify_point())).collect(),
EntityKind::Insert(i) => std::iter::once(i.insert.xy()).chain(i.grip_attribs().map(|(_, a)| a.text.justify_point())).collect(),
EntityKind::Dimension(d) => vec![d.p13.xy(), d.p14.xy(), d.defpt.xy(), d.text_mid.xy()],
EntityKind::MLine(m) => m.points(),
EntityKind::Leader(l) => l.vertices.iter().map(|v| v.xy()).collect(),
+6
View File
@@ -191,6 +191,12 @@ fn one_u() -> u32 {
}
impl Insert {
/// The attributes that have a grip of their own (grips 1, 2… after the insertion point), with
/// their index in `attribs`: those shown and not locked in position, as AutoCAD offers them.
pub fn grip_attribs(&self) -> impl Iterator<Item = (usize, &Attrib)> {
self.attribs.iter().enumerate().filter(|(_, a)| !a.invisible && !a.modes.lock_position)
}
/// Block-to-world transform (2D part).
pub fn transform(&self, base: Vec2) -> Mat3 {
Mat3::translate(self.insert.xy())
+754 -60
View File
@@ -9,7 +9,8 @@
//! until a chunk sets them. Chunks CADCraft doesn't decode (meshes, shells, lightweight
//! polylines, materials) are skipped.
use super::{Arc, Circle, Common, Entity, EntityKind, Handle, Hatch, HatchLoop, Line, Lineweight, LwPolyline, Text, Unknown};
use super::{Arc, Circle, Common, Ellipse, Entity, EntityKind, Handle, Hatch, HatchLoop, Line, Lineweight, LwPolyline, Text, Unknown};
use crate::RawTag;
use cadcraft_color::{Color, Rgb};
use cadcraft_geom::{PolyVertex, Vec2, Vec3};
@@ -35,16 +36,20 @@ pub struct ProxyTables {
}
impl Unknown {
/// The proxy graphics bytes of an ACAD_PROXY_ENTITY: the 310 groups after its size group
/// (92, or 160 in newer files), cut to that size. Empty for other records, for an entity
/// without graphics and for one whose data isn't hex.
/// The proxy graphics bytes of an entity: the 310 groups after its size group (92, or 160 in
/// newer files), cut to that size. An ACAD_PROXY_ENTITY holds them in its proxy data: the size
/// group is the first after the `AcDbProxyEntity` subclass marker (from the start in a record
/// without one), so a 92 or 160 among the entity's own groups before it isn't taken for it.
/// An entity of another type CADCraft keeps as read holds them in its `AcDbEntity` part when
/// it was saved with a picture of itself (a LARGE_RADIAL_DIMENSION or an ARC_DIMENSION, or an
/// object of another application; #3438). Empty for an entity without graphics and for one
/// whose data isn't hex.
pub fn proxy_graphics_bytes(&self) -> Vec<u8> {
if !self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") {
return Vec::new();
}
let Some(at) = self.tags.iter().position(|t| t.code == 92 || t.code == 160) else { return Vec::new() };
let size = self.tags.get(at).and_then(|t| t.value.trim().parse::<usize>().ok()).unwrap_or(0).min(MAX_BYTES);
let mut out = Vec::with_capacity(size);
let Some((at, size)) = self.graphics_size_group() else { return Vec::new() };
// Reserve what the 310 groups hold, not what the size claims: a size far past the data
// would otherwise reserve up to MAX_BYTES for nothing.
let held: usize = self.tags.iter().skip(at + 1).take_while(|t| t.code == 310).map(|t| t.value.trim().len() / 2).sum();
let mut out = Vec::with_capacity(size.min(held));
for t in self.tags.iter().skip(at + 1).take_while(|t| t.code == 310) {
// Damaged data draws nothing rather than a picture cut at a guess.
if !push_hex(&mut out, &t.value) {
@@ -59,6 +64,232 @@ impl Unknown {
}
}
impl Unknown {
/// The `*D` block a dimension CADCraft keeps as read names (group 2 of its `AcDbDimension`
/// part): a LARGE_RADIAL_DIMENSION or an ARC_DIMENSION. AutoCAD draws a dimension from that
/// block, so CADCraft draws it from there too, and saving keeps it (#3438, #1161). `None`
/// for other records.
pub fn dimension_block(&self) -> Option<&str> {
let m = self.tags.iter().position(|t| t.code == 100 && t.value.trim() == "AcDbDimension")?;
self.tags[m + 1..].iter().take_while(|t| t.code != 100).find(|t| t.code == 2).map(|t| t.value.trim()).filter(|n| !n.is_empty())
}
/// Where the proxy graphics size group (92, or 160 in newer files) is, and the size it gives
/// (at most [`MAX_BYTES`]): in an ACAD_PROXY_ENTITY the first after the `AcDbProxyEntity`
/// marker, in another kept entity the one in its `AcDbEntity` part.
fn graphics_size_group(&self) -> Option<(usize, usize)> {
let at = if self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") {
let from = self.tags.iter().position(|t| t.code == 100 && t.value.trim() == "AcDbProxyEntity").map_or(0, |m| m + 1);
self.tags.iter().skip(from).position(|t| t.code == 92 || t.code == 160).map(|i| from + i)
} else {
// The groups of the AcDbEntity subclass, up to the entity's own subclass marker.
self.tags.iter().position(|t| t.code == 100 && t.value.trim() == "AcDbEntity").and_then(|m| {
let own = &self.tags[m + 1..];
own.iter().take_while(|t| t.code != 100).position(|t| t.code == 92 || t.code == 160).map(|i| m + 1 + i)
})
}?;
let size = self.tags.get(at).and_then(|t| t.value.trim().parse::<usize>().ok()).unwrap_or(0).min(MAX_BYTES);
Some((at, size))
}
/// The record's groups with the layer indices of its proxy graphics (ATTRIBUTE_LAYER) turned
/// into the written LAYER table `written`, by name; everything else as read. The name of an
/// index is the one the record's own decoded graphics draw on after it (so a proxy copied from
/// another drawing, or one whose layer was renamed, keeps the layer it shows); an index no
/// drawn entity follows takes the name from the file's table `read` (see
/// [`crate::Drawing::proxy_layers`]). A layer that is gone becomes layer 0 (the proxy's own
/// layer, as in a block); an index past the table, or one of a record without a name, stays
/// past the written one, which keeps the layer before it as AutoCAD does. Only the 310 groups
/// that hold the declared size are read and rewritten. `None` when no index changes, or the
/// graphics aren't readable.
pub fn with_proxy_layers(&self, read: &[String], written: &[String]) -> Option<Vec<RawTag>> {
// Only a proxy entity's own graphics: a kept dimension draws from its block instead.
if !self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") {
return None;
}
let (at, size) = self.graphics_size_group()?;
let (mut bytes, mut groups) = (Vec::new(), Vec::new());
for i in (at + 1..self.tags.len()).take_while(|&i| self.tags[i].code == 310) {
if bytes.len() >= size {
break;
}
let before = bytes.len();
if !push_hex(&mut bytes, &self.tags[i].value) {
return None;
}
groups.push((i, bytes.len() - before));
}
let end = size.min(bytes.len());
// The ATTRIBUTE_LAYER chunks: where each index sits.
let mut refs: Vec<(usize, u32)> = Vec::new();
let mut chunk = 8usize;
while let (Some(len), Some(kind)) = (u32_at(&bytes[..end], chunk), u32_at(&bytes[..end], chunk + 4)) {
let len = len as usize;
if len < 8 || chunk.saturating_add(len) > end {
break;
}
if kind == 16
&& let Some(i) = u32_at(&bytes[..chunk + len], chunk + 8)
{
refs.push((chunk + 8, i));
}
chunk += len;
}
if refs.is_empty() {
return None;
}
let indices: Vec<u32> = refs.iter().map(|r| r.1).collect();
let learned = self.layers_by_index(&bytes[..end], &indices);
if read.is_empty() && learned.is_empty() {
return None;
}
// Each written name's first place, found once.
let mut place: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
for (p, n) in written.iter().enumerate() {
place.entry(n.to_ascii_lowercase()).or_insert(u32::try_from(p).unwrap_or(u32::MAX));
}
let zero = place.get("0").copied();
let past = u32::try_from(written.len()).unwrap_or(u32::MAX).max(u32::try_from(read.len()).unwrap_or(u32::MAX));
let mut resolved: std::collections::HashMap<u32, u32> = std::collections::HashMap::new();
let mut changed = false;
for (offset, i) in refs {
let j = *resolved.entry(i).or_insert_with(|| {
let name = match learned.get(&i) {
Some(name) => name.as_deref(),
None => read.get(i as usize).map(String::as_str),
};
match name.filter(|n| !n.is_empty()) {
Some(name) => place.get(&name.to_ascii_lowercase()).copied().or(zero).unwrap_or(i),
None if i >= past => i,
None => past,
}
});
if j != i {
bytes[offset..offset + 4].copy_from_slice(&j.to_le_bytes());
changed = true;
}
}
if !changed {
return None;
}
let mut tags = self.tags.clone();
let mut from = 0;
for (g, n) in groups {
tags[g].value = bytes[from..from + n].iter().map(|b| format!("{b:02X}")).collect();
from += n;
}
Some(tags)
}
/// The layer each ATTRIBUTE_LAYER index of `bytes` (the record's `indices`) stands for in
/// this record's decoded graphics: the bytes decoded again with index `i` named `#i` give the
/// same entities in the same order, so each one's marker meets its real layer. `None` for an
/// index after which the graphics stay on the layer before (one past the table it was read
/// with). An index above 65,535 isn't named here (it resolves through the file's table, like
/// one no entity follows). Empty when the graphics don't match
/// (not decoded from these bytes); an index whose entities disagree is left out.
fn layers_by_index(&self, bytes: &[u8], indices: &[u32]) -> std::collections::HashMap<u32, Option<String>> {
/// What the entities after an index say about it.
enum Seen {
/// They are on this layer, and the ones before them weren't.
Named(String),
/// They are on the same layer as the ones before them: the index keeps that layer,
/// or names it.
Kept(String),
/// It keeps the layer before (two kept observations on different layers).
Keeps,
}
const MAX: u32 = 65_535;
let mut out: std::collections::HashMap<u32, Option<String>> = std::collections::HashMap::new();
if self.graphics.is_empty() {
return out;
}
let max = indices.iter().copied().filter(|&i| i <= MAX).max().unwrap_or(0);
let markers = ProxyTables { layers: (0..=max).map(|i| format!("\u{1}{i}")).collect(), ..ProxyTables::default() };
let marked = proxy_entities(bytes, &markers, Handle(0));
if marked.len() != self.graphics.len() {
return out;
}
let same = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
let mut seen: std::collections::HashMap<u32, Seen> = std::collections::HashMap::new();
let mut conflict = std::collections::HashSet::new();
let mut before: Option<(&str, &str)> = None;
for (m, g) in marked.iter().zip(&self.graphics) {
let (mark, real) = (m.common.layer.as_str(), g.common.layer.as_str());
let changed_here = before.is_none_or(|(prev_mark, _)| prev_mark != mark);
let kept = before.is_some_and(|(_, prev_real)| same(prev_real, real));
before = Some((mark, real));
let Some(i) = mark.strip_prefix('\u{1}').and_then(|i| i.parse::<u32>().ok()) else { continue };
if !changed_here {
// The same marker on another real layer: an index in between (one past the table
// the marker decoding doesn't see as such) changed it, so this one can't be named.
if !kept {
conflict.insert(i);
}
continue;
}
let real = real.to_string();
let merged = match (seen.remove(&i), kept) {
(None, false) => Some(Seen::Named(real)),
(None, true) => Some(Seen::Kept(real)),
(Some(Seen::Named(a) | Seen::Kept(a)), false) | (Some(Seen::Named(a)), true) if same(&a, &real) => Some(Seen::Named(a)),
(Some(Seen::Kept(a)), true) => Some(if same(&a, &real) { Seen::Kept(a) } else { Seen::Keeps }),
(Some(Seen::Keeps), true) => Some(Seen::Keeps),
_ => None,
};
match merged {
Some(s) => {
seen.insert(i, s);
}
None => {
conflict.insert(i);
}
}
}
for (i, s) in seen {
if !conflict.contains(&i) {
out.insert(i, if let Seen::Named(n) = s { Some(n) } else { None });
}
}
out
}
}
impl crate::Drawing {
/// Rename layer `old` to `new` where proxy graphics use it: in [`crate::Drawing::proxy_layers`],
/// so saving finds the layer under its new name, and in the decoded graphics, which draw on
/// it at once. RENAME calls it, LAYMRG for each merged layer (its graphics move to the
/// target, as its objects do) and LAYDEL with layer 0.
pub fn rename_proxy_layer(&mut self, old: &str, new: &str) {
for n in &mut self.proxy_layers {
if n.eq_ignore_ascii_case(old) {
*n = new.to_string();
}
}
let uses = |e: &Entity| matches!(&e.kind, EntityKind::Unknown(u) if u.graphics.iter().any(|g| g.common.layer.eq_ignore_ascii_case(old)));
let fix = |e: &mut Entity| {
if let EntityKind::Unknown(u) = &mut e.kind {
for g in u.graphics.iter_mut().filter(|g| g.common.layer.eq_ignore_ascii_case(old)) {
g.common.layer = new.to_string();
}
}
};
let mut stores: Vec<&mut crate::EntityStore> = vec![&mut self.model];
stores.extend(self.layouts.iter_mut().map(|l| &mut l.entities));
for b in self.blocks.values_mut() {
if b.entities.iter().any(|e| uses(e)) {
stores.push(&mut std::sync::Arc::make_mut(b).entities);
}
}
for store in stores {
let hs: Vec<Handle> = store.iter().filter(|e| uses(e)).map(|e| e.handle).collect();
for h in hs {
store.modify(h, fix);
}
}
}
}
/// Append the bytes of hex string `s`. False on a character that isn't a hex digit.
fn push_hex(out: &mut Vec<u8>, s: &str) -> bool {
let digits: Vec<u8> = s.trim().bytes().collect();
@@ -99,6 +330,7 @@ struct Decoder<'a> {
handle: Handle,
/// Layer, colour, linetype and lineweight for the entities that follow.
pen: Common,
/// Whether polygons and circles that follow are filled (ATTRIBUTE_FILL).
fill: bool,
/// Model transforms pushed by PUSH_MATRIX, innermost last (row-major 3x4 of the 4x4).
matrices: Vec<[f64; 12]>,
@@ -119,9 +351,9 @@ impl Decoder<'_> {
// CIRCLE_3P: three points on it.
3 => {
if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point())
&& let Some((c, r)) = circle_through(self.xy(p1), self.xy(p2), self.xy(p3))
&& let Some(fit) = Fit3::through(p1, p2, p3)
{
self.push(EntityKind::Circle(Circle { center: c.to3(0.0), radius: r }));
self.circle_in(fit.center, fit.radius, fit.e1, fit.e2);
}
}
// CIRCULAR_ARC: centre, radius, normal, start vector, sweep angle (around the normal).
@@ -133,11 +365,12 @@ impl Decoder<'_> {
// CIRCULAR_ARC_3P: start, a point on the arc, end.
5 => {
if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point()) {
self.arc_3p(self.xy(p1), self.xy(p2), self.xy(p3));
self.arc_3p_local(p1, p2, p3);
}
}
// POLYLINE and POLYGON: a count, then the points.
6 | 7 => {
// POLYLINE and POLYGON: a count, then the points; POLYLINE_WITH_NORMAL: a count, the
// points and a normal (the dimension lines of a LARGE_RADIAL_DIMENSION's picture).
6 | 7 | 32 => {
let Some(n) = b.u32() else { return };
let n = (n as usize).min(MAX_VERTICES);
let pts: Vec<Vec2> = (0..n).map_while(|_| b.point()).map(|p| self.xy(p)).collect();
@@ -192,9 +425,10 @@ impl Decoder<'_> {
self.pen.color = Color::from_aci(i16::try_from(c).unwrap_or(256));
}
}
// ATTRIBUTE_LAYER: index into the layer table; an index past it leaves the layer.
// ATTRIBUTE_LAYER: index into the layer table; an index past it, or one of a record
// without a name, leaves the layer.
16 => {
if let Some(name) = b.u32().and_then(|i| self.tables.layers.get(i as usize)) {
if let Some(name) = b.u32().and_then(|i| self.tables.layers.get(i as usize)).filter(|n| !n.is_empty()) {
self.pen.layer = name.clone();
}
}
@@ -204,12 +438,18 @@ impl Decoder<'_> {
if let Some(i) = b.u32() {
self.pen.linetype = match i {
32766 => "ByBlock".into(),
_ => self.tables.linetypes.get(i as usize).cloned().unwrap_or_else(|| "ByLayer".into()),
_ => self.tables.linetypes.get(i as usize).filter(|n| !n.is_empty()).cloned().unwrap_or_else(|| "ByLayer".into()),
};
}
}
// ATTRIBUTE_FILL: the next polygon is filled.
20 => self.fill = b.u32().is_some_and(|f| f != 0),
// ATTRIBUTE_FILL: a trait like the colour, in force until the next one: 1 fills the
// polygons and circles that follow, 2 (and anything else) doesn't (AcGiFillType
// kAcGiFillAlways, kAcGiFillNever).
20 => {
if let Some(f) = b.u32() {
self.fill = f == 1;
}
}
// ATTRIBUTE_TRUE_COLOR: a colour with its method in the top byte.
22 => {
if let Some(v) = b.u32() {
@@ -277,12 +517,60 @@ impl Decoder<'_> {
self.matrices.iter().map(|m| (m[0] * m[5] - m[1] * m[4]).abs().sqrt()).product()
}
/// A full circle around `c`, through the pushed matrices.
/// Where the pushed matrices take `c` and the unit vectors `e1`, `e2` of a circle's plane: the
/// circle of radius 1 around `c` is drawn as `c' + u·cos a + v·sin a`. The vectors go through
/// the matrices' linear parts only, so a small scale isn't lost against a large translation.
fn axes(&self, c: Vec3, e1: Vec3, e2: Vec3) -> (Vec2, Vec2, Vec2) {
(self.xy(c), self.linear(e1), self.linear(e2))
}
/// Direction `v` through the pushed matrices' linear parts, innermost first, in the XY plane.
fn linear(&self, v: Vec3) -> Vec2 {
let mut v = v;
for m in self.matrices.iter().rev() {
v = Vec3::new(m[0] * v.x + m[1] * v.y + m[2] * v.z, m[4] * v.x + m[5] * v.y + m[6] * v.z, m[8] * v.x + m[9] * v.y + m[10] * v.z);
}
v.xy()
}
/// A full circle around `c`, through the pushed matrices: an ellipse when they scale its
/// plane unevenly or shear it. While ATTRIBUTE_FILL is on, a solid hatch under it: AutoCAD
/// draws a filled shape's outline too, with its lineweight.
fn circle(&mut self, c: Vec3, r: f64) {
let r = r * self.scale();
let c = self.xy(c);
if r.is_finite() && r > 0.0 && c.is_finite() {
self.push(EntityKind::Circle(Circle { center: c.to3(0.0), radius: r }));
self.circle_in(c, r, X, Y);
}
/// The circle of radius `r` around `c` in the plane of the unit vectors `e1` and `e2`, as
/// `circle` draws one in the chunk's XY plane.
fn circle_in(&mut self, c: Vec3, r: f64, e1: Vec3, e2: Vec3) {
let (at, u, v) = self.axes(c, e1, e2);
if !(r.is_finite() && r > 0.0 && at.is_finite()) {
return;
}
match round(u * r, v * r) {
Some(r) => {
if self.fill {
// Two half-circle arcs (bulge 1).
let side = |p: Vec2| PolyVertex { p, bulge: 1.0, start_width: 0.0, end_width: 0.0 };
self.solid(vec![side(at + Vec2::new(r, 0.0)), side(at - Vec2::new(r, 0.0))]);
}
self.push(EntityKind::Circle(Circle { center: at.to3(0.0), radius: r }));
}
None => {
let Some(e) = ellipse(at, u * r, v * r, 0.0, std::f64::consts::TAU) else {
return self.edge_on(at, u * r, v * r, 0.0, std::f64::consts::TAU);
};
if self.fill {
// Bulges draw circular arcs only: the fill follows the ellipse in 72
// straight sides, finer than a plotted pixel at the sizes proxies use.
let side = |i: u32| {
let a = std::f64::consts::TAU * f64::from(i) / 72.0;
PolyVertex { p: at + u * (r * a.cos()) + v * (r * a.sin()), bulge: 0.0, start_width: 0.0, end_width: 0.0 }
};
self.solid((0..72).map(side).collect());
}
self.push(EntityKind::Ellipse(e));
}
}
}
@@ -296,12 +584,62 @@ impl Decoder<'_> {
let dir = if normal.z < 0.0 { -1.0 } else { 1.0 };
let a0 = start.y.atan2(start.x);
let a1 = a0 + dir * sweep;
let on = |a: f64| c + Vec3::new(r * a.cos(), r * a.sin(), 0.0);
let mid = on((a0 + a1) / 2.0);
if sweep.abs() >= std::f64::consts::TAU - 1e-9 {
return self.circle(c, r);
}
self.arc_3p(self.xy(on(a0)), self.xy(mid), self.xy(on(a1)));
self.arc_between(c, r, X, Y, a0, a1);
}
/// The arc of radius `r` around `c` from angle `a0` to `a1` (from `e1` towards `e2`, the unit
/// vectors of its plane), either way round, through the pushed matrices: an elliptical arc
/// when they don't keep it round.
fn arc_between(&mut self, c: Vec3, r: f64, e1: Vec3, e2: Vec3, a0: f64, a1: f64) {
let (at, u, v) = self.axes(c, e1, e2);
let on = |a: f64| at + u * (r * a.cos()) + v * (r * a.sin());
if round(u * r, v * r).is_some() {
return self.arc_3p(on(a0), on((a0 + a1) / 2.0), on(a1));
}
match ellipse(at, u * r, v * r, a0.min(a1), a0.max(a1)) {
Some(e) => self.push(EntityKind::Ellipse(e)),
None => self.edge_on(at, u * r, v * r, a0.min(a1), a0.max(a1)),
}
}
/// A circle or arc `c + u·cos a + v·sin a` (`a` from `a0` to `a1`) seen edge-on: `u` and `v`
/// on one line, so it draws as the line between its two farthest points along it.
fn edge_on(&mut self, c: Vec2, u: Vec2, v: Vec2, a0: f64, a1: f64) {
use std::f64::consts::{PI, TAU};
let d = if u.len() >= v.len() { u } else { v };
if !(c.is_finite() && d.is_finite() && v.is_finite() && u.is_finite() && d.len() > 0.0) {
return;
}
let d = d * (1.0 / d.len());
// Along d the point is at R·cos(a − φ): farthest out at φ and φ + π, where the sweep has them.
let phi = v.dot(d).atan2(u.dot(d));
let inside = |a: f64| (a - a0).rem_euclid(TAU) <= a1 - a0;
let on = |a: f64| c + u * a.cos() + v * a.sin();
let mut ends = [a0, a1, phi, phi + PI].into_iter().filter(|&a| a == a0 || a == a1 || inside(a)).map(on).map(|p| (p - c).dot(d));
let first = ends.next().unwrap_or(0.0);
let (lo, hi) = ends.fold((first, first), |(lo, hi), t| (lo.min(t), hi.max(t)));
if hi > lo {
self.push(EntityKind::Line(Line { a: (c + d * lo).to3(0.0), b: (c + d * hi).to3(0.0) }));
}
}
/// The arc from `p1` through `p2` to `p3`, chunk coordinates: fitted in the plane of the
/// three points and drawn through the pushed matrices, which may make it elliptical.
fn arc_3p_local(&mut self, p1: Vec3, p2: Vec3, p3: Vec3) {
if self.matrices.is_empty() && p1.z == p2.z && p2.z == p3.z {
return self.arc_3p(p1.xy(), p2.xy(), p3.xy());
}
let Some(fit) = Fit3::through(p1, p2, p3) else {
return self.polyline(vec![self.xy(p1), self.xy(p3)], false);
};
let (a1, a2, a3) = (fit.angle(p1), fit.angle(p2), fit.angle(p3));
let ccw = |from: f64, to: f64| (to - from).rem_euclid(std::f64::consts::TAU);
// Counter-clockwise from p1 to p3 when p2 lies on that way, else from p3 to p1.
let (from, sweep) = if ccw(a1, a2) <= ccw(a1, a3) { (a1, ccw(a1, a3)) } else { (a3, ccw(a3, a1)) };
self.arc_between(fit.center, fit.radius, fit.e1, fit.e2, from, from + sweep);
}
/// The arc from `p1` through `p2` to `p3`.
@@ -317,29 +655,15 @@ impl Decoder<'_> {
self.push(EntityKind::Arc(Arc { center: c.to3(0.0), radius: r, start, end }));
}
/// A polyline, or a closed polygon: filled (a solid hatch) when ATTRIBUTE_FILL asked for it,
/// which applies to this one polygon only.
/// A polyline, or a closed polygon: on a solid hatch while ATTRIBUTE_FILL is on (the outline
/// is drawn too, as for a circle).
fn polyline(&mut self, pts: Vec<Vec2>, polygon: bool) {
let fill = std::mem::take(&mut self.fill);
if pts.iter().any(|p| !p.is_finite()) || pts.is_empty() {
return;
}
if polygon && fill && pts.len() >= 3 {
if polygon && self.fill && pts.len() >= 3 {
let vertices = pts.iter().map(|&p| PolyVertex { p, bulge: 0.0, start_width: 0.0, end_width: 0.0 }).collect();
return self.push(EntityKind::Hatch(Hatch {
pattern: "SOLID".into(),
solid: true,
loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
style: 0,
elevation: 0.0,
gradient: None,
origin: Vec2::ZERO,
background: None,
pattern_lines: Vec::new(),
}));
self.solid(vertices);
}
match pts.as_slice() {
[a, b] if !polygon => self.push(EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) })),
@@ -350,6 +674,29 @@ impl Decoder<'_> {
}
}
/// A solid hatch with the one boundary `vertices`.
fn solid(&mut self, vertices: Vec<PolyVertex>) {
// At the cap the fill gives way to the outline that follows it: a shape left with only
// its fill couldn't be picked or snapped to.
if self.out.len() + 1 >= MAX_ENTITIES {
return;
}
self.push(EntityKind::Hatch(Hatch {
pattern: "SOLID".into(),
solid: true,
loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
style: 0,
elevation: 0.0,
gradient: None,
origin: Vec2::ZERO,
background: None,
pattern_lines: Vec::new(),
}));
}
/// A single-line text, its style the first one whose font file the chunk names.
fn text(&mut self, t: TextChunk) {
let TextChunk { p, dir, height, width, oblique, value, font } = t;
@@ -407,17 +754,90 @@ struct TextChunk {
font: String,
}
/// The circle through three points (centre, radius), if they aren't on one line.
fn circle_through(a: Vec2, b: Vec2, c: Vec2) -> Option<(Vec2, f64)> {
let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));
if !d.is_finite() || d.abs() < 1e-12 {
/// The radius of the circle with conjugate radii `u` and `v` when they are one: as long as each
/// other and at right angles (a matrix that turns, mirrors and scales evenly).
fn round(u: Vec2, v: Vec2) -> Option<f64> {
let (lu, lv) = (u.len(), v.len());
let tol = 1e-9 * lu.max(lv);
((lu - lv).abs() <= tol && u.dot(v).abs() <= tol * lu.max(lv) && lu.is_finite() && lu > 0.0).then_some(lu)
}
/// The ellipse `c + u·cos a + v·sin a` for `a` from `a0` to `a1` (counter-clockwise in the
/// parameter): its axes from the conjugate radii `u` and `v`, the arc carried over to the
/// ellipse's own parameter (counter-clockwise from its major axis).
fn ellipse(c: Vec2, u: Vec2, v: Vec2, a0: f64, a1: f64) -> Option<Ellipse> {
use std::f64::consts::{FRAC_PI_2, TAU};
// c + u·cos a + v·sin a = c + p·cos(a − t) + q·sin(a − t): p and q at right angles.
let t = 0.5 * (2.0 * u.dot(v)).atan2(u.len2() - v.len2());
let p = u * t.cos() + v * t.sin();
let q = v * t.cos() - u * t.sin();
// The ellipse turns counter-clockwise with its parameter only when q is p turned left;
// a mirroring matrix reverses it.
let mirrored = p.cross(q) < 0.0;
let q = if mirrored { -q } else { q };
let (mut s0, mut s1) = if mirrored { (t - a1, t - a0) } else { (a0 - t, a1 - t) };
// The major axis is the longer of p and q.
let (major, minor) = if q.len() > p.len() {
s0 -= FRAC_PI_2;
s1 -= FRAC_PI_2;
(q, p.len())
} else {
(p, q.len())
};
let ratio = minor / major.len();
if !(c.is_finite() && major.is_finite() && major.len() > 0.0 && ratio.is_finite() && ratio > 0.0) {
return None;
}
let (a2, b2, c2) = (a.x * a.x + a.y * a.y, b.x * b.x + b.y * b.y, c.x * c.x + c.y * c.y);
let center =
Vec2::new((a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d, (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d);
let r = (a - center).len();
(center.is_finite() && r.is_finite() && r > 0.0).then_some((center, r))
let full = (a1 - a0) >= TAU - 1e-9;
let (start, end) = if full { (0.0, TAU) } else { (s0.rem_euclid(TAU), s1.rem_euclid(TAU)) };
Some(Ellipse { center: c.to3(0.0), major: major.to3(0.0), ratio, start, end })
}
/// The circle through three points (centre, radius), if they aren't on one line.
fn circle_through(a: Vec2, b: Vec2, c: Vec2) -> Option<(Vec2, f64)> {
cadcraft_geom::Circle::from_3_points(a, b, c).filter(|f| f.radius > 0.0).map(|f| (f.center, f.radius))
}
const X: Vec3 = Vec3 { x: 1.0, y: 0.0, z: 0.0 };
const Y: Vec3 = Vec3 { x: 0.0, y: 1.0, z: 0.0 };
/// The circle through three points in space: its centre, radius and the unit vectors `e1`, `e2`
/// of its plane. For points of equal `z` they are X and Y, so angles are the chunk's.
struct Fit3 {
center: Vec3,
radius: f64,
e1: Vec3,
e2: Vec3,
}
impl Fit3 {
/// The fit, if the points aren't on one line (relative to the triangle's size, so it holds at
/// any scale).
fn through(p1: Vec3, p2: Vec3, p3: Vec3) -> Option<Fit3> {
let (u, v) = (p2 - p1, p3 - p1);
let w = u.cross(v);
let w2 = w.dot(w);
if !(w2.is_finite() && w.len() > 1e-12 * (u.len() * v.len()) && w2 > 0.0) {
return None;
}
// The centre in point-relative coordinates: ((|u|² v − |v|² u) × w) / (2 |w|²).
let center = p1 + (v * u.dot(u) - u * v.dot(v)).cross(w) * (0.5 / w2);
let radius = (p1 - center).len();
// The plane's normal towards +Z (which way the arc turns comes from the middle point), and
// X (or Y) laid into the plane.
let up = if w.z < 0.0 { -1.0 } else { 1.0 };
let n = w * (up / w.len());
let along = |a: Vec3| a - n * a.dot(n);
let e1 = if along(X).len() > 1e-6 { along(X).normalized() } else { along(Y).normalized() };
let e2 = n.cross(e1);
(center.is_finite() && radius.is_finite() && radius > 0.0 && e2.is_finite()).then_some(Fit3 { center, radius, e1, e2 })
}
/// The angle of `p` around the centre, from `e1` towards `e2`.
fn angle(&self, p: Vec3) -> f64 {
let d = p - self.center;
d.dot(self.e2).atan2(d.dot(self.e1))
}
}
/// The little-endian u32 at `at`, if `bytes` holds one there.
@@ -591,15 +1011,160 @@ mod tests {
assert!(matches!(&e.kind, EntityKind::LwPolyline(p) if p.vertices.len() == 3 && !p.closed));
}
/// ATTRIBUTE_FILL is a trait like the colour: 1 (kAcGiFillAlways) fills every polygon and
/// circle until a 2 (kAcGiFillNever) ends it, whatever is drawn in between. AutoCAD
/// Mechanical writes 2 before its balloons' circles and 1 before their arrowheads and dots.
#[test]
fn a_filled_polygon_is_a_solid_hatch_and_fill_applies_once() {
fn fill_is_a_trait_until_turned_off() {
let mut tri = 3u32.to_le_bytes().to_vec();
for (x, y) in [(0.0, 0.0), (4.0, 0.0), (2.0, 3.0)] {
tri.extend(pt(x, y));
}
let es = proxy_entities(&graphics(&[chunk(20, &1u32.to_le_bytes()), chunk(7, &tri), chunk(7, &tri)]), &tables(), Handle(1));
assert!(matches!(&es[0].kind, EntityKind::Hatch(h) if h.solid && h.loops[0].vertices.len() == 3));
assert!(matches!(&es[1].kind, EntityKind::LwPolyline(p) if p.closed));
let mut line = 2u32.to_le_bytes().to_vec();
line.extend(pt(0.0, 0.0));
line.extend(pt(1.0, 0.0));
let mut dot = pt(5.0, 5.0);
dot.extend(0.5f64.to_le_bytes());
dot.extend(pt(0.0, 0.0));
let (on, off) = (chunk(20, &1u32.to_le_bytes()), chunk(20, &2u32.to_le_bytes()));
let es = proxy_entities(
&graphics(&[on, chunk(6, &line), chunk(7, &tri), chunk(2, &dot), chunk(7, &tri), off, chunk(7, &tri), chunk(2, &dot)]),
&tables(),
Handle(1),
);
let kinds: Vec<&str> = es.iter().map(|e| e.kind.type_name()).collect();
// A filled shape is a solid hatch with its outline on top.
assert_eq!(kinds, ["Line", "Hatch", "Polyline", "Hatch", "Circle", "Hatch", "Polyline", "Polyline", "Circle"]);
assert!(matches!(&es[1].kind, EntityKind::Hatch(h) if h.solid && h.loops[0].vertices.len() == 3));
assert!(matches!(&es[2].kind, EntityKind::LwPolyline(p) if p.closed));
// The filled circle: two half-circle arcs around its centre.
let disc: Vec<(Vec2, f64)> = match &es[3].kind {
EntityKind::Hatch(h) => h.loops[0].vertices.iter().map(|v| (v.p, v.bulge)).collect(),
other => panic!("{other:?}"),
};
assert_eq!(disc, [(Vec2::new(5.5, 5.0), 1.0), (Vec2::new(4.5, 5.0), 1.0)]);
assert!(matches!(&es[6].kind, EntityKind::LwPolyline(p) if p.closed));
}
/// A circle or arc under a matrix that scales its plane unevenly is an ellipse, measured
/// and snapped as one; one that scales evenly stays a circle or arc.
#[test]
fn circles_and_arcs_under_an_uneven_matrix_are_ellipses() {
use std::f64::consts::{FRAC_PI_2, PI, TAU};
let push = |sx: f64, sy: f64| {
let mut m = [0.0f64; 16];
(m[0], m[5], m[10], m[15], m[3]) = (sx, sy, 1.0, 1.0, 10.0);
chunk(29, &m.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>())
};
let mut circle = pt(0.0, 0.0);
circle.extend(1.0f64.to_le_bytes());
circle.extend(pt(0.0, 0.0));
let quarter = {
let mut a = pt(0.0, 0.0);
a.extend(1.0f64.to_le_bytes());
a.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
a.extend(pt(1.0, 0.0));
a.extend(FRAC_PI_2.to_le_bytes());
a.extend(0u32.to_le_bytes());
a
};
// Three points of the same quarter arc, as CIRCULAR_ARC_3P gives them.
let h = std::f64::consts::FRAC_1_SQRT_2;
let quarter_3p: Vec<u8> = [pt(1.0, 0.0), pt(h, h), pt(0.0, 1.0)].concat();
let near = |a: f64, b: f64| (a - b).abs() < 1e-9;
let ell = |e: &Entity| match &e.kind {
EntityKind::Ellipse(e) => (e.center, e.major, e.ratio, e.start, e.end),
other => panic!("{other:?}"),
};
let es = proxy_entities(&graphics(&[push(2.0, 1.0), chunk(2, &circle), chunk(4, &quarter), chunk(5, &quarter_3p)]), &tables(), Handle(1));
let (c, major, ratio, start, end) = ell(&es[0]);
assert!(c == Vec3::new(10.0, 0.0, 0.0) && near(major.x.abs(), 2.0) && near(major.y, 0.0) && near(ratio, 0.5) && (start, end) == (0.0, TAU));
for e in &es[1..] {
let (_, major, ratio, start, end) = ell(e);
// The major axis may point either way along x; the arc runs from (12, 0) to (10, 1).
let at = |t: f64| Vec2::new(10.0, 0.0) + major.xy() * t.cos() + major.xy().perp() * (ratio * t.sin());
assert!((at(start) - Vec2::new(12.0, 0.0)).len() < 1e-9 && (at(end) - Vec2::new(10.0, 1.0)).len() < 1e-9, "{start} {end}");
assert!(near((end - start).rem_euclid(TAU), FRAC_PI_2));
}
// Mirrored along x and stretched: the quarter arc runs from (10, 1) to (8, 0).
let es = proxy_entities(&graphics(&[push(-2.0, 1.0), chunk(4, &quarter)]), &tables(), Handle(1));
let (_, major, ratio, start, end) = ell(&es[0]);
let at = |t: f64| Vec2::new(10.0, 0.0) + major.xy() * t.cos() + major.xy().perp() * (ratio * t.sin());
assert!((at(start) - Vec2::new(10.0, 1.0)).len() < 1e-9 && (at(end) - Vec2::new(8.0, 0.0)).len() < 1e-9, "{start} {end}");
// A filled circle under it: a solid hatch along the ellipse, under the ellipse.
let fill = chunk(20, &1u32.to_le_bytes());
let es = proxy_entities(&graphics(&[push(2.0, 1.0), fill, chunk(2, &circle)]), &tables(), Handle(1));
match (&es[0].kind, &es[1].kind) {
(EntityKind::Hatch(h), EntityKind::Ellipse(_)) => {
let xs = h.loops[0].vertices.iter().map(|v| v.p.x);
let (lo, hi) = xs.fold((f64::MAX, f64::MIN), |(lo, hi), x| (lo.min(x), hi.max(x)));
assert!(near(lo, 8.0) && near(hi, 12.0), "{lo} {hi}");
}
other => panic!("{other:?}"),
}
// Picked and snapped by the ellipse only, not the hatch's sides.
let u = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: es };
let prims = EntityKind::Unknown(u).prims();
assert!(matches!(prims.as_slice(), [crate::entity::Prim::Ellipse(_)]), "{prims:?}");
// A tiny scale under a far translation keeps the circle: radius 1e8 at scale 1e-8 is 1.
let mut far = [0.0f64; 16];
(far[0], far[5], far[10], far[15], far[3], far[7]) = (1e-8, 1e-8, 1.0, 1.0, 1e9, 1e9);
let far = chunk(29, &far.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>());
let mut big = pt(0.0, 0.0);
big.extend(1e8f64.to_le_bytes());
big.extend(pt(0.0, 0.0));
let es = proxy_entities(&graphics(&[far, chunk(2, &big)]), &tables(), Handle(1));
assert!(matches!(&es[..], [e] if matches!(&e.kind, EntityKind::Circle(c) if (c.radius - 1.0).abs() < 1e-6)), "{es:?}");
// Even scaling, mirrored or not, keeps circles and arcs.
let es = proxy_entities(&graphics(&[push(-3.0, 3.0), chunk(2, &circle), chunk(4, &quarter), chunk(5, &quarter_3p)]), &tables(), Handle(1));
assert!(matches!(&es[0].kind, EntityKind::Circle(c) if near(c.radius, 3.0)));
for e in &es[1..] {
let angle = |a: f64, b: f64| near((a - b).rem_euclid(TAU).min((b - a).rem_euclid(TAU)), 0.0);
assert!(matches!(&e.kind, EntityKind::Arc(a) if near(a.radius, 3.0) && angle(a.start, FRAC_PI_2) && angle(a.end, PI)), "{e:?}");
}
}
/// Three-point chunks are fitted in the plane of their points, then mapped: a circle across XY
/// turned into it, points far smaller than the scale that enlarges them, and circles and arcs
/// seen edge-on.
#[test]
fn three_point_chunks_fit_in_their_own_plane() {
use std::f64::consts::TAU;
let near = |a: f64, b: f64| (a - b).abs() < 1e-9;
let p3 = |p: [f64; 3]| p.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>();
let mat = |m: [f64; 16]| chunk(29, &m.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>());
let turn = mat([0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]);
let across = [p3([0.0, 1.0, 0.0]), p3([0.0, 0.0, 1.0]), p3([0.0, -1.0, 0.0])].concat();
let tiny = mat([1e7, 0.0, 0.0, 0.0, 0.0, 1e7, 0.0, 0.0, 0.0, 0.0, 1e7, 0.0, 0.0, 0.0, 0.0, 1.0]);
let small = [p3([1e-7, 0.0, 0.0]), p3([0.0, 1e-7, 0.0]), p3([-1e-7, 0.0, 0.0])].concat();
// The arc's half is the one through the middle point.
for (m, pts, mid) in [(turn, across.clone(), Vec2::new(1.0, 0.0)), (tiny, small, Vec2::new(0.0, 1.0))] {
let es = proxy_entities(&graphics(&[m, chunk(3, &pts), chunk(5, &pts)]), &tables(), Handle(1));
assert!(matches!(&es[0].kind, EntityKind::Circle(c) if c.center.xy().len() < 1e-9 && near(c.radius, 1.0)), "{es:?}");
match &es[1].kind {
EntityKind::Arc(a) => {
let m = a.start + (a.end - a.start).rem_euclid(TAU) / 2.0;
assert!(near(a.radius, 1.0) && (Vec2::new(m.cos(), m.sin()) - mid).len() < 1e-9, "{a:?}");
}
other => panic!("{other:?}"),
}
}
// Seen edge-on (in a vertical plane, no matrix) a circle or arc is a line over all it
// covers in plan: for the arc through (0, 1) from (0, 0.6) to (0, 0.6), beyond its ends.
let edge = |pts: Vec<u8>, kind: u32| match proxy_entities(&graphics(&[chunk(kind, &pts)]), &tables(), Handle(1)).as_slice() {
[Entity { kind: EntityKind::Line(l), .. }] => {
let (lo, hi) = (l.a.y.min(l.b.y), l.a.y.max(l.b.y));
assert!(near(l.a.x, 0.0) && near(l.b.x, 0.0), "{l:?}");
(lo, hi)
}
other => panic!("{other:?}"),
};
let (lo, hi) = edge(across.clone(), 3);
assert!(near(lo, -1.0) && near(hi, 1.0));
let (lo, hi) = edge(across, 5);
assert!(near(lo, -1.0) && near(hi, 1.0));
let (lo, hi) = edge([p3([0.0, 0.6, 0.8]), p3([0.0, 1.0, 0.0]), p3([0.0, 0.6, -0.8])].concat(), 5);
assert!(near(lo, 0.6) && near(hi, 1.0), "{lo} {hi}");
}
/// A quarter arc counter-clockwise from 0°, and the same sweep around a downward normal,
@@ -675,8 +1240,137 @@ mod tests {
assert_eq!(u.proxy_graphics_bytes(), [1, 2, 3, 4, 5]);
let other = Unknown { dxf_type: "ACAD_PROXY_OBJECT".into(), ..u.clone() };
assert!(other.proxy_graphics_bytes().is_empty());
let bad = Unknown { tags: vec![tag(92, "4"), tag(310, "01zz")], ..u };
let bad = Unknown { tags: vec![tag(92, "4"), tag(310, "01zz")], ..u.clone() };
assert!(bad.proxy_graphics_bytes().is_empty());
// The size group is the first after the AcDbProxyEntity marker: a 160 or 92 before it
// belongs to the entity's common data.
let marked = Unknown {
tags: vec![
tag(100, "AcDbEntity"),
tag(160, "2"),
tag(310, "EEEE"),
tag(100, "AcDbProxyEntity"),
tag(90, "498"),
tag(92, "3"),
tag(310, "010203"),
],
..u.clone()
};
assert_eq!(marked.proxy_graphics_bytes(), [1, 2, 3]);
// A size far past the data gives the data there is.
let short = Unknown { tags: vec![tag(92, "16000000"), tag(310, "0102")], ..u };
assert_eq!(short.proxy_graphics_bytes(), [1, 2]);
}
/// Another entity saved with a picture of itself (a LARGE_RADIAL_DIMENSION) holds it in its
/// AcDbEntity part; a 92 among its own groups after that isn't taken for it. Its dimension
/// lines are POLYLINE_WITH_NORMAL chunks (type 32).
#[test]
fn a_kept_entity_draws_the_picture_in_its_acdbentity_part() {
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let mut line = 2u32.to_le_bytes().to_vec();
line.extend(pt(250.0, 150.0));
line.extend(pt(290.0, 190.0));
line.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
let g = graphics(&[chunk(32, &line)]);
let hex: String = g.iter().map(|b| format!("{b:02X}")).collect();
let size = g.len().to_string();
let u = Unknown {
dxf_type: "LARGE_RADIAL_DIMENSION".into(),
tags: vec![
tag(100, "AcDbEntity"),
tag(8, "0"),
tag(92, &size),
tag(310, &hex),
tag(100, "AcDbDimension"),
tag(2, "*D1"),
tag(100, "AcDbRadialDimensionLarge"),
tag(40, "0.785398"),
],
graphics: Vec::new(),
};
assert_eq!(u.proxy_graphics_bytes(), g);
let es = proxy_entities(&u.proxy_graphics_bytes(), &tables(), Handle(1));
assert!(
matches!(&es[..], [e] if matches!(&e.kind, EntityKind::Line(l) if l.a == Vec3::new(250.0, 150.0, 0.0) && l.b == Vec3::new(290.0, 190.0, 0.0)))
);
// Without graphics in the AcDbEntity part, a 92 in the entity's own data is not one.
let own = Unknown { tags: vec![tag(100, "AcDbEntity"), tag(8, "0"), tag(100, "AcDbSomething"), tag(92, "4"), tag(310, "01020304")], ..u };
assert!(own.proxy_graphics_bytes().is_empty());
}
/// Saving renames the layer indices by name into the written table, reading only the 310
/// groups the declared size needs: a damaged group after them doesn't stop it.
#[test]
fn layer_indices_follow_the_written_table() {
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let mut circle = pt(0.0, 0.0);
circle.extend(1.0f64.to_le_bytes());
circle.extend(pt(0.0, 0.0));
let g = graphics(&[chunk(16, &2u32.to_le_bytes()), chunk(2, &circle)]);
let hex: String = g.iter().map(|b| format!("{b:02X}")).collect();
let read: Vec<String> = ["0", "A", "B", "C"].map(String::from).to_vec();
let tables = ProxyTables { layers: read.clone(), ..ProxyTables::default() };
let u = Unknown {
dxf_type: "ACAD_PROXY_ENTITY".into(),
tags: vec![tag(100, "AcDbProxyEntity"), tag(92, &g.len().to_string()), tag(310, &hex), tag(310, "GG")],
graphics: proxy_entities(&g, &tables, Handle(1)),
};
assert_eq!(u.graphics[0].common.layer, "B");
let written: Vec<String> = ["0", "B", "C"].map(String::from).to_vec();
let tags = u.with_proxy_layers(&read, &written).expect("remapped");
let again = Unknown { tags, ..u.clone() };
assert_eq!(
proxy_entities(&again.proxy_graphics_bytes(), &ProxyTables { layers: written, ..ProxyTables::default() }, Handle(1))[0].common.layer,
"B"
);
assert_eq!(again.tags[3].value, "GG", "the group after the graphics is kept as read");
}
/// An index whose graphics stay on the layer before (99 here, past the table) doesn't make
/// the index before it (3) look contradictory when that one comes again; an index above
/// 65,535 isn't named (it resolves through the file's table), and the others still are.
#[test]
fn indices_are_named_around_kept_layers_and_huge_indices() {
let mut circle = pt(0.0, 0.0);
circle.extend(1.0f64.to_le_bytes());
circle.extend(pt(0.0, 0.0));
let read: Vec<String> = ["0", "A", "C", "B"].map(String::from).to_vec();
let tables = ProxyTables { layers: read, ..ProxyTables::default() };
let named = |indices: &[u32]| {
let mut chunks = Vec::new();
for &i in indices {
chunks.push(chunk(16, &i.to_le_bytes()));
chunks.push(chunk(2, &circle));
}
let g = graphics(&chunks);
let u = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: proxy_entities(&g, &tables, Handle(1)) };
let mut learned: Vec<(u32, Option<String>)> = u.layers_by_index(&g, indices).into_iter().collect();
learned.sort();
learned
};
assert_eq!(named(&[0, 3, 99, 3]), [(0, Some("0".into())), (3, Some("B".into())), (99, None)]);
assert_eq!(named(&[2, 70_000]), [(2, Some("C".into()))]);
// Layer 4 (past the table, so it keeps layer 0), a circle, then layers 1 and 4 at once (4
// keeps A): both circles follow index 4 in the marker decoding, on different layers.
let g = graphics(&[
chunk(16, &4u32.to_le_bytes()),
chunk(2, &circle),
chunk(16, &1u32.to_le_bytes()),
chunk(16, &4u32.to_le_bytes()),
chunk(2, &circle),
]);
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let hex: String = g.iter().map(|b| format!("{b:02X}")).collect();
let u = Unknown {
dxf_type: "ACAD_PROXY_ENTITY".into(),
tags: vec![tag(100, "AcDbProxyEntity"), tag(92, &g.len().to_string()), tag(310, &hex)],
graphics: proxy_entities(&g, &tables, Handle(1)),
};
assert_eq!(u.graphics.iter().map(|e| e.common.layer.as_str()).collect::<Vec<_>>(), ["0", "A"]);
assert!(!u.layers_by_index(&g, &[4, 1, 4]).contains_key(&4), "index 4 isn't named");
// Saved with the same table, nothing changes, so both circles stay where they are.
assert!(u.with_proxy_layers(&tables.layers, &tables.layers).is_none());
}
/// Truncated chunks, sizes past the end, huge counts and garbage draw what they can and
+75 -28
View File
@@ -271,7 +271,8 @@ fn text_box(t: &crate::Text, len: usize) -> Bounds2 {
/// geometry in real drawings. Layer "0" takes the insert's layer, which the caller has checked.
/// `off_counts`: a layer turned off counts too, as in the drawing's extents ([`extent_bounds`]).
fn in_block_visible(d: &Drawing, e: &Entity, off_counts: bool) -> bool {
// Attribute definitions are not drawn in an insert (its attribs are, see below).
// Attribute definitions are not drawn in an insert (its attribs are, see below), except
// constant ones, which the insert's bounds add on their own.
!matches!(e.kind, EntityKind::AttDef(_)) && e.common.visible && layer_counts(d, &e.common.layer, off_counts)
}
@@ -291,6 +292,72 @@ fn attrib_layer<'a>(d: &'a Drawing, ins: &crate::Insert, a: &'a crate::Attrib) -
})
}
/// The bounds of a block's contents, in block coordinates: its geometry, which every reference to
/// the block shows, and the value of each constant attribute definition ATTMODE shows, by tag, which
/// only a block reference draws (a dimension's block does not), and only when the reference
/// carries no attribute of that tag. They are kept apart so that the one cache serves every
/// reference, whichever asks first.
struct Contents<'a> {
geometry: Bounds2,
constants: Vec<(&'a str, Bounds2)>,
}
impl Contents<'_> {
/// What reference `ins` shows of the block: its geometry and the constant values `ins` has
/// no attribute for (that attribute is drawn instead, and counted with the attributes).
fn in_reference(&self, ins: &crate::Insert) -> Bounds2 {
self.constants
.iter()
.filter(|(tag, _)| !ins.attribs.iter().any(|r| r.tag.eq_ignore_ascii_case(tag)))
.fold(self.geometry, |b, (_, c)| b.union(c))
}
}
/// [`Contents`] of `blk` referenced at `depth`, measured once and kept in `blocks`.
fn contents<'a, 'm>(
d: &'a Drawing,
blk: &'a crate::Block,
depth: usize,
blocks: &'m mut HashMap<(&'a str, usize), Contents<'a>>,
off_counts: bool,
) -> Option<&'m Contents<'a>> {
let key = (blk.name.as_str(), depth);
if !blocks.contains_key(&key) {
let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new() };
// ATTMODE, as the renderer applies it to a constant value: 0 shows none, 1 the visible
// ones, 2 all of them.
let attmode = d.header.i64("ATTMODE", 1);
for be in blk.entities.iter() {
match &be.kind {
EntityKind::AttDef(a)
if a.constant
&& attmode != 0
&& (!a.invisible || attmode == 2)
&& be.common.visible
&& layer_counts(d, &be.common.layer, off_counts) =>
{
c.constants.push((a.tag.as_str(), constant_box(a, be.common.matches_layout_orientation())));
}
_ if in_block_visible(d, be, off_counts) => c.geometry = c.geometry.union(&bounds_in(d, be, depth + 1, blocks, off_counts)),
_ => {}
}
}
blocks.insert(key, c);
}
blocks.get(&key)
}
/// The box of a constant attribute definition's value, as a block reference draws it: upright
/// when the definition matches the layout's orientation, like other text (#2498).
fn constant_box(a: &crate::Attrib, upright: bool) -> Bounds2 {
let turn = |r: f64| if upright { 0.0 } else { r };
match a.multiline_text() {
Some(m) if !blank(&m.contents) => mtext_box(&crate::MText { rotation: turn(m.rotation), ..m }),
None if !blank(&a.text.value) => text_box(&crate::Text { rotation: turn(a.text.rotation), ..a.text.clone() }, a.text.value.chars().count()),
_ => Bounds2::EMPTY,
}
}
/// A text that draws no glyph (empty, or only blanks and non-breaking spaces) takes no room.
fn blank(s: &str) -> bool {
s.replace("\\~", " ").chars().all(char::is_whitespace)
@@ -344,9 +411,9 @@ pub fn extent_bounds(d: &Drawing, e: &Entity) -> Bounds2 {
#[derive(Default)]
pub struct BlockBoundsCache<'a> {
/// By block name and depth, block contents on layers turned off left out ([`entity_bounds`]).
drawn: HashMap<(&'a str, usize), Bounds2>,
drawn: HashMap<(&'a str, usize), Contents<'a>>,
/// The same with those contents counted ([`extent_bounds`]).
extents: HashMap<(&'a str, usize), Bounds2>,
extents: HashMap<(&'a str, usize), Contents<'a>>,
}
/// [`entity_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`.
@@ -359,7 +426,7 @@ pub fn extent_bounds_cached<'a>(d: &'a Drawing, e: &Entity, cache: &mut BlockBou
bounds_of(d, e, 0, true, &mut cache.extents)
}
fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blocks: &mut HashMap<(&'a str, usize), Bounds2>) -> Bounds2 {
fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blocks: &mut HashMap<(&'a str, usize), Contents<'a>>) -> Bounds2 {
// A top-level annotative object measures as it draws at the current annotation scale.
if depth == 0 {
match d.anno_draw(e) {
@@ -378,7 +445,7 @@ fn unknown_bounds<'a>(
d: &'a Drawing,
u: &crate::Unknown,
depth: usize,
blocks: &mut HashMap<(&'a str, usize), Bounds2>,
blocks: &mut HashMap<(&'a str, usize), Contents<'a>>,
off_counts: bool,
) -> Bounds2 {
if u.graphics.is_empty() {
@@ -399,7 +466,7 @@ fn unknown_bounds<'a>(
/// definition per depth instead of one per reference (which grows exponentially with the nesting
/// depth). The depth is part of the key because [`MAX_BLOCK_DEPTH`] cuts a deep visit short: its
/// bounds must not stand in for a shallower reference to the same block (#706).
fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<(&'a str, usize), Bounds2>, off_counts: bool) -> Bounds2 {
fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<(&'a str, usize), Contents<'a>>, off_counts: bool) -> Bounds2 {
match &e.kind {
EntityKind::Table(t) if t.is_broken() => t.bounds(),
EntityKind::Text(t) if blank(&t.value) => Bounds2::EMPTY,
@@ -422,17 +489,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
let mut b = Bounds2::EMPTY;
if let Some(blk) = d.block(&ins.block) {
let m = ins.transform(blk.base.xy());
let inner = match blocks.get(&(blk.name.as_str(), depth)) {
Some(b) => *b,
None => {
let mut inner = Bounds2::EMPTY;
for be in blk.entities.iter().filter(|be| in_block_visible(d, be, off_counts)) {
inner = inner.union(&bounds_in(d, be, depth + 1, blocks, off_counts));
}
blocks.insert((blk.name.as_str(), depth), inner);
inner
}
};
let inner = contents(d, blk, depth, blocks, off_counts).map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) };
// XCLIP: the reference app takes the boundary's box, also where it reaches past the
// block or misses it (an inverted clip can show anything, so it keeps the block's).
@@ -491,17 +548,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
// Reuse the shared block-bounds cache (as the Insert branch does) so a dimension
// block with branching or self-referencing children costs one pass per definition
// per depth, not one per reference (which grows exponentially) (CWE-400).
let inner = match blocks.get(&(blk.name.as_str(), depth)) {
Some(cached) => *cached,
None => {
let mut inner = Bounds2::EMPTY;
for be in blk.entities.iter().filter(|be| in_block_visible(d, be, off_counts)) {
inner = inner.union(&bounds_in(d, be, depth + 1, blocks, off_counts));
}
blocks.insert((blk.name.as_str(), depth), inner);
inner
}
};
let inner = contents(d, blk, depth, blocks, off_counts).map_or(Bounds2::EMPTY, |c| c.geometry);
// The block draws translated by the insertion point (group 12), so its bounds
// move with it (#2634); the cache above keeps the block's own bounds.
let off = dm.insertion_point.xy();
+9
View File
@@ -111,6 +111,8 @@ pub struct Drawing {
pub mline_styles: Vec<MLineStyle>,
pub blocks: BTreeMap<String, std::sync::Arc<Block>>,
pub model: EntityStore,
/// Model layout's page setup, or the default extents-to-fit setup for a new drawing.
pub model_page: Option<PageSetup>,
pub layouts: Vec<Layout>,
/// The layout a file marks active (its block is `*Paper_Space`, the others `*Paper_SpaceN`),
/// written active again. `None`, or a layout that no longer exists: the first by tab order.
@@ -158,6 +160,11 @@ pub struct Drawing {
pub portable_fonts: bool,
/// The pixels of the raster images that are loaded (IMAGE). Never written to a file.
pub rasters: Rasters,
/// The LAYER table of the file this drawing was read from, in the file's order and under
/// the layers' current names: proxy graphics name layers by their index in it, and saving
/// turns those indices into the written table's (#3094). An empty name stands for a record
/// without one. Empty for a drawing not read from a file.
pub proxy_layers: Vec<String>,
}
impl Default for Drawing {
@@ -201,6 +208,7 @@ impl Drawing {
mline_styles: vec![MLineStyle::default()],
blocks: BTreeMap::new(),
model: EntityStore::new(),
model_page: None,
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)],
active_layout: None,
views: Vec::new(),
@@ -221,6 +229,7 @@ impl Drawing {
skipped_records: BTreeMap::new(),
portable_fonts: false,
rasters: Rasters::default(),
proxy_layers: Vec::new(),
}
}
+15 -1
View File
@@ -782,6 +782,10 @@ impl Block {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PageSetup {
/// Original plot subclass and the modeled values it was read with.
/// Only edits that clone the page retain these original fields; the JSON form does not carry them.
#[serde(skip)]
pub file_plot_settings: Option<Box<FilePlotSettings>>,
pub device: String,
pub paper: String,
/// Paper size in millimetres (portrait width/height before rotation).
@@ -789,7 +793,7 @@ pub struct PageSetup {
pub height_mm: f64,
pub margins_mm: [f64; 4],
pub landscape: bool,
/// "layout" | "extents" | "display" | "window" | "limits".
/// "layout" | "extents" | "display" | "window" | "limits" | "view".
pub plot_area: String,
/// Plot window corners `[x1, y1, x2, y2]` (DXF plot layout groups 48, 49, 140, 141); used when `plot_area` is "window".
pub plot_window: [f64; 4],
@@ -838,6 +842,7 @@ pub struct PageSetup {
impl Default for PageSetup {
fn default() -> Self {
PageSetup {
file_plot_settings: None,
device: "None".into(),
paper: "ANSI A (8.50 x 11.00 Inches)".into(),
width_mm: 215.9,
@@ -862,6 +867,15 @@ impl Default for PageSetup {
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct FilePlotSettings {
/// Groups after AcDbPlotSettings and before AcDbLayout, including unmodeled fields.
/// See the Autodesk DXF Reference, LAYOUT and PLOTSETTINGS.
pub tags: Vec<craft_dxf::Tag>,
/// The interpreted page with no nested file settings, for detecting edits on save.
pub page: PageSetup,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Layout {
+126
View File
@@ -520,6 +520,21 @@ fn block_entity_with_invisible_flag_is_ignored_in_insert_extents() {
assert_eq!(d.extents(&Space::Model).max, Vec2::new(6000.0, 6000.0));
}
#[test]
fn a_visible_constant_attribute_definition_counts_in_insert_extents() {
// #3413: a reference draws a constant definition's value, so its extents reach it.
let def = |constant: bool, invisible: bool| {
let mut a = plain_attrib("C");
a.text.insert = Vec3::new(0.0, 50.0, 0.0);
(a.constant, a.invisible) = (constant, invisible);
Entity::new(Handle(2), EntityKind::AttDef(a))
};
let near = extents_pair(&drawing_with_block(def(false, false))).1;
assert!(extents_pair(&drawing_with_block(def(true, false))).1.y > near.y + 40.0);
// An invisible constant one, like a variable one, does not count.
assert_eq!(extents_pair(&drawing_with_block(def(true, true))).1, near);
}
#[test]
fn block_entity_on_frozen_layer_is_ignored_and_on_a_layer_turned_off_counts() {
let mut d = drawing_with_block(far_line("Hidden"));
@@ -764,3 +779,114 @@ fn dim_style_spellings_of_one_field_apply_once() {
assert!(st.apply_fields(m).is_empty());
assert_eq!(st.text_height, want);
}
/// A dimension's block in a parent block: `first` the dimension, or the reference to the same
/// block "B" (a line and a visible constant attribute definition at y = 50).
fn parent_of_dimension_and_insert(dimension_first: bool) -> Drawing {
// Only "P" is referenced from model space, so "B" is measured inside it and nowhere else.
let mut d = Drawing::new_imperial();
let mut b = Block::new("B");
b.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
let mut a = plain_attrib("C");
a.text.insert = Vec3::new(0.0, 50.0, 0.0);
a.constant = true;
b.entities.push(Entity::new(Handle(2), EntityKind::AttDef(a)));
d.blocks.insert("B".into(), std::sync::Arc::new(b));
let dim = EntityKind::Dimension(Dimension {
kind: DimKind::Linear { rotation: 0.0 },
defpt: Vec3::new(1.0, 1.0, 0.0),
text_mid: Vec3::new(0.5, 1.0, 0.0),
p13: Vec3::ZERO,
p14: Vec3::new(1.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 1.0,
text_rotation: 0.0,
user_text_pos: false,
block: Some("B".into()),
overrides: Default::default(),
assoc: vec![],
marks: Default::default(),
insertion_point: Vec3::ZERO,
});
let mut kids = vec![dim, plain_insert("B")];
if !dimension_first {
kids.reverse();
}
let mut parent = Block::new("P");
for (i, k) in kids.into_iter().enumerate() {
parent.entities.push(Entity::new(Handle(i as u64 + 10), k));
}
d.blocks.insert("P".into(), std::sync::Arc::new(parent));
d.add(&Space::Model, Common::default(), plain_insert("P")).unwrap();
d
}
#[test]
fn constant_values_count_whichever_reference_measures_the_block_first() {
// A dimension's block draws no constant value, a block reference does, and both read one
// cache of block bounds: the reference's extents must not depend on which comes first.
let first = extents_pair(&parent_of_dimension_and_insert(true));
assert_eq!(first, extents_pair(&parent_of_dimension_and_insert(false)));
assert!(first.1.y > 40.0, "the constant value at y = 50 counts: {first:?}");
}
#[test]
fn a_constant_value_that_matches_the_layout_orientation_is_measured_upright() {
// Drawn upright whatever rotation is stored (#2498), so the extents are those of rotation 0.
let def = |rotation: f64, upright: bool| {
let mut a = plain_attrib("C");
a.text.value = "a long constant value".into();
a.text.rotation = rotation;
a.constant = true;
let mut e = Entity::new(Handle(2), EntityKind::AttDef(a));
if upright {
e.common.xdata = vec![RawTag { code: 1001, value: "AcadAnnoPO".into() }, RawTag { code: 1070, value: "1".into() }];
}
e
};
let flat = extents_pair(&drawing_with_block(def(0.0, false)));
assert_eq!(extents_pair(&drawing_with_block(def(std::f64::consts::FRAC_PI_2, true))), flat);
assert_ne!(extents_pair(&drawing_with_block(def(std::f64::consts::FRAC_PI_2, false))), flat, "a plain one keeps its rotation");
}
#[test]
fn a_constant_value_the_reference_has_an_attribute_for_does_not_count() {
// Such a reference draws its attribute, not the definition's value, so a far-off definition
// does not stretch its extents; a reference without that attribute still shows the value.
let with = |attribs: Vec<Attrib>| {
let mut d = Drawing::new_imperial();
let mut blk = Block::new("B");
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
let mut a = plain_attrib("C");
a.text.insert = Vec3::new(0.0, 5000.0, 0.0);
a.constant = true;
blk.entities.push(Entity::new(Handle(2), EntityKind::AttDef(a)));
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
ins.attribs = attribs;
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
extents_pair(&d).1
};
assert!(with(vec![]).y > 4000.0);
assert!(with(vec![plain_attrib("c")]).y < 100.0);
}
#[test]
fn constant_values_count_in_extents_as_attmode_shows_them() {
// The renderer shows no constant value at ATTMODE 0, and the invisible ones too at 2.
let top = |attmode: i64, invisible: bool| {
let mut a = plain_attrib("C");
a.text.insert = Vec3::new(0.0, 50.0, 0.0);
(a.constant, a.invisible) = (true, invisible);
let mut d = drawing_with_block(Entity::new(Handle(2), EntityKind::AttDef(a)));
d.header.set_i64("ATTMODE", attmode);
extents_pair(&d).1.y
};
assert!(top(1, false) > 40.0);
assert!(top(0, false) < 40.0, "ATTMODE 0 hides it");
assert!(top(1, true) < 40.0);
assert!(top(2, true) > 40.0, "ATTMODE 2 shows an invisible one");
}
+1
View File
@@ -14,6 +14,7 @@ cadcraft-color = { workspace = true }
cadcraft-doc = { workspace = true }
craft-mime = { workspace = true }
craft-dxf = { workspace = true }
craft-csv = { workspace = true }
cadcraft-constraints = { workspace = true }
cadcraft-fonts = { workspace = true }
cadcraft-render = { workspace = true }
+44
View File
@@ -0,0 +1,44 @@
//! Live array parameters of a running ARRAYRECT / ARRAYPOLAR: what the interactive command has
//! while it runs, read and written from the array window and kept in step with the command line.
use crate::Vec2;
/// Which array the live parameters belong to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ArrayLiveKind {
Rectangular,
Polar,
}
/// The parameters of the running array command, with the fields of the other kind left at zero.
#[derive(Clone, Debug, PartialEq)]
pub struct ArrayLive {
pub kind: ArrayLiveKind,
/// Rectangular: number of columns.
pub cols: u64,
/// Both: number of rows.
pub rows: u64,
/// Rectangular: distance between columns.
pub col_spacing: f64,
/// Both: distance between rows.
pub row_spacing: f64,
/// Both: number of levels.
pub levels: u64,
/// Both: distance between levels.
pub level_spacing: f64,
/// Both: elevation added per row.
pub row_elevation: f64,
/// Both: whether the array is associative.
pub associative: bool,
/// Polar: number of items.
pub items: u64,
/// Polar: fill angle in degrees (positive = counterclockwise).
pub fill: f64,
/// Polar: whether items are rotated.
pub rotate: bool,
/// Polar: the centre; `None` for a rectangular array.
pub center: Option<Vec2>,
/// Polar only: the angle between items, degrees, derived from items and fill.
/// `None` for Rectangular.
pub between: Option<f64>,
}
+3 -2
View File
@@ -14,7 +14,7 @@ mod draw;
mod draw2;
mod draworder;
mod edit;
mod exchange;
pub mod exchange;
pub mod file;
mod gripcmds;
mod griphot;
@@ -47,9 +47,10 @@ mod qselect;
mod selecttools;
mod settings;
mod spline_opts;
mod table;
pub mod table;
mod tolerance;
mod trimextend;
pub use trimextend::PREVIEW_MAX_PICKS as TRIM_PREVIEW_MAX_PICKS;
mod txt2mtxt;
pub use txt2mtxt::Txt2MtxtOptions;
mod ucs;
+4 -2
View File
@@ -46,7 +46,7 @@ pub(super) fn linear_kind(p1: Vec2, p2: Vec2, at: Vec2, rotation: Option<f64>, a
DimKind::Linear { rotation: rotation.unwrap_or_else(auto) }
}
/// Add a dimension. With DIMASSOC on, definition points that sit on object endpoints,
/// Add a dimension. With DIMASSOC 2, definition points that sit on object endpoints,
/// vertices or centres are attached to them (associative dimensions).
pub(super) fn add_dim(s: &mut Session, k: EntityKind) -> Result<Handle> {
let mut k = k;
@@ -74,8 +74,10 @@ pub(super) fn add_dim(s: &mut Session, k: EntityKind) -> Result<Handle> {
Ok(h)
}
/// Only DIMASSOC mode 2 attaches newly created dimensions to their source geometry.
pub(super) fn assoc_enabled(s: &Session) -> bool {
s.doc().map(|d| d.header.i64("DIMASSOC", 2) != 0).unwrap_or(false)
// Mode 1 keeps a dimension as one object without linking it to source geometry.
s.doc().map(|d| d.header.i64("DIMASSOC", 2) == 2).unwrap_or(false)
}
pub(super) fn with_assoc(k: EntityKind, assoc: Vec<DimAssoc>) -> EntityKind {
+12 -7
View File
@@ -161,17 +161,22 @@ pub(super) fn run_dimtedit(s: &mut Session, p: &Value) -> Result<Value> {
}
/// DIMSPACE: equal spacing of parallel linear dimensions from a base dimension.
/// [Auto spacing](https://help.autodesk.com/cloudhelp/2023/ENU/AutoCAD-LT-MAC/files/GUID-18DF8B02-3E43-4531-ACE0-75FA7161F209.htm)
/// uses twice the base dimension's text height.
pub(super) fn run_dimspace(s: &mut Session, p: &Value) -> Result<Value> {
let base = hex_param(p, "base").ok_or_else(|| bad("dimspace", "`base` dimension is required"))?;
let hs: Vec<Handle> = dims_of(s, &targets(s, p)?).into_iter().filter(|h| *h != base).collect();
let d = s.doc()?;
let Some(EntityKind::Dimension(b)) = d.entity(base).map(|e| e.kind.clone()) else { return Err(bad("dimspace", "`base` is not a dimension")) };
let st = d.dim_style(&b.style).cloned().unwrap_or_default().with_overrides(&b.overrides);
let spacing = p
.get("spacing")
.and_then(Value::as_f64)
.filter(|v| v.is_finite() && *v >= 0.0)
.unwrap_or(st.baseline_spacing * st.effective_scale(d.header.f64("DIMSCALE", 1.0)) * 2.0);
let spacing = p.get("spacing").and_then(Value::as_f64).filter(|v| v.is_finite() && *v >= 0.0).unwrap_or_else(|| {
let st = d.dim_style(&b.style).cloned().unwrap_or_default().with_overrides(&b.overrides);
let text_height = d
.text_style(&st.text_style)
.map(|style| style.height)
.filter(|height| height.is_finite() && *height > 0.0)
.unwrap_or_else(|| st.text_height * st.effective_scale(d.header.f64("DIMSCALE", 1.0)));
2.0 * text_height
});
let dir = match b.kind {
DimKind::Linear { rotation } => Vec2::from_angle(rotation),
DimKind::Aligned => (b.p14.xy() - b.p13.xy()).normalized(),
@@ -209,7 +214,7 @@ pub(super) fn run_dimspace(s: &mut Session, p: &Value) -> Result<Value> {
}
/// DIMSPACE at the command line: select the base dimension, select the dimensions to space, then
/// the spacing (Enter or Auto takes the DIMDLI-based default).
/// the spacing (Enter or Auto uses the base dimension's text height).
#[derive(Default)]
pub(super) struct DimSpaceM {
base: Option<Handle>,
+40
View File
@@ -318,6 +318,46 @@ fn dimtedit_and_dimspace() {
assert!((dim(&s, b).defpt.y - 1.5).abs() < 1e-9, "{:?}", dim(&s, b).defpt);
}
#[test]
fn dimspace_auto_uses_the_base_dimension_text_height_and_scale() {
let mut s = Session::new();
let text_height = 3.0;
let scale = 1.5;
s.execute("dimstyle", &json!({ "name": "Base", "DIMTXT": 2, "DIMDLI": 7, "DIMSCALE": scale })).unwrap();
let base = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 4] })).unwrap());
s.execute("dimoverride", &json!({ "handles": [base.hex()], "DIMTXT": text_height })).unwrap();
s.execute("dimstyle.current", &json!({ "name": "Standard" })).unwrap();
let first = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [20, 0], "at": [10, 20] })).unwrap());
let second = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [30, 0], "at": [15, 36] })).unwrap());
s.execute("dimspace", &json!({ "base": base.hex(), "handles": [first.hex(), second.hex()] })).unwrap();
let positions = [base, first, second].map(|handle| dim(&s, handle).defpt.y);
let expected_spacing = 2.0 * text_height * scale;
assert!((positions[0] - 4.0).abs() < 1e-9, "positions: {positions:?}");
assert!(positions.windows(2).all(|pair| (pair[1] - pair[0] - expected_spacing).abs() < 1e-9), "positions: {positions:?}");
}
#[test]
fn dimspace_auto_uses_the_base_dimension_fixed_text_style_height() {
let mut s = Session::new();
let fixed_height = 2.5;
s.execute("style", &json!({ "name": "Fixed", "height": fixed_height })).unwrap();
s.execute("dimstyle", &json!({ "name": "Base", "DIMTXSTY": "Fixed", "DIMTXT": 3, "DIMDLI": 7, "DIMSCALE": 2 })).unwrap();
let base = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 4] })).unwrap());
s.execute("dimstyle.current", &json!({ "name": "Standard" })).unwrap();
let target = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [20, 0], "at": [10, 20] })).unwrap());
s.start("dimspace").unwrap();
s.input(Input::Pick(vec![base])).unwrap();
s.input(Input::Pick(vec![target])).unwrap();
s.input(Input::Enter).unwrap();
s.input(Input::Text("Auto".into())).unwrap();
let spacing = dim(&s, target).defpt.y - dim(&s, base).defpt.y;
assert!((spacing - 2.0 * fixed_height).abs() < 1e-9, "spacing: {spacing}");
}
#[test]
fn text_style_rename_follows_block_definition_text() {
let mut s = Session::new();
+149 -9
View File
@@ -368,6 +368,19 @@ fn preview_copies(s: &Session, hs: &[Handle], mats: impl Iterator<Item = Mat3>)
fn other(m: impl Into<String>) -> EngineError {
EngineError::Other(m.into())
}
/// The fill angle (degrees) that gives `b` between `items` items, with the command
/// line's own rule and error messages.
fn fill_for_between(items: u64, b: f64) -> Result<f64> {
if !b.is_finite() || b.abs() < 1e-9 {
return Err(other("Requires a nonzero angle."));
}
let n = items.max(1) as f64;
let fill = if (b.abs() * n - 360.0).abs() < 1e-9 { 360.0 * b.signum() } else { b * (n - 1.0).max(1.0) };
if fill.abs() > 360.0 + 1e-9 {
return Err(other("The items would span more than 360 degrees; enter a smaller angle or fewer items."));
}
Ok(fill.clamp(-360.0, 360.0))
}
fn fmt(v: f64) -> String {
format!("{v:.4}")
@@ -692,6 +705,45 @@ impl RectM {
};
Ok(Step::Continue)
}
fn live(&self) -> crate::ArrayLive {
crate::ArrayLive {
kind: crate::ArrayLiveKind::Rectangular,
cols: self.cols,
rows: self.rows,
col_spacing: self.cs,
row_spacing: self.rs,
levels: self.levels,
level_spacing: self.ls,
row_elevation: self.elev,
associative: self.assoc,
items: 0,
fill: 0.0,
rotate: false,
center: None,
between: None,
}
}
/// Apply the array window's values: they are validated first, so a refused value leaves the
/// command exactly as it was.
fn apply_live(&mut self, s: &Session, v: &crate::ArrayLive) -> Result<()> {
if v.kind != crate::ArrayLiveKind::Rectangular {
return Err(other("That is a polar array; these are the rectangular parameters."));
}
if v.cols < 1 || v.rows < 1 || v.levels < 1 {
return Err(other("Requires at least one column, row and level."));
}
let levels = if v.associative { v.levels } else { 1 };
check_size(s, v.rows.saturating_mul(v.cols).saturating_mul(levels), self.objs.len())?;
if ![v.col_spacing, v.row_spacing, v.level_spacing, v.row_elevation].iter().all(|d| d.is_finite()) {
return Err(other("Requires finite distances."));
}
(self.cols, self.rows, self.levels) = (v.cols, v.rows, v.levels);
(self.cs, self.rs, self.ls, self.elev) = (v.col_spacing, v.row_spacing, v.level_spacing, v.row_elevation);
self.assoc = v.associative;
Ok(())
}
}
fn yes(b: bool) -> &'static str {
@@ -704,6 +756,16 @@ fn assoc_prompt(cur: bool) -> Prompt {
}
impl Interactive for RectM {
fn array_live(&self) -> Option<crate::ArrayLive> {
Some(self.live())
}
fn set_array_live(&mut self, s: &mut Session, v: &crate::ArrayLive) -> Result<()> {
self.apply_live(s, v)
}
fn array_set_main(&mut self) -> bool {
self.stage = RStage::Main;
true
}
fn name(&self) -> &'static str {
"ARRAYRECT"
}
@@ -996,9 +1058,15 @@ impl PolarM {
fn ready(&mut self, s: &mut Session) -> Step {
self.stage = PStage::Center;
self.assoc = assoc_default(s);
// Start at the centre prompt, pre-filled with the selection's centre.
self.center = Vec2::ZERO;
// Rows and levels default to 1.5 × the selection's size apart.
if let Ok(d) = s.doc() {
let b = bounds(d, &self.objs);
let c = b.center();
if c.is_finite() {
self.center = c;
}
let size = b.width().max(b.height());
if size.is_finite() && size > 1e-9 {
(self.rs, self.ls) = (size * 1.5, size * 1.5);
@@ -1083,9 +1151,89 @@ impl PolarM {
};
d.filter(|d| d.is_finite() && d.abs() > 1e-12).map(Some).ok_or_else(|| other("Requires a nonzero distance."))
}
fn live(&self) -> crate::ArrayLive {
crate::ArrayLive {
kind: crate::ArrayLiveKind::Polar,
cols: 0,
rows: self.rows,
col_spacing: 0.0,
row_spacing: self.rs,
levels: self.levels,
level_spacing: self.ls,
row_elevation: self.elev,
associative: self.assoc,
items: self.items,
fill: self.fill,
rotate: self.rotate,
center: Some(self.center),
between: Some(self.between()),
}
}
/// Apply the array window's values: they are validated first, so a refused value leaves the
/// command exactly as it was.
fn apply_live(&mut self, s: &Session, v: &crate::ArrayLive) -> Result<()> {
if v.kind != crate::ArrayLiveKind::Polar {
return Err(other("That is a rectangular array; these are the polar parameters."));
}
if v.items < 1 || v.rows < 1 || v.levels < 1 {
return Err(other("Requires at least one item, row and level."));
}
let levels = if v.associative { v.levels } else { 1 };
check_size(s, v.rows.saturating_mul(v.items).saturating_mul(levels), self.objs.len())?;
// The Angle between field derives the fill; an edited Fill angle always wins.
let between_changed = v.between.is_some_and(|b| !b.is_finite() || (b - self.between()).abs() > 1e-9);
let fill_changed = (v.fill - self.fill).abs() > 1e-9;
let fill = match v.between {
Some(b) if between_changed && !fill_changed => fill_for_between(v.items, b)?,
_ => v.fill,
};
if !fill.is_finite() || fill.abs() <= 0.0 || fill.abs() > 360.0 {
return Err(other("Requires a fill angle between -360 and 360 degrees (not 0)."));
}
if ![v.row_spacing, v.level_spacing, v.row_elevation].iter().all(|d| d.is_finite()) {
return Err(other("Requires finite distances."));
}
if let Some(c) = v.center
&& !c.is_finite()
{
return Err(other("Requires a finite center point."));
}
(self.items, self.rows, self.levels) = (v.items, v.rows, v.levels);
(self.rs, self.ls, self.elev) = (v.row_spacing, v.level_spacing, v.row_elevation);
self.fill = fill;
self.rotate = v.rotate;
self.assoc = v.associative;
// The centre is always taken, but the command only moves on when it actually changed;
// the window copying the prefilled centre straight back never advances.
if let Some(c) = v.center {
if c != self.center && self.stage == PStage::Center {
self.stage = PStage::Main;
}
self.center = c;
}
Ok(())
}
}
impl Interactive for PolarM {
fn array_live(&self) -> Option<crate::ArrayLive> {
Some(self.live())
}
fn set_array_live(&mut self, s: &mut Session, v: &crate::ArrayLive) -> Result<()> {
self.apply_live(s, v)
}
fn array_set_main(&mut self) -> bool {
if matches!(self.stage, PStage::Center | PStage::CenterBase | PStage::CenterBaseKey) {
return false;
}
self.stage = PStage::Main;
true
}
fn array_pick_center(&mut self) -> bool {
self.stage = PStage::Center;
true
}
fn name(&self) -> &'static str {
"ARRAYPOLAR"
}
@@ -1241,15 +1389,7 @@ impl Interactive for PolarM {
(Between, Input::Enter) => Main,
(Between, _) => match angle(&i, self.between(), &s.angle_settings())? {
Some(b) => {
if b.abs() < 1e-9 {
return Err(other("Requires a nonzero angle."));
}
let n = self.items as f64;
let fill = if (b.abs() * n - 360.0).abs() < 1e-9 { 360.0 * b.signum() } else { b * (n - 1.0).max(1.0) };
if fill.abs() > 360.0 + 1e-9 {
return Err(other("The items would span more than 360 degrees; enter a smaller angle or fewer items."));
}
self.fill = fill;
self.fill = fill_for_between(self.items, b)?;
Main
}
None => stage,
+39 -10
View File
@@ -15,7 +15,7 @@ use super::machines::{SelOutcome, SelectPhase, number};
use super::{CommandSpec, bad, bool_or, f64_or, find_command, ok, point_param, point_req, point_value, str_param, targets};
use super::has_doc;
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
use crate::{Accept, AttribAsk, AttribEntry, EngineError, Input, Interactive, Origin, Prompt, Result, Session, Step};
mod attdef;
mod attedit;
@@ -43,14 +43,14 @@ pub fn specs() -> Vec<CommandSpec> {
.menu(&["Insert", "Block..."])
.alias(&["i", "-insert", "ddinsert"])
.params("{name (\"*NAME\": exploded), file?: DXF/DWG path (defines or redefines block `name`, default the file name, from its model space; base point $INSBASE), at: [x,y], scale?: number | [x, y], rotation? (degrees), basePoint?: [x,y] (block coordinates), attribs?: {TAG: value}, explode?: bool}")
.interactive(|_| Ok(Box::new(InsertM::default()))),
.interactive(|s| Ok(Box::new(InsertM { person: s.command_origin() == Origin::Person, ..InsertM::default() }))),
CommandSpec::new("blockspalette", "Blocks Palette", run_blockspalette)
.params("{references?: bool (default true; counting reads every object)} → {blocks: [{name, description, references?}], truncated} (the app opens the Blocks palette instead)")
.enabled(has_doc)
.noundo(),
CommandSpec::new("minsert", "Multiple Insert", run_minsert)
.params("{name, file?: DXF/DWG path (as INSERT), at: [x,y], scale?: number | [x, y], rotation? (degrees), basePoint?: [x,y], attribs?: {TAG: value}, rows?: 1..32767 (default 1), columns?: 1..32767 (default 1), rowSpacing?, columnSpacing? (along the reference's own axes, not scaled with it)}")
.interactive(|_| Ok(Box::new(InsertM { minsert: true, ..InsertM::default() }))),
.interactive(|s| Ok(Box::new(InsertM { minsert: true, person: s.command_origin() == Origin::Person, ..InsertM::default() }))),
CommandSpec::new("attdef", "Define Attributes...", run_attdef)
.menu(&["Draw", "Block", "Define Attributes..."])
.alias(&["att", "-attdef"])
@@ -73,14 +73,14 @@ pub fn specs() -> Vec<CommandSpec> {
.enabled(has_doc)
.noundo(),
CommandSpec::new("blocks.reference.set", "Set Dynamic Property", run_reference_set)
.params("{handle (a dynamic block reference), name (a custom property as Properties names it: a visibility state, a lookup, a distance or \"Position1 X\"), value (lengths in drawing units)} → {properties}")
.params("{handle (a dynamic block reference), name (a custom property as Properties names it: a visibility state, a lookup, a distance, \"Position1 X\", an angle or a flip state), value (lengths in drawing units, angles in degrees; a flip state by name or 0/1)} → {properties}")
.enabled(has_doc),
CommandSpec::new("blocks.reference.grips", "Dynamic Block Grips", dyngrip::run_grips)
.params("{handle} → [{node, part: base|end|at, shape: linear|point|list, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)")
.params("{handle} → [{node, part: base|end|at|basex-endy|basey-endx, shape: linear|point|list|rotation|flip, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)")
.enabled(has_doc)
.noundo(),
CommandSpec::new("blocks.reference.grip", "Drag Dynamic Grip", dyngrip::run_grip)
.params("{handle, node (the parameter's graph id), part: base|end|at, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it")
.params("{handle, node (the parameter's graph id), part: base|end|at|basex-endy|basey-endx, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it, a rotation's circle turns its angle, a polar or XY parameter's squares move its base, end or corners")
.enabled(has_doc),
CommandSpec::new("purge", "Purge", purge::run)
.alias(&["pu", "-purge"])
@@ -858,6 +858,16 @@ struct InsertM {
rotation: Option<f64>,
/// The attributes asked for: tag, prompt, default value, and Verify (asked again).
attdefs: Vec<(String, String, String, bool)>,
/// How many of `attdefs` have their value: counted here, not by `values`, whose key is the
/// tag, so two definitions with one tag are still each asked once.
asked: usize,
/// ATTDIA 1 and a person started the command: the values are asked for in the Edit
/// Attributes dialog. A script, LISP routine or JSON call that opened INSERT has nobody to
/// answer a dialog, so it asks at the command line, even after the program is done.
dialog: bool,
/// A person started this command ([`Session::command_origin`]), fixed for its whole life:
/// only then may ATTDIA 1 open the dialog.
person: bool,
values: serde_json::Map<String, Value>,
/// Verify attributes asked again so far.
verified: usize,
@@ -889,7 +899,7 @@ impl InsertM {
s.echo("Enter attribute values");
}
// Then the Verify attributes are asked again, with the values typed.
if self.stage == InsStage::Attribs && self.values.len() >= self.attdefs.len() && self.verified < self.verifying().len() {
if self.stage == InsStage::Attribs && self.asked >= self.attdefs.len() && self.verified < self.verifying().len() {
if self.verified == 0 {
s.echo("Verify attribute values");
}
@@ -897,7 +907,7 @@ impl InsertM {
return Ok(Step::Continue);
}
if self.stage == InsStage::Attribs
&& self.values.len() >= self.attdefs.len()
&& self.asked >= self.attdefs.len()
&& let (Some(n), Some(a), Some(sc), Some(r)) = (self.name.clone(), self.at, self.scale, self.rotation)
{
let h = insert_scaled(s, &n, a, self.scale3(sc), r, self.base, &self.values, self.grid())?;
@@ -948,6 +958,8 @@ impl InsertM {
s.echo(format!("Block \"{name}\" not found."));
return Ok(());
};
// A program cannot click the dialog: it asks at the command line, as ATTDIA 0 does.
self.dialog = s.settings.attdia && self.person;
self.attdefs = if self.explode || !s.settings.attreq {
Vec::new()
} else {
@@ -962,6 +974,7 @@ impl InsertM {
})
.collect()
};
self.asked = 0;
self.name = Some(b.name.clone());
self.stage = InsStage::Point;
Ok(())
@@ -1051,7 +1064,7 @@ impl Interactive for InsertM {
InsStage::Cell(a) => Prompt::new("Specify opposite corner", Accept::POINT).corner(a),
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::NUMBER),
InsStage::Attribs => {
let (_, prompt, default, _) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default();
let (_, prompt, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
let p = Prompt::new(if prompt.is_empty() { "Enter attribute value".into() } else { prompt }, Accept::TEXT);
// No default shown when there is none ("Value:", AutoCAD 2024), not "<>".
if default.is_empty() { p } else { p.default(default) }
@@ -1258,12 +1271,16 @@ impl Interactive for InsertM {
}
}
InsStage::Attribs => {
let (tag, _, default, _) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default();
let (tag, _, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
let v = match i {
Input::Text(t) => t,
// A canvas click is no answer to a text prompt: the dialog stays up and the
// attribute is asked for again, as Verify does. Enter keeps the default.
Input::Point(_) => return Ok(Step::Continue),
_ => default,
};
self.values.insert(tag, Value::String(v));
self.asked += 1;
return self.advance(s);
}
// Enter keeps the value typed.
@@ -1301,6 +1318,18 @@ impl Interactive for InsertM {
self.grid().apply(&mut ins);
vec![EntityKind::Insert(ins)]
}
fn attribute_entry(&self) -> Option<AttribEntry> {
// Only before the first answer: values typed at the command line go on there.
if !self.dialog || self.stage != InsStage::Attribs || self.asked > 0 || self.attdefs.is_empty() {
return None;
}
let rows = self
.attdefs
.iter()
.map(|(tag, prompt, default, verify)| AttribAsk { tag: tag.clone(), prompt: prompt.clone(), default: default.clone(), verify: *verify })
.collect();
Some(AttribEntry::idle(self.name.clone().unwrap_or_default(), rows))
}
}
mod attribs;
+72 -22
View File
@@ -1,7 +1,7 @@
//! Grips of dynamic block references: `blocks.reference.grips` lists them, `blocks.reference.grip`
//! drags one (one undo step), and [`Session::start_dyn_grip`] starts the drag the UI's click on a
//! grip begins, with the reference re-evaluated under the cursor as its preview. Typing a number
//! at a distance's grip sets the distance.
//! at a distance's grip sets the distance, at a rotation grip the angle (degrees).
use cadcraft_doc::color::Color;
use cadcraft_doc::dynblock::{self, GripPart, GripShape};
@@ -30,7 +30,8 @@ pub(super) fn run_grip(s: &mut Session, p: &Value) -> Result<Value> {
.and_then(Value::as_i64)
.and_then(|n| i32::try_from(n).ok())
.ok_or_else(|| bad(cmd, "`node` (a parameter's graph id) is required"))?;
let part = str_param(p, "part").and_then(GripPart::from_name).ok_or_else(|| bad(cmd, "`part` must be base, end or at"))?;
let part =
str_param(p, "part").and_then(GripPart::from_name).ok_or_else(|| bad(cmd, "`part` must be base, end, at, basex-endy or basey-endx"))?;
let to = point_param(p, "to").ok_or_else(|| bad(cmd, "`to` [x, y] is required"))?;
drag(s, h, node, part, to).map_err(|e| bad(cmd, e))?;
let properties = dynblock::custom_properties(s.doc()?, h).map(|(_, p)| p).unwrap_or_default();
@@ -46,11 +47,25 @@ fn drag(s: &mut Session, h: Handle, node: i32, part: GripPart, to: Vec2) -> std:
return Err("the reference is on a locked layer".into());
}
let mut d = s.doc().map_err(|e| e.to_string())?.clone();
dynblock::drag_grip(&mut d, h, node, part, to)?;
drag_in(s, &mut d, h, node, part, to)?;
*s.doc_mut().map_err(|e| e.to_string())? = d;
Ok(())
}
/// Drag grip (`node`, `part`) of reference `h` to `to` in drawing `d`; an alignment grip aligns
/// the reference with the object at the cursor (within the aperture), as AutoCAD does.
fn drag_in(s: &Session, d: &mut Drawing, h: Handle, node: i32, part: GripPart, to: Vec2) -> std::result::Result<(), String> {
let alignment = dynblock::reference(d, h)
.and_then(|r| dynblock::dynamic_block(d, &r.definition))
.is_some_and(|m| m.parameters.iter().any(|p| p.node == node && matches!(p.kind, dynblock::ParameterKind::Alignment { .. })));
if !alignment {
return dynblock::drag_grip(d, h, node, part, to);
}
let aperture = s.pixel_size() * s.settings.aperture.max(1.0);
let near = crate::snap::nearest_with_direction(d, &s.space(), to, aperture, s.viewport_frozen(), h);
dynblock::align_grip(d, h, node, to, near)
}
/// The properties an object of a block draws with in reference `r`: on layer 0 it is on the
/// reference's layer, and its ByBlock colour, linetype, lineweight and transparency are the
/// reference's (as the renderer draws a block's contents).
@@ -102,7 +117,11 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
_ => None,
});
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
Entity { handle: Handle(0), common, kind: EntityKind::Text(a.text.clone()) }
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
None => EntityKind::Text(a.text.clone()),
};
Entity { handle: Handle(0), common, kind }
}));
out
}
@@ -114,11 +133,16 @@ struct DynGripEdit {
part: GripPart,
/// Where the grip is (the rubber band's start).
from: Vec2,
/// The property it changes, and whether it is a distance (a typed number sets it).
/// The property it changes, and the grip's shape (a typed number sets a distance or angle).
property: String,
distance: bool,
shape: GripShape,
/// Where the grip can stop (a value list or increments): tick marks across its travel.
stops: Vec<(Vec2, Vec2)>,
}
/// Half a tick mark's length, in pixels.
const TICK_PX: f64 = 6.0;
impl Interactive for DynGripEdit {
fn name(&self) -> &'static str {
"GRIP"
@@ -129,19 +153,22 @@ impl Interactive for DynGripEdit {
}
fn prompt(&self, _s: &Session) -> Prompt {
let (msg, accept) = if self.distance {
("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER)
} else {
("** STRETCH ** Specify stretch point", Accept::POINT)
let (msg, accept) = match self.shape {
GripShape::Linear => ("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER),
GripShape::Rotation => ("** ROTATE ** Specify rotation point or angle", Accept::POINT_OR_NUMBER),
GripShape::Alignment => ("Specify point location", Accept::POINT),
_ => ("** STRETCH ** Specify stretch point", Accept::POINT),
};
Prompt::new(msg, accept).kw(&["eXit"]).base(self.from)
let p = Prompt::new(msg, accept).kw(&["eXit"]).base(self.from);
// A rotation grip asks for an angle: Dynamic Input shows one angle box.
if self.shape == GripShape::Rotation { p.angle() } else { p }
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let to = match i {
Input::Point(p) => p,
Input::Deferred(d) => d.at,
Input::Text(t) if self.distance => {
Input::Text(t) if matches!(self.shape, GripShape::Linear | GripShape::Rotation) => {
let mut d = s.doc()?.clone();
dynblock::set_property(&mut d, self.handle, &self.property, t.trim()).map_err(EngineError::Other)?;
*s.doc_mut()? = d;
@@ -155,9 +182,30 @@ impl Interactive for DynGripEdit {
Ok(Step::Done)
}
/// The rubber band from the grip.
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
vec![crate::cmd::helpers::line(self.from, c)]
/// The rubber band from the grip, and ticks at the stops of a value list or increments.
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
let half = TICK_PX * s.pixel_size();
let mut out: Vec<EntityKind> = self
.stops
.iter()
.map(|(at, way)| {
let n = way.perp() * half;
crate::cmd::helpers::line(*at - n, *at + n)
})
.collect();
out.push(crate::cmd::helpers::line(self.from, c));
out
}
/// A rotation grip's angle at the cursor, as Properties will show it.
fn live_value(&self, s: &Session, c: Vec2) -> Option<String> {
if self.shape != GripShape::Rotation {
return None;
}
let mut d = s.doc().ok()?.clone();
dynblock::drag_grip(&mut d, self.handle, self.node, self.part, c).ok()?;
let (_, props) = dynblock::custom_properties(&d, self.handle)?;
props.into_iter().find(|p| p.name.eq_ignore_ascii_case(&self.property)).map(|p| format!("{}°", p.value))
}
/// The reference re-evaluated at the cursor, drawn as it will look (its own colours, so
@@ -165,7 +213,7 @@ impl Interactive for DynGripEdit {
fn preview_objects(&self, s: &Session, c: Vec2) -> Vec<Entity> {
let Ok(d) = s.doc() else { return Vec::new() };
let mut d = d.clone();
match dynblock::drag_grip(&mut d, self.handle, self.node, self.part, c) {
match drag_in(s, &mut d, self.handle, self.node, self.part, c) {
Ok(()) => drawn(&d, self.handle),
Err(_) => Vec::new(),
}
@@ -174,8 +222,8 @@ impl Interactive for DynGripEdit {
impl Session {
/// Start dragging grip `part` of parameter `node` of dynamic block reference `handle` (the
/// UI's click on a dynamic grip). A list grip (visibility, lookup) has no drag: the UI offers
/// its choices and sets them with `blocks.reference.set`.
/// UI's click on a dynamic grip). A list grip (visibility, lookup) or a flip grip has no
/// drag: the UI offers the choices, or flips, with `blocks.reference.set`.
pub fn start_dyn_grip(&mut self, handle: Handle, node: i32, part: GripPart) -> Result<()> {
if self.running.is_some() {
self.cancel();
@@ -184,17 +232,19 @@ impl Session {
.into_iter()
.find(|g| g.node == node && g.part == part)
.ok_or_else(|| EngineError::Other("no such grip".into()))?;
if g.shape == GripShape::List {
return Err(EngineError::Other("a list grip is chosen from, not dragged".into()));
if matches!(g.shape, GripShape::List | GripShape::Flip) {
return Err(EngineError::Other("a list or flip grip is clicked, not dragged".into()));
}
let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, distance: g.shape == GripShape::Linear };
let label = if g.shape == GripShape::Rotation { "** ROTATE **" } else { "** STRETCH **" };
let stops = dynblock::grip_stops(self.doc()?, handle, node, part);
let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, shape: g.shape, stops };
let machine = crate::guard::Guarded::wrap(Box::new(edit));
let st = self.state()?;
let (before, selection_before) = (st.doc.clone(), st.selection.clone());
self.running = Some(Running { id: "grip".into(), machine, before, selection_before });
self.pending_window = None;
self.point_mods.clear();
self.echo("** STRETCH **");
self.echo(label);
Ok(())
}
}
+3
View File
@@ -171,6 +171,8 @@ pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
frontier.extend(override_arrows(dm));
}
EntityKind::MLeader(m) => frontier.extend(m.block.as_ref().map(|b| b.block.clone())),
// A dimension kept as read draws, and is saved with, the block it names (#3438).
EntityKind::Unknown(u) => frontier.extend(u.dimension_block().map(str::to_string)),
_ => {}
}
}
@@ -188,6 +190,7 @@ pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
frontier.extend(override_arrows(dm));
}
EntityKind::MLeader(m) => frontier.extend(m.block.as_ref().map(|b| b.block.clone())),
EntityKind::Unknown(u) => frontier.extend(u.dimension_block().map(str::to_string)),
_ => {}
}
}
+3 -5
View File
@@ -9,10 +9,7 @@ use super::helpers::{arc, circle, line, lwpoly, polygon_from_edge, polygon_typed
use super::machines::number;
use super::pline_opts::{Outcome, PlineAsk};
use super::{
CommandSpec, bad, bool_or, distinct_points, f64_or, f64_req, find_command, point_param, point_req, point_value, points_param, size_param,
str_param,
};
use super::{CommandSpec, bad, bool_or, distinct_points, f64_or, f64_req, point_param, point_req, point_value, points_param, size_param, str_param};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step, snap};
@@ -32,7 +29,8 @@ use line_pline::{LineM, PlineM, run_line, run_pline};
use point::{DonutM, PointM, RayM, run_donut, run_point, run_ray};
use polygon::{PolygonM, run_polygon};
use solid::{SolidM, run_solid};
use spline::{SplineM, run_spline};
pub(super) use spline::SplineM;
use spline::run_spline;
use text::{MTextM, TextM, run_mtext, run_text};
pub(crate) use text::{justify, justify_prompt};
+34 -22
View File
@@ -1,7 +1,7 @@
use super::{
Accept, EntityKind, Input, Interactive, Prompt, Result, Session, Spline, Step, Value, Vec2, added, bad, bool_or, distinct_points, find_command,
points_param,
Accept, EntityKind, Input, Interactive, Prompt, Result, Session, Spline, Step, Value, Vec2, added, bad, bool_or, distinct_points, points_param,
};
use crate::cmd::draw2::SplineCvM;
pub(super) fn run_spline(s: &mut Session, p: &Value) -> Result<Value> {
if p.get("object").is_some() {
@@ -26,11 +26,11 @@ pub(super) fn run_spline(s: &mut Session, p: &Value) -> Result<Value> {
}
#[derive(Default)]
pub(super) struct SplineM {
pub(in crate::cmd) struct SplineM {
pts: Vec<Vec2>,
asking_method: bool,
/// `Method` > `CV` hands over to the control-vertex machine (`spline.cv`).
delegate: Option<Box<dyn Interactive>>,
/// Both entry points share Method and Object; CV handles its own points and degree.
cv: Option<SplineCvM>,
/// Knots, end tangents and fit tolerance chosen so far.
opts: cadcraft_geom::FitOptions,
/// An option asking a further question (Knots, Tangency, toLerance, Object).
@@ -38,6 +38,10 @@ pub(super) struct SplineM {
}
impl SplineM {
pub(in crate::cmd) fn cv() -> Self {
Self { cv: Some(SplineCvM::default()), ..Self::default() }
}
fn make(&self, closed: bool) -> Spline {
Spline::fit_with(&self.pts, closed, self.opts)
}
@@ -49,18 +53,25 @@ impl Interactive for SplineM {
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.opts.knots = crate::cmd::spline_opts::current_knots(s);
if let Some(cv) = &mut self.cv {
return cv.begin(s);
}
s.echo(format!("Current settings: Method=Fit Knots={}", self.opts.knots.name()));
Ok(Step::Continue)
}
fn prompt(&self, s: &Session) -> Prompt {
if let Some(d) = &self.delegate {
return d.prompt(s);
}
if let Some(a) = &self.ask {
return a.prompt(&self.opts, &self.pts);
}
if self.asking_method {
return Prompt::new("Enter spline creation method", crate::cmd::curves::KW).kw(&["Fit", "CV"]).default("Fit");
return Prompt::new("Enter spline creation method", crate::cmd::curves::KW).kw(&["Fit", "CV"]).default(if self.cv.is_some() {
"CV"
} else {
"Fit"
});
}
if let Some(cv) = &self.cv {
return cv.prompt(s);
}
match self.pts.len() {
0 => Prompt::new("Specify first point", Accept::POINT).kw(&["Method", "Knots", "Object"]),
@@ -72,9 +83,6 @@ impl Interactive for SplineM {
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if let Some(d) = &mut self.delegate {
return d.input(s, i);
}
if let Some(a) = &mut self.ask {
use crate::cmd::spline_opts::Outcome;
return match a.input(s, i, &mut self.opts, &self.pts)? {
@@ -96,21 +104,25 @@ impl Interactive for SplineM {
if self.asking_method {
match i {
Input::Keyword(k) if k == "CV" => {
let Some(factory) = find_command("spline.cv").and_then(|c| c.interactive) else {
return Err(crate::EngineError::Other("CV: not available yet".into()));
};
let mut m = factory(s)?;
self.asking_method = false;
let step = m.begin(s)?;
self.delegate = Some(m);
return Ok(step);
return self.cv.get_or_insert_with(SplineCvM::default).begin(s);
}
Input::Keyword(_) | Input::Enter => self.asking_method = false,
Input::Keyword(k) if k == "Fit" => {
self.asking_method = false;
self.cv = None;
return self.begin(s);
}
Input::Enter => self.asking_method = false,
Input::Text(_) => return Err(crate::EngineError::Other("Invalid option keyword.".into())),
_ => {}
}
return Ok(Step::Continue);
}
if let Some(cv) = &mut self.cv
&& !matches!(&i, Input::Keyword(k) if k == "Method" || k == "Object")
{
return cv.input(s, i);
}
match i {
Input::Point(p) => {
self.pts.push(p);
@@ -148,8 +160,8 @@ impl Interactive for SplineM {
}
}
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
if let Some(d) = &self.delegate {
return d.preview(s, c);
if let Some(cv) = &self.cv {
return cv.preview(s, c);
}
if self.pts.is_empty() {
return Vec::new();
+3 -2
View File
@@ -28,7 +28,8 @@ mod xline;
pub(crate) use arc::arc_machine;
use arc::{ArcContinueM, ArcV, run_arc_continue, run_arc_variant, seq};
use centermark::{CenterM, run_centerline, run_centermark};
use curves3d::{HelixM, Poly3dM, SplineCvM, run_3dpoly, run_helix, run_spline_cv};
pub(super) use curves3d::SplineCvM;
use curves3d::{HelixM, Poly3dM, run_3dpoly, run_helix, run_spline_cv};
use divide::{DivideM, run_divide, run_measure};
use ellipse::{run_ellipse_arc, run_ellipse_axis};
pub(crate) use rect::{RectM2, run_rectang2};
@@ -149,7 +150,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("spline.cv", "Control Vertices", run_spline_cv)
.menu(&["Draw", "Spline", "Control Vertices"])
.params("{control: [[x,y],...], degree?: 1..10 (default 3), closed?}")
.interactive(|_| Ok(Box::new(SplineCvM::default()))),
.interactive(|_| Ok(Box::new(super::draw::SplineM::cv()))),
CommandSpec::new("centermark", "Center Mark", run_centermark)
.menu(&["Draw", "Center Mark"])
.params("{handle | handles} (circles/arcs; lines on the CENTER linetype)")
+5 -3
View File
@@ -284,7 +284,7 @@ pub(super) fn run_spline_cv(s: &mut Session, p: &Value) -> Result<Value> {
}
#[derive(Default)]
pub(super) struct SplineCvM {
pub(in crate::cmd) struct SplineCvM {
pts: Vec<Vec2>,
degree: Option<usize>,
asking_degree: bool,
@@ -312,7 +312,9 @@ impl Interactive for SplineCvM {
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if self.asking_degree {
if let Input::Text(t) = &i {
let d = number(t).filter(|d| (1.0..=10.0).contains(d)).ok_or_else(|| other("Degree must be 1..10."))?;
let d = number(t)
.filter(|d| d.fract() == 0.0 && (1.0..=10.0).contains(d))
.ok_or_else(|| other("Degree must be a whole number from 1 to 10."))?;
self.degree = Some(d as usize);
}
self.asking_degree = false;
@@ -340,7 +342,7 @@ impl Interactive for SplineCvM {
s.add_entity(EntityKind::Spline(sp))?;
return Ok(Step::Done);
}
_ => s.echo(format!("{k}: use SPLINE for fit points.")),
_ => return Err(other("Invalid option keyword.")),
}
Ok(Step::Continue)
}
+185 -17
View File
@@ -1,5 +1,5 @@
//! Moving drawings in and out: EXPORT (DXF, DWG, SVG, PNG or PDF), IMPORT (the objects of another
//! DXF/DWG file), PREVIEW (a picture of the plot) and PUBLISH (plot several sheets at once).
//! DXF/DWG file or a PDF page), PREVIEW (a picture of the plot) and PUBLISH (plot several sheets at once).
//! ATTACH, SHARE and 3DORBIT are registered so the tool bar and command line say they are not
//! available yet.
//!
@@ -35,7 +35,11 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("import", "Import...", run_import)
.menu(&["File", "Import..."])
.alias(&["imp"])
.params("{path | data: base64, name?: \"x.dwg\"} (DXF or DWG), at?: [x,y] (default 0,0), scale?: (default 1) → {imported, handles, layers, styles, blocks}"),
.params("{path | data: base64, name?: \"x.dwg\"} (DXF or DWG; PDF pages can be imported too), at?: [x,y] (default 0,0), scale?: (default 1) → {imported, handles, layers, styles, blocks}"),
CommandSpec::new("pdfimport", "Import PDF...", run_pdfimport)
.menu(&["File", "Import PDF..."])
.alias(&["pdfi"])
.params("{path | data: base64, name?: \"x.pdf\", page?: 1.. (default 1), password?, at?: [x,y] (default 0,0), scale?: (default 1), text?: true, fills?: true, lineweights?: true} → {imported, handles, layers, pages, page, warnings?}: vector paths, fills and supported text become editable objects; raster images and other unsupported content are reported. A scanned PDF has no editable vector content"),
CommandSpec::new("export", "Export...", run_export)
.menu(&["File", "Export..."])
.alias(&["exp"])
@@ -135,28 +139,158 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- IMPORT ----------
fn run_import(s: &mut Session, p: &Value) -> Result<Value> {
let hooks = io().ok_or_else(|| bad("import", "file formats are not available in this build"))?;
/// A PDF page reader installed by the app that links the PDF library.
pub type PdfImportHook = fn(&[u8], &Value) -> std::result::Result<(Drawing, usize), String>;
static PDF_IMPORT: std::sync::OnceLock<PdfImportHook> = std::sync::OnceLock::new();
/// Install the PDF page reader used by OPEN, IMPORT and PDFIMPORT.
pub fn set_pdf_import(hook: PdfImportHook) {
let _ = PDF_IMPORT.set(hook);
}
fn is_pdf(bytes: &[u8]) -> bool {
bytes.starts_with(b"%PDF-")
}
/// Read a PDF's first page as a metric drawing when this host has installed a PDF reader.
pub(super) fn open_pdf(bytes: &[u8]) -> Option<std::result::Result<Drawing, String>> {
if !is_pdf(bytes) {
return None;
}
let read = PDF_IMPORT.get()?;
Some(read(bytes, &json!({ "unit": 25.4 / 72.0 })).and_then(|(drawing, _)| {
if drawing.model.is_empty() {
let notes = drawing.read_notes.join("; ");
let message = if notes.is_empty() {
"PDF page 1 has no editable vector content; scanned drawings need manual tracing".to_string()
} else {
format!("PDF page 1 has no editable vector content; scanned drawings need manual tracing. {notes}")
};
Err(message)
} else {
Ok(drawing)
}
}))
}
/// Read an import source from a path or base64 data.
fn source_file(cmd: &str, p: &Value, default_name: &str) -> Result<(Vec<u8>, String)> {
if let Some(path) = str_param(p, "path") {
return Ok((read_file(path)?, path.to_string()));
}
let data = str_param(p, "data").ok_or_else(|| bad(cmd, "`path` or `data` (base64) is required"))?;
Ok((base64_decode(data).ok_or_else(|| bad(cmd, "invalid base64"))?, str_param(p, "name").unwrap_or(default_name).to_string()))
}
/// Parse the optional insertion point and scale shared by import commands.
fn placement(cmd: &str, p: &Value) -> Result<(Vec2, f64)> {
let at = match p.get("at") {
Some(v) => point_value(v).ok_or_else(|| bad("import", "`at` must be a point [x, y]"))?,
Some(v) => point_value(v).ok_or_else(|| bad(cmd, "`at` must be a point [x, y]"))?,
None => Vec2::ZERO,
};
let scale = match p.get("scale") {
Some(v) => v
.as_f64()
.filter(|k| k.is_finite() && (1e-9..=1e9).contains(&k.abs()))
.ok_or_else(|| bad("import", "`scale` must be a non-zero number"))?,
Some(v) => {
v.as_f64().filter(|k| k.is_finite() && (1e-9..=1e9).contains(&k.abs())).ok_or_else(|| bad(cmd, "`scale` must be a non-zero number"))?
}
None => 1.0,
};
let (bytes, name) = if let Some(path) = str_param(p, "path") {
(read_file(path)?, path.to_string())
} else {
let data = str_param(p, "data").ok_or_else(|| bad("import", "`path` or `data` (base64) is required"))?;
(base64_decode(data).ok_or_else(|| bad("import", "invalid base64"))?, str_param(p, "name").unwrap_or("import.dxf").to_string())
};
Ok((at, scale))
}
fn source_name(name: &str) -> String {
std::path::Path::new(name).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default()
}
fn run_import(s: &mut Session, p: &Value) -> Result<Value> {
let (at, scale) = placement("import", p)?;
let (bytes, name) = source_file("import", p, "import.dxf")?;
if is_pdf(&bytes) {
return import_pdf(s, "import", p, &bytes, &name, at, scale);
}
let hooks = io().ok_or_else(|| bad("import", "file formats are not available in this build"))?;
let src = (hooks.read)(&bytes, &name).map_err(|e| bad("import", e))?;
let file = std::path::Path::new(&name).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
import_drawing(s, &src, at, scale, &file)
import_drawing(s, &src, at, scale, &source_name(&name))
}
/// Convert millimetres to the current drawing's `$INSUNITS`.
fn units_per_mm(d: &Drawing) -> f64 {
match d.header.i64("INSUNITS", 4) {
1 => 1.0 / 25.4,
2 => 1.0 / 304.8,
3 => 1.0 / 1_609_344.0,
5 => 0.1,
6 => 0.001,
7 => 1e-6,
8 => 39_370.078_74,
9 => 39.370_078_74,
10 => 1.0 / 914.4,
11 => 1e7,
12 => 1e6,
13 => 1e3,
14 => 0.01,
15 => 1e-4,
16 => 1e-5,
17 => 1e-12,
18 => 1.0 / 1.495_978_707e14,
19 => 1.0 / 9.460_730_472_580_8e18,
20 => std::f64::consts::PI / (648_000.0 * 1.495_978_707e14),
// US survey units: a survey foot is 1200/3937 m.
21 => 3937.0 / 1_200_000.0,
22 => 3937.0 / 100_000.0,
23 => 3937.0 / 3_600_000.0,
24 => 3937.0 / 6_336_000_000.0,
_ => 1.0,
}
}
fn run_pdfimport(s: &mut Session, p: &Value) -> Result<Value> {
let (at, scale) = placement("pdfimport", p)?;
let (bytes, name) = source_file("pdfimport", p, "import.pdf")?;
if !is_pdf(&bytes) {
return Err(bad("pdfimport", format!("{} is not a PDF file", source_name(&name))));
}
import_pdf(s, "pdfimport", p, &bytes, &name, at, scale)
}
fn import_pdf(s: &mut Session, cmd: &str, p: &Value, bytes: &[u8], name: &str, at: Vec2, scale: f64) -> Result<Value> {
let read = PDF_IMPORT.get().ok_or_else(|| bad(cmd, "PDF import is not available in this build"))?;
let unit = 25.4 / 72.0 * units_per_mm(s.doc()?);
let mut options = serde_json::Map::new();
options.insert("unit".into(), json!(unit));
for key in ["page", "password", "text", "fills", "lineweights"] {
if let Some(value) = p.get(key) {
options.insert(key.into(), value.clone());
}
}
let (source, pages) = read(bytes, &Value::Object(options)).map_err(|e| bad(cmd, e))?;
let page = p.get("page").and_then(Value::as_u64).unwrap_or(1);
if source.model.is_empty() {
let detail = source.read_notes.join("; ");
let message = if detail.is_empty() {
"the selected PDF page has no editable vector content; scanned drawings need manual tracing".to_string()
} else {
format!("the selected PDF page has no editable vector content; scanned drawings need manual tracing. {detail}")
};
return Err(bad(cmd, message));
}
let warnings = source.read_notes.clone();
let mut result = import_drawing(s, &source, at, scale, &source_name(name))?;
if let Some(object) = result.as_object_mut() {
object.insert("pages".into(), json!(pages));
object.insert("page".into(), json!(page));
object.insert("warnings".into(), json!(warnings));
let imported = object.get("imported").and_then(Value::as_u64).unwrap_or(0);
let mut message = format!("{imported} objects imported from page {page} of {pages} of {}", source_name(name));
if !source.read_notes.is_empty() {
message.push_str(". Some PDF content was omitted or approximated. See the command history for details.");
for note in &source.read_notes {
s.echo(note.clone());
}
}
object.insert("message".into(), json!(message));
}
Ok(result)
}
/// Copy `src`'s model space into the current space (scaled about the origin, then moved to
@@ -592,6 +726,40 @@ mod tests {
s
}
fn scanned_pdf(_: &[u8], _: &Value) -> std::result::Result<(Drawing, usize), String> {
let mut drawing = Drawing::new_metric();
drawing.read_notes.push("PDF: 1 raster image was not imported".into());
Ok((drawing, 1))
}
#[test]
fn scanned_pdf_does_not_open_or_import_as_an_empty_drawing() {
set_pdf_import(scanned_pdf);
let data = base64_encode(b"%PDF-1.7 synthetic scan");
let mut s = Session::new();
let before = s.doc().unwrap().model.len();
let open = s.execute("open", &json!({ "data": data, "name": "scan.pdf" })).unwrap_err().to_string();
assert!(open.contains("no editable vector content") && open.contains("raster image"), "{open}");
let import = s.execute("pdfimport", &json!({ "data": data, "name": "scan.pdf" })).unwrap_err().to_string();
assert!(import.contains("manual tracing") && import.contains("raster image"), "{import}");
assert_eq!(s.doc().unwrap().model.len(), before, "no empty drawing was opened or imported");
}
#[test]
fn survey_units_convert_like_their_international_counterparts() {
let per_mm = |insunits: i64| {
let mut d = Drawing::new_metric();
d.header.set_i64("INSUNITS", insunits);
units_per_mm(&d)
};
// Survey feet, inches, yards and miles beside feet, inches, yards and miles.
for (survey, international) in [(21, 2), (22, 1), (23, 10), (24, 3)] {
let ratio = per_mm(survey) / per_mm(international);
// The survey unit is two parts per million longer.
assert!(ratio < 1.0 && ratio > 1.0 - 1e-5, "INSUNITS {survey}: {ratio}");
}
}
fn temp(name: &str) -> std::path::PathBuf {
std::env::temp_dir().join(format!("cadcraft-exchange-{}-{name}", std::process::id()))
}
+9 -4
View File
@@ -16,7 +16,7 @@ use super::{CommandSpec, EngineError, Interactive, always, bad, bool_or, find_co
use crate::{Accept, Input, Prompt, Result, Session, Step};
/// The rules the Command Aliases dialog checks before it sends an alias to ALIASEDIT.
pub use pgp::{MAX_ALIAS_PROFILE_BYTES, MAX_ALIASES, alias_name, alias_profile, command_id, restore_aliases};
pub use pgp::{MAX_ALIAS_PROFILE_BYTES, MAX_ALIASES, alias_name, alias_profile, command_id, restore_aliases, user_alias_command};
pub(crate) use pgp::{greek_alias, specs as alias_specs, user_alias};
pub use template::{qnew_template, set_qnew_template};
@@ -382,11 +382,16 @@ pub fn finish_open(s: &mut Session, f: ReadFile) -> Result<Value> {
/// Parse a drawing's bytes, and search its folder for fonts where the automation roots allow.
fn read_bytes(bytes: &[u8], name: &str, path: Option<String>) -> Result<ReadFile> {
let hooks = io().ok_or_else(|| bad("open", "file formats are not available in this build"))?;
let drawing = (hooks.read)(bytes, name).map_err(|e| bad("open", e))?;
let drawing = match super::exchange::open_pdf(bytes) {
Some(result) => result.map_err(|e| bad("open", e))?,
None => {
let hooks = io().ok_or_else(|| bad("open", "file formats are not available in this build"))?;
(hooks.read)(bytes, name).map_err(|e| bad("open", e))?
}
};
// A file that isn't a drawing (an imported SVG) gives the drawing no file name: QSAVE then
// asks where to save instead of exporting over the original.
let path = path.filter(|p| is_drawing_file(p));
let path = path.filter(|p| is_drawing_file(p) && !bytes.starts_with(b"%PDF-"));
// The SHX fonts its text styles name are looked for beside the drawing too.
if let Some(dir) = path.as_deref().and_then(|p| std::path::Path::new(p).parent()) {
// A bare file name is in the current folder.
+15
View File
@@ -54,6 +54,21 @@ fn store() -> MutexGuard<'static, Aliases> {
USER.get_or_init(|| Mutex::new(Aliases::default())).lock().unwrap_or_else(PoisonError::into_inner)
}
/// The command a user alias stands for, `name` typed in any case; `None` when it is no user alias.
/// The interface resolves a lone typed alias with this before its own command routes, so a user
/// alias of HATCH opens the Hatch dialog as HATCH does.
pub fn user_alias_command(name: &str) -> Option<String> {
// Keys are stored with their ASCII letters in lower case. Past ASCII, the key and the name
// are compared in lower case, so `ΚΡ` finds `κρ` and `éx` finds a key stored as `Éx`.
let name = name.trim();
if let Some(command) = user_alias(&name.to_ascii_lowercase()) {
return Some(command);
}
let lower = name.to_lowercase();
let aliases = store();
aliases.map.iter().find(|(key, _)| key.to_lowercase() == lower).map(|(_, command)| command.clone())
}
/// The command a user alias stands for (`name` in lower case).
pub(crate) fn user_alias(name: &str) -> Option<String> {
store().map.get(name).cloned()
+6 -4
View File
@@ -253,14 +253,16 @@ fn run_grip_rotate(s: &mut Session, p: &Value) -> Result<Value> {
fn run_grip_scale(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let base = base_point(s, "grip.scale", p, &hs)?;
let m = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) {
Some(f) if f > 0.0 => Mat3::scale_about(base, f),
let f = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) {
Some(f) if f > 1e-12 => f,
Some(_) => return Err(bad("grip.scale", "factor must be positive")),
None => {
mode_matrix(GripMode::Scale, base, point_req("grip.scale", p, "to")?).ok_or_else(|| bad("grip.scale", "scale factor would be zero"))?
let f = base.dist(point_req("grip.scale", p, "to")?);
if f.is_finite() && f > 1e-12 { f } else { return Err(bad("grip.scale", "scale factor would be zero")) }
}
};
apply(s, &hs, &m, bool_or(p, "copy", false))
let r = super::modify::scale_entities(s, &hs, super::modify::at_elevation(s, base), f, bool_or(p, "copy", false))?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
fn run_grip_mirror(s: &mut Session, p: &Value) -> Result<Value> {
+48 -19
View File
@@ -14,7 +14,7 @@ use cadcraft_geom::{Mat3, Vec2};
use super::gripcmds::stretch_grips;
use super::helpers::line;
use super::machines::number;
use super::modify::transform_entities;
use super::modify::{at_elevation, scale_entities, transform_entities};
use crate::grips::{GripAction, GripMode, grip_action, grip_actions, mode_matrix};
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Running, Session, Step};
@@ -220,14 +220,7 @@ impl GripEdit {
}
}
/// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes).
fn edit(&mut self, s: &mut Session, to: Vec2, m: Option<Mat3>) -> Result<Step> {
let before = s.state()?.doc.clone();
let changed = match (self.mode, m) {
(GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(),
(_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(),
(_, None) => return Err(other("Invalid point.")),
};
fn finish_edit(&mut self, before: Arc<Drawing>, changed: bool) -> Result<Step> {
if !changed {
return Err(other("The objects can't be edited that way (locked, or the result would be degenerate)."));
}
@@ -240,6 +233,27 @@ impl GripEdit {
}
}
/// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes).
fn edit(&mut self, s: &mut Session, to: Vec2, m: Option<Mat3>) -> Result<Step> {
let before = s.state()?.doc.clone();
let changed = match (self.mode, m) {
(GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(),
(_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(),
(_, None) => return Err(other("Invalid point.")),
};
self.finish_edit(before, changed)
}
/// Scale `targets` uniformly about `base` in 3D, scaling text heights, elevations and thickness.
fn edit_scale(&mut self, s: &mut Session, f: f64) -> Result<Step> {
if !f.is_finite() || f <= 1e-12 {
return Err(other("Invalid point."));
}
let before = s.state()?.doc.clone();
let changed = !scale_entities(s, &self.targets, at_elevation(s, self.base), f, self.copy)?.is_empty();
self.finish_edit(before, changed)
}
fn mode_input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Keyword(k) => match k.as_str() {
@@ -286,12 +300,20 @@ impl GripEdit {
Ok(Step::Continue)
}
Input::Point(p) => {
let m = self.matrix(p);
self.edit(s, p, m)
if self.mode == GripMode::Scale {
self.edit_scale(s, self.base.dist(p))
} else {
let m = self.matrix(p);
self.edit(s, p, m)
}
}
Input::Deferred(d) => {
let m = self.matrix(d.at);
self.edit(s, d.at, m)
if self.mode == GripMode::Scale {
self.edit_scale(s, self.base.dist(d.at))
} else {
let m = self.matrix(d.at);
self.edit(s, d.at, m)
}
}
Input::Text(t) => match self.mode {
GripMode::Rotate => {
@@ -300,7 +322,7 @@ impl GripEdit {
}
GripMode::Scale => {
let f = positive(number(&t))?;
self.edit(s, self.base, Some(Mat3::scale_about(self.base, f)))
self.edit_scale(s, f)
}
_ => Err(other("Requires a point or an option keyword.")),
},
@@ -327,14 +349,21 @@ impl GripEdit {
(Ask::RefFirst, Input::Text(t)) => self.ask = Ask::RefNew(value(&t)?),
(Ask::RefFirst, Input::Enter) => self.ask = Ask::RefNew(if rotate { 0.0 } else { 1.0 }),
(Ask::RefSecond(a), Input::Point(p)) => self.ask = Ask::RefNew(between(a, p)?),
(Ask::RefNew(_), Input::Point(p)) => {
let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?;
return self.edit(s, p, Some(m));
(Ask::RefNew(r), Input::Point(p)) => {
if rotate {
let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?;
return self.edit(s, p, Some(m));
}
let f = positive(Some(self.base.dist(p) / r))?;
return self.edit_scale(s, f);
}
(Ask::RefNew(r), Input::Text(t)) => {
let v = value(&t)?;
let m = if rotate { Mat3::rotate_about(self.base, v - r) } else { Mat3::scale_about(self.base, positive(Some(v / r))?) };
return self.edit(s, self.base, Some(m));
if rotate {
return self.edit(s, self.base, Some(Mat3::rotate_about(self.base, v - r)));
}
let f = positive(Some(v / r))?;
return self.edit_scale(s, f);
}
(_, Input::Enter) => self.ask = Ask::Mode,
_ => {}
+143 -11
View File
@@ -4,15 +4,15 @@
//! the drawing as a crossed-out frame.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, PoisonError};
use cadcraft_doc::{Drawing, EntityKind, Image, Raster};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
use super::file::base64_decode;
use super::{CommandSpec, bad, f64_or, point_param, str_param};
use super::{CommandSpec, bad, point_value, str_param};
use crate::{Result, Session};
/// Most image files loaded per drawing.
@@ -27,6 +27,9 @@ const MAX_IMAGE_BASE64: u64 = MAX_IMAGE_BYTES.div_ceil(3) * 4;
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 bytes one decoded image takes: the image reader decodes at most 128 million pixels, four
/// bytes each (`cadcraft_io::raster::MAX_IMAGE_PIXELS`).
const MAX_DECODED_BYTES: u64 = 512_000_000;
/// Most image files decoded at the same time when a drawing opens.
const MAX_LOADERS: usize = 4;
/// Longest image path taken from a caller.
@@ -183,13 +186,11 @@ fn over_limit(path: &str) -> String {
/// what opening a drawing with large images waits for). The results are in the order of `paths`.
fn decode_files(paths: &[&str], host: Option<&str>) -> Vec<std::result::Result<Raster, String>> {
// Decoded bytes so far, shared by the loaders: past the limit no further file is started.
let decoded_bytes = AtomicU64::new(0);
let budget = Budget::default();
let load = |path: &str| -> std::result::Result<Raster, String> {
if decoded_bytes.load(Ordering::Relaxed) > MAX_LOADED_BYTES {
return Err(format!("not loaded (more than {} MB of images)", MAX_LOADED_BYTES >> 20));
}
let mut decoding = budget.start().ok_or_else(|| format!("not loaded (more than {} MB of images)", MAX_LOADED_BYTES >> 20))?;
let r = read_file(path, host).and_then(|bytes| decode(&bytes))?;
decoded_bytes.fetch_add(bytes_of(&r), Ordering::Relaxed);
decoding.bytes = bytes_of(&r);
Ok(r)
};
let mut results: Vec<Option<std::result::Result<Raster, String>>> = paths.iter().map(|_| None).collect();
@@ -224,6 +225,83 @@ fn decode_files(paths: &[&str], host: Option<&str>) -> Vec<std::result::Result<R
results.into_iter().zip(paths).map(|(result, path)| result.unwrap_or_else(|| load(path))).collect()
}
/// The decoded bytes the loaders of one drawing share.
#[derive(Default)]
struct Budget {
spent: Mutex<Spent>,
/// Signaled when a file finishes decoding.
finished: Condvar,
}
/// Decoded bytes so far, and how many files are being decoded.
#[derive(Default)]
struct Spent {
decoded: u64,
decoding: u64,
}
/// Whether a loader may start decoding a file.
#[derive(Debug, PartialEq)]
enum Admit {
Start,
/// Not until another file finishes.
Wait,
/// The images decoded so far are past the limit.
Full,
}
impl Spent {
/// A file starts while the images decoded so far, and the largest image each file being
/// decoded can become, fit under `limit`. A file always starts when no other one is being
/// decoded, so that the images run past `limit` by one image at most.
fn admit(&mut self, limit: u64, largest: u64) -> Admit {
if self.decoded > limit {
return Admit::Full;
}
let reserved = self.decoding.saturating_add(1).saturating_mul(largest);
if self.decoding > 0 && self.decoded.saturating_add(reserved) > limit {
return Admit::Wait;
}
self.decoding = self.decoding.saturating_add(1);
Admit::Start
}
/// A file finished decoding into `bytes` (0 when it failed).
fn finish(&mut self, bytes: u64) {
self.decoding = self.decoding.saturating_sub(1);
self.decoded = self.decoded.saturating_add(bytes);
}
}
impl Budget {
/// Wait until a file may start decoding; `None` once the images decoded so far are past the
/// limit.
fn start(&self) -> Option<Decoding<'_>> {
let mut spent = self.spent.lock().unwrap_or_else(PoisonError::into_inner);
loop {
match spent.admit(MAX_LOADED_BYTES, MAX_DECODED_BYTES) {
Admit::Start => return Some(Decoding { budget: self, bytes: 0 }),
Admit::Full => return None,
Admit::Wait => spent = self.finished.wait(spent).unwrap_or_else(PoisonError::into_inner),
}
}
}
}
/// A file being decoded. Dropping it counts `bytes` as decoded and lets a waiting loader check
/// again, also when the decoding failed.
struct Decoding<'a> {
budget: &'a Budget,
bytes: u64,
}
impl Drop for Decoding<'_> {
fn drop(&mut self) {
self.budget.spent.lock().unwrap_or_else(PoisonError::into_inner).finish(self.bytes);
self.budget.finished.notify_all();
}
}
/// How many files are decoded at once: one per processor, at most [`MAX_LOADERS`] (each large
/// image needs several hundred megabytes while it is decoded) and no more than there are files.
fn loader_count(files: usize) -> usize {
@@ -268,6 +346,9 @@ pub(crate) fn run_imageattach(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(ID, "`path` is too long"));
}
let place = placement(p)?;
if p.get("name").is_some_and(|n| !(n.is_null() || n.is_string())) {
return Err(bad(ID, "`name` must be text"));
}
let raster = pixels(s, p, &path)?;
let (w, h) = (f64::from(raster.width()), f64::from(raster.height()));
// One pixel in drawing units, along the image's bottom edge (`u`) and its left edge (`v`).
@@ -305,18 +386,32 @@ struct Placement {
/// `at`, `rotation` and the width (`width`, else `scale`: an image is one unit wide at scale 1).
fn placement(p: &Value) -> Result<Placement> {
let at = point_param(p, "at").unwrap_or(Vec2::ZERO);
let at = match p.get("at") {
None | Some(Value::Null) => Vec2::ZERO,
Some(v) => point_value(v).ok_or_else(|| bad(ID, "`at` must be a point"))?,
};
if !(at.x.is_finite() && at.y.is_finite()) {
return Err(bad(ID, "`at` must be a point"));
}
// `scale` is checked even when `width` takes precedence over it.
let scale = number(p, "scale")?;
let width = match p.get("width") {
Some(v) => v.as_f64().filter(|w| w.is_finite()).ok_or_else(|| bad(ID, "`width` must be a number"))?,
None => f64_or(p, "scale", 1.0),
None => scale.unwrap_or(1.0),
};
if !(width.is_finite() && width > 0.0) {
return Err(bad(ID, "`scale` and `width` must be greater than zero"));
}
Ok(Placement { at, rotation: f64_or(p, "rotation", 0.0).to_radians(), width })
let rotation = number(p, "rotation")?.unwrap_or(0.0);
Ok(Placement { at, rotation: rotation.to_radians(), width })
}
/// The number `key` of `p`: `None` when it is omitted or null, an error when it is not a number.
fn number(p: &Value, key: &str) -> Result<Option<f64>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_f64().filter(|x| x.is_finite()).map(Some).ok_or_else(|| bad(ID, format!("`{key}` must be a number"))),
}
}
/// The pixels of the image at `path`: decoded from `data` when the caller hands the file over,
@@ -384,3 +479,40 @@ fn describe(d: &Drawing, path: &str, host: Option<&str>) -> Value {
};
json!({ "path": path, "foundAt": found_at, "status": status, "pixels": loaded.map(|r| json!([r.width(), r.height()])) })
}
#[cfg(test)]
mod tests {
use super::*;
/// A file starts only while the largest image each file being decoded can become still fits,
/// one file always starts when none is being decoded, and none starts past the limit.
#[test]
fn loaders_start_files_within_the_limit() {
let mut s = Spent::default();
// Room for two of the largest images.
assert_eq!(s.admit(10, 4), Admit::Start);
assert_eq!(s.admit(10, 4), Admit::Start);
assert_eq!(s.admit(10, 4), Admit::Wait);
s.finish(3);
assert_eq!(s.admit(10, 4), Admit::Wait, "3 decoded and two files that can become 4 each are past 10");
s.finish(5);
// Over the limit only by the one file being decoded.
assert_eq!(s.admit(10, 4), Admit::Start);
s.finish(4);
assert_eq!(s.admit(10, 4), Admit::Full);
// A failed file counts nothing.
let mut s = Spent::default();
assert_eq!(s.admit(10, 4), Admit::Start);
s.finish(0);
assert_eq!((s.decoded, s.decoding), (0, 0));
}
/// Files that fail still let the other loaders go on: every file gets a result.
#[test]
fn decode_files_finishes_when_every_file_fails() {
let paths = ["a.png", "b.png", "c.png", "d.png", "e.png", "f.png"];
let results = decode_files(&paths, None);
assert_eq!(results.len(), paths.len());
assert!(results.iter().all(std::result::Result::is_err), "none of these files exists");
}
}
+63 -6
View File
@@ -4,7 +4,7 @@ mod prompts;
mod state_prompts;
use cadcraft_color::Color;
use cadcraft_doc::{Layer, Lineweight};
use cadcraft_doc::{EntityKind, Layer, Lineweight};
use serde_json::{Value, json};
use super::machines::SelectRun;
@@ -101,7 +101,8 @@ fn run_list(s: &mut Session, _p: &Value) -> Result<Value> {
Ok(json!({ "layers": layers, "states": d.layer_states.iter().map(|st| st.name.clone()).collect::<Vec<_>>() }))
}
/// Lower-case names of layers that have objects on them (model, layouts and block definitions).
/// Lower-case names of layers that have objects on them (model, layouts and block definitions),
/// or that proxy graphics draw on: AutoCAD keeps those too.
pub fn used_layers(d: &cadcraft_doc::Drawing) -> std::collections::HashSet<String> {
let mut set = std::collections::HashSet::new();
let ents = d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter()));
@@ -113,6 +114,9 @@ pub fn used_layers(d: &cadcraft_doc::Drawing) -> std::collections::HashSet<Strin
for layer in super::blocks::object_attribs(e).iter().filter_map(|a| a.props.layer.as_ref()) {
set.insert(layer.to_ascii_lowercase());
}
if let EntityKind::Unknown(u) = &e.kind {
set.extend(u.graphics.iter().map(|g| g.common.layer.to_ascii_lowercase()));
}
}
set
}
@@ -258,6 +262,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
}
}
merge::rename_in_viewports(d, &old, &nn);
d.rename_proxy_layer(&old, &nn);
if cur.eq_ignore_ascii_case(&old) {
d.header.set_str("CLAYER", &nn);
}
@@ -302,10 +307,7 @@ fn run_delete(s: &mut Session, p: &Value) -> Result<Value> {
if name == "0" || name.eq_ignore_ascii_case("Defpoints") || d.header.str("CLAYER", "0").eq_ignore_ascii_case(&name) {
return Err(bad("layer.delete", "cannot delete layer 0, Defpoints or the current layer"));
}
let used = d.model.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&name))
|| d.layouts.iter().any(|l| l.entities.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&name)))
|| d.blocks.values().any(|b| b.entities.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&name)));
if used {
if used_layers(d).contains(&name.to_ascii_lowercase()) {
return Err(bad("layer.delete", "layer has objects on it"));
}
d.layers.retain(|l| !l.name.eq_ignore_ascii_case(&name));
@@ -778,6 +780,61 @@ mod tests {
assert!(s.doc().unwrap().layer("A").is_some());
}
/// A session with layers A, B and C and a proxy on layer 0 whose graphics draw a line on B
/// (#3094).
fn proxy_on_b() -> Session {
use cadcraft_doc::{Common, Entity, EntityKind, Handle, Line, Space, Unknown};
let mut s = Session::new();
for name in ["A", "B", "C"] {
s.execute("layer.new", &json!({ "name": name })).unwrap();
}
let line = Entity {
handle: Handle(0),
common: Common { layer: "B".into(), ..Common::default() },
kind: EntityKind::Line(Line { a: cadcraft_doc::geom::Vec3::ZERO, b: cadcraft_doc::geom::Vec3::new(1.0, 0.0, 0.0) }),
};
let proxy = EntityKind::Unknown(Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: vec![line] });
s.doc_mut().unwrap().add(&Space::Model, Common::default(), proxy).unwrap();
s
}
fn graphics_layer(s: &Session) -> String {
s.doc()
.unwrap()
.model
.iter()
.find_map(|e| match &e.kind {
cadcraft_doc::EntityKind::Unknown(u) => u.graphics.first().map(|g| g.common.layer.clone()),
_ => None,
})
.unwrap()
}
/// As in AutoCAD, PURGE and layer.delete keep a layer only proxy graphics draw on.
#[test]
fn layers_proxy_graphics_draw_on_are_in_use() {
let mut s = proxy_on_b();
assert!(s.execute("layer.delete", &json!({ "name": "B" })).is_err());
s.execute("purge", &json!({})).unwrap();
let d = s.doc().unwrap();
assert!(d.layer("B").is_some() && d.layer("A").is_none() && d.layer("C").is_none());
}
/// RENAME and LAYMRG take the graphics with the layer, LAYDEL drops them to layer 0.
#[test]
fn rename_merge_and_laydel_move_proxy_graphics() {
let mut s = proxy_on_b();
s.doc_mut().unwrap().proxy_layers = vec!["0".into(), "A".into(), "B".into(), "C".into()];
s.execute("layer.set", &json!({ "name": "B", "newName": "B2" })).unwrap();
assert_eq!(graphics_layer(&s), "B2");
assert_eq!(s.doc().unwrap().proxy_layers, ["0", "A", "B2", "C"]);
s.execute("laymrg", &json!({ "from": "B2", "to": "C" })).unwrap();
assert_eq!(graphics_layer(&s), "C");
assert_eq!(s.doc().unwrap().proxy_layers, ["0", "A", "C", "C"]);
s.execute("laydel", &json!({ "name": "C" })).unwrap();
assert_eq!(graphics_layer(&s), "0");
}
#[test]
fn rename_repoints_paper_space_and_block_entities() {
let mut s = Session::new();
+9
View File
@@ -175,6 +175,10 @@ pub(super) fn run_laymrg(s: &mut Session, p: &Value) -> Result<Value> {
hs.len()
});
forget_in_viewports(d, &set);
// Proxy graphics drawn on a merged layer move to the target, as its objects do.
for source in &sources {
d.rename_proxy_layer(source, &target);
}
d.layers.retain(|l| !set.contains(&l.name.to_ascii_lowercase()));
let mut msg = format!("Merged {} into \"{target}\": {} moved.", quoted(&sources), plural(moved, "object"));
if set.contains(&d.header.str("CLAYER", "0").to_ascii_lowercase()) {
@@ -202,6 +206,11 @@ pub(super) fn run_laydel(s: &mut Session, p: &Value) -> Result<Value> {
hs.len()
});
forget_in_viewports(d, &set);
// A proxy isn't deleted for drawing on a deleted layer (its parts can't be); they fall back
// to layer 0, the proxy's own layer.
for source in &sources {
d.rename_proxy_layer(source, "0");
}
d.layers.retain(|l| !set.contains(&l.name.to_ascii_lowercase()));
s.set_selection(Vec::new());
let msg = format!("Deleted {} and {}.", quoted(&sources), plural(erased, "object"));
+7 -3
View File
@@ -18,6 +18,7 @@ use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, St
mod break_join;
mod explode;
mod extrim;
mod fillet;
mod offset;
mod oops;
@@ -35,12 +36,15 @@ use oops::run_oops;
pub(crate) use oops::{Erased, erase_kept};
use select_then::{DisplaceM, Op, SelectThen};
use stretch::{StretchM, run_stretch};
pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities};
use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale};
pub(crate) use trim::{CUT_ONCE, Edges, extend, json_pick_error, trim};
pub(crate) use transform::{at_elevation, holds_ole_frame, ole_refusal, refuse_ole_frames, scale_entities, transform_entities};
use transform::{mirror_entities, mirror_kind, run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale};
pub(crate) use trim::{
CUT_ONCE, Edges, Overlay, edge_segments, edge_segments_over, extend, extend_kind, extended, json_pick_error, trim, trim_kind, trimmed,
};
pub fn specs() -> Vec<CommandSpec> {
vec![
extrim::spec(),
CommandSpec::new("erase", "Erase", run_erase)
.menu(&["Modify", "Erase"])
.alias(&["e", "delete"])
+719
View File
@@ -0,0 +1,719 @@
//! EXTRIM (Express Tools): every object that crosses one cutting edge loses its part on the side
//! picked. The edge is traced a hair's breadth away on that side, and each object that crossing
//! line meets is trimmed there, with the picked object as the only cutting edge. Objects that don't
//! cross the edge, and the edge itself, stay as they are.
use std::cell::RefCell;
use cadcraft_color::Color;
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, entity_bounds};
use cadcraft_geom::{Bounds2, Line, Vec2, line_line, point_in_polygon};
use serde_json::{Value, json};
use super::offset::offset_points;
use super::{Edges, trim};
use crate::cmd::helpers::lwpoly;
use crate::cmd::{CommandSpec, bad, point_param, targets};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
/// Most points of the line traced along the edge.
const MAX_FENCE: usize = 10_000;
/// Most objects one call trims.
const MAX_OBJECTS: usize = 10_000;
/// Most stretches one call removes (an object can lose several).
const MAX_STRETCHES: usize = 10_000;
/// Most objects the preview draws (beyond that it shows nothing, to keep the cursor smooth).
const MAX_PREVIEW: usize = 2000;
/// The traced line's distance from the edge, as a fraction of the edge's size.
const TRACE_GAP: f64 = 1e-5;
pub(super) fn spec() -> CommandSpec {
CommandSpec::new("extrim", "Extended Trim", run_extrim)
.menu(&["Tools", "Additional Tools", "Extended Trim"])
.params("{edge: hex (line, arc, circle, ellipse, polyline or spline), side: [x,y] (inside or outside a closed edge, an arc's circle or an elliptical arc's ellipse; one side of an open edge)} → trimmed, handles, skipped: {locked, other, uncut}")
.interactive(|s| Ok(Box::new(ExtrimM::new(s))))
}
/// Whether objects of this kind can be the cutting edge.
fn edge_kind(k: &EntityKind) -> bool {
matches!(
k,
EntityKind::Line(_) | EntityKind::Arc(_) | EntityKind::Circle(_) | EntityKind::Ellipse(_) | EntityKind::LwPolyline(_) | EntityKind::Spline(_)
)
}
/// Whether TRIM can cut objects of this kind.
fn trimmable(k: &EntityKind) -> bool {
edge_kind(k)
}
/// Whether the object closes on itself, from what it is rather than from where its ends lie: an
/// open polyline drawn back to its start is still open.
fn closed_kind(k: &EntityKind) -> bool {
match k {
EntityKind::Circle(_) => true,
EntityKind::LwPolyline(p) => p.closed,
EntityKind::Ellipse(e) => {
cadcraft_geom::Ellipse { center: e.center.xy(), major: e.major.xy(), ratio: e.ratio, start: e.start, end: e.end }.is_full()
}
EntityKind::Spline(sp) => sp.closed,
_ => false,
}
}
/// Consecutive polylines joined end to end (an object's primitives come in drawing order).
fn chains(polys: Vec<Vec<Vec2>>, tol: f64) -> Vec<Vec<Vec2>> {
let mut out: Vec<Vec<Vec2>> = Vec::new();
for p in polys.into_iter().filter(|p| p.len() >= 2) {
match out.last_mut() {
Some(cur) if cur.last().zip(p.first()).is_some_and(|(a, b)| a.near(*b, tol)) => cur.extend(p.into_iter().skip(1)),
_ => out.push(p),
}
}
out
}
/// Twice the signed area of a closed polyline (positive: counter-clockwise).
fn signed_area(pts: &[Vec2]) -> f64 {
pts.windows(2).filter_map(|w| Some(w.first()?.cross(*w.get(1)?))).sum()
}
/// Which side of the edge's direction the trace runs on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Side {
Left,
Right,
}
impl Side {
/// The trace's offset sign along the edge's left normal.
fn factor(self) -> f64 {
match self {
Side::Left => 1.0,
Side::Right => -1.0,
}
}
}
/// The full circle or ellipse an arc or elliptical arc lies on: inside and outside it, as OFFSET
/// takes them, decide the side even for a pick past the arc's ends.
#[derive(Clone, Copy)]
enum Round {
Circle { center: Vec2, radius: f64 },
Ellipse { center: Vec2, major: Vec2, ratio: f64 },
}
impl Round {
fn of(k: &EntityKind) -> Option<Round> {
match k {
EntityKind::Arc(a) => Some(Round::Circle { center: a.center.xy(), radius: a.radius }),
EntityKind::Ellipse(e) => Some(Round::Ellipse { center: e.center.xy(), major: e.major.xy(), ratio: e.ratio }),
_ => None,
}
}
fn center(self) -> Vec2 {
match self {
Round::Circle { center, .. } | Round::Ellipse { center, .. } => center,
}
}
fn inside(self, p: Vec2) -> bool {
match self {
Round::Circle { center, radius } => p.dist(center) < radius,
Round::Ellipse { center, major, ratio } => {
let a = major.len();
let b = a * ratio.abs();
let u = major.normalized();
let d = p - center;
let (x, y) = (d.dot(u) * b, d.dot(u.perp()) * a);
x * x + y * y < (a * b) * (a * b)
}
}
}
}
/// The cutting edge traced along, with the scale of the trim.
#[derive(Clone)]
struct Edge {
handle: Handle,
pts: Vec<Vec2>,
closed: bool,
/// An arc's circle (an elliptical arc's ellipse), and whether its inside is to the left of
/// the edge's direction.
round: Option<(Round, bool)>,
/// Distance of the traced line from the edge.
gap: f64,
}
impl Edge {
/// The cutting edge `h`: a line, arc, circle, ellipse, polyline or spline of the current space.
fn new(s: &Session, h: Handle) -> Result<Edge> {
let d = s.doc()?;
let e = d.entity(h).ok_or_else(|| bad("extrim", format!("no object {}", h.hex())))?;
if !edge_kind(&e.kind) {
return Err(bad("extrim", "the cutting edge must be a line, arc, circle, ellipse, polyline or spline"));
}
if d.space_of(h).as_ref() != Some(&s.space()) || !d.is_visible(e) {
return Err(bad("extrim", format!("object {} is not a visible object of the current space", h.hex())));
}
let b = entity_bounds(d, e, 0);
let size = b.width() + b.height();
if !size.is_finite() || size <= 0.0 {
return Err(bad("extrim", "the cutting edge has no length"));
}
let closed = closed_kind(&e.kind);
// A finer trace for a small edge; a coarser one when a long or curved edge would need too
// many points. The trace stays within a twentieth of the gap of the true edge, so the
// traced line never strays to the other side.
let mut gap = (size * TRACE_GAP).max(1e-9);
for _ in 0..6 {
let Some(pts) = chains(crate::select::hit_polylines(d, e, gap / 20.0), gap / 20.0).into_iter().next() else { break };
if pts.len() <= MAX_FENCE {
// The centre lies on the inside of the arc's bend.
let mid = (pts.len() / 2).max(1);
let inside_left = |r: Round| match (pts.get(mid - 1), pts.get(mid)) {
(Some(a), Some(b)) => (*b - *a).cross(r.center() - *a) > 0.0,
_ => true,
};
let round = if closed { None } else { Round::of(&e.kind) }.map(|r| (r, inside_left(r)));
return Ok(Edge { handle: h, pts, closed, round, gap });
}
gap *= 4.0;
}
Err(bad("extrim", "the cutting edge is too complex"))
}
/// Which side the trace runs on for a pick at `p`; `None` for a point on the edge.
fn side(&self, p: Vec2) -> Option<Side> {
if !p.is_finite() {
return None;
}
let segs = || self.pts.windows(2).filter_map(|w| Some(Line::new(*w.first()?, *w.get(1)?)));
let (near, dist) = segs().map(|l| (l, l.dist(p))).min_by(|a, b| a.1.total_cmp(&b.1))?;
if dist <= self.gap {
return None;
}
let left = match self.round {
_ if self.closed => {
// Inside a counter-clockwise outline is to its left.
point_in_polygon(&self.pts, p) == (signed_area(&self.pts) > 0.0)
}
Some((round, inside_left)) => round.inside(p) == inside_left,
None => (near.b - near.a).cross(p - near.closest(p)) > 0.0,
};
Some(if left { Side::Left } else { Side::Right })
}
/// The line traced beside the edge on `side`.
fn trace(&self, side: Side) -> Vec<Vec2> {
offset_points(&self.pts, self.gap * side.factor(), self.closed)
}
}
/// One stretch of an object the trim removes: where it is picked, and its outline.
struct Stretch {
pick: Vec2,
parts: Vec<Vec<Vec2>>,
}
/// Where the trim would cut: each object the trace crosses, with the stretches it loses, and
/// what it leaves alone.
#[derive(Default)]
struct Plan {
work: Vec<(Handle, Vec<Stretch>)>,
locked: usize,
other: usize,
/// Objects the edge crosses but no trim can cut there (a circle crossed once).
uncut: Vec<Handle>,
}
/// Segments of `pts` with their bounds, bucketed in a grid so crossings are found without
/// testing every pair.
struct Grid {
segs: Vec<(Line, Bounds2)>,
bounds: Bounds2,
n: usize,
cells: Vec<Vec<usize>>,
}
impl Grid {
fn new(pts: &[Vec2]) -> Grid {
let segs: Vec<(Line, Bounds2)> =
pts.windows(2).filter_map(|w| Some((Line::new(*w.first()?, *w.get(1)?), Bounds2::from_points([*w.first()?, *w.get(1)?])))).collect();
let bounds = Bounds2::from_points(pts.iter().copied());
// About as many cells as segments.
let n = ((segs.len() as f64).sqrt().ceil() as usize).clamp(1, 128);
let mut g = Grid { segs: Vec::new(), bounds, n, cells: vec![Vec::new(); n * n] };
for (i, (_, b)) in segs.iter().enumerate() {
for c in g.cells_of(b) {
if let Some(cell) = g.cells.get_mut(c) {
cell.push(i);
}
}
}
g.segs = segs;
g
}
/// The cells `b` overlaps.
fn cells_of(&self, b: &Bounds2) -> Vec<usize> {
let w = self.bounds.width().max(1e-12);
let h = self.bounds.height().max(1e-12);
let n = self.n;
let col = |x: f64| ((((x - self.bounds.min.x) / w) * n as f64).floor().max(0.0) as usize).min(n - 1);
let row = |y: f64| ((((y - self.bounds.min.y) / h) * n as f64).floor().max(0.0) as usize).min(n - 1);
let (c0, c1, r0, r1) = (col(b.min.x), col(b.max.x), row(b.min.y), row(b.max.y));
(r0..=r1).flat_map(|r| (c0..=c1).map(move |c| r * n + c)).collect()
}
/// Where segment `l` crosses the grid's segments.
fn crossings(&self, l: &Line) -> Vec<Vec2> {
let lb = Bounds2::from_points([l.a, l.b]);
if !lb.intersects(&self.bounds) {
return Vec::new();
}
let mut seen = std::collections::HashSet::new();
self.cells_of(&lb)
.into_iter()
.filter_map(|c| self.cells.get(c))
.flatten()
.filter(|i| seen.insert(**i))
.filter_map(|i| self.segs.get(*i))
.filter(|(_, b)| b.intersects(&lb))
.filter_map(|(s, _)| line_line(l, s))
.collect()
}
}
/// An object outline measured along its length, for cutting stretches out of it.
struct Outline<'a> {
pts: &'a [Vec2],
/// Distance along the outline to each point.
at: Vec<f64>,
}
impl<'a> Outline<'a> {
fn new(pts: &'a [Vec2]) -> Outline<'a> {
let mut at = Vec::with_capacity(pts.len());
let mut t = 0.0;
at.push(t);
for w in pts.windows(2) {
if let (Some(a), Some(b)) = (w.first(), w.get(1)) {
t += a.dist(*b);
}
at.push(t);
}
Outline { pts, at }
}
fn total(&self) -> f64 {
self.at.last().copied().unwrap_or(0.0)
}
/// The distances along the outline where it crosses `grid`, sorted, each once.
fn crossings(&self, grid: &Grid) -> Vec<f64> {
let mut out = Vec::new();
for (i, w) in self.pts.windows(2).enumerate() {
let (Some(a), Some(b), Some(t0)) = (w.first(), w.get(1), self.at.get(i)) else { continue };
out.extend(grid.crossings(&Line::new(*a, *b)).into_iter().map(|c| t0 + a.dist(c)));
}
out.sort_by(f64::total_cmp);
// A crossing at a vertex shows up on both segments that meet there.
let eps = self.total() * 1e-9;
out.dedup_by(|a, b| (*a - *b).abs() <= eps);
out
}
/// The part of the outline between distances `from` and `to`.
fn part(&self, from: f64, to: f64) -> Vec<Vec2> {
let mut out = Vec::new();
let first = self.at.partition_point(|t| *t < from).saturating_sub(1);
for i in first..self.pts.len().saturating_sub(1) {
let (Some(a), Some(b), Some(t0), Some(t1)) = (self.pts.get(i), self.pts.get(i + 1), self.at.get(i), self.at.get(i + 1)) else { break };
if *t0 > to {
break;
}
if *t1 < from || t1 <= t0 {
continue;
}
let p = |t: f64| *a + (*b - *a) * ((t.clamp(*t0, *t1) - t0) / (t1 - t0));
if out.is_empty() {
out.push(p(from));
}
out.push(p(to.min(*t1)));
}
out
}
}
/// The stretches of one object outline the trim removes on the traced side: between the edge
/// crossings either side of each place the trace meets the outline. Every crossing is found once.
/// `None` for a closed outline the edge crosses only once, which no trim can open.
fn stretches_of(pts: &[Vec2], closed: bool, edge: &Grid, trace: &Grid) -> Option<Vec<Vec<Vec<Vec2>>>> {
let o = Outline::new(pts);
let total = o.total();
let eps = total * 1e-9;
let mut cuts = o.crossings(edge);
if closed {
// The seam: the outline's start and end are one point, so a crossing there is one cut.
for t in &mut cuts {
if *t >= total - eps {
*t = 0.0;
}
}
cuts.sort_by(f64::total_cmp);
cuts.dedup_by(|a, b| (*a - *b).abs() <= eps);
} else {
// An object that only touches the edge with an end isn't cut there, as TRIM has it.
cuts.retain(|t| *t > eps && *t < total - eps);
}
let hits = o.crossings(trace);
if cuts.is_empty() || hits.is_empty() {
return Some(Vec::new());
}
if closed && cuts.len() < 2 {
return None;
}
let mut out = Vec::new();
// Each stretch once, however many times the trace meets it.
let mut done = std::collections::HashSet::new();
for tp in hits {
// The edge crossings either side, as indices into `cuts`.
let k = cuts.partition_point(|t| *t < tp);
let lo = k.checked_sub(1);
let hi = (k < cuts.len()).then_some(k);
let (lo, hi) = if closed { (lo.or(cuts.len().checked_sub(1)), hi.or(Some(0))) } else { (lo, hi) };
if !done.insert((lo, hi)) {
continue;
}
let at = |i: Option<usize>| i.and_then(|i| cuts.get(i).copied());
out.push(match (at(lo), at(hi)) {
// Across the seam of a closed outline.
(Some(a), Some(b)) if closed && a >= b => vec![o.part(a, total), o.part(0.0, b)],
(Some(a), Some(b)) => vec![o.part(a, b)],
(None, Some(b)) => vec![o.part(0.0, b)],
(Some(a), None) => vec![o.part(a, total)],
(None, None) => continue,
});
}
Some(out)
}
/// The trim of everything crossing `edge` on `side`, worked out without changing anything.
fn plan(d: &Drawing, space: &cadcraft_doc::Space, edge: &Edge, side: Side) -> Result<Plan> {
let trace = edge.trace(side);
let trace_grid = Grid::new(&trace);
let edge_grid = Grid::new(&edge.pts);
let tol = edge.gap / 20.0;
let mut p = Plan::default();
let mut stretches_total = 0;
for h in crate::select::select_fence(d, space, &trace) {
if h == edge.handle {
continue;
}
let Some(e) = d.entity(h) else { continue };
if !trimmable(&e.kind) {
p.other += 1;
continue;
}
if d.layer(&e.common.layer).is_some_and(|l| l.locked) || crate::cmd::blocks::refedit::locked(d, h) {
p.locked += 1;
continue;
}
let outlines = chains(crate::select::hit_polylines(d, e, tol), tol);
// A closed object is one closed outline.
let closed = closed_kind(&e.kind) && outlines.len() == 1;
let mut stretches: Vec<Stretch> = Vec::new();
for pts in &outlines {
let Some(parts) = stretches_of(pts, closed, &edge_grid, &trace_grid) else {
p.uncut.push(h);
continue;
};
for parts in parts {
// Trimmed at the middle of the stretch, well clear of the edge, so the cut
// doesn't depend on how closely the trim follows a curved edge.
let Some(pick) = parts.iter().max_by(|a, b| arc_length(a).total_cmp(&arc_length(b))).and_then(|q| midpoint(q)) else { continue };
stretches.push(Stretch { pick, parts });
}
}
stretches_total += stretches.len();
if !stretches.is_empty() {
p.work.push((h, stretches));
}
if p.work.len() > MAX_OBJECTS {
return Err(bad("extrim", format!("more than {MAX_OBJECTS} objects cross the cutting edge; trim a smaller area")));
}
if stretches_total > MAX_STRETCHES {
return Err(bad("extrim", format!("more than {MAX_STRETCHES} stretches would be trimmed; trim a smaller area")));
}
}
Ok(p)
}
fn arc_length(pts: &[Vec2]) -> f64 {
pts.windows(2).filter_map(|w| Some(w.first()?.dist(*w.get(1)?))).sum()
}
/// The point halfway along `pts`.
fn midpoint(pts: &[Vec2]) -> Option<Vec2> {
let mut left = arc_length(pts) / 2.0;
for w in pts.windows(2) {
let (a, b) = (*w.first()?, *w.get(1)?);
let l = a.dist(b);
if l >= left && l > 0.0 {
return Some(a + (b - a) * (left / l));
}
left -= l;
}
pts.last().copied()
}
/// The length of an object's drawn outline.
fn length(d: &Drawing, e: &Entity, tol: f64) -> f64 {
crate::select::hit_polylines(d, e, tol).iter().flat_map(|pl| pl.windows(2).filter_map(|w| Some(w.first()?.dist(*w.get(1)?)))).sum()
}
pub(super) fn run_extrim(s: &mut Session, p: &Value) -> Result<Value> {
let h = match p.get("edge") {
Some(Value::String(t)) => {
Handle::parse_hex(t).ok_or_else(|| bad("extrim", "`edge` must be an object handle (a hex string such as \"1A2\")"))?
}
// One cutting edge: several objects would leave which one cuts to chance.
None | Some(Value::Null) => match targets(s, p)?.as_slice() {
[] => return Err(bad("extrim", "`edge` is required")),
[h] => *h,
_ => return Err(bad("extrim", "give exactly one cutting edge")),
},
Some(_) => return Err(bad("extrim", "`edge` must be an object handle (a hex string such as \"1A2\")")),
};
let point = point_param(p, "side").ok_or_else(|| bad("extrim", "`side` ([x, y]) is required"))?;
let edge = Edge::new(s, h)?;
let side = edge.side(point).ok_or_else(|| bad("extrim", "pick the side away from the cutting edge"))?;
trim_side(s, &edge, side)
}
/// Trim every object crossing `edge` on `side`: one undo step, everything checked first.
fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result<Value> {
let space = s.space();
let plan = plan(s.doc()?, &space, edge, side)?;
let edges = Edges { only: Some(std::slice::from_ref(&edge.handle)), implied: false };
let tol = edge.gap / 20.0;
let mut trimmed = 0;
let mut created = Vec::new();
// Objects some planned cut failed on, reported rather than counted as done.
let mut uncut = plan.uncut;
for (h, stretches) in plan.work {
let mut live = vec![h];
let mut cut = false;
// The object as it is before any cut: its lines and arcs, exactly.
let exact = s.doc()?.entity(h).and_then(|e| exact_outline(&e.kind));
for x in stretches.into_iter().map(|st| st.pick) {
// The pick lies on the flattened outline, which strays from a large-radius arc by up to
// a millionth of its radius (far more than `tol` next to a short edge): bring it onto
// the object itself, and measure the pieces exactly too.
let x = exact.as_deref().map_or(x, |segs| on_outline(segs, x));
// A trim replaces the object with pieces: the pick goes to the piece it lies on (none:
// that part is already gone). The pick is on the outline traced within `tol`, so 3 tol
// allows for that and for rounding, and is far less than the distance to any other
// piece, since a stretch's middle is well away from the edge where pieces meet.
let target = {
let d = s.doc()?;
live.iter()
.filter_map(|l| {
let e = d.entity(*l)?;
let dist =
exact_outline(&e.kind).map_or_else(|| crate::select::entity_distance(d, e, x, tol), |segs| on_outline(&segs, x).dist(x));
Some((*l, dist))
})
.filter(|(_, dist)| *dist <= 3.0 * tol)
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(l, _)| l)
};
// No piece there: a planned stretch the trim can't find. Say so rather than count
// the object as trimmed through.
let Some(t) = target else {
if !uncut.contains(&h) {
uncut.push(h);
}
continue;
};
let Ok(pieces) = trim(s, t, x, edges) else {
if !uncut.contains(&h) {
uncut.push(h);
}
continue;
};
cut = true;
live.retain(|l| *l != t);
for n in pieces {
// Never leave a piece of no length behind.
let d = s.doc()?;
if d.entity(n).is_some_and(|e| length(d, e, tol) <= tol) {
s.doc_mut()?.remove_entity(n);
} else {
live.push(n);
}
}
}
if cut {
trimmed += 1;
created.extend(live.into_iter().filter(|l| *l != h));
}
}
let mut message = format!("{trimmed} object(s) trimmed.");
if plan.locked > 0 {
message.push_str(&format!(" {} on locked layers left as they are.", plan.locked));
}
if plan.other > 0 {
message.push_str(&format!(" {} that can't be trimmed (blocks, hatches, text…) left as they are.", plan.other));
}
if !uncut.is_empty() {
message.push_str(&format!(" {} could not be cut everywhere the edge crosses them.", uncut.len()));
}
Ok(json!({
"trimmed": trimmed,
"handles": created.iter().map(|h| h.hex()).collect::<Vec<_>>(),
"skipped": { "locked": plan.locked, "other": plan.other, "uncut": uncut.len() },
"message": message,
}))
}
/// An object's outline as exact lines and arcs, when it is made of nothing else (lines, arcs,
/// circles, polylines); `None` for ellipses, splines and the rest.
fn exact_outline(k: &EntityKind) -> Option<Vec<cadcraft_geom::Segment>> {
let mut out = Vec::new();
for p in k.prims() {
match p {
cadcraft_doc::Prim::Seg(sg) => out.push(sg),
cadcraft_doc::Prim::Circle(c) => out.push(cadcraft_geom::Segment::Arc {
arc: cadcraft_geom::Arc { center: c.center, radius: c.radius, start: 0.0, end: std::f64::consts::TAU },
ccw: true,
}),
_ => return None,
}
}
(!out.is_empty()).then_some(out)
}
/// The point of `segs` nearest `p`.
fn on_outline(segs: &[cadcraft_geom::Segment], p: Vec2) -> Vec2 {
segs.iter().map(|sg| sg.closest(p)).min_by(|a, b| a.dist(p).total_cmp(&b.dist(p))).unwrap_or(p)
}
/// The parts the trim would remove, drawn red.
fn preview(d: &Drawing, space: &cadcraft_doc::Space, edge: &Edge, side: Side) -> Vec<Entity> {
let Ok(plan) = plan(d, space, edge, side) else { return Vec::new() };
if plan.work.len() > MAX_PREVIEW {
return Vec::new();
}
let mut out = Vec::new();
for (h, stretches) in plan.work {
let Some(e) = d.entity(h) else { continue };
for part in stretches.into_iter().flat_map(|st| st.parts).filter(|p| p.len() >= 2) {
let mut ent = Entity::new(Handle(0), lwpoly(part.into_iter().map(cadcraft_geom::PolyVertex::new).collect(), false));
ent.common.color = Color::Index(1);
ent.common.layer = e.common.layer.clone();
out.push(ent);
}
}
out
}
/// EXTRIM at the prompts: the cutting edge (or the one object selected beforehand), then the side,
/// with the parts that will go shown red as the cursor moves.
pub(super) struct ExtrimM {
edge: Option<Edge>,
/// The preview for each side (left, right), worked out once.
previews: RefCell<[Option<Vec<Entity>>; 2]>,
}
impl ExtrimM {
fn new(_s: &Session) -> Self {
ExtrimM { edge: None, previews: RefCell::new([None, None]) }
}
fn set_edge(&mut self, s: &mut Session, h: Handle) -> bool {
match Edge::new(s, h) {
Ok(e) => {
self.edge = Some(e);
self.previews = RefCell::new([None, None]);
true
}
Err(e) => {
s.echo(e.to_string());
false
}
}
}
}
impl Interactive for ExtrimM {
fn name(&self) -> &'static str {
"EXTRIM"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
// One object selected beforehand is the cutting edge.
if s.settings.pickfirst
&& let [h] = s.selection().as_slice()
&& s.doc().ok().and_then(|d| d.entity(*h)).is_some_and(|e| edge_kind(&e.kind))
{
let h = *h;
self.set_edge(s, h);
}
Ok(Step::Continue)
}
fn prompt(&self, _s: &Session) -> Prompt {
match self.edge {
None => Prompt::new("Select the cutting edge (line, arc, circle, ellipse, polyline or spline)", Accept::SELECT),
Some(_) => Prompt::new("Specify the side to trim on", Accept::POINT),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match (&self.edge, i) {
(_, Input::Cancel) => Ok(Step::Cancel),
(_, Input::Enter) => Ok(Step::Done),
(None, Input::Pick(hs)) => {
match hs.as_slice() {
[h] => {
self.set_edge(s, *h);
}
[] => s.echo("No object found."),
_ => s.echo("Select exactly one cutting edge."),
}
Ok(Step::Continue)
}
(Some(edge), Input::Point(p)) => {
let Some(side) = edge.side(p) else {
s.echo("Pick the side away from the cutting edge.");
return Ok(Step::Continue);
};
let edge = edge.clone();
s.set_selection(Vec::new());
match trim_side(s, &edge, side) {
Ok(v) => s.echo(v.get("message").and_then(Value::as_str).unwrap_or_default().to_string()),
Err(e) => s.echo(e.to_string()),
}
Ok(Step::Done)
}
_ => Ok(Step::Continue),
}
}
fn preview_objects(&self, s: &Session, cursor: Vec2) -> Vec<Entity> {
let Some(edge) = &self.edge else { return Vec::new() };
let Some(side) = edge.side(cursor) else { return Vec::new() };
let slot = usize::from(side == Side::Right);
let cached = self.previews.borrow().get(slot).cloned().flatten();
let mut v = match cached {
Some(v) => v,
None => {
let Ok(d) = s.doc() else { return Vec::new() };
let v = preview(d, &s.space(), edge, side);
if let Some(c) = self.previews.borrow_mut().get_mut(slot) {
*c = Some(v.clone());
}
v
}
};
// A band a few pixels wide at the current zoom, so it shows over the object it covers.
let width = 3.0 * s.pixel_size();
for e in &mut v {
if let EntityKind::LwPolyline(p) = &mut e.kind {
p.const_width = width;
}
}
v
}
}
+1 -1
View File
@@ -105,7 +105,7 @@ fn decimate(pts: &[Vec2], max: usize) -> Vec<Vec2> {
v
}
fn offset_points(pts: &[Vec2], d: f64, closed: bool) -> Vec<Vec2> {
pub(super) fn offset_points(pts: &[Vec2], d: f64, closed: bool) -> Vec<Vec2> {
let n = pts.len();
let mut out = Vec::with_capacity(n);
for i in 0..n {
+101 -58
View File
@@ -2,7 +2,8 @@ use super::break_join::join;
use super::explode::explode;
use super::transform::{at_elevation, erase, scale_entities, transform_entities};
use super::{
Accept, EngineError, EntityKind, Handle, Input, Interactive, Mat3, Prompt, Result, SelOutcome, SelectPhase, Session, Step, Vec2, line, number,
Accept, EngineError, EntityKind, Handle, Input, Interactive, Mat3, Prompt, Result, SelOutcome, SelectPhase, Session, Step, Vec2, line,
mirror_entities, mirror_kind, number,
};
// ---------------- interactive ----------------
@@ -26,12 +27,11 @@ pub(super) struct SelectThen {
objs: Vec<Handle>,
pts: Vec<Vec2>,
reference: bool,
/// ROTATE Reference: the reference angle (radians), once known. Its first point, and the
/// first of the two new-angle points, are kept in `ref_from`.
/// ROTATE Reference: the reference angle (radians), once known.
ref_angle: Option<f64>,
/// ROTATE Reference: the new angle is given by two points (the `Points` option).
/// ROTATE/SCALE Reference: the new angle/length is given by two points (the `Points` option).
ref_points: bool,
/// SCALE Reference: first point of a reference length given by two points.
/// ROTATE/SCALE Reference: first point of a reference or `Points` pair given by two points.
ref_from: Option<Vec2>,
/// SCALE Reference: the reference length, once known.
ref_len: Option<f64>,
@@ -126,30 +126,47 @@ impl SelectThen {
}
}
/// SCALE Reference: reference length (typed, or two points), then new length (typed, or a
/// point measured from the base point). The scale factor is new length / reference length.
/// SCALE Reference: reference length (typed, or two points), then new length (typed, a point
/// measured from the base point, or two points after `Points`). The scale factor is new length /
/// reference length.
fn scale_reference(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let Some(base) = self.pts.first().copied() else { return Ok(Step::Done) };
match (self.ref_len, self.ref_from, i) {
(None, None, Input::Point(p)) => {
if matches!(&i, Input::Keyword(k) if k == "Copy") {
self.copy_mode = true;
s.echo("Scaling a copy of the selected objects.");
return Ok(Step::Continue);
}
let Some(r) = self.ref_len else {
match (self.ref_from, i) {
(None, Input::Point(p)) => self.ref_from = Some(p),
(None, Input::Text(t)) => self.ref_len = Some(require_length(number(&t))?),
(None, Input::Enter) => self.ref_len = Some(1.0),
(Some(a), Input::Point(p)) => {
self.ref_len = Some(require_length(Some(a.dist(p)))?);
self.ref_from = None;
}
(_, Input::Enter) => return Ok(Step::Done),
_ => {}
}
return Ok(Step::Continue);
};
match (self.ref_points, self.ref_from, i) {
(false, _, Input::Keyword(k)) if k == "Points" => {
self.ref_points = true;
self.ref_from = None;
Ok(Step::Continue)
}
(false, _, Input::Point(p)) => self.scale_by(s, base, base.dist(p) / r),
(false, _, Input::Text(t)) => {
let n = require_length(number(&t))?;
self.scale_by(s, base, n / r)
}
(true, None, Input::Point(p)) => {
self.ref_from = Some(p);
Ok(Step::Continue)
}
(None, None, Input::Text(t)) => {
self.ref_len = Some(require_length(number(&t))?);
Ok(Step::Continue)
}
(None, None, Input::Enter) => {
self.ref_len = Some(1.0);
Ok(Step::Continue)
}
(None, Some(a), Input::Point(p)) => {
self.ref_len = Some(require_length(Some(a.dist(p)))?);
Ok(Step::Continue)
}
(Some(r), _, Input::Point(p)) => self.scale_by(s, base, base.dist(p) / r),
(Some(r), _, Input::Text(t)) => {
let n = require_length(number(&t))?;
(true, Some(a), Input::Point(p)) => {
let n = require_length(Some(a.dist(p)))?;
self.scale_by(s, base, n / r)
}
(_, _, Input::Enter) => Ok(Step::Done),
@@ -157,6 +174,26 @@ impl SelectThen {
}
}
/// The prompt while SCALE Reference collects its lengths.
fn scale_reference_prompt(&self) -> Prompt {
let base = self.pts.first().copied();
match (self.ref_len, self.ref_points, self.ref_from) {
(None, _, None) => Prompt::new("Specify reference length", Accept::POINT_OR_NUMBER).kw(&["Copy"]).default("1"),
(None, _, Some(p)) | (Some(_), true, Some(p)) => Prompt::new("Specify second point", Accept::POINT).base(p),
(Some(_), false, _) => Prompt::new("Specify new length", Accept::POINT_OR_NUMBER).kw(&["Points", "Copy"]).base_opt(base).distance(),
(Some(_), true, None) => Prompt::new("Specify first point", Accept::POINT),
}
}
/// Live factor and rubber-band anchor while SCALE Reference previews with the cursor at `c`.
fn scale_reference_factor(&self, base: Vec2, c: Vec2) -> Option<(f64, Vec2)> {
match (self.ref_len, self.ref_points, self.ref_from) {
(Some(r), false, _) => positive_length(Some(base.dist(c) / r)).map(|f| (f, base)),
(Some(r), true, Some(a)) => positive_length(Some(a.dist(c) / r)).map(|f| (f, a)),
_ => None,
}
}
/// ROTATE Reference: reference angle (typed, or two points), then the new angle (typed, a
/// point measured from the base point, or two points after `Points`). The objects turn by the
/// new angle minus the reference angle.
@@ -248,10 +285,11 @@ impl SelectThen {
}
}
/// Objects whose text MIRROR keeps readable instead of mirroring it with the geometry.
fn keeps_reading_when_mirrored(k: &EntityKind) -> bool {
/// Objects MIRROR must preview individually: readable text and hatches retaining fill direction.
fn needs_mirror_preview(k: &EntityKind) -> bool {
match k {
EntityKind::Insert(i) => !i.attribs.is_empty(),
EntityKind::Hatch(h) => !h.solid || h.gradient.is_some(),
k => matches!(
k,
EntityKind::Text(_)
@@ -265,8 +303,8 @@ fn keeps_reading_when_mirrored(k: &EntityKind) -> bool {
}
}
/// Text objects transformed for each frame of a MIRROR preview (on the CPU); more are not drawn.
const MAX_MIRROR_TEXT_PREVIEW: usize = 1000;
/// Objects transformed for each frame of a MIRROR preview (on the CPU); more are not drawn.
const MAX_MIRROR_OBJECT_PREVIEW: usize = 1000;
/// A finite length greater than zero (rejects 0, negatives, NaN and infinity).
fn positive_length(v: Option<f64>) -> Option<f64> {
@@ -314,11 +352,7 @@ impl Interactive for SelectThen {
let k = self.pts.len();
let base = self.pts.first().copied();
if self.op == Op::Scale && self.reference {
return match (self.ref_len, self.ref_from) {
(Some(_), _) => Prompt::new("Specify new length", Accept::POINT_OR_NUMBER).base_opt(base),
(None, Some(p)) => Prompt::new("Specify second point", Accept::POINT).base(p),
(None, None) => Prompt::new("Specify reference length", Accept::POINT_OR_NUMBER).default("1"),
};
return self.scale_reference_prompt();
}
if self.op == Op::Rotate && self.reference {
return self.rotate_reference_prompt();
@@ -347,6 +381,7 @@ impl Interactive for SelectThen {
_ => Prompt::new("", Accept::POINT),
}
}
/// Advance the selected transform command, applying MIRROR fill policy at commit.
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if !self.sel.done {
match self.sel.feed(s, &i)? {
@@ -364,7 +399,7 @@ impl Interactive for SelectThen {
if self.ask_erase {
let yes = matches!(&i, Input::Keyword(k) if k == "Yes") || matches!(&i, Input::Text(t) if t.trim().to_ascii_lowercase().starts_with('y'));
let (a, b) = (self.pts[0], self.pts[1]);
transform_entities(s, &self.objs, &Mat3::mirror(a, b), !yes)?;
mirror_entities(s, &self.objs, &Mat3::mirror(a, b), !yes)?;
s.set_selection(Vec::new());
return Ok(Step::Done);
}
@@ -456,6 +491,7 @@ impl Interactive for SelectThen {
_ => Ok(Step::Continue),
}
}
/// Build bounded transform previews, retaining readable text and hatch fill directions.
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
if self.op == Op::Rotate && self.reference {
return self.rotate_reference_preview(s, c);
@@ -464,16 +500,15 @@ impl Interactive for SelectThen {
return Vec::new();
}
let Some(base) = self.pts.first().copied() else { return Vec::new() };
let m = match self.op {
Op::Move | Op::Copy => Mat3::translate(c - base),
Op::Rotate => Mat3::rotate_about(base, base.angle_to(c)),
Op::Scale if !self.reference => Mat3::scale_about(base, base.dist(c).max(1e-9)),
Op::Scale => match self.ref_len.and_then(|r| positive_length(Some(base.dist(c) / r))) {
Some(f) => Mat3::scale_about(base, f),
None if self.ref_len.is_some() => return Vec::new(),
let (m, rubber_from) = match self.op {
Op::Move | Op::Copy => (Mat3::translate(c - base), base),
Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base),
Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base),
Op::Scale => match self.scale_reference_factor(base, c) {
Some((f, from)) => (Mat3::scale_about(base, f), from),
None => return self.ref_from.map(|a| vec![line(a, c)]).unwrap_or_default(),
},
Op::Mirror if !self.ask_erase => Mat3::mirror(base, c),
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
_ => return Vec::new(),
};
let Ok(d) = s.doc() else { return Vec::new() };
@@ -484,43 +519,51 @@ impl Interactive for SelectThen {
.filter_map(|h| d.entity(*h))
.map(|e| {
let mut k = e.kind.clone();
k.transform(&m);
if self.op == Op::Mirror {
mirror_kind(&mut k, &m);
} else {
k.transform(&m);
}
k
})
.collect();
out.push(line(base, c));
out.push(line(rubber_from, c));
out
}
/// Separate shared GPU transforms from objects that need an individual MIRROR preview.
fn drag(&self, s: &Session, c: Vec2) -> Option<crate::prompt::Drag> {
if (self.op == Op::Rotate && self.reference) || !self.sel.done {
return None;
}
let base = self.pts.first().copied()?;
let matrix = match self.op {
Op::Move | Op::Copy => Mat3::translate(c - base),
Op::Rotate => Mat3::rotate_about(base, base.angle_to(c)),
Op::Scale if !self.reference => Mat3::scale_about(base, base.dist(c).max(1e-9)),
Op::Scale => Mat3::scale_about(base, self.ref_len.and_then(|r| positive_length(Some(base.dist(c) / r)))?),
Op::Mirror if !self.ask_erase => Mat3::mirror(base, c),
let (matrix, rubber_from) = match self.op {
Op::Move | Op::Copy => (Mat3::translate(c - base), base),
Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base),
Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base),
Op::Scale => {
let (f, from) = self.scale_reference_factor(base, c)?;
(Mat3::scale_about(base, f), from)
}
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
_ => return None,
};
let mut extra = vec![line(base, c)];
let mut extra = vec![line(rubber_from, c)];
if self.op != Op::Mirror {
return Some(crate::prompt::Drag { handles: self.objs.clone(), matrix, extra, clipboard: false });
}
// Mirrored text keeps reading left to right (MIRRTEXT 0), which the matrix alone can't
// draw: those objects are transformed one by one, the rest is mirrored on the GPU.
// Readable text and unchanged hatch directions cannot be drawn by reflecting their
// already-rendered primitives: preview those objects individually, the rest on the GPU.
let d = s.doc().ok()?;
let mut handles = Vec::with_capacity(self.objs.len());
let mut texts = 0;
let mut individual = 0;
for h in &self.objs {
let Some(e) = d.entity(*h) else { continue };
if !keeps_reading_when_mirrored(&e.kind) {
if !needs_mirror_preview(&e.kind) {
handles.push(*h);
} else if texts < MAX_MIRROR_TEXT_PREVIEW {
texts += 1;
} else if individual < MAX_MIRROR_OBJECT_PREVIEW {
individual += 1;
let mut k = e.kind.clone();
k.transform(&matrix);
mirror_kind(&mut k, &matrix);
extra.push(k);
}
}
+26 -1
View File
@@ -1,3 +1,4 @@
use cadcraft_doc::EntityKind;
use cadcraft_geom::Vec3;
use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, erase_kept, f64_req, json, point_param, point_req, targets};
@@ -9,6 +10,29 @@ pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy:
edit_entities(s, hs, copy, |e| e.kind.transform(m))
}
/// MIRROR's default hatch policy retains the fill direction while reflecting its boundary.
/// Keep this in the command layer: a reflection of an entire inserted block still transforms
/// all of its contents, rather than applying the policy for individually selected hatches.
pub(super) fn mirror_kind(k: &mut EntityKind, m: &Mat3) {
let angles = match k {
EntityKind::Hatch(h) => Some((h.angle, h.gradient.as_ref().map(|g| g.angle))),
_ => None,
};
k.transform(m);
if let (EntityKind::Hatch(h), Some((angle, gradient_angle))) = (k, angles) {
h.angle = angle;
if let (Some(g), Some(angle)) = (&mut h.gradient, gradient_angle) {
g.angle = angle;
}
}
}
/// Reflect selected entities with the command policy that retains individual hatch fill directions.
pub(super) fn mirror_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<Vec<Handle>> {
refuse_ole_frames(s, hs, m, copy)?;
edit_entities(s, hs, copy, |e| mirror_kind(&mut e.kind, m))
}
/// Scale `hs` by `f` about `base` in 3D, as AutoCAD 2024's SCALE does: about the base point's XY,
/// and every height of the objects about its Z, their thickness too.
pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64, copy: bool) -> Result<Vec<Handle>> {
@@ -151,6 +175,7 @@ pub(super) fn run_scale(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
/// Validate MIRROR parameters and apply the reflection, optionally replacing the source entities.
pub(super) fn run_mirror(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let a = point_req("mirror", p, "p1")?;
@@ -159,6 +184,6 @@ pub(super) fn run_mirror(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("mirror", "mirror line points coincide"));
}
let erase_src = bool_or(p, "erase", false);
let r = transform_entities(s, &hs, &Mat3::mirror(a, b), !erase_src)?;
let r = mirror_entities(s, &hs, &Mat3::mirror(a, b), !erase_src)?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
+81 -28
View File
@@ -18,28 +18,51 @@ pub(crate) struct Edges<'a> {
}
/// All primitives of the cutting edges (excluding `exclude`).
fn edge_segments(s: &Session, edges: Edges, exclude: Handle) -> Result<Vec<Segment>> {
pub(crate) fn edge_segments(s: &Session, edges: Edges, exclude: Handle) -> Result<Vec<Segment>> {
edge_segments_over(s, edges, exclude, &Overlay::new())
}
/// Objects as a run of trims would have left them, without changing the drawing: for each object
/// of the drawing it names, the pieces in its place, each with its handle (the first keeps the
/// object's, as [`replace_with_pieces`] does; none: the object is gone). TRIM's Fence and
/// Crossing preview works a whole run out this way.
pub(crate) type Overlay = std::collections::HashMap<Handle, Vec<(Handle, EntityKind)>>;
/// [`edge_segments`] with the objects `overlay` names in their pieces' place.
pub(crate) fn edge_segments_over(s: &Session, edges: Edges, exclude: Handle, overlay: &Overlay) -> Result<Vec<Segment>> {
let d = s.doc()?;
let space = s.space();
let store = d.space(&space).ok_or(EngineError::NoDocument)?;
let mut out = Vec::new();
for e in store.iter() {
if e.handle == exclude || !d.is_visible(e) {
continue;
}
if let Some(es) = edges.only
&& !es.contains(&e.handle)
{
continue;
}
let mut add = |kind: &EntityKind| {
if edges.implied
&& let Some(segs) = implied_edge(&e.kind)
&& let Some(segs) = implied_edge(kind)
{
out.extend(segs);
return;
}
for p in kind.prims() {
out.extend(prim_to_segments(&p));
}
};
// An object is an edge when it is one of `edges.only` (all of them: `None`). A trim leaves
// its first piece under the object's handle and the others under new ones, so only the first
// stays one of the picked edges, as in a run of trims on the drawing itself.
let is_edge = |h: &Handle| edges.only.is_none_or(|es| es.contains(h));
for e in store.iter() {
if !d.is_visible(e) {
continue;
}
for p in e.kind.prims() {
out.extend(prim_to_segments(&p));
match overlay.get(&e.handle) {
Some(pieces) => {
for (h, k) in pieces {
if *h != exclude && is_edge(h) {
add(k);
}
}
}
None if e.handle != exclude && is_edge(&e.handle) => add(&e.kind),
None => {}
}
}
Ok(out)
@@ -137,19 +160,36 @@ pub(crate) fn json_pick_error(s: &Session, h: Handle, pick: Vec2, edges: Edges,
EngineError::Other(message.into())
}
/// Trim `h` at the piece containing `pick`. Returns the handles that replace it.
/// Trim `h` at the piece containing `pick`. Returns what it became: its pieces, `h` first
/// ([`replace_with_pieces`]).
pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Result<Vec<Handle>> {
let cut = edge_segments(s, edges, h)?;
match trimmed(s, h, pick, edges, &cut)? {
Some(pieces) => replace_with_pieces(s, h, pieces),
None => Ok(vec![h]),
}
}
/// What a trim of `h` at `pick` against `cut` (its cutting edges, [`edge_segments`]) leaves of
/// it, without changing the drawing: the pieces that stay, in [`replace_with_pieces`]'s order
/// (none: the object goes). `None`: the pick is on one of a polyline's own cuts, which trims
/// nothing. TRIM's preview and the trim itself both come from here, so they can't disagree.
pub(crate) fn trimmed(s: &Session, h: Handle, pick: Vec2, edges: Edges, cut: &[Segment]) -> Result<Option<Vec<EntityKind>>> {
if crate::cmd::curves::is_locked(s, h) {
return Err(EngineError::Other("The object is on a locked layer.".into()));
}
let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?;
let cut = edge_segments(s, edges, h)?;
let d = s.doc()?;
let e = d.entity(h).ok_or_else(|| EngineError::Other("no such object".into()))?;
// A polyline that is one of the edges (picked, or with every object in either mode) cuts
// itself too.
let itself = edges.only.is_none_or(|o| o.contains(&h));
let pieces: Vec<EntityKind> = match &e.kind {
trim_kind(&e.kind, pick, itself, cut)
}
/// [`trimmed`] for an object of shape `kind` (not on a locked layer); `itself`: it is one of the
/// cutting edges, so a polyline cuts itself too.
pub(crate) fn trim_kind(kind: &EntityKind, pick: Vec2, itself: bool, cut: &[Segment]) -> Result<Option<Vec<EntityKind>>> {
let pieces: Vec<EntityKind> = match kind {
EntityKind::Line(l) => {
let ln = Line::new(l.a.xy(), l.b.xy());
let mut ts: Vec<f64> = cut
@@ -229,13 +269,13 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu
}
keep.into_iter().collect()
}
EntityKind::LwPolyline(p) => match trim_polyline(p, &cut, pick, itself)? {
EntityKind::LwPolyline(p) => match trim_polyline(p, cut, pick, itself)? {
Some(pieces) => pieces,
None => return Ok(vec![h]),
None => return Ok(None),
},
k => crate::cmd::modify2::trim_other(k, &cut, pick)?,
k => crate::cmd::modify2::trim_other(k, cut, pick)?,
};
replace_with_pieces(s, h, pieces)
Ok(Some(pieces))
}
/// Put `pieces` in place of object `h` as AutoCAD 2024's BREAK and TRIM leave them: the first
@@ -564,12 +604,26 @@ fn extend_arc_segment(ga: &Arc, end: Vec2, sweep: f64, cut: &[Segment]) -> Optio
/// Extend the end of `h` nearest `pick` to the nearest boundary edge.
pub(crate) fn extend(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Result<()> {
let cut = edge_segments(s, edges, h)?;
let new_kind = extended(s, h, pick, &cut)?;
s.doc_mut()?.modify_entity(h, |e| e.kind = new_kind)?;
Ok(())
}
/// The object `h` as an extend at `pick` to `cut` (its boundary edges, [`edge_segments`]) leaves
/// it, without changing the drawing. EXTEND's preview and the extend itself both come from here.
pub(crate) fn extended(s: &Session, h: Handle, pick: Vec2, cut: &[Segment]) -> Result<EntityKind> {
if crate::cmd::curves::is_locked(s, h) {
return Err(EngineError::Other("The object is on a locked layer.".into()));
}
let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?;
let cut = edge_segments(s, edges, h)?;
let new_kind = match &e.kind {
let d = s.doc()?;
let e = d.entity(h).ok_or_else(|| EngineError::Other("no such object".into()))?;
extend_kind(&e.kind, pick, cut)
}
/// [`extended`] for an object of shape `kind` (not on a locked layer).
pub(crate) fn extend_kind(kind: &EntityKind, pick: Vec2, cut: &[Segment]) -> Result<EntityKind> {
let new_kind = match kind {
EntityKind::Line(l) => {
let (a, b) = (l.a.xy(), l.b.xy());
let from_b = pick.dist(b) < pick.dist(a);
@@ -617,7 +671,7 @@ pub(crate) fn extend(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Re
let none = || EngineError::Other("Object does not intersect an edge.".into());
if let Some((ga, _)) = cadcraft_geom::bulge_to_arc(prev, end, bulge) {
// An arc end segment runs on round its circle, as an arc does.
let (np, b) = extend_arc_segment(&ga, end, 4.0 * bulge.atan(), &cut).ok_or_else(none)?;
let (np, b) = extend_arc_segment(&ga, end, 4.0 * bulge.atan(), cut).ok_or_else(none)?;
if let Some(v) = vs.get_mut(i_end) {
v.p = np;
}
@@ -640,8 +694,7 @@ pub(crate) fn extend(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Re
// Width, elevation and linetype generation stay as they were.
EntityKind::LwPolyline(cadcraft_doc::LwPolyline { vertices: vs, ..p.clone() })
}
k => crate::cmd::modify2::extend_other(k, &cut, pick)?,
k => crate::cmd::modify2::extend_other(k, cut, pick)?,
};
s.doc_mut()?.modify_entity(h, |e| e.kind = new_kind)?;
Ok(())
Ok(new_kind)
}
+4
View File
@@ -4,8 +4,10 @@
mod breaks;
mod cells;
pub(crate) mod formula;
mod paste;
pub(crate) use cells::{recalc, tablestyle_cell_style};
pub use paste::{MAX_PASTE_CELLS, is_tsv_table, parse_tsv};
use cadcraft_doc::{EntityKind, Handle, Table, TableCell};
use cadcraft_geom::Vec2;
@@ -35,6 +37,8 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("table.deletecol", "Delete Column", run_delete_col).params("{handle, col}"),
CommandSpec::new("table.merge", "Merge Cells", run_merge).params("{handle, row, col, rows, cols}"),
CommandSpec::new("table.unmerge", "Unmerge Cells", run_unmerge).params("{handle, row, col}"),
CommandSpec::new("pastetable", "Paste Table", paste::run_pastetable)
.params("{tsv: string, at?: [x,y], text_height?: number} → {handle, rows, cols}"),
]
.into_iter()
.chain(cells::specs())
+304
View File
@@ -0,0 +1,304 @@
//! Paste tabular clipboard data (TSV from Excel or other spreadsheets) as a native `ACAD_TABLE`.
use cadcraft_doc::{EntityKind, Table, TableCell, TableStyle};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
use super::{MAX_COLS, MAX_ROWS, style_of};
use crate::cmd::helpers::{line, v3};
use crate::cmd::{bad, point_param, str_param};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
/// Maximum UTF-8 byte length accepted for a pasted TSV payload (16 MiB).
pub const MAX_TSV_BYTES: usize = 16 << 20;
/// Maximum total grid cells created from pasted TSV (`rows * cols`).
pub const MAX_PASTE_CELLS: usize = 20_000;
/// Above this many cells, interactive cursor preview draws the outer table box instead of laying
/// out every cell each frame.
const PREVIEW_CELL_LIMIT: usize = 200;
/// Parse RFC-4180 tab-delimited text into a uniform rectangular grid of cells via [`craft_csv`].
///
/// Supports quoted fields (`"..."`), escaped doubled quotes (`""`), and multiline cells inside
/// quotes (`\n` / `\r\n` normalized to `\n`). Enforces [`MAX_TSV_BYTES`], [`MAX_ROWS`],
/// [`MAX_COLS`], and the total cell budget [`MAX_PASTE_CELLS`]. Requires at least 2 cells
/// (`rows * cols >= 2`) and at least one non-whitespace cell.
pub fn parse_tsv(text: &str) -> std::result::Result<Vec<Vec<String>>, String> {
if text.len() > MAX_TSV_BYTES {
return Err(format!("pasted table exceeds {} MB limit", MAX_TSV_BYTES >> 20));
}
let clean = text.strip_prefix('\u{feff}').unwrap_or(text);
let mut rows: Vec<Vec<String>> = Vec::new();
let mut max_cols = 0usize;
let mut err: Option<String> = None;
craft_csv::parse_records(clean, '\t', '"', MAX_COLS + 1, |mut rec| {
if rec.len() > MAX_COLS {
err = Some(format!("pasted table exceeds {MAX_COLS} columns"));
return false;
}
if rows.len() >= MAX_ROWS {
err = Some(format!("pasted table exceeds {MAX_ROWS} rows"));
return false;
}
max_cols = max_cols.max(rec.len());
if (rows.len() + 1).saturating_mul(max_cols) > MAX_PASTE_CELLS {
err = Some(format!("pasted table exceeds {MAX_PASTE_CELLS} cell limit"));
return false;
}
for cell in &mut rec {
if cell.contains('\r') {
*cell = cell.replace("\r\n", "\n").replace('\r', "\n");
}
}
rows.push(rec);
true
});
if let Some(msg) = err {
return Err(msg);
}
let total = rows.len().saturating_mul(max_cols);
if rows.is_empty() || max_cols == 0 || total < 2 {
return Err("pasted text must contain at least 2 table cells".into());
}
if rows.iter().all(|r| r.iter().all(|c| c.trim().is_empty())) {
return Err("pasted table contains no text".into());
}
for r in &mut rows {
r.resize(max_cols, String::new());
}
Ok(rows)
}
/// Whether `text` looks like non-DXF tab-delimited spreadsheet data containing at least 2 cells.
pub fn is_tsv_table(text: &str) -> bool {
if text.is_empty() || text.len() > MAX_TSV_BYTES || !text.contains('\t') {
return false;
}
let mut lines = text.lines().map(str::trim);
if lines.next() == Some("0") && lines.next() == Some("SECTION") {
return false;
}
parse_tsv(text).is_ok()
}
/// Build an `ACAD_TABLE` entity from parsed cell strings, sizing columns and rows cleanly.
fn build_table(st: &TableStyle, at: Vec2, data: &[Vec<String>], text_height: Option<f64>) -> Table {
let cols = data.first().map_or(1, Vec::len).max(1);
let th = text_height.unwrap_or_else(|| if st.text_height.is_finite() && st.text_height > 0.0 { st.text_height } else { 2.5 });
let margin = if st.text_height.is_finite() && st.text_height > 0.0 { st.margin * (th / st.text_height) } else { th * 0.5 };
let mut col_chars = vec![1usize; cols];
let mut row_heights = Vec::with_capacity(data.len());
let mut cells = Vec::with_capacity(data.len());
for row in data {
let mut max_lines = 1usize;
let mut table_row = Vec::with_capacity(cols);
for (c, raw) in row.iter().enumerate() {
let line_count = raw.split('\n').count().clamp(1, 50);
max_lines = max_lines.max(line_count);
let max_chars = raw.split('\n').map(|line| line.chars().count()).max().unwrap_or(0).clamp(1, 60);
if let Some(slot) = col_chars.get_mut(c) {
*slot = (*slot).max(max_chars);
}
table_row.push(TableCell { text: cadcraft_doc::mtext_literal(raw), ..TableCell::default() });
}
row_heights.push(th * (max_lines as f64 * 5.0 / 3.0) + 2.0 * margin);
cells.push(table_row);
}
let min_col_w = (th * 4.0 + 2.0 * margin).max(th * 5.0);
let col_widths: Vec<f64> = col_chars.into_iter().map(|chars| (0.75 * th * chars as f64 + 2.0 * margin + 0.5 * th).max(min_col_w)).collect();
Table { insert: v3(at), col_widths, row_heights, cells, style: st.name.clone(), text_height: th, title: false, header: false, ..Table::default() }
}
fn parse_text_height(p: &Value) -> Result<Option<f64>> {
let val = match p.get("text_height").or_else(|| p.get("textHeight")) {
None | Some(Value::Null) => return Ok(None),
Some(v) => v,
};
val.as_f64()
.filter(|h| h.is_finite() && *h > 0.0 && *h <= 1e9)
.map(Some)
.ok_or_else(|| bad("pastetable", "`text_height` must be a finite positive number"))
}
fn parse_at(p: &Value) -> Result<Vec2> {
match p.get("at") {
None | Some(Value::Null) => Ok(Vec2::ZERO),
Some(_) => point_param(p, "at").ok_or_else(|| bad("pastetable", "`at` must be a point [x, y]")),
}
}
pub(super) fn run_pastetable(s: &mut Session, p: &Value) -> Result<Value> {
let tsv = str_param(p, "tsv").ok_or_else(|| bad("pastetable", "`tsv` string is required"))?;
let at = parse_at(p)?;
let th = parse_text_height(p)?;
let data = parse_tsv(tsv).map_err(|m| bad("pastetable", m))?;
let rows = data.len();
let cols = data.first().map_or(0, Vec::len);
let st = style_of(s);
let table = build_table(&st, at, &data, th);
let h = s.add_entity(EntityKind::Table(table))?;
s.set_selection(vec![h]);
Ok(json!({ "handle": h.hex(), "rows": rows, "cols": cols }))
}
struct PasteTableM {
table: Table,
rows: usize,
cols: usize,
}
impl Interactive for PasteTableM {
fn name(&self) -> &'static str {
"PASTETABLE"
}
fn begin(&mut self, _s: &mut Session) -> Result<Step> {
Ok(Step::Continue)
}
fn prompt(&self, _s: &Session) -> Prompt {
Prompt::new("Specify insertion point", Accept::POINT)
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Cancel | Input::Enter => Ok(Step::Cancel),
Input::Point(p) => {
let mut t = self.table.clone();
t.insert = v3(p);
let h = s.add_entity(EntityKind::Table(t))?;
s.set_selection(vec![h]);
s.echo(format!("Pasted {}x{} table.", self.rows, self.cols));
Ok(Step::Done)
}
_ => Ok(Step::Continue),
}
}
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
if self.rows.saturating_mul(self.cols) <= PREVIEW_CELL_LIMIT {
let mut t = self.table.clone();
t.insert = v3(c);
return vec![EntityKind::Table(t)];
}
let w: f64 = self.table.col_widths.iter().sum();
let h: f64 = self.table.row_heights.iter().sum();
let a = c;
let b = c + Vec2::new(w, 0.0);
let d = c + Vec2::new(w, -h);
let e = c + Vec2::new(0.0, -h);
vec![line(a, b), line(b, d), line(d, e), line(e, a)]
}
}
impl Session {
/// Start interactive placement of a native `ACAD_TABLE` parsed from tab-delimited clipboard
/// text (`tsv`), asking for an insertion point through the standard interactive command path.
pub fn start_paste_table(&mut self, tsv: &str, text_height: Option<f64>) -> Result<()> {
if let Some(h) = text_height
&& !(h.is_finite() && h > 0.0 && h <= 1e9)
{
return Err(bad("pastetable", "`text_height` must be a finite positive number"));
}
let data = parse_tsv(tsv).map_err(|m| bad("pastetable", m))?;
let rows = data.len();
let cols = data.first().map_or(0, Vec::len);
let st = style_of(self);
let table = build_table(&st, Vec2::ZERO, &data, text_height);
let enabled = crate::find_command("pastetable").map_or((|_| Ok(())) as fn(&Session) -> std::result::Result<(), String>, |c| c.enabled);
self.launch_interactive("pastetable", enabled, Box::new(PasteTableM { table, rows, cols }))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_rfc4180_tsv_with_multiline_and_quoted_cells() {
let input = "\u{feff}Item\tDescription\tQty\r\n\"Bolt M8\"\t\"Line 1\r\nLine 2\"\t10\r\n\"Say \"\"Hi\"\"\"\tPlain\t20\r\n";
let got = parse_tsv(input).unwrap();
assert_eq!(got, vec![vec!["Item", "Description", "Qty"], vec!["Bolt M8", "Line 1\nLine 2", "10"], vec!["Say \"Hi\"", "Plain", "20"],]);
}
#[test]
fn rejects_invalid_single_cell_empty_dxf_and_over_budget_inputs() {
assert!(parse_tsv("SingleCell").is_err());
assert!(parse_tsv("\"quoted\ttab\"").is_err());
assert!(parse_tsv("\t\n\t\n").is_err());
assert!(!is_tsv_table("SingleCell"));
assert!(!is_tsv_table("\"quoted\ttab\""));
assert!(!is_tsv_table("just plain text\non two lines"));
assert!(!is_tsv_table("0\nSECTION\n2\tTAB"));
assert!(is_tsv_table("A\tB"));
assert!(is_tsv_table("A\t\n1\t"));
// Column budget > MAX_COLS rejected during parse.
let too_wide = vec!["x"; MAX_COLS + 1].join("\t");
let err = parse_tsv(&too_wide).unwrap_err();
assert!(err.contains("columns"), "{err}");
// Cell budget > MAX_PASTE_CELLS rejected during parse.
let wide_row = vec!["x"; MAX_COLS].join("\t");
let over_rows = (MAX_PASTE_CELLS / MAX_COLS) + 2;
let oversized = vec![wide_row; over_rows].join("\n");
let err = parse_tsv(&oversized).unwrap_err();
assert!(err.contains("cell limit") || err.contains("rows"), "{err}");
}
#[test]
fn pads_ragged_rows_to_uniform_columns() {
let got = parse_tsv("A\tB\tC\n1\n2\t3\n").unwrap();
assert_eq!(got, vec![vec!["A", "B", "C"], vec!["1", "", ""], vec!["2", "3", ""]]);
}
#[test]
fn pastetable_command_creates_scaled_multiline_table() {
let mut s = Session::new();
let res =
s.execute("pastetable", &json!({ "tsv": "ColA\tLong Header Value\n\"Row 1\nRow 2\"\t42", "at": [10, 20], "text_height": 2.0 })).unwrap();
assert_eq!(res["rows"], 2);
assert_eq!(res["cols"], 2);
let h = cadcraft_doc::Handle::parse_hex(res["handle"].as_str().unwrap()).unwrap();
let e = s.doc().unwrap().entity(h).unwrap();
let EntityKind::Table(t) = &e.kind else { panic!("expected table") };
assert_eq!(t.insert.xy(), Vec2::new(10.0, 20.0));
assert_eq!(t.text_height, 2.0);
assert!(!t.title && !t.header);
assert_eq!(t.cells[1][0].text, "Row 1\\PRow 2");
assert!(t.row_heights[1] > t.row_heights[0], "multiline row gets extra height");
assert!(t.col_widths[1] > t.col_widths[0], "wider column gets extra width");
}
#[test]
fn interactive_start_paste_table_places_on_point_and_supports_undo() {
let mut s = Session::new();
s.start_paste_table("A\tB\n1\t2\n", None).unwrap();
assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("pastetable"));
assert!(!s.preview(Vec2::new(5.0, 5.0)).is_empty());
s.input(Input::Point(Vec2::new(100.0, 50.0))).unwrap();
assert!(s.running.is_none());
assert_eq!(s.doc().unwrap().model.len(), 1);
let e = s.doc().unwrap().model.iter().next().unwrap();
let EntityKind::Table(t) = &e.kind else { panic!("expected table") };
assert_eq!(t.insert.xy(), Vec2::new(100.0, 50.0));
assert_eq!(t.cells.len(), 2);
s.undo().unwrap();
assert!(s.doc().unwrap().model.is_empty());
}
#[test]
fn start_paste_table_uses_standard_command_lifecycle() {
let mut empty = Session::empty();
assert!(matches!(empty.start_paste_table("A\tB\n1\t2\n", None), Err(crate::EngineError::Disabled(_, _))));
let mut s = Session::new();
let before_started = s.commands_started;
s.start_paste_table("A\tB\n1\t2\n", None).unwrap();
assert_eq!(s.commands_started, before_started + 1);
assert_eq!(s.last_command.as_deref(), Some("pastetable"));
}
}
+260 -6
View File
@@ -2,20 +2,28 @@
//! (TRIMEXTENDMODE), cutting/boundary edges, Fence, Crossing, Project (PROJMODE), Edge (EDGEMODE),
//! eRase and Undo. The geometry of one trim or extend is in modify.rs.
use std::cell::RefCell;
use std::sync::Arc;
use cadcraft_doc::{Drawing, EntityKind, Handle};
use cadcraft_geom::{Bounds2, Line, Vec2, line_line};
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle};
use cadcraft_geom::{Bounds2, Line, Segment, Vec2, line_line};
use serde_json::{Value, json};
use super::curves::KW;
use super::helpers::{line, lwpoly, rect_vertices};
use super::modify::{CUT_ONCE, Edges, extend, json_pick_error, trim};
use super::modify::{
CUT_ONCE, Edges, Overlay, edge_segments, edge_segments_over, extend, extend_kind, extended, json_pick_error, trim, trim_kind, trimmed,
};
use super::{bad, point_param, points_param};
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
/// Most fence points the JSON form takes.
const MAX_FENCE: usize = 10_000;
/// Most picks a Fence or Crossing preview works out ([`TrimM`]'s `highlight_all`). Each pick
/// gathers the cutting edges over the whole drawing again, on every cursor move, so a fence across
/// a crowded drawing shows no part highlight at all rather than slow the drawing area down; the
/// fence itself still trims everything it crosses.
pub const PREVIEW_MAX_PICKS: usize = 64;
/// TRIMEXTENDMODE: 1 (default) Quick, 0 Standard.
fn quick_mode(s: &Session) -> bool {
@@ -57,6 +65,13 @@ fn apply(s: &mut Session, h: Handle, at: Vec2, extending: bool, edges: Edges, qu
/// Trim (or extend) every object the fence `pts` crosses, at each crossing (extend: at the first).
/// Returns how many trims or extends were made.
fn fence(s: &mut Session, pts: &[Vec2], extending: bool, edges: Edges, quick: bool) -> Result<usize> {
let (work, tol) = fence_work(s, pts)?;
run_picks(s, work, extending, edges, quick, tol)
}
/// What a fence through `pts` trims or extends: each object it crosses with its crossings, in
/// fence order, and the tolerance they were found to.
fn fence_work(s: &Session, pts: &[Vec2]) -> Result<(Vec<(Handle, Vec<Vec2>)>, f64)> {
let space = s.space();
let d = s.doc()?;
let fb = Bounds2::from_points(pts.iter().copied());
@@ -81,7 +96,7 @@ fn fence(s: &mut Session, pts: &[Vec2], extending: bool, edges: Edges, quick: bo
}
work.push((h, xs));
}
run_picks(s, work, extending, edges, quick, tol)
Ok((work, tol))
}
/// How far along a segment from its end a crossing window's pick is kept: past the 5e-7 within
@@ -92,6 +107,13 @@ const OFF_VERTEX: f64 = 1e-6;
/// Trim (or extend) every object a crossing window from `a` to `b` touches, picked at its point
/// in the window nearest the first corner `a`.
fn crossing(s: &mut Session, a: Vec2, b: Vec2, extending: bool, edges: Edges, quick: bool) -> Result<usize> {
let (work, tol) = crossing_work(s, a, b)?;
run_picks(s, work, extending, edges, quick, tol)
}
/// What a crossing window from `a` to `b` trims or extends: each object it touches with its pick
/// point, and the tolerance they were found to.
fn crossing_work(s: &Session, a: Vec2, b: Vec2) -> Result<(Vec<(Handle, Vec<Vec2>)>, f64)> {
let space = s.space();
let d = s.doc()?;
let bx = Bounds2::new(a, b);
@@ -130,7 +152,82 @@ fn crossing(s: &mut Session, a: Vec2, b: Vec2, extending: bool, edges: Edges, qu
work.push((h, vec![p]));
}
}
run_picks(s, work, extending, edges, quick, tol)
Ok((work, tol))
}
/// What [`run_picks`] would change, worked out without changing the drawing: for each trim, the
/// piece it removes (a whole object Quick mode erases), and for each extend the stretch it adds,
/// with the handle of the object it belongs to. Each object is trimmed at its picks in turn, as
/// `run_picks` does, against edges that include what the run has already made of other objects
/// ([`Overlay`]), so the preview of a fence or a crossing window is what it will do. `px`: the
/// tolerance the changes are drawn to.
fn picks_preview(
s: &Session,
work: &[(Handle, Vec<Vec2>)],
extending: bool,
edges: Edges,
quick: bool,
tol: f64,
px: f64,
) -> Vec<(Handle, EntityKind)> {
let Ok(d) = s.doc() else { return Vec::new() };
let mut overlay = Overlay::new();
let mut out = Vec::new();
// Handles for the pieces a trim makes, apart from any in the drawing.
let mut next = u64::MAX;
let mut fresh = || {
next -= 1;
Handle(next)
};
for (h, picks) in work {
let Some(orig) = d.entity(*h) else { continue };
if crate::cmd::curves::is_locked(s, *h) {
continue;
}
let entity = |handle: Handle, kind: &EntityKind| Entity { handle, common: orig.common.clone(), kind: kind.clone() };
let mut live: Vec<(Handle, EntityKind)> = vec![(*h, orig.kind.clone())];
for x in picks {
let target = live
.iter()
.enumerate()
.map(|(i, (ph, k))| (i, crate::select::entity_distance(d, &entity(*ph, k), *x, tol)))
.filter(|(_, dist)| *dist <= 3.0 * tol)
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(i, _)| i);
let Some(i) = target else { continue };
let Some((ph, piece)) = live.get(i).cloned() else { continue };
overlay.insert(*h, live.clone());
let Ok(cut) = edge_segments_over(s, edges, ph, &overlay) else { continue };
if extending {
if let Ok(grown) = extend_kind(&piece, *x, &cut) {
out.extend(uncovered(d, &entity(ph, &grown), std::slice::from_ref(&piece), px).into_iter().map(|k| (*h, k)));
if let Some(slot) = live.get_mut(i) {
slot.1 = grown;
}
}
break;
}
let itself = edges.only.is_none_or(|o| o.contains(&ph));
match trim_kind(&piece, *x, itself, &cut) {
Ok(Some(kept)) => {
out.extend(uncovered(d, &entity(ph, &piece), &kept, px).into_iter().map(|k| (*h, k)));
live.remove(i);
let mut kept = kept.into_iter();
if let Some(first) = kept.next() {
live.insert(i, (ph, first));
}
live.extend(kept.map(|k| (fresh(), k)));
}
Err(err) if quick && misses_edges(&err) => {
out.push((*h, piece));
live.remove(i);
}
Ok(None) | Err(_) => {}
}
}
overlay.insert(*h, live);
}
out
}
/// Trim (or extend) each object at its pick points. A trim leaves the object in pieces, so later
@@ -264,11 +361,54 @@ pub(crate) struct TrimM {
stage: Stage,
/// The drawing before each trim, extend or erase, for Undo.
undo: Vec<Arc<Drawing>>,
/// The edges of the object under the cursor, for the rollover highlight ([`CutCache`]).
cut: RefCell<Option<CutCache>>,
}
/// The cutting or boundary edges of the object under the cursor, kept while the drawing, the
/// object and the modes stay the same. The rollover highlight works a trim out at every cursor
/// move, and in Quick mode the edges are every object in the drawing: gathering them once keeps
/// moving the cursor along one object cheap.
struct CutCache {
doc: usize,
h: Handle,
quick: bool,
implied: bool,
cut: Vec<Segment>,
}
impl TrimM {
pub(crate) fn new(extend: bool) -> Self {
TrimM { extend, edges: None, stage: Stage::Pick, undo: Vec::new() }
TrimM { extend, edges: None, stage: Stage::Pick, undo: Vec::new(), cut: RefCell::new(None) }
}
/// What a click on `h` at `cursor` changes: the piece a trim removes (the whole object when a
/// Quick-mode trim erases it), or the stretch an extend adds. `None` when the click would
/// change nothing or can't be worked out; the rollover highlight then shows the whole object.
fn change(&self, s: &Session, h: Handle, cursor: Vec2) -> Option<Vec<EntityKind>> {
let (quick, implied) = (quick_mode(s), edge_mode(s));
let doc = Arc::as_ptr(&s.state().ok()?.doc) as usize;
let mut cache = self.cut.borrow_mut();
if !cache.as_ref().is_some_and(|c| c.doc == doc && c.h == h && c.quick == quick && c.implied == implied) {
let cut = edge_segments(s, self.edges(quick, implied), h).ok()?;
*cache = Some(CutCache { doc, h, quick, implied, cut });
}
let cut = &cache.as_ref()?.cut;
let d = s.doc().ok()?;
let e = d.entity(h)?;
// Half a pixel: finer than the eye can tell apart, coarse enough to stay quick.
let tol = (s.pixel_size() / 2.0).max(1e-9);
let part = if self.extend {
let grown = Entity { kind: extended(s, h, cursor, cut).ok()?, ..(**e).clone() };
uncovered(d, &grown, std::slice::from_ref(&e.kind), tol)
} else {
match trimmed(s, h, cursor, self.edges(quick, implied), cut) {
Ok(Some(kept)) => uncovered(d, e, &kept, tol),
Ok(None) => return None,
Err(err) if quick && misses_edges(&err) => vec![e.kind.clone()],
Err(_) => return None,
}
};
(!part.is_empty()).then_some(part)
}
fn edges(&self, quick: bool, implied: bool) -> Edges<'_> {
Edges { only: self.edges.as_deref(), implied: !quick && implied }
@@ -407,6 +547,8 @@ impl Interactive for TrimM {
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
// The edges may change (picked again, Undo): gather them afresh for the highlight.
self.cut.take();
let quick = quick_mode(s);
let implied = edge_mode(s);
let extending = self.extend;
@@ -555,6 +697,30 @@ impl Interactive for TrimM {
},
}
}
fn highlight(&self, s: &Session, h: Handle, cursor: Vec2) -> Option<Vec<EntityKind>> {
if self.stage != Stage::Pick {
return None;
}
self.change(s, h, cursor)
}
fn highlight_all(&self, s: &Session, cursor: Vec2) -> Option<Vec<(Handle, EntityKind)>> {
let (quick, implied) = (quick_mode(s), edge_mode(s));
let found = match &self.stage {
Stage::Fence(pts) if !pts.is_empty() => {
let pts: Vec<Vec2> = pts.iter().copied().chain(std::iter::once(cursor)).collect();
fence_work(s, &pts)
}
Stage::QuickFence(a) => fence_work(s, &[*a, cursor]),
Stage::Crossing(Some(a)) => crossing_work(s, *a, cursor),
_ => return None,
};
let (work, tol) = found.ok()?;
if work.iter().map(|(_, picks)| picks.len()).sum::<usize>() > PREVIEW_MAX_PICKS {
return None;
}
let px = (s.pixel_size() / 2.0).max(1e-9);
Some(picks_preview(s, &work, self.extend, self.edges(quick, implied), quick, tol, px))
}
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
match &self.stage {
Stage::Fence(pts) if !pts.is_empty() => pts
@@ -571,3 +737,91 @@ impl Interactive for TrimM {
}
}
}
/// The stretches of `e`'s outline that none of `others` runs along, as polylines flattened to
/// `tol`: what a trim takes away (the object less the pieces it keeps), or what an extend adds
/// (the object as extended less the object as it was). Each segment of the outline is first split
/// where one of `others` ends on it, so a stretch is either all on them or all off them.
fn uncovered(d: &Drawing, e: &Entity, others: &[EntityKind], tol: f64) -> Vec<EntityKind> {
// Two flattenings of one curve, each within `tol` of it, lie within twice that of each other.
let near = 3.0 * tol;
let theirs: Vec<Vec<Vec2>> =
chains(others.iter().flat_map(|k| crate::select::hit_polylines(d, &Entity { kind: k.clone(), ..e.clone() }, tol)).collect());
let ends: Vec<Vec2> = theirs.iter().flat_map(|pl| [pl.first().copied(), pl.last().copied()]).flatten().collect();
// Their segments, each with its box and the ends of the piece it belongs to, worked out once:
// the test below runs for every stretch of the outline.
let spans: Vec<(Line, Bounds2, Vec2, Vec2)> = theirs
.iter()
.flat_map(|pl| {
let ends = (pl.first().copied(), pl.last().copied());
pl.windows(2).filter_map(move |w| {
let (a, b) = (*w.first()?, *w.get(1)?);
Some((Line::new(a, b), Bounds2::from_points([a, b]), ends.0?, ends.1?))
})
})
.collect();
// On them: near one of them, and not only near one of their ends (a point just past where a
// piece ends is near that end, yet off the piece). A segment whose box is farther than `near`
// from the point can't be that near it, so it is passed over without working out its distance.
let on_theirs = |p: Vec2| {
spans.iter().any(|(l, b, first, last)| {
if p.x < b.min.x - near || p.x > b.max.x + near || p.y < b.min.y - near || p.y > b.max.y + near {
return false;
}
let c = l.closest(p);
c.dist(p) <= near && !(c.near(*first, 1e-12 * (1.0 + c.len())) || c.near(*last, 1e-12 * (1.0 + c.len())))
})
};
let mut out = Vec::new();
let mut run: Vec<Vec2> = Vec::new();
let mut flush = |run: &mut Vec<Vec2>| {
if run.len() >= 2 {
out.push(lwpoly(std::mem::take(run).into_iter().map(cadcraft_geom::PolyVertex::new).collect(), false));
}
run.clear();
};
for pl in chains(crate::select::hit_polylines(d, e, tol)) {
for w in pl.windows(2) {
let (Some(&a), Some(&b)) = (w.first(), w.get(1)) else { continue };
let ab = Line::new(a, b);
let len = ab.len();
if len <= 0.0 {
continue;
}
let mut ts: Vec<f64> = ends.iter().filter(|p| ab.closest(**p).dist(**p) <= near).map(|p| ab.param_of(*p).clamp(0.0, 1.0)).collect();
ts.extend([0.0, 1.0]);
ts.sort_by(f64::total_cmp);
ts.dedup_by(|x, y| (*x - *y).abs() * len <= 1e-9 * (1.0 + a.len()));
for t in ts.windows(2) {
let (Some(&t0), Some(&t1)) = (t.first(), t.get(1)) else { continue };
let (p, q) = (ab.at(t0), ab.at(t1));
if on_theirs(ab.at((t0 + t1) / 2.0)) {
flush(&mut run);
} else {
if run.last().is_none_or(|l| !l.near(p, 1e-12 * (1.0 + p.len()))) {
flush(&mut run);
run.push(p);
}
run.push(q);
}
}
}
flush(&mut run);
}
out
}
/// `pls` with each one that starts where the one before it ends joined onto it: a curve's
/// flattening may come as many short pieces, one after the other.
fn chains(pls: Vec<Vec<Vec2>>) -> Vec<Vec<Vec2>> {
let mut out: Vec<Vec<Vec2>> = Vec::new();
for pl in pls {
match (out.last_mut(), pl.first()) {
(Some(last), Some(&first)) if last.last().is_some_and(|l| l.near(first, 1e-12 * (1.0 + first.len()))) => {
last.extend(pl.into_iter().skip(1));
}
_ => out.push(pl),
}
}
out
}
@@ -41,6 +41,7 @@ pub const FILES: &[&str] = &[
"options",
"pagesetup",
"pdfbook",
"pdfimport",
"plot",
"plotstyle",
"plottermanager",
@@ -100,6 +101,7 @@ pub const NO_FILES: &[&str] = &[
"pasteclip",
"pasteblock",
"pasteorig",
"pastetable",
"erase.selection",
"selectall",
"ai_deselect",
@@ -278,6 +280,7 @@ pub const NO_FILES: &[&str] = &[
"stretch",
"offset",
"trim",
"extrim",
"extend",
"fillet",
"chamfer",
+4 -1
View File
@@ -170,13 +170,16 @@ pub fn stretch_grip(kind: &EntityKind, index: usize, to: Vec2) -> Option<EntityK
if index == 0 {
return Some(translated(kind, delta));
}
let a = i.attribs.get_mut(index - 1)?;
let k = i.grip_attribs().nth(index - 1).map(|(k, _)| k)?;
let a = i.attribs.get_mut(k)?;
let ip = a.text.insert.xy() + delta;
set_xy(&mut a.text.insert, ip);
if let Some(al) = &mut a.text.align_pt {
let q = al.xy() + delta;
set_xy(al, q);
}
// A multiline attribute is drawn from its multiline text: it moves too.
a.transform_multiline(&Mat3::translate(delta));
}
EntityKind::Dimension(d) => {
match index {
+69
View File
@@ -92,6 +92,33 @@ impl Interactive for Guarded {
Vec::new()
})
}
fn live_value(&self, s: &Session, cursor: Vec2) -> Option<String> {
if self.broken.get().is_some() {
return None;
}
catch_unwind(AssertUnwindSafe(|| self.inner.live_value(s, cursor))).unwrap_or_else(|_| {
self.broken.set(Some("panic in preview"));
None
})
}
fn highlight(&self, s: &Session, h: cadcraft_doc::Handle, cursor: Vec2) -> Option<Vec<EntityKind>> {
if self.broken.get().is_some() {
return None;
}
catch_unwind(AssertUnwindSafe(|| self.inner.highlight(s, h, cursor))).unwrap_or_else(|_| {
self.broken.set(Some("panic in preview"));
None
})
}
fn highlight_all(&self, s: &Session, cursor: Vec2) -> Option<Vec<(cadcraft_doc::Handle, EntityKind)>> {
if self.broken.get().is_some() {
return None;
}
catch_unwind(AssertUnwindSafe(|| self.inner.highlight_all(s, cursor))).unwrap_or_else(|_| {
self.broken.set(Some("panic in preview"));
None
})
}
fn drag(&self, s: &Session, cursor: Vec2) -> Option<crate::prompt::Drag> {
if self.broken.get().is_some() {
return None;
@@ -128,6 +155,48 @@ impl Interactive for Guarded {
None
})
}
fn attribute_entry(&self) -> Option<crate::prompt::AttribEntry> {
if self.broken.get().is_some() {
return None;
}
catch_unwind(AssertUnwindSafe(|| self.inner.attribute_entry())).unwrap_or_else(|_| {
self.broken.set(Some("panic in prompt"));
None
})
}
fn array_live(&self) -> Option<crate::ArrayLive> {
if self.broken.get().is_some() {
return None;
}
catch_unwind(AssertUnwindSafe(|| self.inner.array_live())).unwrap_or_else(|_| {
self.broken.set(Some("panic in prompt"));
None
})
}
fn set_array_live(&mut self, s: &mut Session, v: &crate::ArrayLive) -> Result<()> {
if let Some(m) = self.broken.get() {
return Err(EngineError::Internal(self.inner.name().to_ascii_lowercase(), m.into()));
}
catch_unwind(AssertUnwindSafe(|| self.inner.set_array_live(s, v))).unwrap_or_else(|p| Err(self.internal(&*p)))
}
fn array_set_main(&mut self) -> bool {
if self.broken.get().is_some() {
return false;
}
catch_unwind(AssertUnwindSafe(|| self.inner.array_set_main())).unwrap_or_else(|_| {
self.broken.set(Some("panic in prompt"));
false
})
}
fn array_pick_center(&mut self) -> bool {
if self.broken.get().is_some() {
return false;
}
catch_unwind(AssertUnwindSafe(|| self.inner.array_pick_center())).unwrap_or_else(|_| {
self.broken.set(Some("panic in prompt"));
false
})
}
}
#[cfg(test)]
+30 -1
View File
@@ -7,6 +7,7 @@
//! [`Session::input`], [`Session::cmdline`]) exactly like typing at AutoCAD's command line.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
pub mod array_live;
pub mod assoc;
#[cfg(not(target_arch = "wasm32"))]
@@ -48,6 +49,7 @@ use cadcraft_geom::{Bounds2, Vec2};
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub use array_live::{ArrayLive, ArrayLiveKind};
pub use cadcraft_doc as doc;
pub use cadcraft_fonts as fonts;
pub use cadcraft_geom as geom;
@@ -55,7 +57,7 @@ pub use cadcraft_render as render;
pub use cmd::blocks::WblockPicks;
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices};
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
pub use prompt::{Accept, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
pub use prompt::{Accept, AttribAsk, AttribEntry, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
mod doc_state;
mod error;
@@ -80,6 +82,18 @@ pub fn build_version() -> &'static str {
&VERSION
}
/// Who started the command running now ([`Session::start`]): a person at the command line or
/// from a menu, toolbar or palette, or a program (a script, an AutoLISP `(command …)`, a JSON
/// call). The origin is fixed when the command starts and kept for its whole life: only a
/// person's INSERT opens the Edit Attributes dialog, since nobody is there to answer one that a
/// program opened, and nobody has seen it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Origin {
#[default]
Person,
Program,
}
/// The editor session: open drawings, settings, the running command and the command log.
pub struct Session {
pub docs: Vec<DocState>,
@@ -91,11 +105,23 @@ pub struct Session {
pub running: Option<Running>,
/// How many commands were started, nested transparent ones left out.
pub commands_started: u64,
/// How many inputs the session was given ([`Session::input`]): answers to a running command or
/// to a LISP routine waiting for one, and the Enter that repeats the last command.
pub inputs: u64,
/// Who started the command running now ([`Origin`]): a command keeps the origin it started
/// with, so a scripted or LISP-started INSERT never opens a dialog, even when the user then
/// answers its prompts by hand.
command_origin: Origin,
/// The last command that ended by itself, not cancelled: its number in `commands_started`, and
/// whether it took new handles (it added to the drawing, and nothing took that back).
pub last_finished: Option<(u64, bool)>,
/// A script is running ([`Session::script`]); a SCRIPT command inside it is refused.
in_script: bool,
/// The LISP evaluator is running ([`Session::lisp_drive`]): what a routine feeds the command
/// line — the command it starts, or a `'command` token it types into a running one — is the
/// program's input, so [`Session::start`] records [`Origin::Program`] for it. Saved and
/// restored around each slice of a routine, so nesting keeps the outer answer.
program_input: bool,
/// The command suspended while a transparent command (`'ZOOM`, `'PAN`…) prompts inside it;
/// it resumes when that command ends. One level, as in AutoCAD.
pub suspended: Option<Running>,
@@ -192,8 +218,11 @@ impl Session {
settings: Settings::default(),
running: None,
commands_started: 0,
inputs: 0,
command_origin: Origin::Person,
last_finished: None,
in_script: false,
program_input: false,
suspended: None,
log: Vec::new(),
last_command: None,
+6
View File
@@ -363,11 +363,17 @@ impl Session {
let mut env = self.lisp_env_take();
value::set_string_budget(run.string_bytes, self.lisp.limits.string_bytes);
value::set_cell_limit(self.lisp.limits.cells.max(run.cells_at_start));
// What the routine feeds the command line is the program's input: the command it
// starts, even when another one is running and the token reaches
// [`Session::typed`] first, never opens a dialog. Restored after the slice, a panic
// in it included, so a person's later command keeps its own origin.
let program_input = std::mem::replace(&mut self.program_input, true);
let outcome = {
let machine = &mut run.machine;
let mut ctx = Ctx { s: self, env: &mut env, depth: 0 };
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| machine.run(&mut ctx, SLICE)))
};
self.program_input = program_input;
run.string_bytes = value::string_bytes_used();
let outcome = match outcome {
Ok(o) => o,
+5 -3
View File
@@ -70,7 +70,9 @@ fn items(p: &PickSet) -> Vec<Handle> {
/// selection set picks objects (a name, alone or with a point as `entsel` gives it, also answers
/// a prompt picking one object: [`Session::input_object`]), and `pause` waits for the user. A
/// command not finished by the arguments stays active for the next `command` call. No
/// arguments: cancel the active command.
/// arguments: cancel the active command. Whatever it feeds is the program's input
/// ([`crate::Origin::Program`]): the command it starts here, and the one a `'command` token
/// starts while another command runs, never open a dialog.
pub fn command(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
if a.is_empty() {
if ctx.s.running.is_some() {
@@ -91,7 +93,7 @@ pub fn command(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
}
Value::Str(s) => {
let r = if ctx.s.running.is_none() {
if s.trim().is_empty() { Ok(()) } else { ctx.s.start(s) }
if s.trim().is_empty() { Ok(()) } else { ctx.s.start_programmatic(s) }
} else if s.is_empty() {
ctx.s.input(Input::Enter)
} else {
@@ -813,7 +815,7 @@ fn interactive_ssget(ctx: &mut Ctx<'_>, filter: Option<Value>) -> Result<Flow, L
if ctx.s.running.is_some() {
return Ok(Flow::Value(Value::Nil));
}
if let Err(e) = ctx.s.start("select") {
if let Err(e) = ctx.s.start_programmatic("select") {
return Err(LispError::new(e.to_string()));
}
let f = super::eval::lookup(ctx.env, &super::value::Sym::new("SSGET"));
+91
View File
@@ -103,6 +103,10 @@ pub struct Prompt {
/// the routine writes, so it cannot be read for the word "Select" (#1598).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub picks_one: bool,
/// The value asked for is an angle about the base (a rotation grip): Dynamic Input shows one
/// angle box, with the command's live value ([`Interactive::live_value`]).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub angle: bool,
/// The prompt takes a block's name as well as its keywords: a Greek word that is an existing
/// block's name is that block, not a keyword read from its Latin keys.
#[serde(skip_serializing_if = "std::ops::Not::not")]
@@ -154,6 +158,11 @@ impl Prompt {
self.grip = Some(g);
self
}
/// An angle about the base is asked for (the `angle` field).
pub fn angle(mut self) -> Self {
self.angle = true;
self
}
/// The visual chooser the UI can show (the `picker` field).
pub fn picker(mut self, p: Picker) -> Self {
self.picker = Some(p);
@@ -326,6 +335,24 @@ pub trait Interactive: Send {
fn preview_objects(&self, _s: &Session, _cursor: Vec2) -> Vec<cadcraft_doc::Entity> {
Vec::new()
}
/// The value the cursor would give, as the prompt asks for it (an angle as the drawing
/// shows angles): what Dynamic Input shows in its box before anything is typed.
fn live_value(&self, _s: &Session, _cursor: Vec2) -> Option<String> {
None
}
/// What the rollover highlight shows of the object `h` under the cursor, when it is not the
/// whole object (TRIM: the piece a click there removes; EXTEND: what it adds). `None`: the
/// whole object, as for any other command.
fn highlight(&self, _s: &Session, _h: cadcraft_doc::Handle, _cursor: Vec2) -> Option<Vec<EntityKind>> {
None
}
/// What the running command will change wherever the cursor is, highlighted in place of the
/// object under it (TRIM's Fence and Crossing: every piece the fence or the window will
/// remove), each with the handle of the object it is part of. `None`: nothing of the kind,
/// and the object under the cursor is highlighted as [`Interactive::highlight`] says.
fn highlight_all(&self, _s: &Session, _cursor: Vec2) -> Option<Vec<(cadcraft_doc::Handle, EntityKind)>> {
None
}
/// The preview as existing objects under one transform, when it is that (MOVE, COPY,
/// ROTATE, SCALE). The UI then draws them from geometry uploaded once instead of rebuilding
/// the transformed copies every frame; `None` falls back to [`Interactive::preview`].
@@ -348,6 +375,28 @@ pub trait Interactive: Send {
fn display_only(&self, _s: &Session) -> Option<DisplayOnly> {
None
}
/// The attribute values the command waits for, all at once, when the UI should ask for them
/// in the Edit Attributes dialog (INSERT with ATTDIA 1). Typed answers still work.
fn attribute_entry(&self) -> Option<AttribEntry> {
None
}
/// The live parameters of the running array (ARRAYRECT / ARRAYPOLAR), for the array window.
fn array_live(&self) -> Option<crate::ArrayLive> {
None
}
/// Replace the running array's live parameters, as the array window's fields change them.
fn set_array_live(&mut self, _s: &mut Session, _v: &crate::ArrayLive) -> Result<()> {
Err(crate::EngineError::Other("this command has no live array parameters".into()))
}
/// Put the command back at its Main option loop (the state eXit/Enter finishes from).
/// False when the command cannot commit yet (e.g. the polar centre is still unspecified).
fn array_set_main(&mut self) -> bool {
false
}
/// Ask the next canvas point to be the polar centre. False when the command has no centre.
fn array_pick_center(&mut self) -> bool {
false
}
}
/// See [`Interactive::display_only`]: the only things drawn in the current view while a command
@@ -389,6 +438,48 @@ pub enum EditorKind {
Dimension { measured: String },
}
/// See [`Interactive::attribute_entry`]: the block being inserted and the attributes asked for,
/// in order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AttribEntry {
pub block: String,
pub rows: Vec<AttribAsk>,
/// The drawing the command runs in ([`crate::DocState::uid`]) and its number in
/// [`Session::commands_started`], stamped by [`Session::attribute_entry`]: a dialog draft
/// belongs to one command, so a command started afterwards never takes it.
pub drawing: u64,
pub command: u64,
}
/// One attribute an INSERT asks for: its tag, prompt and default value; the value of a Verify
/// one is asked again once every value is in.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AttribAsk {
pub tag: String,
pub prompt: String,
pub default: String,
pub verify: bool,
}
impl AttribEntry {
/// An entry as the command builds it, before [`Session::attribute_entry`] stamps the drawing
/// and command number it belongs to.
pub(crate) fn idle(block: String, rows: Vec<AttribAsk>) -> Self {
AttribEntry { block, rows, drawing: 0, command: 0 }
}
/// The answers that give the attributes `values` (one per row, in order; a missing one is
/// the default) when typed in turn: every value, then each Verify attribute's again, as
/// INSERT asks them once the dialog has shown the values.
pub fn answers(&self, values: &[String]) -> Vec<String> {
let value = |i: usize| values.get(i).cloned().unwrap_or_else(|| self.rows.get(i).map(|r| r.default.clone()).unwrap_or_default());
let mut out: Vec<String> = (0..self.rows.len()).map(value).collect();
let verify: Vec<String> = self.rows.iter().enumerate().filter(|(_, r)| r.verify).map(|(i, _)| value(i)).collect();
out.extend(verify);
out
}
}
/// See [`Interactive::drag`].
#[derive(Clone, Debug)]
pub struct Drag {
+630 -12
View File
@@ -6,26 +6,64 @@ use cadcraft_geom::{Bounds2, Line, Vec2, point_in_polygon};
use crate::spatial::{self, SpatialIndex};
use crate::{Accept, Prompt};
/// A dimension kept as read whose graphics are a reference to its `*D` block (#3438).
fn draws_a_block(e: &Entity) -> bool {
matches!(&e.kind, EntityKind::Unknown(u) if u.graphics.iter().any(|g| matches!(g.kind, EntityKind::Insert(_))))
}
/// Polylines approximating an entity for hit testing, tessellated at `tol`.
pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec<Vec<Vec2>> {
if matches!(e.kind, EntityKind::Insert(_)) {
let list = insert_geometry(d, e, tol);
return list
.prims
.iter()
.flat_map(|p| match p.kind {
cadcraft_render::Kind::Tris | cadcraft_render::Kind::Mask => {
list.points(p).as_chunks::<3>().0.iter().map(|t| vec![t[0], t[1], t[2], t[0]]).collect()
}
cadcraft_render::Kind::Infinite { ray } => match list.points(p) {
[base, dir] => {
let far = 1e9;
vec![vec![if ray { *base } else { *base - *dir * far }, *base + *dir * far]]
}
_ => Vec::new(),
},
// An image's points are its unclipped corners: it is hit on the outline of what
// it shows, so a clipped-away part doesn't pick the reference.
cadcraft_render::Kind::Image { index } => match list.images.get(index as usize) {
Some(img) if img.clips.is_empty() => {
let [a, b, c, d] = img.corners();
vec![vec![a, b, c, d, a]]
}
Some(img) => shown_image_tris(img).as_chunks::<3>().0.iter().map(|t| vec![t[0], t[1], t[2], t[0]]).collect(),
None => Vec::new(),
},
_ => vec![list.points(p).to_vec()],
})
.collect();
}
match &e.kind {
EntityKind::Text(_)
| EntityKind::MText(_)
| EntityKind::Insert(_)
| EntityKind::Dimension(_)
| EntityKind::AttDef(_)
| EntityKind::Table(_)
| EntityKind::Tolerance(_)
| EntityKind::MLeader(_)
| EntityKind::Image(_) => {
// Text-like objects are hit inside their box.
| EntityKind::Image(_)
| EntityKind::Unknown(_)
if !matches!(e.kind, EntityKind::Unknown(_)) || draws_a_block(e) =>
{
// Text-like objects are hit inside their box; a dimension kept as read that draws its
// block, like a dimension.
let b = entity_bounds(d, e, 0);
if b.is_empty() {
return Vec::new();
}
let c = b.corners();
let mut v = vec![vec![c[0], c[1], c[2], c[3], c[0]]];
if matches!(e.kind, EntityKind::Dimension(_) | EntityKind::Insert(_) | EntityKind::MLeader(_)) {
if matches!(e.kind, EntityKind::Dimension(_) | EntityKind::MLeader(_)) || draws_a_block(e) {
let list = cadcraft_render::build_entities(
d,
std::iter::once(e),
@@ -84,6 +122,44 @@ pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec<Vec<Vec2>> {
}
}
fn insert_geometry(d: &Drawing, e: &Entity, tol: f64) -> cadcraft_render::DisplayList {
cadcraft_render::build_entities(d, std::iter::once(e), &cadcraft_render::Options { tolerance: tol, linetypes: false, ..Default::default() })
}
/// The part of an image its clips leave showing, as triangles (three points each); empty when a
/// clip has no outline to cut with.
fn shown_image_tris(img: &cadcraft_render::DImage) -> Vec<Vec2> {
let [a, b, c, d] = img.corners();
let mut tris = vec![a, b, c, a, c, d];
for outline in &img.clips {
let Some(clip) = cadcraft_render::clip::PolyClip::new(outline) else { return Vec::new() };
tris = clip.clip_triangles(&tris);
if tris.is_empty() {
break;
}
}
tris
}
fn insert_fill_hits_box(d: &Drawing, e: &Entity, bx: &Bounds2, tol: f64) -> bool {
let list = insert_geometry(d, e, tol);
list.prims.iter().any(|p| {
if let cadcraft_render::Kind::Image { index } = p.kind {
let Some(img) = list.images.get(index as usize) else { return false };
return !cadcraft_render::clip::clip_triangles(&shown_image_tris(img), bx).is_empty();
}
if !matches!(p.kind, cadcraft_render::Kind::Tris | cadcraft_render::Kind::Mask) {
return false;
}
list.points(p).as_chunks::<3>().0.iter().any(|t| {
let triangle = [t[0], t[1], t[2]];
bx.corners().iter().any(|q| point_in_polygon(&triangle, *q))
|| triangle.iter().any(|q| bx.contains(*q))
|| (0..3).any(|i| seg_hits_box(triangle[i], triangle[(i + 1) % 3], bx))
})
})
}
fn dist_to_polyline(pts: &[Vec2], p: Vec2) -> f64 {
if pts.len() == 1 {
return pts.first().map(|q| q.dist(p)).unwrap_or(f64::INFINITY);
@@ -97,7 +173,7 @@ pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 {
let mut best = polys.iter().map(|pl| dist_to_polyline(pl, p)).fold(f64::INFINITY, f64::min);
let filled = matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::Table(_))
|| matches!(e.kind, EntityKind::Tolerance(_));
if (filled && entity_bounds(d, e, 0).contains(p)) || in_text(d, e, p) {
if (filled && entity_bounds(d, e, 0).contains(p)) || in_blank_mtext(d, e, p) || in_text(d, e, p) {
best = 0.0;
}
// A solid hatch fills its loops with odd parity under its island style, as it is drawn, not
@@ -185,10 +261,125 @@ pub(crate) fn kept_as_read(k: &EntityKind) -> bool {
/// Entities to test, in the order to test them, each with its bounds when already known.
pub(crate) type Cands<'a> = Box<dyn Iterator<Item = (&'a Entity, Option<Bounds2>)> + 'a>;
pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option<Bounds2>) -> Bounds2 {
known.unwrap_or_else(|| entity_bounds(d, e, 0))
/// Whether an MTEXT's contents draw nothing (empty, or only spaces and `\~`): it has no glyph
/// strokes, and the document's bounds for it are empty so it stays out of the drawing extents.
/// Called for every MTEXT when the spatial index is built, so it does not allocate.
fn is_blank_mtext(t: &cadcraft_doc::MText) -> bool {
t.contents.split(r"\~").all(|s| s.chars().all(char::is_whitespace))
}
/// The frame a blank MTEXT is picked in (#2810), for a top-level MTEXT and for a multileader's
/// MTEXT content: its insertion point, rotation and the box before turning (`x0, x1, y0, y1`
/// about the insertion point): its width (the text height when it has none) by its text height,
/// placed by its attachment point, at the size it draws at the current annotation scale (the
/// shared `anno_scaled`, which also moves a multileader's text about its landing). `None` for any
/// other entity, a multileader without text content, a blank MTEXT without a usable size or
/// position, or an annotative one the current annotation scale hides.
fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> {
// Kind and blankness first: scaling clones the entity, so only blank text pays for it.
let text = match &e.kind {
EntityKind::MText(t) => t,
EntityKind::MLeader(m) => m.text.as_ref()?,
_ => return None,
};
if !is_blank_mtext(text) {
return None;
}
let f = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Plain => 1.0,
cadcraft_doc::AnnoDraw::Scaled(f) if f.is_finite() && f > 0.0 => f,
cadcraft_doc::AnnoDraw::Scaled(_) => 1.0,
cadcraft_doc::AnnoDraw::Hidden => return None,
};
let scaled;
let e = if f != 1.0 {
scaled = cadcraft_doc::anno_scaled(e, f);
&scaled
} else {
e
};
let t = match &e.kind {
EntityKind::MText(t) => t,
EntityKind::MLeader(m) => m.text.as_ref()?,
_ => return None,
};
if !t.height.is_finite() || t.height <= 0.0 || !t.insert.xy().is_finite() || !t.rotation.is_finite() {
return None;
}
let w = if t.width.is_finite() && t.width > 0.0 { t.width } else { t.height };
let h = t.height;
let insert = t.insert.xy();
if !w.is_finite() || !h.is_finite() || !insert.is_finite() {
return None;
}
let dx = match t.attach {
2 | 5 | 8 => -w / 2.0,
3 | 6 | 9 => -w,
_ => 0.0,
};
let top = match t.attach {
4..=6 => h / 2.0,
7..=9 => h,
_ => 0.0,
};
// A top-level MTEXT that matches the layout orientation is drawn upright (the renderer draws
// non-blank text that way), so its blank frame is too; a multileader keeps its text's stored rotation.
let rotation = if matches!(e.kind, EntityKind::MText(_)) && e.common.matches_layout_orientation() { 0.0 } else { t.rotation };
Some((insert, rotation, [dx, dx + w, top - h, top]))
}
/// The box around a blank MTEXT's turned frame (a top-level MTEXT or a multileader's MTEXT
/// content), for the spatial index and windows (a crossing window may catch a little extra near a
/// corner, as it does for other text).
fn blank_mtext_box(d: &Drawing, e: &Entity) -> Option<Bounds2> {
let (o, rot, [x0, x1, y0, y1]) = blank_mtext_frame(d, e)?;
let corners = [Vec2::new(x0, y1), Vec2::new(x1, y1), Vec2::new(x1, y0), Vec2::new(x0, y0)];
Some(Bounds2::from_points(corners.map(|c| o + c.rotate(rot))))
}
/// Whether `p` is on a blank MTEXT or a multileader's blank MTEXT content: inside its box turned
/// with the text, not the larger box around it.
fn in_blank_mtext(d: &Drawing, e: &Entity, p: Vec2) -> bool {
let Some((o, rot, [x0, x1, y0, y1])) = blank_mtext_frame(d, e) else { return false };
let q = (p - o).rotate(-rot);
q.x >= x0 && q.x <= x1 && q.y >= y0 && q.y <= y1
}
/// Drawn bounds extended by a blank MTEXT frame, including a multileader's text content.
/// Use the same bounds for a scan and for the spatial index.
pub(crate) fn pick_bounds(d: &Drawing, e: &Entity, drawn: Bounds2) -> Bounds2 {
match blank_mtext_box(d, e) {
Some(frame) => drawn.union(&frame),
None => drawn,
}
}
/// The insertion points snap's INS mode offers for a blank MTEXT or multileader (the stored
/// points); empty for any other entity.
fn blank_snap_points(e: &Entity) -> Vec<Vec2> {
// select.rs blank_snap_points must offer the same points as snap.rs's INS arms.
match &e.kind {
EntityKind::MText(t) if is_blank_mtext(t) => vec![t.insert.xy()],
EntityKind::MLeader(m) if m.text.as_ref().is_some_and(is_blank_mtext) => {
m.text.iter().map(|t| t.insert.xy()).chain(m.block.iter().map(|b| b.insert.xy())).collect()
}
_ => Vec::new(),
}
}
/// Whether `e` is within reach of a snap probe only through its blank MTEXT frame: the drawn
/// geometry (expanded by `aperture`) misses `probe`, and no insertion point INS would offer (text
/// or block content) is a candidate: one counts only when `ins` is on and it is within `aperture`
/// of `cursor`, the distance snap accepts a candidate by (a corner of the square probe is not).
/// Such an entity is for picking and selection, not a snap candidate.
pub(crate) fn blank_frame_only(d: &Drawing, e: &Entity, probe: &Bounds2, cursor: Vec2, aperture: f64, ins: bool) -> bool {
let points = blank_snap_points(e);
!points.is_empty() && !(ins && points.iter().any(|p| p.dist(cursor) <= aperture)) && !entity_bounds(d, e, 0).expand(aperture).intersects(probe)
}
pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option<Bounds2>) -> Bounds2 {
known.unwrap_or_else(|| pick_bounds(d, e, entity_bounds(d, e, 0)))
}
pub(crate) fn is_infinite(e: &Entity) -> bool {
matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_))
}
@@ -344,8 +535,15 @@ pub(crate) fn in_window(d: &Drawing, e: &Entity, known: Option<Bounds2>, bx: &Bo
pl.windows(2).any(|w| w.first().zip(w.get(1)).is_some_and(|(a, b)| seg_hits_box(*a, *b, bx)))
}
});
// A crossing box entirely inside a text/block bounding rectangle also selects it.
if hit || (eb.contains_box(bx) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Insert(_))) {
// A crossing box inside a text bounding rectangle selects the text.
if hit
|| (eb.contains_box(bx) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_)))
|| (matches!(e.kind, EntityKind::Insert(_)) && insert_fill_hits_box(d, e, bx, tol))
{
return true;
}
// Likewise inside a blank MTEXT's frame (a multileader's too), where picking also selects it.
if blank_mtext_box(d, e).is_some_and(|frame| frame.contains_box(bx)) {
return true;
}
// SOLID/TRACE are filled polygons. A crossing window wholly within the
@@ -557,7 +755,7 @@ impl SelectMode {
#[cfg(test)]
mod tests {
use super::*;
use cadcraft_doc::{Common, RayLine};
use cadcraft_doc::{Common, Image, Raster, RayLine};
use cadcraft_geom::Vec3;
fn fence_hits(kind: EntityKind, fence: [(f64, f64); 2]) -> usize {
@@ -600,6 +798,272 @@ mod tests {
assert_eq!(pick(&d, &Space::Model, Vec2::new(41.3, 50.0), 1.0), Some(line));
}
fn mtext_at(contents: &str, attach: u8, rotation: f64) -> EntityKind {
EntityKind::MText(cadcraft_doc::MText {
insert: Vec3::new(0.0, 0.0, 0.0),
height: 2.5,
width: 10.0,
attach,
rotation,
style: "Standard".into(),
contents: contents.into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
})
}
/// A blank MTEXT has no strokes and empty drawn bounds, but it is still an object: a click
/// inside its width x height box picks it, and a click outside does not (#2810).
#[test]
fn a_blank_mtext_is_picked_inside_its_box() {
let blank = |c: &str| matches!(mtext_at(c, 1, 0.0), EntityKind::MText(t) if is_blank_mtext(&t));
assert!(!blank(r"a\~"));
assert!(blank(r"\~ \~"));
for contents in ["", " ", r"\~ "] {
let mut d = Drawing::new_metric();
let h = d.add(&Space::Model, Common::default(), mtext_at(contents, 1, 0.0)).unwrap();
let at = |x: f64, y: f64| pick(&d, &Space::Model, Vec2::new(x, y), 0.1);
assert_eq!(at(5.0, -1.0), Some(h), "{contents:?}");
assert_eq!(at(0.5, -2.0), Some(h), "{contents:?}");
assert_eq!(at(5.0, 3.0), None, "above the box, {contents:?}");
assert_eq!(at(12.0, -1.0), None, "right of the box, {contents:?}");
assert_eq!(pick_all(&d, &Space::Model, Vec2::new(5.0, -1.0), 0.1), vec![h]);
let w = Bounds2::new(Vec2::new(4.0, -2.0), Vec2::new(6.0, -1.0));
assert_eq!(select_window(&d, &Space::Model, w, true), vec![h], "crossing {contents:?}");
}
}
#[test]
fn a_blank_mleader_text_is_picked_inside_its_box() {
for contents in [" ", ""] {
let mut s = crate::Session::new();
let result = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap();
let h = Handle::parse_hex(result["handle"].as_str().unwrap()).unwrap();
// The command omits the text object for an empty string. Preserve the box here to
// exercise a stored empty MTEXT, which can still exist in an imported MLEADER.
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") };
m.text.as_mut().unwrap().contents = contents.into();
})
.unwrap();
let d = s.doc().unwrap();
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
let t = m.text.as_ref().unwrap();
let p = t.insert.xy() + Vec2::new(t.height / 2.0, -t.height / 4.0);
let aperture = t.height / 100.0;
assert_eq!(pick(d, &Space::Model, p, aperture), Some(h), "{contents:?}");
let d = s.doc_mut().unwrap();
for i in 0..spatial::MIN_INDEXED {
let y = 100.0 + i as f64;
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(50.0, y, 0.0), b: Vec3::new(60.0, y, 0.0) });
d.add(&Space::Model, Common::default(), line).unwrap();
}
assert!(spatial::index(d, &Space::Model).is_some());
assert_eq!(pick(d, &Space::Model, p, aperture), Some(h), "indexed {contents:?}");
}
}
#[test]
fn a_pick_away_from_normal_mleader_text_and_lines_misses() {
let mut s = crate::Session::new();
let result = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 10]], "text": "Visible" })).unwrap();
let h = Handle::parse_hex(result["handle"].as_str().unwrap()).unwrap();
assert_eq!(pick(s.doc().unwrap(), &Space::Model, Vec2::new(2.0, 8.0), 0.05), None);
// Give the text a wide box: a click inside it, right of the glyphs and off the leader, is
// still a miss, since only blank text is picked by its frame.
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") };
m.text.as_mut().unwrap().width = 5.0;
})
.unwrap();
let d = s.doc().unwrap();
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
let t = m.text.as_ref().unwrap();
let p = t.insert.xy() + Vec2::new(t.width * 0.8, 0.0);
assert_eq!(pick(d, &Space::Model, p, 0.02), None, "right of the glyphs, inside the frame");
assert_eq!(pick(d, &Space::Model, t.insert.xy() + Vec2::new(0.3, 0.0), 0.02), Some(h), "on the glyphs");
}
/// Only blank MTEXT has a frame: an annotative non-blank MTEXT and an annotative LINE have none
/// (and the kind and blankness are decided before any annotation scaling).
#[test]
fn only_blank_mtext_has_a_frame_even_when_annotative() {
let mut d = Drawing::new_metric();
d.header.set_str("CANNOSCALE", "1:2");
let half = d.anno_scale("1:2").cloned().unwrap();
let common = || Common { anno_scales: vec![half.clone()], ..Common::default() };
let text = d.add(&Space::Model, common(), mtext_at("Visible", 1, 0.0)).unwrap();
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(5.0, 0.0, 0.0) });
let line = d.add(&Space::Model, common(), line).unwrap();
let blank = d.add(&Space::Model, common(), mtext_at(" ", 1, 0.0)).unwrap();
for (h, framed) in [(text, false), (line, false), (blank, true)] {
let e = d.entity(h).unwrap();
assert_eq!(blank_mtext_frame(&d, e).is_some(), framed);
}
}
/// A multileader whose text is blank, with the text 6 units right of the landing, 4 wide and
/// 2 high, attached top-left.
fn blank_mleader(s: &mut crate::Session) -> Handle {
let result = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap();
let h = Handle::parse_hex(result["handle"].as_str().unwrap()).unwrap();
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") };
let landing = m.landing;
let t = m.text.as_mut().unwrap();
t.insert = landing + Vec3::new(6.0, 0.0, 0.0);
t.width = 4.0;
t.height = 2.0;
t.attach = 1;
t.rotation = 0.0;
})
.unwrap();
h
}
/// A crossing window wholly inside a blank multileader text's box selects it, as a click does.
#[test]
fn a_crossing_window_inside_a_blank_mleader_text_box_selects_it() {
let mut s = crate::Session::new();
let h = blank_mleader(&mut s);
let d = s.doc().unwrap();
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
let o = m.text.as_ref().unwrap().insert.xy();
let inside = Bounds2::new(o + Vec2::new(1.0, -1.5), o + Vec2::new(2.0, -0.5));
assert_eq!(select_window(d, &Space::Model, inside, true), vec![h]);
let outside = Bounds2::new(o + Vec2::new(5.0, -1.5), o + Vec2::new(6.0, -0.5));
assert!(select_window(d, &Space::Model, outside, true).is_empty());
}
/// An annotative multileader's blank text is picked where it draws at the current annotation
/// scale: its size and its offset from the landing both scale.
#[test]
fn an_annotative_blank_mleader_text_is_picked_at_its_drawn_offset_and_size() {
let mut s = crate::Session::new();
let h = blank_mleader(&mut s);
let d = s.doc_mut().unwrap();
d.header.set_str("CANNOSCALE", "1:2");
let half = d.anno_scale("1:2").cloned().unwrap();
d.modify_entity(h, |e| e.common.anno_scales = vec![half]).unwrap();
let d = s.doc().unwrap();
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
let l = m.landing.xy();
// At 1:2 the box is 8 x 4 from the landing + (12, 0) (top-left): x 12..20, y -4..0.
let at = |x: f64, y: f64| pick(d, &Space::Model, l + Vec2::new(x, y), 0.02);
assert_eq!(at(16.0, -1.0), Some(h), "inside the scaled box, outside the unscaled one");
assert_eq!(at(19.5, -3.5), Some(h), "far corner of the scaled box");
assert_eq!(at(8.0, -1.0), None, "inside the unscaled box, outside the scaled one");
assert_eq!(at(22.0, -1.0), None, "right of the scaled box");
}
/// The box follows the attachment point and the rotation, and a width of 0 falls back to the
/// text height.
#[test]
fn a_blank_mtext_box_follows_attachment_and_rotation() {
let mut d = Drawing::new_metric();
// Middle-centre: the box spans x -5..5, y -1.25..1.25.
let h = d.add(&Space::Model, Common::default(), mtext_at(" ", 5, 0.0)).unwrap();
let at = |d: &Drawing, x: f64, y: f64| pick(d, &Space::Model, Vec2::new(x, y), 0.05);
assert_eq!(at(&d, -4.0, 1.0), Some(h));
assert_eq!(at(&d, 4.0, -1.0), Some(h));
assert_eq!(at(&d, 4.0, 2.0), None);
// Turned a quarter turn about the insertion point: the box spans x -1.25..1.25, y -5..5.
let mut d = Drawing::new_metric();
let h = d.add(&Space::Model, Common::default(), mtext_at(" ", 5, std::f64::consts::FRAC_PI_2)).unwrap();
assert_eq!(at(&d, 1.0, 4.0), Some(h));
assert_eq!(at(&d, 4.0, 1.0), None);
// No width: as wide as the text is high.
let mut d = Drawing::new_metric();
let EntityKind::MText(mut t) = mtext_at("", 1, 0.0) else { panic!("mtext") };
t.width = 0.0;
let h = d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
assert_eq!(at(&d, 2.0, -1.0), Some(h));
assert_eq!(at(&d, 5.0, -1.0), None);
}
/// A top-level MTEXT that matches the layout orientation is drawn upright, ignoring its stored
/// rotation, so its frame is the unturned one (the renderer and the extents do the same).
#[test]
fn rotated_blank_mtext_matching_layout_orientation_is_picked_in_its_unrotated_frame() {
let mut d = Drawing::new_metric();
let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() };
let common = Common { xdata: vec![tag(1001, "AcadAnnoPO"), tag(1070, "1")], ..Common::default() };
let h = d.add(&Space::Model, common, mtext_at(" ", 1, std::f64::consts::FRAC_PI_2)).unwrap();
let at = |x: f64, y: f64| pick(&d, &Space::Model, Vec2::new(x, y), 0.05);
// Unrotated frame x 0..10, y -2.5..0; the rotated one would be x 0..2.5, y 0..10.
assert_eq!(at(5.0, -1.0), Some(h), "inside the unrotated frame");
assert_eq!(at(1.0, 5.0), None, "inside only the rotated frame");
}
/// A turned blank MTEXT is hit in its turned box, not in the axis-aligned box around it (whose
/// empty corners lie off the text).
#[test]
fn a_turned_blank_mtext_is_picked_in_its_turned_box() {
let mut d = Drawing::new_metric();
let h = d.add(&Space::Model, Common::default(), mtext_at(" ", 1, 30f64.to_radians())).unwrap();
let at = |x: f64, y: f64| pick(&d, &Space::Model, Vec2::new(x, y), 0.05);
// Local (5, -1.25), the centre of the box.
assert_eq!(at(4.955, 1.418), Some(h));
// Inside the box around the turned one, but local (2.87, 2.96) is above the text.
assert_eq!(at(1.0, 4.0), None);
}
/// An annotative blank MTEXT is picked in the box it draws at the current annotation scale,
/// and not at all while that scale hides it.
#[test]
fn an_annotative_blank_mtext_is_picked_at_its_drawn_size() {
let mut d = Drawing::new_metric();
d.header.set_str("CANNOSCALE", "1:2");
let half = d.anno_scale("1:2").cloned().unwrap();
let common = Common { anno_scales: vec![half], ..Common::default() };
// Middle-centre at 1:2: twice the size, x -10..10, y -2.5..2.5.
let h = d.add(&Space::Model, common, mtext_at(" ", 5, 0.0)).unwrap();
let at = |d: &Drawing, x: f64, y: f64| pick(d, &Space::Model, Vec2::new(x, y), 0.05);
assert_eq!(at(&d, 8.0, 2.0), Some(h), "inside the scaled box");
assert_eq!(at(&d, 11.0, 0.0), None, "outside the scaled box");
let w = Bounds2::new(Vec2::new(7.0, 1.0), Vec2::new(9.0, 2.0));
assert_eq!(select_window(&d, &Space::Model, w, true), vec![h], "crossing the scaled box");
// At 1:1 with only supported scales shown, the object is hidden: nothing to pick.
d.header.set_str("CANNOSCALE", "1:1");
d.header.set_i64("ANNOALLVISIBLE", 0);
assert_eq!(at(&d, 0.0, 0.0), None, "hidden");
let w = Bounds2::new(Vec2::new(-1.0, -1.0), Vec2::new(1.0, 1.0));
assert!(select_window(&d, &Space::Model, w, true).is_empty(), "hidden, crossing");
}
/// A drawing large enough for the spatial index must still offer a blank MTEXT as a candidate.
#[test]
fn a_blank_mtext_is_picked_in_an_indexed_drawing() {
let mut d = Drawing::new_metric();
for i in 0..(crate::spatial::MIN_INDEXED + 10) {
let y = 100.0 + i as f64;
let l = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(50.0, y, 0.0), b: Vec3::new(60.0, y, 0.0) });
d.add(&Space::Model, Common::default(), l).unwrap();
}
let h = d.add(&Space::Model, Common::default(), mtext_at("", 1, 0.0)).unwrap();
assert!(spatial::index(&d, &Space::Model).is_some());
assert_eq!(pick(&d, &Space::Model, Vec2::new(5.0, -1.0), 0.1), Some(h));
assert_eq!(pick(&d, &Space::Model, Vec2::new(5.0, 3.0), 0.1), None);
}
/// Text with words is still picked by its drawn box only.
#[test]
fn a_click_far_from_a_normal_mtext_misses() {
let mut d = Drawing::new_metric();
let h = d.add(&Space::Model, Common::default(), mtext_at("AB", 1, 0.0)).unwrap();
assert_eq!(pick(&d, &Space::Model, Vec2::new(1.0, -1.0), 0.1), Some(h));
assert_eq!(pick(&d, &Space::Model, Vec2::new(8.0, -1.0), 0.1), None);
assert_eq!(pick(&d, &Space::Model, Vec2::new(1.0, 5.0), 0.1), None);
}
/// An OLE2FRAME draws as its frame, so a click on an edge picks it (review on #2587); a click in
/// the middle of the frame, or on a frame without both corners, does not.
#[test]
@@ -652,8 +1116,8 @@ mod tests {
let e = d.entity(h).unwrap();
let drawn = cadcraft_render::build_entities(&d, std::iter::once(e.as_ref()), &cadcraft_render::Options { text: false, ..Default::default() });
assert!(drawn.prims.len() > 10_000, "the pattern draws {} dashes", drawn.prims.len());
// The line, and the block's bounding rectangle.
assert_eq!(hit_polylines(&d, e, 0.01).len(), 2);
// Hit testing uses the line without laying out every dash.
assert_eq!(hit_polylines(&d, e, 0.01).len(), 1);
}
/// A dashed line in a block is hit across its gaps, as one outside a block is.
@@ -668,6 +1132,126 @@ mod tests {
let gap = end + (start - end) * 0.5;
assert_eq!(pick(&d, &Space::Model, gap, end.dist(start) / 8.0), Some(h));
}
#[test]
fn crossing_a_transformed_block_requires_its_drawn_geometry() {
let mut d = Drawing::new_metric();
let mut block = cadcraft_doc::Block::new("two lines");
for y in [0.0, 5.0] {
block.entities.push(Entity::new(
Handle(10 + y as u64),
EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) }),
));
}
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
let insert = cadcraft_doc::Insert {
block: "two lines".into(),
insert: Vec3::new(30.0, 40.0, 0.0),
scale: Vec3::new(2.0, 2.0, 1.0),
rotation: std::f64::consts::FRAC_PI_2,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
let bx = |a, b| Bounds2::new(a, b);
let empty = bx(Vec2::new(24.0, 48.0), Vec2::new(26.0, 52.0));
let crossed = bx(Vec2::new(19.0, 48.0), Vec2::new(21.0, 52.0));
assert!(select_window(&d, &Space::Model, empty, true).is_empty());
assert_eq!(select_window(&d, &Space::Model, crossed, true), vec![h]);
assert!(select_window(&d, &Space::Model, crossed, false).is_empty());
assert_eq!(pick(&d, &Space::Model, Vec2::new(25.0, 40.0), 0.1), None);
}
#[test]
fn crossing_a_block_fill_uses_the_filled_shape() {
let mut d = Drawing::new_metric();
let mut block = cadcraft_doc::Block::new("filled triangle");
let a = Vec3::new(0.0, 0.0, 0.0);
let b = Vec3::new(10.0, 0.0, 0.0);
let c = Vec3::new(0.0, 10.0, 0.0);
block.entities.push(Entity::new(Handle(10), EntityKind::Solid(cadcraft_doc::Solid { corners: [a, b, c, c] })));
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
let insert = cadcraft_doc::Insert {
block: "filled triangle".into(),
insert: Vec3::new(0.0, 0.0, 0.0),
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
let empty = Bounds2::new(Vec2::new(7.0, 7.0), Vec2::new(8.0, 8.0));
let filled = Bounds2::new(Vec2::new(2.0, 2.0), Vec2::new(3.0, 3.0));
assert!(select_window(&d, &Space::Model, empty, true).is_empty());
assert_eq!(select_window(&d, &Space::Model, filled, true), vec![h]);
}
#[test]
fn crossing_a_block_ray_and_xline_uses_their_direction() {
for (kind, behind) in [(true, false), (false, true)] {
let mut d = Drawing::new_metric();
let mut block = cadcraft_doc::Block::new("infinite");
let line = RayLine { base: Vec3::new(100.0, 100.0, 0.0), dir: Vec3::new(1.0, 0.0, 0.0) };
block.entities.push(Entity::new(Handle(10), if kind { EntityKind::Ray(line) } else { EntityKind::XLine(line) }));
block
.entities
.push(Entity::new(Handle(11), EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(200.0, 0.0, 0.0) })));
block.entities.push(Entity::new(
Handle(12),
EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(200.0, 0.0, 0.0), b: Vec3::new(200.0, 200.0, 0.0) }),
));
block.entities.push(Entity::new(
Handle(13),
EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(200.0, 200.0, 0.0), b: Vec3::new(0.0, 200.0, 0.0) }),
));
block
.entities
.push(Entity::new(Handle(14), EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 200.0, 0.0), b: Vec3::new(0.0, 0.0, 0.0) })));
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
let insert = cadcraft_doc::Insert { block: "infinite".into(), ..Default::default() };
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
let ahead = Bounds2::new(Vec2::new(149.0, 99.0), Vec2::new(151.0, 101.0));
let back = Bounds2::new(Vec2::new(49.0, 99.0), Vec2::new(51.0, 101.0));
assert_eq!(select_window(&d, &Space::Model, ahead, true), vec![h]);
assert_eq!(select_window(&d, &Space::Model, back, true).contains(&h), behind);
}
}
#[test]
fn crossing_a_block_image_respects_its_clip() {
let mut d = Drawing::new_metric();
d.rasters.insert("map.png", std::sync::Arc::new(Raster::new(2, 2, vec![255; 16]).unwrap()));
let mut block = cadcraft_doc::Block::new("picture");
block.entities.push(Entity::new(
Handle(10),
EntityKind::Image(Image {
insert: Vec3::ZERO,
u: Vec3::new(5.0, 0.0, 0.0),
v: Vec3::new(0.0, 5.0, 0.0),
size: Vec2::new(2.0, 2.0),
path: "map.png".into(),
clipping: true,
clip: vec![Vec2::new(-0.5, -0.5), Vec2::new(0.5, 1.5)],
..Default::default()
}),
));
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
let h = d
.add(&Space::Model, Common::default(), EntityKind::Insert(cadcraft_doc::Insert { block: "picture".into(), ..Default::default() }))
.unwrap();
let visible = Bounds2::new(Vec2::new(2.0, 4.0), Vec2::new(3.0, 6.0));
let hidden = Bounds2::new(Vec2::new(7.0, 4.0), Vec2::new(8.0, 6.0));
assert_eq!(select_window(&d, &Space::Model, visible, true), vec![h]);
assert!(select_window(&d, &Space::Model, hidden, true).is_empty());
}
}
#[cfg(test)]
@@ -817,4 +1401,38 @@ mod hatch_pattern_pick_tests {
let d = solid_hatch(loops(), 2);
assert!(pick(&d, &Space::Model, Vec2::new(5.0, 5.0), 0.05).is_some());
}
/// A window around everything a blank multileader draws (its geometry and its text frame)
/// selects it, at either annotation scale: the stored insertion points snap offers do not
/// widen the box a window has to contain (#2810).
#[test]
fn window_around_a_blank_multileader_still_selects_it() {
use cadcraft_geom::Vec3;
for scale in ["1:2", "2:1"] {
let mut s = crate::Session::new();
let r = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
let d = s.doc_mut().unwrap();
d.header.set_str("CANNOSCALE", scale);
let sc = d.anno_scale(scale).cloned().unwrap();
d.modify_entity(h, |e| {
e.common.anno_scales = vec![sc];
let EntityKind::MLeader(m) = &mut e.kind else { return };
let landing = m.landing;
if let Some(t) = m.text.as_mut() {
t.insert = landing + Vec3::new(6.0, 0.0, 0.0);
t.width = 4.0;
t.height = 2.0;
t.attach = 1;
t.rotation = 0.0;
}
})
.unwrap();
let d = &*d;
let e = d.entity(h).unwrap();
let frame = blank_mtext_box(d, e).expect("a blank multileader has a frame");
let bx = entity_bounds(d, e, 0).union(&frame).expand(0.01);
assert!(select_window(d, &Space::Model, bx, false).contains(&h), "scale {scale}");
}
}
}
+2 -2
View File
@@ -3,8 +3,8 @@ use super::error::{EngineError, Result};
use super::running::{PendingWindow, Running};
use super::view::View;
use super::{
Arc, Bounds2, Drag, Drawing, Entity, Handle, Input, Prompt, Session, Space, Step, Value, Vec2, assoc, cmd, find_command, guard, lisp, pointmod,
prompt, select, snap, sysvars, units,
Arc, Bounds2, Drag, Drawing, Entity, Handle, Input, Origin, Prompt, Session, Space, Step, Value, Vec2, assoc, cmd, find_command, guard, lisp,
pointmod, prompt, select, snap, sysvars, units,
};
mod cmdline;
+137 -5
View File
@@ -1,8 +1,8 @@
use crate::DisplayOnly;
use super::{
Arc, Bounds2, Drag, Drawing, EngineError, Entity, Handle, Input, PendingWindow, Prompt, Result, Running, Session, Snapshot, Step, Value, Vec2,
assoc, cmd, find_command, guard, pointmod, select, snap, sysvars,
Arc, Bounds2, Drag, Drawing, EngineError, Entity, Handle, Input, Origin, PendingWindow, Prompt, Result, Running, Session, Snapshot, Step, Value,
Vec2, assoc, cmd, find_command, guard, pointmod, select, snap, sysvars,
};
impl Session {
@@ -41,8 +41,60 @@ impl Session {
blocks.keys().find(|k| *k == word).or_else(|| blocks.keys().find(|k| same(k))).cloned()
}
/// Start a command by name or alias as if typed at the command line.
/// Launch a non-nested interactive state machine through the standard command-start checks
/// (`enabled`, `refused_in_editor`, `commands_started`, `last_command`, `Guarded`, `feed`).
pub(crate) fn launch_interactive(
&mut self,
id: &str,
enabled: fn(&Session) -> std::result::Result<(), String>,
machine: Box<dyn crate::Interactive>,
) -> Result<()> {
self.last_polar = None;
self.pick_hint = None;
if self.running.is_some() {
self.cancel();
}
self.commands_started = self.commands_started.wrapping_add(1);
self.command_origin = if self.in_script || self.program_input { Origin::Program } else { Origin::Person };
enabled(self).map_err(|m| EngineError::Disabled(id.into(), m))?;
if let Some(why) = cmd::blocks::bedit::refused_in_editor(self, id) {
return Err(EngineError::Disabled(id.into(), why));
}
self.last_command = Some(id.to_string());
self.echo(format!("Command: {}", id.to_ascii_uppercase()));
let guarded = guard::Guarded::wrap(machine);
let st = self.state()?;
let (before, selection_before) = (st.doc.clone(), st.selection.clone());
self.running = Some(Running { id: id.to_string(), machine: guarded, before, selection_before });
self.pending_window = None;
self.point_mods.clear();
self.feed(None)?;
Ok(())
}
/// Who started the command running now ([`Origin`]): fixed when it started, so a scripted or
/// LISP-started command keeps its origin while it prompts.
pub fn command_origin(&self) -> Origin {
self.command_origin
}
/// Start a command by name or alias as if typed at the command line. A script's commands are
/// the program's ([`Origin::Program`]), as those of [`Session::start_programmatic`] are, and so
/// is a command started by a token a LISP routine feeds through [`Session::typed`]: `(command
/// "LINE" "0,0" "'-INSERT" …)` replaces LINE with an INSERT the routine started.
pub fn start(&mut self, name: &str) -> Result<()> {
let origin = if self.in_script || self.program_input { Origin::Program } else { Origin::Person };
self.start_from(name, origin)
}
/// Start a command as a program does: an AutoLISP `(command …)` cannot answer a dialog, so
/// none opens for what it starts, even after the routine ends.
pub fn start_programmatic(&mut self, name: &str) -> Result<()> {
self.start_from(name, Origin::Program)
}
/// [`Session::start`] with the command's origin recorded for its whole life.
fn start_from(&mut self, name: &str, origin: Origin) -> Result<()> {
self.last_polar = None;
self.pick_hint = None;
let name = name.trim();
@@ -74,7 +126,7 @@ impl Session {
// A bare system variable name (ORTHOMODE, GRIDMODE…) acts as SETVAR on that variable.
let var = lower.to_ascii_uppercase();
if !name.starts_with(['_', '.', '-']) && sysvars::get(self, &var).is_some() {
self.start(if transparent { "'setvar" } else { "setvar" })?;
self.start_from(if transparent { "'setvar" } else { "setvar" }, origin)?;
return self.input(Input::Text(var));
}
return Err(EngineError::UnknownCommand(typed.to_string()));
@@ -101,10 +153,15 @@ impl Session {
return self.input(Input::Keyword("Undo".into()));
}
if !nested {
self.commands_started = self.commands_started.wrapping_add(1);
// The command this one replaces is cancelled first: its cancellation can run a paused
// LISP routine's `*error*` handler, and a handler that starts a command records that
// command's Program origin. Origin and number go in after it, so they describe this
// start and the factory below still sees the origin this command was started with.
if self.running.is_some() {
self.cancel();
}
self.commands_started = self.commands_started.wrapping_add(1);
self.command_origin = origin;
}
(spec.enabled)(self).map_err(|m| EngineError::Disabled(spec.id.into(), m))?;
if let Some(why) = cmd::blocks::bedit::refused_in_editor(self, spec.id) {
@@ -162,6 +219,7 @@ impl Session {
/// command (as in AutoCAD) and points do nothing. A LISP routine waiting in a `get…`
/// function takes the input instead; one paused in `command` carries on after it.
pub fn input(&mut self, input: Input) -> Result<()> {
self.inputs = self.inputs.wrapping_add(1);
if self.lisp_input(input.clone()) {
return Ok(());
}
@@ -541,6 +599,17 @@ impl Session {
self.running.as_ref().and_then(|r| r.machine.text_editor())
}
/// The attribute values the running command asks for in the Edit Attributes dialog
/// ([`Interactive::attribute_entry`]), stamped with the drawing it runs in and its number in
/// [`Session::commands_started`]: a dialog draft kept for a cancelled command never belongs
/// to the one started after it, even for the same block.
pub fn attribute_entry(&self) -> Option<crate::AttribEntry> {
let mut entry = self.running.as_ref().and_then(|r| r.machine.attribute_entry())?;
entry.drawing = self.docs.get(self.active).map_or(0, |d| d.uid);
entry.command = self.commands_started;
Some(entry)
}
pub fn current_prompt(&self) -> Option<Prompt> {
if let Some(p) = self.lisp_prompt() {
return Some(p);
@@ -608,6 +677,29 @@ impl Session {
out
}
/// The value the cursor would give at the active command's prompt (see
/// [`Interactive::live_value`]).
pub fn live_value(&self, cursor: Vec2) -> Option<String> {
self.running.as_ref()?.machine.live_value(self, cursor)
}
/// What the rollover highlight shows of the object `h` under the cursor, with its properties,
/// when the running command highlights only a part of it ([`Interactive::highlight`]: TRIM
/// the piece a click there removes, EXTEND what it adds). `None`: the whole object.
pub fn highlight(&self, h: Handle, cursor: Vec2) -> Option<Vec<Entity>> {
let kinds = self.running.as_ref()?.machine.highlight(self, h, cursor)?;
let common = self.doc().ok()?.entity(h)?.common.clone();
Some(kinds.into_iter().map(|k| Entity { handle: h, common: common.clone(), kind: k }).collect())
}
/// What the running command will change wherever the cursor is, with each part's properties
/// ([`Interactive::highlight_all`]: TRIM's Fence and Crossing). `None`: nothing of the kind.
pub fn highlight_all(&self, cursor: Vec2) -> Option<Vec<Entity>> {
let parts = self.running.as_ref()?.machine.highlight_all(self, cursor)?;
let d = self.doc().ok()?;
Some(parts.into_iter().filter_map(|(h, k)| Some(Entity { handle: h, common: d.entity(h)?.common.clone(), kind: k })).collect())
}
/// What the drawing area shows in place of the drawing while a command runs (DVIEW's preview
/// set, see [`Interactive::display_only`]), also while a transparent command interrupts it.
/// `None`: the drawing.
@@ -624,4 +716,44 @@ impl Session {
let extra = d.extra.iter().map(|k| Entity { handle: Handle(0), common: common.clone(), kind: k.clone() }).collect();
Some((d, extra))
}
/// The live parameters of the running array command ([`Interactive::array_live`]).
pub fn array_live(&self) -> Option<crate::ArrayLive> {
self.running.as_ref().and_then(|r| r.machine.array_live())
}
/// Change the running array's live parameters. With no array running this does nothing; an
/// invalid value is refused and leaves the command as it was.
pub fn set_array_live(&mut self, v: &crate::ArrayLive) -> Result<()> {
if self.array_live().is_none() {
return Ok(());
}
let Some(mut run) = self.running.take() else { return Ok(()) };
let r = run.machine.set_array_live(self, v);
self.running = Some(run);
r
}
/// Ask the running polar array for its centre as the next canvas point
/// ([`Interactive::array_pick_center`]).
pub fn array_pick_center(&mut self) -> bool {
self.running.as_mut().is_some_and(|r| r.machine.array_pick_center())
}
/// Finish the running array: `Ok(true)` when the command ended, `Ok(false)` when there is no
/// array command or it is still selecting objects.
pub fn commit_array(&mut self) -> Result<bool> {
if self.array_live().is_none() {
return Ok(false);
}
if self.current_prompt().is_some_and(|p| p.accept.select) {
return Ok(false);
}
if let Some(r) = self.running.as_mut()
&& !r.machine.array_set_main()
{
return Ok(false);
}
self.feed(Some(Input::Keyword("eXit".into())))?;
Ok(self.running.is_none())
}
}
+4
View File
@@ -138,6 +138,9 @@ pub struct Settings {
/// ATTREQ: 0 inserts blocks with their attributes' default values instead of asking for them
/// (default: 1).
pub attreq: bool,
/// ATTDIA: INSERT typed or from a menu asks for attribute values in the Edit Attributes
/// dialog; on by default, as in AutoCAD (Initial value 1).
pub attdia: bool,
}
impl Default for Settings {
@@ -205,6 +208,7 @@ impl Default for Settings {
ucs_angle: 0.0,
auditctl: false,
attreq: true,
attdia: true,
}
}
}
+274 -18
View File
@@ -7,7 +7,7 @@ mod viewport;
pub use viewport::ViewportPoint;
use cadcraft_doc::{Drawing, EntityKind, Insert, MAX_BLOCK_DEPTH, Prim, Space};
use cadcraft_doc::{Drawing, EntityKind, Handle, Insert, MAX_BLOCK_DEPTH, Prim, Space};
use cadcraft_geom::{Bounds2, Circle, EPS, Ellipse, Mat3, PI, Segment, Vec2, intersect_ext};
use serde::Serialize;
@@ -385,7 +385,7 @@ fn osnap_in_with_prims(
frozen: &[String],
clip: Option<Bounds2>,
) -> Option<(Vec<SnapHit>, Vec<Prim>)> {
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen)?;
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen, None)?;
// Intersections between nearby primitives; Apparent Intersection also where their extensions
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
// that don't reach each other).
@@ -475,9 +475,60 @@ pub(crate) fn gather(
aperture: f64,
osmode: u32,
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
gather_in(d, space, ix, cursor, aperture, osmode, &[])
gather_in(d, space, ix, cursor, aperture, osmode, &[], None)
}
/// The point nearest `cursor` within `aperture` on the visible objects of `space` other than
/// `skip` (and on the objects inside block references), with the object's direction there (a unit
/// vector; a circle's or arc's runs counterclockwise): what an alignment grip aligns a dynamic
/// block reference with. Objects on the layers `frozen` in the active viewport aren't drawn there,
/// so they are passed over.
pub(crate) fn nearest_with_direction(
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
frozen: &[String],
skip: Handle,
) -> Option<(Vec2, Vec2)> {
let ix = crate::spatial::index(d, space);
let (_, prims) = gather_in(d, space, &ix, cursor, aperture, 0, frozen, Some(skip))?;
let mut best: Option<(f64, Vec2, Vec2)> = None;
let mut consider = |at: Vec2, dir: Vec2| {
let dd = at.dist(cursor);
if at.is_finite() && dir.len() > 1e-12 && dir.is_finite() && dd <= aperture && best.is_none_or(|(bd, _, _)| dd < bd) {
best = Some((dd, at, dir * (1.0 / dir.len())));
}
};
for p in prims.iter().take(2000) {
if let Prim::Circle(c) = p {
let at = c.closest(cursor);
consider(at, (at - c.center).perp());
continue;
}
if let Prim::Infinite { base, dir, ray } = p {
let len = dir.len();
if len > 1e-12 {
let u = *dir * (1.0 / len);
// A ray runs one way from its base: behind it, its base is the nearest point.
let t = (cursor - *base).dot(u);
consider(*base + u * if *ray { t.max(0.0) } else { t }, u);
}
continue;
}
for seg in prim_segments(p) {
let seg = fix_circle(&seg);
let at = seg.closest(cursor);
match seg {
Segment::Line(l) => consider(at, l.b - l.a),
Segment::Arc { arc, .. } => consider(at, (at - arc.center).perp()),
}
}
}
best.map(|(_, at, dir)| (at, dir))
}
#[allow(clippy::too_many_arguments)]
fn gather_in(
d: &Drawing,
space: &Space,
@@ -486,6 +537,7 @@ fn gather_in(
aperture: f64,
osmode: u32,
frozen: &[String],
skip: Option<Handle>,
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
let probe = Bounds2::new(cursor, cursor).expand(aperture);
let mut cands: Vec<(u32, Vec2)> = Vec::new();
@@ -493,13 +545,19 @@ fn gather_in(
let mut count = 0usize;
let mut budget = MAX_BLOCK_LEAVES;
for (e, known) in crate::select::candidates(d, space, ix, &probe.expand(aperture), true, false)? {
if !d.is_visible(e) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer)) {
if !d.is_visible(e) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer)) || Some(e.handle) == skip {
continue;
}
let inf = crate::select::is_infinite(e);
if !inf && !crate::select::bounds_of(d, e, known).expand(aperture).intersects(&probe) {
continue;
}
// A blank MTEXT frame covering the cursor is for picking: it neither uses up the candidate
// limit nor the intersection slots unless its drawn geometry is in reach, or INS is on and an
// insertion point is within the aperture.
if !inf && crate::select::blank_frame_only(d, e, &probe, cursor, aperture, osmode & mode::INS != 0) {
continue;
}
count += 1;
if count > 2000 {
break;
@@ -515,6 +573,7 @@ fn gather_in(
}
EntityKind::AttDef(a) => cands.push((mode::INS, a.text.justify_point())),
// A multileader: its text's insertion point, or its block content's.
// select.rs blank_snap_points must offer the same points.
EntityKind::MLeader(m) => {
cands.extend(m.text.iter().map(|t| (mode::INS, t.insert.xy())));
cands.extend(m.block.iter().map(|b| (mode::INS, b.insert.xy())));
@@ -531,6 +590,15 @@ fn gather_in(
if let EntityKind::Dimension(dm) = &e.kind {
sink.dimension(d, dm, &mut budget, frozen);
}
// A dimension kept as read draws its block through a reference in its graphics (#3438),
// and snaps to the objects inside it the same way.
if let EntityKind::Unknown(u) = &e.kind {
for g in &u.graphics {
if let EntityKind::Insert(ins) = &g.kind {
block_leaves(d, ins, &Mat3::IDENTITY, 0, &mut budget, frozen, &mut |k, m| sink.object(k, Some(m)));
}
}
}
}
Some((cands, near_prims))
}
@@ -772,20 +840,7 @@ impl Sink<'_> {
fn dimension(&mut self, d: &Drawing, dm: &cadcraft_doc::Dimension, budget: &mut usize, frozen: &[String]) {
match dm.block.as_ref().and_then(|n| d.block(n)) {
Some(blk) => {
// The block holds world geometry: a reference at its own base point places it as is.
let ins = Insert {
block: blk.name.clone(),
insert: blk.base,
scale: cadcraft_geom::Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
block_leaves(d, &ins, &Mat3::IDENTITY, 0, budget, frozen, &mut |k, m| self.object(k, Some(m)));
block_leaves(d, &dimension_reference(blk, dm), &Mat3::IDENTITY, 0, budget, frozen, &mut |k, m| self.object(k, Some(m)));
}
None => {
let g = cadcraft_render::dimension_in(d, dm);
@@ -862,6 +917,18 @@ fn block_leaves(d: &Drawing, ins: &Insert, m: &Mat3, depth: usize, budget: &mut
match &be.kind {
EntityKind::AttDef(_) => {}
EntityKind::Insert(inner) => block_leaves(d, inner, &mm, depth + 1, budget, frozen, f),
// A dimension draws its block, as at the top level.
EntityKind::Dimension(dm) if let Some(blk) = dm.block.as_ref().and_then(|n| d.block(n)) => {
block_leaves(d, &dimension_reference(blk, dm), &mm, depth + 1, budget, frozen, f);
}
k @ EntityKind::Unknown(u) => {
f(k, &mm);
for g in &u.graphics {
if let EntityKind::Insert(inner) = &g.kind {
block_leaves(d, inner, &mm, depth + 1, budget, frozen, f);
}
}
}
k => f(k, &mm),
}
}
@@ -869,6 +936,24 @@ fn block_leaves(d: &Drawing, ins: &Insert, m: &Mat3, depth: usize, budget: &mut
}
}
/// The reference that places a dimension's block as the renderer draws it: the block holds world
/// geometry, moved by the insertion point (DXF group 12, which an older AutoCAD sets for a moved
/// dimension; #2634).
fn dimension_reference(blk: &cadcraft_doc::Block, dm: &cadcraft_doc::Dimension) -> Insert {
Insert {
block: blk.name.clone(),
insert: blk.base + dm.insertion_point,
scale: cadcraft_geom::Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
}
}
/// Whether `p` comes within `aperture` of the box `probe`.
fn prim_near(p: &Prim, probe: &Bounds2, aperture: f64) -> bool {
let b = match p {
@@ -1171,6 +1256,27 @@ mod tests {
d
}
#[test]
fn alignment_targets_stay_on_a_ray_and_off_frozen_layers() {
let mut d = Drawing::new_imperial();
let ray = |base: (f64, f64)| EntityKind::Ray(cadcraft_doc::RayLine { base: Vec3::new(base.0, base.1, 0.0), dir: Vec3::new(1.0, 0.0, 0.0) });
d.add(&Space::Model, Common::default(), ray((0.0, 0.0))).unwrap();
// Behind the ray: its base is the nearest point, out of a small aperture.
assert_eq!(nearest_with_direction(&d, &Space::Model, Vec2::new(-5.0, 0.0), 0.5, &[], Handle(0)), None);
let (at, _) = nearest_with_direction(&d, &Space::Model, Vec2::new(-0.2, 0.1), 0.5, &[], Handle(0)).unwrap();
assert!(at.dist(Vec2::ZERO) < 1e-12, "{at:?}");
let (at, _) = nearest_with_direction(&d, &Space::Model, Vec2::new(5.0, 0.1), 0.5, &[], Handle(0)).unwrap();
assert!(at.dist(Vec2::new(5.0, 0.0)) < 1e-12, "{at:?}");
// A line on a layer frozen in the viewport isn't a target.
let mut d = drawing();
d.ensure_layer("Hidden");
let c = Common { layer: "Hidden".into(), ..Common::default() };
let l = EntityKind::Line(Line { a: Vec3::new(0.0, 30.0, 0.0), b: Vec3::new(10.0, 30.0, 0.0) });
d.add(&Space::Model, c, l).unwrap();
assert!(nearest_with_direction(&d, &Space::Model, Vec2::new(5.0, 30.1), 0.5, &[], Handle(0)).is_some());
assert_eq!(nearest_with_direction(&d, &Space::Model, Vec2::new(5.0, 30.1), 0.5, &["HIDDEN".to_string()], Handle(0)), None);
}
#[test]
fn endpoint_and_mid() {
let d = drawing();
@@ -1180,6 +1286,156 @@ mod tests {
assert_eq!(m.point, Vec2::new(5.0, 0.0));
}
/// Blank MTEXT frames over the cursor are for picking: thousands of them, with their insertion
/// points out of reach, must not crowd a real endpoint out of the snap candidates (#2810).
#[test]
fn blank_mtext_frames_do_not_crowd_out_snap_candidates() {
for line_first in [true, false] {
let mut d = Drawing::new_metric();
let line = EntityKind::Line(Line { a: Vec3::new(5.2, -1.0, 0.0), b: Vec3::new(30.0, -1.0, 0.0) });
if line_first {
d.add(&Space::Model, Common::default(), line.clone()).unwrap();
}
for _ in 0..2100 {
let t = cadcraft_doc::MText {
insert: Vec3::new(0.0, 0.0, 0.0),
height: 2.5,
width: 10.0,
attach: 1,
rotation: 0.0,
style: "Standard".into(),
contents: " ".into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
};
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
}
if !line_first {
d.add(&Space::Model, Common::default(), line).unwrap();
}
// The cursor is inside every box (x 0..10, y -2.5..0), 0.2 from the line's end.
let h = osnap(&d, &Space::Model, Vec2::new(5.0, -1.0), 0.5, mode::END, None, false).unwrap();
assert_eq!(h.point, Vec2::new(5.2, -1.0), "line first: {line_first}");
// A blank MTEXT whose insertion point is in the aperture keeps its INS snap.
let h = osnap(&d, &Space::Model, Vec2::new(0.1, -0.1), 0.5, mode::INS, None, false).unwrap();
assert_eq!(h.point, Vec2::new(0.0, 0.0), "line first: {line_first}");
}
}
/// 2001 blank MTEXT frames covering `cursor` (insertion points at `ins_at`), drawn before a
/// LINE whose end is at `cursor`: the END snap found with `osmode`.
fn crowded_blank_frames_end_snap(ins_at: Vec2, cursor: Vec2, aperture: f64, osmode: u32) -> Option<Vec2> {
let mut d = Drawing::new_metric();
for _ in 0..2001 {
let t = cadcraft_doc::MText {
insert: Vec3::new(ins_at.x, ins_at.y, 0.0),
height: 2.5,
width: 10.0,
attach: 1,
rotation: 0.0,
style: "Standard".into(),
contents: " ".into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
};
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
}
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::new(cursor.x, cursor.y, 0.0), b: Vec3::new(30.0, cursor.y, 0.0) }))
.unwrap();
osnap(&d, &Space::Model, cursor, aperture, osmode, None, false).map(|h| h.point)
}
/// An insertion point in a corner of the square probe is farther than the aperture from the
/// cursor, so snap would never accept it: its frame must not crowd out an END snap.
#[test]
fn blank_insertion_points_in_the_probe_corner_do_not_crowd_out_an_end_snap() {
let cursor = Vec2::new(5.0, -1.0);
let ap = 0.5;
let corner = Vec2::new(cursor.x - 0.9 * ap, cursor.y + 0.9 * ap);
assert!(corner.dist(cursor) > ap, "outside the circle, inside the square probe");
assert_eq!(crowded_blank_frames_end_snap(corner, cursor, ap, mode::END | mode::INS), Some(cursor));
}
/// With INS off a blank MTEXT's insertion point is no snap candidate, even right at the cursor.
#[test]
fn blank_insertion_points_with_ins_off_do_not_crowd_out_an_end_snap() {
let cursor = Vec2::new(5.0, -1.0);
assert_eq!(crowded_blank_frames_end_snap(cursor, cursor, 0.5, mode::END), Some(cursor));
}
/// A blank annotative multileader (text 6 right of its landing, 4 x 2, at 1:2) among 2100 blank
/// MTEXT frames over the cursor. `block_at` also gives it a block content at that offset from
/// the landing. Returns the INS snap at `landing + probe` (aperture 0.5).
fn crowded_blank_mleader_ins(block_at: Option<f64>, probe: Vec2) -> Option<Vec2> {
let mut s = crate::Session::new();
let r = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap();
let h = cadcraft_doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
let landing = {
let d = s.doc_mut().unwrap();
if block_at.is_some() {
// A block whose geometry (a line 60 long) covers its base point, at the stored insertion
// and, drawn at 1:2 about the landing, at the scaled one too.
let mut blk = cadcraft_doc::Block::new("BLK");
let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(60.0, 0.0, 0.0) });
blk.entities.push(cadcraft_doc::Entity::new(cadcraft_doc::Handle(1), line));
d.blocks.insert("BLK".into(), std::sync::Arc::new(blk));
}
d.header.set_str("CANNOSCALE", "1:2");
let half = d.anno_scale("1:2").cloned().unwrap();
d.modify_entity(h, |e| {
e.common.anno_scales = vec![half];
let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") };
let landing = m.landing;
let t = m.text.as_mut().unwrap();
t.insert = landing + Vec3::new(6.0, 0.0, 0.0);
t.width = 4.0;
t.height = 2.0;
t.attach = 1;
t.rotation = 0.0;
if let Some(x) = block_at {
m.block = Some(cadcraft_doc::Insert {
block: "BLK".into(),
insert: landing + Vec3::new(x, 0.0, 0.0),
scale: Vec3::new(1.0, 1.0, 1.0),
..Default::default()
});
}
})
.unwrap();
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
m.landing.xy()
};
let cursor = landing + probe;
// Blank frames (10 x 2.5, top-left at the insert) cover the cursor; their inserts do not.
let d = s.doc_mut().unwrap();
for _ in 0..2100 {
let t = cadcraft_doc::MText {
insert: Vec3::new(cursor.x - 5.0, cursor.y + 1.0, 0.0),
height: 2.5,
width: 10.0,
attach: 1,
rotation: 0.0,
style: "Standard".into(),
contents: " ".into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
};
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
}
osnap(d, &Space::Model, cursor, 0.5, mode::INS, None, false).map(|h| h.point - landing)
}
/// An annotative blank multileader keeps its INS snap (the stored, unscaled insertion point)
/// among thousands of blank frames, and so does its block content.
#[test]
fn annotative_blank_mleader_keeps_its_ins_snaps_among_blank_frames() {
assert_eq!(crowded_blank_mleader_ins(None, Vec2::new(6.1, -0.1)), Some(Vec2::new(6.0, 0.0)), "text");
assert_eq!(crowded_blank_mleader_ins(Some(30.0), Vec2::new(30.1, -0.1)), Some(Vec2::new(30.0, 0.0)), "block");
}
#[test]
fn intersection() {
let d = drawing();
+2 -1
View File
@@ -53,7 +53,8 @@ impl ChunkIx {
if matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_)) {
infinite.push(u32::try_from(i).unwrap_or(u32::MAX));
}
entity_bounds_cached(d, e, 0, &mut cache)
let b = entity_bounds_cached(d, e, 0, &mut cache);
crate::select::pick_bounds(d, e, b)
})
.collect();
let serial = NEXT_SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+4 -1
View File
@@ -89,8 +89,11 @@ const LINEWEIGHTS: [i64; 24] = [0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53,
/// On/off session settings: name, read, write.
type Toggle = (&'static str, fn(&Settings) -> bool, fn(&mut Settings, bool));
const SETTINGS: &[Toggle] = &[
("AUDITCTL", |s| s.auditctl, |s, v| s.auditctl = v),
// ATTDIA 1 (the default): INSERT typed or from a menu asks for attribute values in the Edit
// Attributes dialog; 0: at the command line. ATTREQ 0: INSERT gives every attribute its default.
("ATTDIA", |s| s.attdia, |s, v| s.attdia = v),
("ATTREQ", |s| s.attreq, |s, v| s.attreq = v),
("AUDITCTL", |s| s.auditctl, |s, v| s.auditctl = v),
("TRANSPARENCYDISPLAY", |s| s.transparency_display, |s, v| s.transparency_display = v),
];
+91
View File
@@ -532,6 +532,97 @@ fn scale_reference_typed_and_picked() {
assert!(end(&s).near(Vec2::new(50.0, 0.0), 1e-9));
}
#[test]
fn scale_reference_points_and_copy() {
fn line_ends(s: &Session) -> Vec<Vec2> {
s.doc()
.unwrap()
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(l) => Some(l.b.xy()),
_ => None,
})
.collect()
}
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
// Reference 10 via two points, then Points option with two points of length 30 -> (30, 0).
for t in ["scale", "all", "", "0,0", "r", "0,0", "10,0"] {
s.cmdline(t).unwrap();
}
let p = s.current_prompt().unwrap();
assert_eq!(p.message, "Specify new length");
assert!(p.keywords.contains(&"Points".to_string()));
assert!(p.keywords.contains(&"Copy".to_string()));
s.cmdline("p").unwrap();
assert_eq!(s.current_prompt().unwrap().message, "Specify first point");
s.cmdline("5,5").unwrap();
assert_eq!(s.current_prompt().unwrap().message, "Specify second point");
s.cmdline("5,35").unwrap();
assert!(s.running.is_none());
assert!(line_ends(&s)[0].near(Vec2::new(30.0, 0.0), 1e-9));
// Coinciding Points are rejected without leaving the second-point prompt; a valid point completes.
for t in ["scale", "all", "", "0,0", "r", "30", "p", "5,5", "5,5"] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_some());
assert_eq!(s.current_prompt().unwrap().message, "Specify second point");
s.cmdline("5,25").unwrap();
assert!(s.running.is_none());
assert!(line_ends(&s)[0].near(Vec2::new(20.0, 0.0), 1e-9));
// Copy entered inside Reference mode before reference length keeps the original and adds a scaled copy.
for t in ["scale", "all", "", "0,0", "r", "c", "20", "40"] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none());
let ends = line_ends(&s);
assert_eq!(ends.len(), 2);
assert!(ends.iter().any(|p| p.near(Vec2::new(20.0, 0.0), 1e-9)));
assert!(ends.iter().any(|p| p.near(Vec2::new(40.0, 0.0), 1e-9)));
// Copy entered at "Specify new length" combined with Points scales a copy.
for t in ["scale", "l", "", "0,0", "r", "40", "c", "p", "0,0", "10,0"] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none());
let ends = line_ends(&s);
assert_eq!(ends.len(), 3);
assert!(ends.iter().any(|p| p.near(Vec2::new(10.0, 0.0), 1e-9)));
}
#[test]
fn hot_grip_scale_scales_heights_and_thickness() {
let mut s = Session::new();
let r = s.execute("text", &json!({"at": [10, 0], "height": 2.0, "text": "H"})).unwrap();
let h = cadcraft_doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
e.common.thickness = 3.0;
if let EntityKind::Text(t) = &mut e.kind {
t.insert.z = 5.0;
}
})
.unwrap();
s.set_selection(vec![h]);
s.start_grip_edit(&[(h, 0)]).unwrap();
// STRETCH -> MOVE -> ROTATE -> SCALE
for _ in 0..3 {
s.input(Input::Enter).unwrap();
}
assert!(s.current_prompt().unwrap().message.contains("** SCALE **"));
s.cmdline("2").unwrap();
assert!(s.running.is_none());
let e = s.doc().unwrap().entity(h).unwrap();
assert_eq!(e.common.thickness, 6.0);
let EntityKind::Text(t) = &e.kind else { panic!("expected text") };
assert_eq!(t.height, 4.0);
assert_eq!(t.insert.z, 10.0);
}
#[test]
fn layers_and_properties() {
let mut s = Session::new();
+21
View File
@@ -323,5 +323,26 @@ fn clipboard_travels_as_text() {
t.execute("pasteorig", &json!({})).unwrap();
assert_eq!(t.doc().unwrap().model.len(), 2);
assert!(t.doc().unwrap().block("DOOR").is_some() && t.doc().unwrap().layer("HINGE").is_some());
// A paste asked for from a menu or by name reads the system clipboard first, so text from
// another window replaces a copy made here earlier; text that is not a DXF drawing does not.
let mut u = Session::empty();
u.open_drawing(drawing_b(), "B", None);
assert!(u.execute("pasteclip", &json!({})).is_err(), "nothing to paste yet");
assert!(clipboard::load_system_text(&mut u, &text));
u.execute("pasteclip", &json!({})).unwrap();
assert_eq!(u.doc().unwrap().model.len(), 2, "the system clipboard's objects were pasted");
let mut v = Session::empty();
v.open_drawing(drawing_b(), "B", None);
let local = line(v.doc_mut().unwrap(), "0", (1.0, 1.0), (2.0, 2.0));
let local_handle = local.handle.hex();
v.doc_mut().unwrap().model.push(local);
v.execute("copyclip", &json!({ "handles": [local_handle] })).unwrap();
assert_eq!(v.clipboard.len(), 1);
assert!(!clipboard::load_system_text(&mut v, "just some words"), "not a drawing");
assert_eq!(v.clipboard.len(), 1, "the copy made here stays");
assert!(clipboard::load_system_text(&mut v, &text));
assert_eq!(v.clipboard.len(), 2, "newer text from another window replaces it");
assert!(v.clipboard_source.as_ref().is_some_and(|c| c.uid.is_none()));
let _ = a;
}
+115
View File
@@ -0,0 +1,115 @@
//! DIMASSOC 1 creates dimension objects without coupling them to source geometry; 2 couples them.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Dimension, EntityKind, Handle};
use serde_json::{Value, json};
/// Read the single entity handle returned by a dimension command.
fn handle(v: &Value) -> Handle {
Handle::parse_hex(v["handle"].as_str().unwrap()).unwrap()
}
/// Clone the asserted dimension so later edits can be compared with its previous state.
fn dimension(s: &Session, h: Handle) -> Dimension {
match &s.doc().unwrap().entity(h).unwrap().kind {
EntityKind::Dimension(d) => d.clone(),
other => panic!("expected dimension, got {other:?}"),
}
}
/// Create a synthetic source line and return its first entity handle.
fn line(s: &mut Session, a: [i32; 2], b: [i32; 2]) -> Handle {
let v = s.execute("line", &json!({"points": [a, b]})).unwrap();
Handle::parse_hex(v["handles"][0].as_str().unwrap()).unwrap()
}
/// Set the drawing-wide associativity mode before creating the test dimensions.
fn mode(s: &mut Session, n: i32) {
s.execute("setvar", &json!({"name": "DIMASSOC", "value": n})).unwrap();
}
/// Typed and JSON dimensions retain their mode through DXF, source edits, undo and redo.
#[test]
fn linear_dimensions_respect_the_mode_through_edits_and_dxf() {
for n in [1, 2] {
for typed in [false, true] {
let mut s = Session::new();
mode(&mut s, n);
let source = line(&mut s, [0, 0], [10, 0]);
let d = if typed {
s.cmdline("dimlinear 0,0 10,0 5,4").unwrap();
s.last_dim.unwrap()
} else {
handle(&s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 4]})).unwrap())
};
assert_eq!(dimension(&s, d).assoc.len(), if n == 2 { 2 } else { 0 }, "mode{n}, typed{typed}");
let saved = cadcraft_io::write_dxf(s.doc().unwrap());
let has_link = saved.lines().any(|l| l.trim() == "DIMASSOC");
assert_eq!(has_link, n == 2, "mode{n}: only associative dimensions save a DIMASSOC object");
let mut reopened = Session::new();
reopened.open_drawing(cadcraft_io::read_dxf(saved.as_bytes()).unwrap(), "roundtrip.dxf", None);
for session in [&mut s, &mut reopened] {
session.execute("properties.set", &json!({"handles": [source.hex()], "end": [15, 0]})).unwrap();
let edited = dimension(session, d);
assert_eq!(edited.p14.x, if n == 2 { 15.0 } else { 10.0 });
assert_eq!(cadcraft_engine::render::dimension_in(session.doc().unwrap(), &edited).measurement, if n == 2 { 15.0 } else { 10.0 });
session.undo().unwrap();
assert_eq!(dimension(session, d).p14.x, 10.0);
session.redo().unwrap();
assert_eq!(dimension(session, d).p14.x, edited.p14.x);
}
}
}
}
/// Continue, Baseline and Quick Dimension attach source links only in mode 2.
#[test]
fn indexed_chains_and_qdim_respect_the_mode() {
for n in [1, 2] {
for cmd in ["dimcontinue", "dimbaseline", "qdim"] {
let mut s = Session::new();
mode(&mut s, n);
let source = line(&mut s, [0, 0], [10, 0]);
s.execute("point", &json!({"at": [20, 0]})).unwrap();
s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 4]})).unwrap();
let params = if cmd == "qdim" { json!({"handles": [source.hex()], "at": [5, 6]}) } else { json!({"points": [[20, 0]]}) };
let out = s.execute(cmd, &params).unwrap();
let hs = out["handles"].as_array().unwrap();
assert!(!hs.is_empty());
for h in hs {
let d = dimension(&s, Handle::parse_hex(h.as_str().unwrap()).unwrap());
assert_eq!(d.assoc.len(), if n == 2 { 2 } else { 0 }, "mode{n}, {cmd}");
}
}
}
}
/// Even explicitly selected angular source lines produce associations only in mode 2.
#[test]
fn explicit_angular_links_respect_the_mode() {
for n in [1, 2] {
let mut s = Session::new();
mode(&mut s, n);
let a = line(&mut s, [0, 0], [10, 0]);
let b = line(&mut s, [0, 0], [0, 10]);
let d = handle(&s.execute("dimangular", &json!({"lines": [a.hex(), b.hex()], "at": [4, 4]})).unwrap());
assert_eq!(dimension(&s, d).assoc.len(), if n == 2 { 4 } else { 0 });
}
}
/// Changing the creation mode preserves old links and does not disable explicit reassociation.
#[test]
fn mode_change_keeps_existing_links_and_allows_explicit_reassociation() {
let mut s = Session::new();
let source = line(&mut s, [0, 0], [10, 0]);
let params = json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 4]});
let existing = handle(&s.execute("dimlinear", &params).unwrap());
mode(&mut s, 1);
let new = handle(&s.execute("dimlinear", &params).unwrap());
assert_eq!(dimension(&s, existing).assoc.len(), 2);
assert!(dimension(&s, new).assoc.is_empty());
s.execute("dimreassociate", &json!({"handles": [new.hex()]})).unwrap();
assert_eq!(dimension(&s, new).assoc.len(), 2);
s.execute("properties.set", &json!({"handles": [source.hex()], "end": [15, 0]})).unwrap();
assert_eq!(dimension(&s, existing).p14.x, 15.0);
assert_eq!(dimension(&s, new).p14.x, 15.0);
}
+7
View File
@@ -133,6 +133,13 @@ fn bad_input_is_refused_and_changes_nothing() {
json!({ "path": "a.png", "data": data, "width": -3 }),
json!({ "path": "a.png", "data": data, "width": "wide" }),
json!({ "path": "a.png", "data": data, "width": 1e-320 }),
// A value of the wrong type is refused, not taken as omitted.
json!({ "path": "a.png", "data": data, "scale": "big" }),
json!({ "path": "a.png", "data": data, "width": 2, "scale": "big" }),
json!({ "path": "a.png", "data": data, "rotation": "right" }),
json!({ "path": "a.png", "data": data, "at": "nowhere" }),
json!({ "path": "a.png", "data": data, "at": [1] }),
json!({ "path": "a.png", "data": data, "name": 7 }),
json!({ "path": "x".repeat(5000), "data": data }),
] {
assert!(s.execute("imageattach", &p).is_err(), "{p}");
+441
View File
@@ -0,0 +1,441 @@
//! The live array parameters ([`cadcraft_engine::ArrayLive`]) of a running ARRAYRECT / ARRAYPOLAR:
//! read and written from the array window, and kept in step with the command line.
use cadcraft_engine::doc::{EntityKind, Handle};
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::{ArrayLive, ArrayLiveKind, Input, Session};
use serde_json::json;
/// A session with one line selected pickfirst, so the array command goes straight to its Main
/// option loop.
fn selected() -> Session {
let mut s = Session::new();
let r = s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap()).unwrap();
s.set_selection(vec![h]);
s
}
fn first_handle(s: &Session) -> Handle {
s.doc().unwrap().model.iter().next().unwrap().handle
}
#[test]
fn rect_live_reads_and_writes_through_the_session() {
let mut s = selected();
s.start("arrayrect").unwrap();
let live = s.array_live().unwrap();
assert_eq!(live.kind, ArrayLiveKind::Rectangular);
assert_eq!((live.cols, live.rows, live.levels), (4, 3, 1));
assert_eq!(live.center, None);
assert_eq!((live.items, live.rotate), (0, false));
// Writing through the window.
let mut v = live.clone();
(v.cols, v.rows, v.levels) = (2, 5, 2);
(v.col_spacing, v.row_spacing, v.level_spacing, v.row_elevation) = (3.0, 4.0, 5.0, 0.5);
v.associative = true;
s.set_array_live(&v).unwrap();
let now = s.array_live().unwrap();
assert_eq!((now.cols, now.rows, now.levels), (2, 5, 2));
assert_eq!((now.col_spacing, now.row_spacing, now.level_spacing, now.row_elevation), (3.0, 4.0, 5.0, 0.5));
assert!(now.associative);
// Commit creates the array and clears the running command.
assert!(s.commit_array().unwrap());
assert!(s.running.is_none());
assert!(s.array_live().is_none());
let n = s.doc().unwrap().model.iter().filter(|e| matches!(&e.kind, EntityKind::Insert(_))).count();
assert_eq!(n, 1, "commit did not create an array block reference");
}
#[test]
fn command_line_input_is_reflected_in_array_live() {
let mut s = selected();
s.start("arrayrect").unwrap();
s.cmdline("columns").unwrap();
s.cmdline("6").unwrap();
assert_eq!(s.array_live().unwrap().cols, 6);
// A count is followed by its spacing: Enter keeps it and returns to the option loop.
s.cmdline("").unwrap();
s.cmdline("rows").unwrap();
s.cmdline("2").unwrap();
assert_eq!(s.array_live().unwrap().rows, 2);
// Enter keeps the row spacing and the row elevation, back at the option loop.
s.cmdline("").unwrap();
s.cmdline("").unwrap();
assert_eq!(s.array_live().unwrap().rows, 2);
// `x` (eXit) ends the command, so there is no live array left.
s.cmdline("x").unwrap();
assert!(s.array_live().is_none());
}
#[test]
fn rect_set_array_live_refuses_bad_values_without_changing_state() {
let mut s = selected();
s.start("arrayrect").unwrap();
let before = s.array_live().unwrap();
let mut zero = before.clone();
zero.cols = 0;
assert!(s.set_array_live(&zero).is_err());
assert_eq!(s.array_live().unwrap(), before);
let mut inf = before.clone();
inf.col_spacing = f64::INFINITY;
assert!(s.set_array_live(&inf).is_err());
assert_eq!(s.array_live().unwrap(), before);
// Kind mismatch.
let mut wrong = before.clone();
wrong.kind = ArrayLiveKind::Polar;
assert!(s.set_array_live(&wrong).is_err());
assert_eq!(s.array_live().unwrap(), before);
}
#[test]
fn rect_array_pick_center_is_refused() {
let mut s = selected();
s.start("arrayrect").unwrap();
assert!(!s.array_pick_center());
}
#[test]
fn polar_live_reads_and_writes_and_picks_the_center() {
let mut s = selected();
s.start("arraypolar").unwrap();
// The centre prompt is up: the live values are the defaults.
let live = s.array_live().unwrap();
assert_eq!(live.kind, ArrayLiveKind::Polar);
assert_eq!(live.center, Some(Vec2::new(5.0, 0.0)));
assert_eq!((live.items, live.rows, live.levels), (6, 1, 1));
assert_eq!((live.cols, live.col_spacing), (0, 0.0));
// Pick the centre on the canvas, then feed the point: the command moves to Main.
assert!(s.array_pick_center());
s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap();
assert_eq!(s.array_live().unwrap().center, Some(Vec2::new(5.0, 5.0)));
assert!(!s.current_prompt().unwrap().message.contains("center point of array"));
// Editing the window: items, fill, rotate, rows, spacings.
let mut v = s.array_live().unwrap();
(v.items, v.fill, v.rotate) = (4, 180.0, false);
(v.rows, v.row_spacing, v.level_spacing, v.row_elevation) = (2, 3.0, 4.0, 0.0);
v.associative = false;
s.set_array_live(&v).unwrap();
let now = s.array_live().unwrap();
assert_eq!((now.items, now.fill, now.rotate), (4, 180.0, false));
assert_eq!((now.rows, now.row_spacing, now.level_spacing, now.row_elevation), (2, 3.0, 4.0, 0.0));
assert!(!now.associative);
assert!(s.commit_array().unwrap());
assert!(s.running.is_none());
}
#[test]
fn polar_set_array_live_sets_the_center_and_advances_from_center_stage() {
let mut s = selected();
s.start("arraypolar").unwrap();
// Still at the Center stage.
assert_eq!(s.array_live().unwrap().center, Some(Vec2::new(5.0, 0.0)));
let mut v = s.array_live().unwrap();
v.center = Some(Vec2::new(7.0, -2.0));
s.set_array_live(&v).unwrap();
let now = s.array_live().unwrap();
assert_eq!(now.center, Some(Vec2::new(7.0, -2.0)));
assert!(!s.current_prompt().unwrap().message.contains("center point of array"));
}
#[test]
fn polar_center_none_while_at_center_stays_at_center() {
let mut s = selected();
s.start("arraypolar").unwrap();
let mut v = s.array_live().unwrap();
v.center = None;
s.set_array_live(&v).unwrap();
assert!(s.current_prompt().unwrap().message.contains("center point of array"));
}
#[test]
fn polar_set_array_live_refuses_bad_values() {
let mut s = selected();
s.start("arraypolar").unwrap();
let before = s.array_live().unwrap();
let mut zero = before.clone();
zero.fill = 0.0;
assert!(s.set_array_live(&zero).is_err());
assert_eq!(s.array_live().unwrap(), before);
let mut big = before.clone();
big.fill = 361.0;
assert!(s.set_array_live(&big).is_err());
assert_eq!(s.array_live().unwrap(), before);
let mut no_items = before.clone();
no_items.items = 0;
assert!(s.set_array_live(&no_items).is_err());
assert_eq!(s.array_live().unwrap(), before);
let mut inf = before.clone();
inf.row_spacing = f64::NAN;
assert!(s.set_array_live(&inf).is_err());
assert_eq!(s.array_live().unwrap(), before);
let mut wrong = before.clone();
wrong.kind = ArrayLiveKind::Rectangular;
assert!(s.set_array_live(&wrong).is_err());
assert_eq!(s.array_live().unwrap(), before);
}
#[test]
fn no_running_array_is_a_noop() {
let mut s = Session::new();
assert!(s.array_live().is_none());
let v = ArrayLive {
kind: ArrayLiveKind::Rectangular,
cols: 2,
rows: 2,
col_spacing: 1.0,
row_spacing: 1.0,
levels: 1,
level_spacing: 0.0,
row_elevation: 0.0,
associative: true,
items: 0,
fill: 0.0,
rotate: false,
center: None,
between: None,
};
s.set_array_live(&v).unwrap();
assert!(!s.array_pick_center());
assert!(!s.commit_array().unwrap());
assert!(s.array_live().is_none());
}
#[test]
fn commit_while_selecting_objects_is_refused() {
let mut s = Session::new();
s.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap();
s.start("arrayrect").unwrap();
// No pickfirst selection: the command is still asking for objects.
assert!(!s.commit_array().unwrap());
assert!(s.running.is_some());
// Feed a selection: the command is ready, so it commits.
let h = first_handle(&s);
s.input(Input::Pick(vec![h])).unwrap();
// A pick does not end the selection prompt; Enter does, and the command is ready.
assert!(!s.commit_array().unwrap());
s.input(Input::Enter).unwrap();
assert!(s.array_live().is_some());
assert!(s.commit_array().unwrap());
assert!(s.running.is_none());
}
#[test]
fn commit_creates_polar_copies() {
let mut s = selected();
s.start("arraypolar").unwrap();
s.input(Input::Point(Vec2::new(1.0, 1.0))).unwrap();
let mut v = s.array_live().unwrap();
v.items = 5;
v.fill = 360.0;
s.set_array_live(&v).unwrap();
assert!(s.commit_array().unwrap());
assert!(s.running.is_none());
}
#[test]
fn rect_live_has_no_angle_between() {
let mut s = selected();
s.start("arrayrect").unwrap();
assert_eq!(s.array_live().unwrap().between, None);
// Writing the rectangular values leaves the polar-only field alone.
let mut v = s.array_live().unwrap();
v.between = Some(45.0);
s.set_array_live(&v).unwrap();
assert_eq!(s.array_live().unwrap().between, None);
}
#[test]
fn polar_live_exposes_the_angle_between() {
let mut s = selected();
s.start("arraypolar").unwrap();
// The defaults are 6 items over a full turn: 60 degrees between items.
assert_eq!(s.array_live().unwrap().between, Some(60.0));
let mut v = s.array_live().unwrap();
v.items = 1;
v.fill = 90.0;
s.set_array_live(&v).unwrap();
// A single item has no gap: the angle between is the fill angle.
assert_eq!(s.array_live().unwrap().between, Some(90.0));
}
#[test]
fn polar_set_array_live_derives_the_fill_from_the_angle_between() {
let mut s = selected();
s.start("arraypolar").unwrap();
// Items and Angle between edited together: the fill uses the new item count.
let mut v = s.array_live().unwrap();
v.items = 4;
v.between = Some(45.0);
s.set_array_live(&v).unwrap();
let now = s.array_live().unwrap();
assert_eq!((now.items, now.fill), (4, 135.0));
assert_eq!(now.between, Some(45.0));
// A full turn spread over 3 items: 180 degrees each.
let mut v = now.clone();
v.items = 3;
v.between = Some(180.0);
s.set_array_live(&v).unwrap();
assert_eq!(s.array_live().unwrap().fill, 360.0);
// An edited Fill angle wins over the angle between.
let mut v = s.array_live().unwrap();
v.items = 4;
v.fill = 90.0;
v.between = Some(45.0);
s.set_array_live(&v).unwrap();
let now = s.array_live().unwrap();
assert_eq!((now.items, now.fill), (4, 90.0));
assert_eq!(now.between, Some(30.0));
}
#[test]
fn polar_set_array_live_refuses_a_bad_angle_between() {
let mut s = selected();
s.start("arraypolar").unwrap();
let before = s.array_live().unwrap();
let mut zero = before.clone();
zero.between = Some(0.0);
assert!(s.set_array_live(&zero).is_err());
assert_eq!(s.array_live().unwrap(), before);
let mut inf = before.clone();
inf.between = Some(f64::NAN);
assert!(s.set_array_live(&inf).is_err());
assert_eq!(s.array_live().unwrap(), before);
// The items would span more than a full turn.
let mut wide = before.clone();
wide.items = 4;
wide.between = Some(180.0);
assert!(s.set_array_live(&wide).is_err());
assert_eq!(s.array_live().unwrap(), before);
}
#[test]
fn commit_at_the_center_refuses_and_leaves_the_command_untouched() {
let mut s = selected();
s.start("arraypolar").unwrap();
let before_doc = s.doc().unwrap().clone();
let before_prompt = s.current_prompt().unwrap().message.clone();
let before_live = s.array_live().unwrap();
assert!(!s.commit_array().unwrap());
assert!(s.running.is_some());
assert_eq!(s.current_prompt().unwrap().message, before_prompt);
assert_eq!(s.doc().unwrap(), &before_doc);
assert_eq!(s.array_live().unwrap(), before_live);
}
#[test]
fn commit_after_an_edited_center_succeeds() {
let mut s = selected();
s.start("arraypolar").unwrap();
let mut v = s.array_live().unwrap();
v.center = Some(Vec2::new(7.0, -2.0));
s.set_array_live(&v).unwrap();
assert!(!s.current_prompt().unwrap().message.contains("center point of array"));
assert!(s.commit_array().unwrap());
assert!(s.running.is_none());
}
#[test]
fn commit_from_the_items_stage_succeeds() {
let mut s = selected();
s.start("arraypolar").unwrap();
s.input(Input::Point(Vec2::new(1.0, 1.0))).unwrap();
s.cmdline("items").unwrap();
assert!(s.current_prompt().unwrap().message.contains("items"));
assert!(s.commit_array().unwrap());
assert!(s.running.is_none());
}
#[test]
fn commit_at_the_center_base_stage_refuses() {
let mut s = selected();
s.start("arraypolar").unwrap();
s.cmdline("base point").unwrap();
assert!(s.current_prompt().unwrap().message.contains("base point"));
let before = s.array_live().unwrap();
assert!(!s.commit_array().unwrap());
assert!(s.running.is_some());
assert_eq!(s.array_live().unwrap(), before);
}
/// The live setter enforces MAXARRAY just like the commit path.
fn low_maxarray(s: &mut Session, max: i64) {
s.execute("setvar", &json!({ "name": "MAXARRAY", "value": max })).unwrap();
}
#[test]
fn live_rect_refuses_an_oversized_total_unchanged() {
let mut s = selected();
s.start("arrayrect").unwrap();
low_maxarray(&mut s, 100);
let before = s.array_live().unwrap();
let mut big = before.clone();
(big.rows, big.cols) = (10, 11);
let e = s.set_array_live(&big).unwrap_err();
assert!(e.to_string().contains("MAXARRAY"), "{e}");
assert_eq!(s.array_live().unwrap(), before);
}
#[test]
fn live_polar_refuses_an_oversized_total_unchanged() {
let mut s = selected();
s.start("arraypolar").unwrap();
low_maxarray(&mut s, 100);
let before = s.array_live().unwrap();
let mut big = before.clone();
(big.items, big.rows) = (20, 6);
let e = s.set_array_live(&big).unwrap_err();
assert!(e.to_string().contains("MAXARRAY"), "{e}");
assert_eq!(s.array_live().unwrap(), before);
}
#[test]
fn live_rect_accepts_exactly_at_the_limit() {
let mut s = selected();
s.start("arrayrect").unwrap();
low_maxarray(&mut s, 100);
let mut v = s.array_live().unwrap();
v.associative = false;
(v.rows, v.cols) = (10, 10);
s.set_array_live(&v).unwrap();
assert_eq!((s.array_live().unwrap().rows, s.array_live().unwrap().cols), (10, 10));
}
#[test]
fn live_rect_excludes_levels_when_not_associative() {
let mut s = selected();
s.start("arrayrect").unwrap();
low_maxarray(&mut s, 100);
// rows × cols = 100 fits; rows × cols × levels would not, but levels is ignored.
let mut v = s.array_live().unwrap();
v.associative = false;
(v.rows, v.cols, v.levels) = (10, 10, 50);
s.set_array_live(&v).unwrap();
assert_eq!(s.array_live().unwrap().levels, 50);
}
+64 -1
View File
@@ -4,7 +4,7 @@
use std::sync::Arc;
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, Text};
use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, MText, MultilineAttrib, Text};
use cadcraft_engine::geom::Vec3;
use serde_json::json;
@@ -45,3 +45,66 @@ fn references_take_lock_position_from_the_definition() {
let Some(EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| e.kind.clone()) else { panic!("no reference") };
assert_eq!(i.attribs[0].modes, AttribModes { verify: false, preset: false, lock_position: true });
}
/// A definition at `x` with `modes`, invisible or not, multiline or not.
fn definition(tag: &str, x: f64, modes: AttribModes, invisible: bool, multiline: bool) -> Attrib {
let text = Text {
insert: Vec3::new(x, 0.0, 0.0),
align_pt: None,
height: 2.0,
value: tag.into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
};
let multiline = multiline.then(|| {
let mtext = MText {
insert: Vec3::new(x, 0.0, 0.0),
height: 2.0,
width: 0.0,
attach: 7,
rotation: 0.0,
style: "Standard".into(),
contents: format!("{tag}\\PTWO"),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
};
MultilineAttrib { mtext, read_as: format!("{tag}\nTWO") }
});
Attrib { tag: tag.into(), text, invisible, constant: false, prompt: tag.into(), props: Default::default(), multiline, modes }
}
#[test]
fn only_shown_unlocked_attributes_have_grips_and_a_multiline_one_moves_its_text() {
let mut d = cadcraft_engine::doc::Drawing::new_imperial();
let locked = AttribModes { lock_position: true, ..AttribModes::default() };
let mut b = Block::new("TAG");
for a in [
definition("FREE", 0.0, AttribModes::default(), false, false),
definition("LOCKED", 10.0, locked, false, false),
definition("HIDDEN", 20.0, AttribModes::default(), true, false),
definition("NOTE", 30.0, AttribModes::default(), false, true),
] {
let h = d.new_handle();
b.entities.push(Entity::new(h, EntityKind::AttDef(a)));
}
d.blocks.insert("TAG".into(), Arc::new(b));
let mut s = Session::empty();
s.open_drawing(d, "tags", None);
let r = s.execute("insert", &json!({ "name": "TAG", "at": [100, 0] })).unwrap();
let h = cadcraft_engine::doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
// The insertion point, FREE and NOTE: no grip for the locked or the invisible attribute.
let g = s.grips_of(h).unwrap();
assert_eq!(g.iter().map(|p| p.x).collect::<Vec<_>>(), [100.0, 100.0, 130.0]);
// NOTE's grip (index 2) dragged up 5: its multiline text moves with it.
s.execute("grip.stretch", &json!({ "handle": h.hex(), "index": 2, "to": [130, 5] })).unwrap();
let Some(EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| e.kind.clone()) else { panic!("no reference") };
let note = i.attribs.iter().find(|a| a.tag == "NOTE").unwrap();
assert_eq!((note.text.insert.y, note.multiline.as_ref().unwrap().mtext.insert.y), (5.0, 5.0));
let free = i.attribs.iter().find(|a| a.tag == "FREE").unwrap();
assert_eq!(free.text.insert.y, 0.0, "the others stay");
}
@@ -36,13 +36,16 @@ fn baseline_spacing_follows_overrides_and_dimscale() {
assert!(near(dli, 1.0), "SETVAR DIMDLI sets the spacing: {dli}");
let zero = baseline_spacing(&[("dimstyle", json!({"name": "Standard", "DIMSCALE": 0}))]);
assert!(near(zero, 0.38), "DIMSCALE 0 in model space is scale 1, not a collapsed spacing: {zero}");
}
// DIMSPACE's default spacing (twice DIMDLI) uses the same scale.
#[test]
fn dimspace_auto_uses_unit_scale_for_zero_dimscale_in_model_space() {
let mut s = Session::new();
s.execute("dimstyle", &json!({"name": "Standard", "DIMSCALE": 0})).unwrap();
let text_height = 0.25;
s.execute("dimstyle", &json!({"name": "Standard", "DIMTXT": text_height, "DIMSCALE": 0})).unwrap();
let a = s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [30, 0], "at": [15, 5]})).unwrap();
let b = s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [50, 0], "at": [25, 6]})).unwrap();
s.execute("dimspace", &json!({"base": a["handle"], "handles": [b["handle"]]})).unwrap();
let gap = dim_line_y(&s, &b["handle"]) - dim_line_y(&s, &a["handle"]);
assert!(near(gap, 0.76), "{gap}");
assert!((gap - 2.0 * text_height).abs() < 1e-9, "{gap}");
}
+53
View File
@@ -145,3 +145,56 @@ fn a_grip_drag_previews_the_reference_in_its_own_colours() {
let blue = cadcraft_engine::doc::color::Color::True(cadcraft_engine::doc::color::Rgb(0x2f, 0x6b, 0xff));
assert!(preview[n..].iter().all(|e| e.common.color == blue));
}
#[test]
fn a_grip_with_a_value_list_marks_its_stops_while_dragged() {
let (mut s, h) = session();
// Width is a list (30, 32, 36) from (0, -4): its end can stop 30, 32 or 36 along it.
let stops = cadcraft_engine::doc::dynblock::grip_stops(s.doc().unwrap(), h, 2, GripPart::End);
let at: Vec<(f64, f64)> = stops.iter().map(|(p, _)| (p.x, p.y)).collect();
assert_eq!(at, [(130.0, -4.0), (132.0, -4.0), (136.0, -4.0)]);
assert!(stops.iter().all(|(_, way)| (way.x - 1.0).abs() < 1e-12 && way.y.abs() < 1e-12));
// A grip that isn't on a list or increments has none; nor a list grip.
assert!(cadcraft_engine::doc::dynblock::grip_stops(s.doc().unwrap(), h, 1, GripPart::At).is_empty());
// The preview marks each stop with a tick across the travel, a few pixels long.
s.start_dyn_grip(h, 2, GripPart::End).unwrap();
let half = 6.0 * s.pixel_size();
let ticks: Vec<(f64, f64)> = s
.preview(Vec2::new(133.0, 0.0))
.into_iter()
.filter_map(|e| match e.kind {
cadcraft_engine::doc::EntityKind::Line(l) if (l.a.x - l.b.x).abs() < 1e-9 && ((l.b.y - l.a.y).abs() - 2.0 * half).abs() < 1e-9 => {
Some((l.a.x, (l.a.y + l.b.y) / 2.0))
}
_ => None,
})
.collect();
assert_eq!(ticks, [(130.0, -4.0), (132.0, -4.0), (136.0, -4.0)]);
}
/// An alignment grip dragged onto a line (the synthetic Align block of the io tests, a line at
/// 30° from (120, 100)): the reference moves onto the line and turns along it, as AutoCAD does;
/// away from objects it only moves.
#[test]
fn an_alignment_grip_aligns_with_the_line_at_the_cursor() {
let src = include_str!("../../../io/tests/data/dynblock_params.txt").replace("\r\n", "\n");
let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap();
let mut s = Session::empty();
s.open_drawing(d, "params", None);
let r = s.execute("insert", &json!({ "name": "Align", "at": [100, 100] })).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
let g = s.execute("blocks.reference.grips", &json!({ "handle": h.hex() })).unwrap();
assert_eq!(g[0]["shape"], "alignment");
// A point on the line, a little below it.
let (c, sn) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
let to = [120.0 + 10.0 * c + 0.01 * sn, 100.0 + 10.0 * sn - 0.01 * c];
s.execute("blocks.reference.grip", &json!({ "handle": h.hex(), "node": 1, "part": "base", "to": to })).unwrap();
let Some(cadcraft_engine::doc::EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| &e.kind) else { panic!("a reference") };
assert!((i.rotation.to_degrees() - 30.0).abs() < 1e-6, "{}", i.rotation.to_degrees());
assert!((i.insert.x - (120.0 + 10.0 * c)).abs() < 1e-6 && (i.insert.y - (100.0 + 10.0 * sn)).abs() < 1e-6, "{:?}", i.insert);
// Far from anything: it only moves.
s.execute("blocks.reference.grip", &json!({ "handle": h.hex(), "node": 1, "part": "base", "to": [0, -50] })).unwrap();
let Some(cadcraft_engine::doc::EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| &e.kind) else { panic!("a reference") };
assert!((i.rotation.to_degrees() - 30.0).abs() < 1e-6 && i.insert.x.abs() < 1e-9 && (i.insert.y + 50.0).abs() < 1e-9);
}
+522
View File
@@ -0,0 +1,522 @@
//! EXTRIM (#2802): everything that crosses one cutting edge loses its part on the side picked.
use cadcraft_engine::doc::{EntityKind, Handle};
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::{Input, Session};
use serde_json::{Value, json};
/// The handle a drawing command returns.
fn h(v: &Value) -> String {
v["handle"].as_str().or_else(|| v["handles"][0].as_str()).unwrap().to_string()
}
fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> String {
h(&s.execute("line", &json!({ "points": [a, b] })).unwrap())
}
fn exists(s: &Session, hex: &str) -> bool {
s.doc().unwrap().entity(Handle::parse_hex(hex).unwrap()).is_some()
}
/// The lines of the drawing, as their end points rounded to 1e-6.
fn lines(s: &Session) -> Vec<[[i64; 2]; 2]> {
let r = |x: f64| (x * 1e6).round() as i64;
let mut v: Vec<[[i64; 2]; 2]> = s
.doc()
.unwrap()
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(l) => {
let (a, b) = ([r(l.a.x), r(l.a.y)], [r(l.b.x), r(l.b.y)]);
Some(if a <= b { [a, b] } else { [b, a] })
}
_ => None,
})
.collect();
v.sort();
v
}
/// `[[x1, y1], [x2, y2]]` in the units of [`lines`].
fn seg(a: [f64; 2], b: [f64; 2]) -> [[i64; 2]; 2] {
let r = |x: f64| (x * 1e6).round() as i64;
let (a, b) = ([r(a[0]), r(a[1])], [r(b[0]), r(b[1])]);
if a <= b { [a, b] } else { [b, a] }
}
/// A two-point preview polyline as a [`seg`].
fn preview_segment(k: &EntityKind) -> [[i64; 2]; 2] {
let EntityKind::LwPolyline(p) = k else { panic!("{k:?}") };
let [a, b] = &p.vertices[..] else { panic!("{p:?}") };
seg([a.p.x, a.p.y], [b.p.x, b.p.y])
}
/// Every point of every object but `edge`, as drawn.
fn points_but(s: &Session, edge: &str) -> Vec<Vec2> {
let d = s.doc().unwrap();
let skip = Handle::parse_hex(edge).unwrap();
d.model.iter().filter(|e| e.handle != skip).flat_map(|e| cadcraft_engine::select::hit_polylines(d, e, 1e-4).into_iter().flatten()).collect()
}
/// The highest point of every object but `edge`.
fn top_but(s: &Session, edge: &str) -> f64 {
points_but(s, edge).iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max)
}
fn extrim(s: &mut Session, edge: &str, side: [f64; 2]) -> Value {
s.execute("extrim", &json!({ "edge": edge, "side": side })).unwrap()
}
#[test]
fn trims_one_side_of_a_line() {
let mut s = Session::new();
let edge = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
for x in [2.0, 5.0, 8.0] {
line(&mut s, [x, -5.0], [x, 5.0]);
}
let v = extrim(&mut s, &edge, [5.0, 3.0]);
assert_eq!(v["trimmed"], 3);
let mut want = vec![seg([0.0, 0.0], [10.0, 0.0])];
want.extend([2.0, 5.0, 8.0].map(|x| seg([x, -5.0], [x, 0.0])));
want.sort();
assert_eq!(lines(&s), want);
}
#[test]
fn trims_the_other_side_of_a_line() {
let mut s = Session::new();
let edge = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
line(&mut s, [5.0, -5.0], [5.0, 5.0]);
extrim(&mut s, &edge, [5.0, -3.0]);
let mut want = vec![seg([0.0, 0.0], [10.0, 0.0]), seg([5.0, 0.0], [5.0, 5.0])];
want.sort();
assert_eq!(lines(&s), want);
}
#[test]
fn an_open_edge_trims_only_along_its_length() {
let mut s = Session::new();
let edge = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
// Crosses the line the edge lies on, but past its end.
line(&mut s, [20.0, -5.0], [20.0, 5.0]);
let v = extrim(&mut s, &edge, [5.0, 3.0]);
assert_eq!(v["trimmed"], 0);
assert_eq!(lines(&s).len(), 2);
}
#[test]
fn inside_and_outside_a_circle() {
let mut s = Session::new();
let c = h(&s.execute("circle", &json!({ "center": [0, 0], "radius": 5 })).unwrap());
line(&mut s, [-10.0, 0.0], [10.0, 0.0]);
extrim(&mut s, &c, [0.0, 1.0]);
assert_eq!(lines(&s), vec![seg([-10.0, 0.0], [-5.0, 0.0]), seg([5.0, 0.0], [10.0, 0.0])]);
let mut s = Session::new();
let c = h(&s.execute("circle", &json!({ "center": [0, 0], "radius": 5 })).unwrap());
line(&mut s, [-10.0, 0.0], [10.0, 0.0]);
let v = extrim(&mut s, &c, [0.0, 8.0]);
assert_eq!(v["trimmed"], 1);
assert_eq!(lines(&s), vec![seg([-5.0, 0.0], [5.0, 0.0])]);
}
#[test]
fn inside_a_closed_polyline() {
let mut s = Session::new();
let r = h(&s.execute("pline", &json!({ "points": [[0, 0], [10, 0], [10, 6], [0, 6]], "closed": true })).unwrap());
line(&mut s, [-5.0, 3.0], [15.0, 3.0]);
line(&mut s, [5.0, -5.0], [5.0, 11.0]);
let v = extrim(&mut s, &r, [2.0, 2.0]);
assert_eq!(v["trimmed"], 2);
let mut want = vec![seg([-5.0, 3.0], [0.0, 3.0]), seg([10.0, 3.0], [15.0, 3.0]), seg([5.0, -5.0], [5.0, 0.0]), seg([5.0, 6.0], [5.0, 11.0])];
want.sort();
assert_eq!(lines(&s), want);
}
#[test]
fn inside_an_ellipse() {
let mut s = Session::new();
let e = h(&s.execute("ellipse", &json!({ "center": [0, 0], "major": [10, 0], "ratio": 0.5 })).unwrap());
line(&mut s, [-20.0, 0.0], [20.0, 0.0]);
extrim(&mut s, &e, [0.0, 1.0]);
// Cut where TRIM cuts at an ellipse: on its flattened outline, within 1e-4 of the axis.
let [[a, b], [c, d]] = lines(&s)[..] else { panic!("{:?}", lines(&s)) };
assert_eq!((a, d), ([-20_000_000, 0], [20_000_000, 0]), "the outer parts stay");
assert!((b[0] + 10_000_000).abs() <= 2_000 && (c[0] - 10_000_000).abs() <= 2_000, "{b:?} {c:?}");
}
#[test]
fn along_a_spline() {
let mut s = Session::new();
let sp = h(&s.execute("spline", &json!({ "control": [[0, 0], [3, 3], [6, -3], [9, 0]] })).unwrap());
// A vertical line through the spline's middle, where it crosses y = 0.
line(&mut s, [4.5, -5.0], [4.5, 5.0]);
let v = extrim(&mut s, &sp, [4.5, 4.0]);
assert_eq!(v["trimmed"], 1);
let [[a, b]] = lines(&s)[..] else { panic!("{:?}", lines(&s)) };
assert_eq!(a, [4_500_000, -5_000_000], "the lower part stays");
assert!(b[1].abs() < 10, "cut at the spline: {b:?}");
}
#[test]
fn an_object_crossing_twice_loses_the_stretch_between() {
let mut s = Session::new();
let edge = line(&mut s, [-10.0, 0.0], [10.0, 0.0]);
let u = h(&s.execute("pline", &json!({ "points": [[0, -2], [0, 2], [4, 2], [4, -2]] })).unwrap());
let v = extrim(&mut s, &edge, [2.0, 1.0]);
assert_eq!(v["trimmed"], 1);
// As TRIM leaves them: the first leg keeps the polyline's handle, the second is new.
assert!(exists(&s, &u));
let pieces = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::LwPolyline(_))).count();
assert_eq!(pieces, 2, "the two legs below the edge stay");
}
#[test]
fn leaves_the_edge_and_objects_that_do_not_cross_it() {
let mut s = Session::new();
let c = h(&s.execute("circle", &json!({ "center": [0, 0], "radius": 5 })).unwrap());
let inside = line(&mut s, [-1.0, 0.0], [1.0, 0.0]);
let v = extrim(&mut s, &c, [0.0, 2.0]);
assert_eq!(v["trimmed"], 0);
assert!(exists(&s, &c));
assert!(exists(&s, &inside), "an object wholly on the side but not crossing the edge stays");
}
#[test]
fn skips_locked_layers_blocks_and_hatches() {
let mut s = Session::new();
let edge = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
s.execute("layer.new", &json!({ "name": "L1" })).unwrap();
let locked = line(&mut s, [2.0, -5.0], [2.0, 5.0]);
s.execute("chprop", &json!({ "handles": [locked.clone()], "layer": "L1" })).unwrap();
s.execute("layer.set", &json!({ "name": "L1", "locked": true })).unwrap();
let b = line(&mut s, [0.0, 0.0], [0.0, 10.0]);
s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [b] })).unwrap();
s.execute("insert", &json!({ "name": "B", "at": [5, -5] })).unwrap();
let r = h(&s.execute("rectang", &json!({ "p1": [7, -2], "p2": [9, 2] })).unwrap());
s.execute("hatch", &json!({ "handles": [r] })).unwrap();
let v = extrim(&mut s, &edge, [5.0, 3.0]);
assert_eq!(v["skipped"]["locked"], 1);
assert!(v["skipped"]["other"].as_u64().unwrap() >= 2, "{v}");
assert!(exists(&s, &locked), "the locked line is not trimmed");
assert!(v["message"].as_str().unwrap().contains("locked"));
}
#[test]
fn one_undo_restores_everything() {
let mut s = Session::new();
let edge = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
for x in [2.0, 5.0, 8.0] {
line(&mut s, [x, -5.0], [x, 5.0]);
}
let before = lines(&s);
extrim(&mut s, &edge, [5.0, 3.0]);
assert_ne!(lines(&s), before);
s.execute("undo", &json!({})).unwrap();
assert_eq!(lines(&s), before);
}
#[test]
fn never_leaves_a_piece_of_no_length() {
let mut s = Session::new();
let edge = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
// Starts a hair below the edge: trimming above would leave a sliver.
line(&mut s, [5.0, -1e-8], [5.0, 5.0]);
extrim(&mut s, &edge, [5.0, 3.0]);
let d = s.doc().unwrap();
for e in d.model.iter() {
if let EntityKind::Line(l) = &e.kind {
assert!(l.a.xy().dist(l.b.xy()) > 1e-6, "sliver left: {l:?}");
}
}
}
#[test]
fn refuses_bad_input_and_changes_nothing() {
let mut s = Session::new();
let edge = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
line(&mut s, [5.0, -5.0], [5.0, 5.0]);
let t = h(&s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap());
let before = lines(&s);
for p in [
json!({ "side": [5, 3] }),
json!({ "edge": "zz", "side": [5, 3] }),
json!({ "edge": 5, "side": [5, 3] }),
json!({ "edge": "FFFFFF", "side": [5, 3] }),
json!({ "edge": t, "side": [5, 3] }),
json!({ "edge": edge, "side": [5, 0] }),
json!({ "edge": edge }),
json!({ "edge": edge, "side": ["a", 3] }),
] {
assert!(s.execute("extrim", &p).is_err(), "{p}");
}
assert_eq!(lines(&s), before);
}
#[test]
fn refuses_an_edge_in_another_space() {
let mut s = Session::new();
let edge = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
assert!(s.execute("extrim", &json!({ "edge": edge, "side": [5, 3] })).is_err());
}
#[test]
fn prompts_for_the_edge_then_the_side() {
let mut s = Session::new();
let edge = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
line(&mut s, [5.0, -5.0], [5.0, 5.0]);
s.set_selection(Vec::new());
s.start("extrim").unwrap();
assert!(s.prompt_text().contains("cutting edge"), "{}", s.prompt_text());
s.input(Input::Pick(vec![Handle::parse_hex(&edge).unwrap()])).unwrap();
assert!(s.prompt_text().contains("side"), "{}", s.prompt_text());
// The preview shows what goes: the upper half of the vertical line.
let shown = s.preview(Vec2::new(5.0, 3.0));
assert_eq!(shown.len(), 1);
s.input(Input::Point(Vec2::new(5.0, 3.0))).unwrap();
assert!(s.current_prompt().is_none());
let mut want = vec![seg([0.0, 0.0], [10.0, 0.0]), seg([5.0, -5.0], [5.0, 0.0])];
want.sort();
assert_eq!(lines(&s), want);
}
#[test]
fn uses_a_preselected_edge() {
let mut s = Session::new();
let edge = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
line(&mut s, [5.0, -5.0], [5.0, 5.0]);
s.set_selection(vec![Handle::parse_hex(&edge).unwrap()]);
s.start("extrim").unwrap();
assert!(s.prompt_text().contains("side"), "{}", s.prompt_text());
s.input(Input::Point(Vec2::new(5.0, -3.0))).unwrap();
let mut want = vec![seg([0.0, 0.0], [10.0, 0.0]), seg([5.0, 0.0], [5.0, 5.0])];
want.sort();
assert_eq!(lines(&s), want);
}
#[test]
fn many_objects_in_one_call() {
let mut s = Session::new();
let c = h(&s.execute("circle", &json!({ "center": [0, 0], "radius": 50 })).unwrap());
for i in 0..500 {
let y = -45.0 + 90.0 * f64::from(i) / 500.0;
line(&mut s, [-100.0, y], [100.0, y]);
}
let v = extrim(&mut s, &c, [0.0, 0.5]);
assert_eq!(v["trimmed"], 500);
assert_eq!(lines(&s).len(), 1000, "two outer pieces of each line");
}
#[test]
fn refuses_more_objects_than_the_limit_and_changes_nothing() {
let mut s = Session::new();
let edge = line(&mut s, [0.0, 0.0], [10_002.0, 0.0]);
// One more crossing object than one call trims.
for i in 0..10_001 {
let x = 0.5 + f64::from(i);
line(&mut s, [x, -1.0], [x, 1.0]);
}
let before = lines(&s);
let e = s.execute("extrim", &json!({ "edge": edge, "side": [5, 0.5] })).unwrap_err();
assert!(e.to_string().contains("objects cross the cutting edge"), "{e}");
assert_eq!(lines(&s), before);
}
#[test]
fn refuses_an_edge_with_too_many_points_and_changes_nothing() {
let mut s = Session::new();
// A zigzag polyline whose corners alone are more points than the trace may have.
let pts: Vec<[f64; 2]> = (0..10_002).map(|i| [f64::from(i), if i % 2 == 0 { 0.0 } else { 1.0 }]).collect();
let edge = h(&s.execute("pline", &json!({ "points": pts })).unwrap());
line(&mut s, [5.5, -5.0], [5.5, 5.0]);
let before = lines(&s);
let e = s.execute("extrim", &json!({ "edge": edge, "side": [5.5, 3.0] })).unwrap_err();
assert!(e.to_string().contains("too complex"), "{e}");
assert_eq!(lines(&s), before);
}
#[test]
fn a_circle_crossed_once_is_reported_not_trimmed() {
let mut s = Session::new();
// The edge ends inside the circle, so it crosses it only once: no trim can open it.
let edge = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
let c = h(&s.execute("circle", &json!({ "center": [10, 0], "radius": 2 })).unwrap());
let crossing = line(&mut s, [5.0, -5.0], [5.0, 5.0]);
s.set_selection(vec![Handle::parse_hex(&edge).unwrap()]);
s.start("extrim").unwrap();
// The preview shows only what will go: the upper half of the vertical line.
let shown = s.preview(Vec2::new(5.0, 3.0));
assert_eq!(shown.len(), 1);
assert_eq!(preview_segment(&shown[0].kind), seg([5.0, 0.0], [5.0, 5.0]));
s.cancel();
let v = extrim(&mut s, &edge, [5.0, 3.0]);
assert_eq!(v["trimmed"], 1);
assert_eq!(v["skipped"]["uncut"], 1, "{v}");
assert!(v["message"].as_str().unwrap().contains("could not be cut"), "{v}");
assert!(exists(&s, &c), "the circle stays whole");
// The vertical line keeps its handle and only its lower half.
let mut want = vec![seg([0.0, 0.0], [10.0, 0.0]), seg([5.0, -5.0], [5.0, 0.0])];
want.sort();
assert_eq!(lines(&s), want);
assert!(exists(&s, &crossing));
}
#[test]
fn an_open_polyline_drawn_back_to_its_start_loses_both_ends() {
let mut s = Session::new();
let edge = line(&mut s, [-5.0, 0.0], [10.0, 0.0]);
// Open, though its last point lands on its first.
h(&s.execute("pline", &json!({ "points": [[0, 2], [0, -2], [4, -2], [4, 2], [0, 2]] })).unwrap());
let v = extrim(&mut s, &edge, [2.0, 3.0]);
assert_eq!(v["trimmed"], 1);
assert!(top_but(&s, &edge) <= 1e-6, "nothing left above the edge: {:?}", points_but(&s, &edge));
}
#[test]
fn an_object_that_only_touches_the_edge_stays_and_is_not_previewed() {
let mut s = Session::new();
let edge = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
let touching = line(&mut s, [5.0, 0.0], [5.0, 5.0]);
line(&mut s, [2.0, -5.0], [2.0, 5.0]);
s.set_selection(vec![Handle::parse_hex(&edge).unwrap()]);
s.start("extrim").unwrap();
let shown = s.preview(Vec2::new(5.0, 3.0));
assert_eq!(shown.len(), 1);
assert_eq!(preview_segment(&shown[0].kind), seg([2.0, 0.0], [2.0, 5.0]));
s.cancel();
let v = extrim(&mut s, &edge, [5.0, 3.0]);
assert_eq!(v["trimmed"], 1);
assert_eq!(v["skipped"]["uncut"], 0, "{v}");
assert!(exists(&s, &touching), "touching is not crossing");
}
#[test]
fn a_circle_crossed_at_its_seam_is_cut_in_half() {
let mut s = Session::new();
// The edge meets the circle at (5, 0), where its outline starts and ends.
let edge = line(&mut s, [-10.0, 0.0], [10.0, 0.0]);
s.execute("circle", &json!({ "center": [0, 0], "radius": 5 })).unwrap();
let v = extrim(&mut s, &edge, [0.0, 8.0]);
assert_eq!(v["trimmed"], 1);
assert!(top_but(&s, &edge) <= 1e-6);
assert!(s.doc().unwrap().model.iter().any(|e| matches!(e.kind, EntityKind::Arc(_))), "the lower half stays as an arc");
}
#[test]
fn trims_arcs_ellipses_splines_and_bulged_polylines() {
let mut s = Session::new();
let edge = line(&mut s, [-30.0, 0.0], [40.0, 0.0]);
s.execute("arc", &json!({ "center": [-20, -2], "radius": 5, "start": 0, "end": 180 })).unwrap();
s.execute("ellipse", &json!({ "center": [-5, 0], "major": [4, 0], "ratio": 0.5 })).unwrap();
s.execute("spline", &json!({ "control": [[4, -2], [7, 4], [10, -4], [13, 2]] })).unwrap();
s.execute("pline", &json!({ "vertices": [{ "p": [20, -1], "bulge": -1 }, [28, -1]] })).unwrap();
assert!(top_but(&s, &edge) > 1.0);
let v = extrim(&mut s, &edge, [0.0, 3.0]);
assert_eq!(v["trimmed"], 4, "{v}");
// Curves are cut where TRIM cuts them, on their flattened outlines.
assert!(top_but(&s, &edge) <= 1e-3, "{}", top_but(&s, &edge));
}
#[test]
fn an_object_with_two_stretches_on_the_side_loses_both() {
let mut s = Session::new();
let edge = line(&mut s, [-5.0, 0.0], [10.0, 0.0]);
s.execute("pline", &json!({ "points": [[0, -1], [1, 1], [2, -1], [3, 1], [4, -1]] })).unwrap();
let v = extrim(&mut s, &edge, [2.0, 3.0]);
assert_eq!(v["trimmed"], 1);
assert!(top_but(&s, &edge) <= 1e-6);
let pieces = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::LwPolyline(_))).count();
assert_eq!(pieces, 3, "the three dips below the edge stay");
}
#[test]
fn past_an_arcs_ends_the_side_is_inside_or_outside_its_circle() {
let mut s = Session::new();
let arc = h(&s.execute("arc", &json!({ "center": [0, 0], "radius": 5, "start": 0, "end": 90 })).unwrap());
line(&mut s, [1.0, 1.0], [6.0, 6.0]);
// Outside the circle, though left of the arc's direction at its nearer end.
extrim(&mut s, &arc, [4.0, -4.0]);
let r = 5.0 / 2f64.sqrt();
let [[a, b]] = lines(&s)[..] else { panic!("{:?}", lines(&s)) };
assert_eq!(a, [1_000_000, 1_000_000], "the inner part stays");
assert!((b[0] as f64 / 1e6 - r).abs() < 1e-3 && (b[1] as f64 / 1e6 - r).abs() < 1e-3, "{b:?}");
}
#[test]
fn refuses_more_stretches_than_the_limit_and_changes_nothing() {
let mut s = Session::new();
let edge = line(&mut s, [-1.0, 0.0], [10_003.0, 0.0]);
// One object dipping across the edge more times than one call trims.
let pts: Vec<[f64; 2]> = (0..20_004).map(|i| [f64::from(i) / 2.0, if i % 2 == 0 { -1.0 } else { 1.0 }]).collect();
let z = h(&s.execute("pline", &json!({ "points": pts })).unwrap());
let e = s.execute("extrim", &json!({ "edge": edge, "side": [5, 3] })).unwrap_err();
assert!(e.to_string().contains("stretches"), "{e}");
assert!(exists(&s, &z));
}
#[test]
fn a_long_polyline_edge_is_accepted() {
let mut s = Session::new();
// 6,000 straight segments: its corners fit the trace once its pieces are joined.
let pts: Vec<[f64; 2]> = (0..6_001).map(|i| [f64::from(i), if i % 2 == 0 { 0.0 } else { 0.5 }]).collect();
let edge = h(&s.execute("pline", &json!({ "points": pts })).unwrap());
line(&mut s, [10.2, -5.0], [10.2, 5.0]);
let v = extrim(&mut s, &edge, [10.2, 3.0]);
assert_eq!(v["trimmed"], 1);
}
#[test]
fn takes_exactly_one_cutting_edge() {
let mut s = Session::new();
let a = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
let b = line(&mut s, [0.0, 2.0], [10.0, 2.0]);
line(&mut s, [5.0, -5.0], [5.0, 5.0]);
let before = lines(&s);
let e = s.execute("extrim", &json!({ "handles": [a.clone(), b.clone()], "side": [5, 3] })).unwrap_err();
assert!(e.to_string().contains("exactly one"), "{e}");
assert_eq!(lines(&s), before);
// At the prompt, a window of two objects is refused and the edge is asked for again.
s.set_selection(Vec::new());
s.start("extrim").unwrap();
s.input(Input::Pick(vec![Handle::parse_hex(&a).unwrap(), Handle::parse_hex(&b).unwrap()])).unwrap();
assert!(s.prompt_text().contains("cutting edge"), "{}", s.prompt_text());
s.input(Input::Pick(vec![Handle::parse_hex(&a).unwrap()])).unwrap();
assert!(s.prompt_text().contains("side"), "{}", s.prompt_text());
}
#[test]
fn large_radius_arcs_weaving_through_a_short_edge_lose_every_stretch_on_the_side() {
// #2808 review: a large arc's flattened outline strays from the arc by up to a millionth of its
// radius, far more than the tolerance next to a short edge, so the stretches must be found on
// the arc itself. Each arc weaves through the teeth of a short zigzag several times.
let mut s = Session::new();
let zig = |x: f64| {
let t = (x * 10.0).fract();
0.004 * if t < 0.5 { t * 2.0 } else { 2.0 - t * 2.0 }
};
let verts: Vec<[f64; 2]> = (0..=20).map(|i| [i as f64 * 0.05, zig(i as f64 * 0.05)]).collect();
let edge = h(&s.execute("pline", &json!({ "vertices": verts })).unwrap());
let radii = [50.0f64, 200.0, 1e3, 5e3, 2e4, 1e5];
for (k, r) in radii.iter().enumerate() {
// The arc's top a little above the middle of the teeth, its ends past the edge's.
let top = 0.002 + k as f64 * 1e-5;
let a = (0.6 / r).asin().to_degrees();
s.execute("arc", &json!({ "center": [0.5, top - r], "radius": r, "start": 90.0 - a, "end": 90.0 + a })).unwrap();
}
let v = extrim(&mut s, &edge, [0.5, 1.0]);
assert_eq!(v["trimmed"], radii.len(), "{v}");
assert_eq!(v["skipped"]["uncut"], 0, "{v}");
let d = s.doc().unwrap();
let skip = Handle::parse_hex(&edge).unwrap();
let above = d
.model
.iter()
.filter(|e| e.handle != skip)
.flat_map(|e| cadcraft_engine::select::hit_polylines(d, e, 1e-9).into_iter().flatten())
.filter(|p| p.x > 0.0 && p.x < 1.0)
.map(|p| p.y - zig(p.x))
.fold(f64::NEG_INFINITY, f64::max);
assert!(above <= 1e-6, "a stretch above the edge was left: {above:e}");
}
@@ -0,0 +1,425 @@
//! INSERT and the attribute modes (gap F17): Preset and constant attributes take their values
//! without asking, ATTREQ 0 gives every attribute its default, ATTDIA 0 asks at the command line
//! (a Verify attribute's value again once every value is in) and ATTDIA 1 (the default) asks for
//! the values all at once in the Edit Attributes dialog (`Session::attribute_entry`), typed
//! answers still working. The JSON form never asks. ATTREQ and ATTDIA are user settings, as in
//! AutoCAD (DWG keeps them in its header only before R2000).
use std::sync::Arc;
use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, Handle, Text};
use cadcraft_engine::geom::{Vec2, Vec3};
use cadcraft_engine::{AttribAsk, Input, Origin, Session};
use serde_json::json;
fn def(tag: &str, prompt: &str, default: &str, y: f64, constant: bool, modes: AttribModes) -> Attrib {
Attrib {
tag: tag.into(),
text: Text {
insert: Vec3::new(0.0, y, 0.0),
align_pt: None,
height: 1.0,
value: default.into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
},
invisible: false,
constant,
prompt: prompt.into(),
props: Default::default(),
multiline: None,
modes,
}
}
/// Block T with the definitions A (Verify), B (Preset), C (plain) and D (constant); ATTREQ and
/// ATTDIA as given (their defaults, ATTREQ 1 and ATTDIA 1, otherwise).
fn session(attreq: Option<bool>, attdia: Option<bool>) -> Session {
let mut d = cadcraft_engine::doc::Drawing::new_imperial();
let mut b = Block::new("T");
let none = AttribModes::default();
for a in [
def("A", "First", "1", 2.0, false, AttribModes { verify: true, ..none }),
def("B", "Second", "two", 4.0, false, AttribModes { preset: true, ..none }),
def("C", "Third", "3", 6.0, false, none),
def("D", "", "fixed", 8.0, true, none),
] {
let h = d.new_handle();
b.entities.push(Entity::new(h, EntityKind::AttDef(a)));
}
d.blocks.insert("T".into(), Arc::new(b));
let mut s = Session::empty();
s.open_drawing(d, "attribs", None);
if let Some(v) = attreq {
s.settings.attreq = v;
}
if let Some(v) = attdia {
s.settings.attdia = v;
}
s
}
/// Start INSERT of T at 100,0 and answer the scale and rotation prompts.
fn insert_up_to_the_attributes(s: &mut Session) {
s.start("insert").unwrap();
s.cmdline("T").unwrap();
s.input(Input::Point(Vec2::new(100.0, 0.0))).unwrap();
s.input(Input::Enter).unwrap(); // X scale 1
s.input(Input::Enter).unwrap(); // Y scale = X
s.input(Input::Enter).unwrap(); // rotation 0
}
/// The attribute values of the last block reference, in order.
fn values(s: &Session) -> Vec<(String, String)> {
let d = s.doc().unwrap();
let Some(EntityKind::Insert(i)) = d.model.iter().filter(|e| matches!(e.kind, EntityKind::Insert(_))).last().map(|e| e.kind.clone()) else {
panic!("no block reference")
};
i.attribs.iter().map(|a| (a.tag.clone(), a.text.value.clone())).collect()
}
fn pairs(v: &[(&str, &str)]) -> Vec<(String, String)> {
v.iter().map(|(t, v)| (t.to_string(), v.to_string())).collect()
}
#[test]
fn a_fresh_session_reads_attdia_1() {
// AutoCAD 2026's ATTDIA page: Type Integer, Saved in Registry, Initial value 1.
let mut s = session(None, None);
assert_eq!(s.execute("getvar", &json!({ "name": "ATTDIA" })).unwrap()["value"], 1);
assert!(s.settings.attdia);
}
#[test]
fn typed_insert_asks_verify_again_and_skips_preset_and_constant() {
// ATTDIA 0 set explicitly, so the command line asks.
let mut s = session(Some(true), Some(false));
assert_eq!(s.execute("getvar", &json!({ "name": "ATTDIA" })).unwrap()["value"], 0);
assert_eq!(s.execute("getvar", &json!({ "name": "ATTREQ" })).unwrap()["value"], 1);
insert_up_to_the_attributes(&mut s);
assert!(s.attribute_entry().is_none(), "ATTDIA 0: no dialog");
assert_eq!(s.prompt_text(), "INSERT First <1>:", "A first");
s.input(Input::Text("10".into())).unwrap();
assert_eq!(s.prompt_text(), "INSERT Third <3>:", "B is Preset: not asked");
s.input(Input::Enter).unwrap(); // C takes its default
// Then the Verify attributes, with the values typed.
assert_eq!(s.prompt_text(), "INSERT First <10>:");
s.input(Input::Text("11".into())).unwrap(); // the value typed at Verify replaces it
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "11"), ("B", "two"), ("C", "3")]));
// Enter at Verify keeps the value given; Enter at A takes its default, verified.
insert_up_to_the_attributes(&mut s);
s.input(Input::Enter).unwrap();
s.input(Input::Text("c".into())).unwrap();
assert_eq!(s.prompt_text(), "INSERT First <1>:");
s.input(Input::Enter).unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "1"), ("B", "two"), ("C", "c")]));
// A script answers in turn too.
s.script("-INSERT T 0,50 1 1 0\na\nc\nz\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "z"), ("B", "two"), ("C", "c")]));
}
#[test]
fn a_point_does_not_answer_an_attribute_prompt() {
// A canvas click reaches INSERT as Input::Point while a text-only attribute prompt waits.
// It is no answer: the prompt stays, and only Enter keeps the default.
let mut s = session(Some(true), Some(false));
insert_up_to_the_attributes(&mut s);
assert_eq!(s.prompt_text(), "INSERT First <1>:");
s.input(Input::Point(Vec2::new(20.0, 20.0))).unwrap();
assert_eq!(s.prompt_text(), "INSERT First <1>:", "the click did not take A's default");
assert!(s.attribute_entry().is_none(), "ATTDIA 0: no dialog");
s.input(Input::Text("10".into())).unwrap();
assert_eq!(s.prompt_text(), "INSERT Third <3>:", "A was answered by the typed text");
s.input(Input::Enter).unwrap(); // C takes its default
assert_eq!(s.prompt_text(), "INSERT First <10>:", "then A's Verify");
s.input(Input::Enter).unwrap(); // Verify keeps the value typed
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "10"), ("B", "two"), ("C", "3")]));
}
#[test]
fn attreq_0_gives_every_attribute_its_default() {
let mut s = session(Some(false), None);
insert_up_to_the_attributes(&mut s);
assert!(s.running.is_none(), "no attribute prompt: {}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "1"), ("B", "two"), ("C", "3")]));
// SETVAR changes it.
s.execute("setvar", &json!({ "name": "ATTREQ", "value": 1 })).unwrap();
s.execute("setvar", &json!({ "name": "ATTDIA", "value": 0 })).unwrap();
insert_up_to_the_attributes(&mut s);
assert_eq!(s.prompt_text(), "INSERT First <1>:");
}
#[test]
fn attdia_1_asks_for_every_value_at_once_and_typed_answers_still_work() {
let mut s = session(None, None);
s.execute("setvar", &json!({ "name": "ATTDIA", "value": 1 })).unwrap();
assert_eq!(s.execute("getvar", &json!({ "name": "ATTDIA" })).unwrap()["value"], 1);
s.start("insert").unwrap();
s.cmdline("T").unwrap();
assert!(s.attribute_entry().is_none(), "not before the attribute prompts");
s.input(Input::Point(Vec2::new(100.0, 0.0))).unwrap();
s.input(Input::Enter).unwrap();
s.input(Input::Enter).unwrap();
s.input(Input::Enter).unwrap();
let e = s.attribute_entry().expect("the dialog's rows");
assert_eq!(e.block, "T");
let ask =
|tag: &str, prompt: &str, default: &str, verify: bool| AttribAsk { tag: tag.into(), prompt: prompt.into(), default: default.into(), verify };
assert_eq!(e.rows, vec![ask("A", "First", "1", true), ask("C", "Third", "3", false)]);
// The dialog's OK: every value, then the Verify attribute's again.
let answers = e.answers(&["x".into(), String::new()]);
assert_eq!(answers, ["x", "", "x"]);
for a in answers {
s.input(Input::Text(a)).unwrap();
}
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "x"), ("B", "two"), ("C", "")]));
// Typed instead: the dialog goes away after the first answer.
insert_up_to_the_attributes(&mut s);
assert!(s.attribute_entry().is_some());
s.input(Input::Text("typed".into())).unwrap();
assert!(s.attribute_entry().is_none());
s.input(Input::Enter).unwrap(); // C takes its default
s.input(Input::Enter).unwrap(); // Verify keeps the value typed
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "typed"), ("B", "two"), ("C", "3")]));
// Cancel from the dialog inserts nothing.
let before = s.doc().unwrap().model.len();
insert_up_to_the_attributes(&mut s);
s.cancel();
assert!(s.running.is_none());
assert_eq!(s.doc().unwrap().model.len(), before);
}
#[test]
fn json_insert_never_asks_whatever_attreq_and_attdia_say() {
for (req, dia) in [(false, false), (true, true)] {
let mut s = session(Some(req), Some(dia));
let r = s.execute("insert", &json!({ "name": "T", "at": [0, 0], "attribs": { "a": "given", "B": "preset given" } })).unwrap();
assert!(r["handle"].is_string());
assert!(s.running.is_none() && s.attribute_entry().is_none());
assert_eq!(values(&s), pairs(&[("A", "given"), ("B", "preset given"), ("C", "3")]));
}
}
#[test]
fn hostile_values_never_panic() {
let mut s = session(None, Some(true));
insert_up_to_the_attributes(&mut s);
let e = s.attribute_entry().expect("asks");
// Too few answers take the defaults, too many are ignored.
assert_eq!(e.answers(&[]), ["1", "3", "1"]);
assert_eq!(e.answers(&["p".into(), "q".into(), "r".into()]), ["p", "q", "p"]);
s.cancel();
for bad in [json!(2), json!(-1), json!("x"), json!(null), json!(1.5)] {
assert!(s.execute("setvar", &json!({ "name": "ATTDIA", "value": bad })).is_err(), "{bad}");
assert!(s.execute("setvar", &json!({ "name": "ATTREQ", "value": bad })).is_err(), "{bad}");
}
assert!(s.settings.attdia && s.settings.attreq, "a refused value changes nothing");
// An INSERT of a block with only Preset and constant attributes asks nothing.
let mut d = cadcraft_engine::doc::Drawing::new_imperial();
let mut b = Block::new("P");
let h: Handle = d.new_handle();
b.entities.push(Entity::new(h, EntityKind::AttDef(def("P", "p", "v", 0.0, false, AttribModes { preset: true, ..AttribModes::default() }))));
d.blocks.insert("P".into(), Arc::new(b));
let mut s = Session::empty();
s.open_drawing(d, "preset", None);
s.script("-INSERT P 0,0 1 1 0\n").unwrap();
assert!(s.running.is_none() && s.attribute_entry().is_none());
assert_eq!(values(&s), pairs(&[("P", "v")]));
}
#[test]
fn a_script_never_asks_in_the_dialog() {
// A script cannot click a dialog: ATTDIA 1 keeps its prompts at the command line, even when
// the script ends with INSERT still waiting for the first attribute.
let mut s = session(None, Some(true));
s.script("-INSERT T 0,50 1 1 0\n").unwrap();
assert_eq!(s.prompt_text(), "INSERT First <1>:", "INSERT still waits after the script");
assert!(s.attribute_entry().is_none(), "a scripted INSERT never opens the dialog");
// The command the script started keeps answering at the command line.
s.input(Input::Text("a".into())).unwrap();
s.input(Input::Text("c".into())).unwrap();
s.input(Input::Text("a".into())).unwrap(); // A's Verify
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "a"), ("B", "two"), ("C", "c")]));
// A typed INSERT with ATTDIA 1 still asks in the dialog.
insert_up_to_the_attributes(&mut s);
assert!(s.attribute_entry().is_some(), "a typed INSERT asks in the dialog");
}
#[test]
fn a_lisp_insert_never_asks_in_the_dialog() {
// (command "-INSERT" …) runs INSERT outside Session::script: the routine cannot click a
// dialog, and it finishes before the first attribute answer.
let mut s = session(None, Some(true));
let r = s.execute("lisp", &json!({ "code": "(command \"-INSERT\" \"T\" \"0,50\" 1 1 0)" })).unwrap();
assert!(r.get("error").is_none(), "{r}");
assert_eq!(s.prompt_text(), "INSERT First <1>:", "INSERT waits at the command line");
assert!(s.attribute_entry().is_none(), "a LISP-started INSERT never opens the dialog");
// The command keeps answering at the command line after the routine ended.
s.input(Input::Text("a".into())).unwrap();
s.input(Input::Text("c".into())).unwrap();
s.input(Input::Text("a".into())).unwrap(); // A's Verify
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "a"), ("B", "two"), ("C", "c")]));
// A typed INSERT with ATTDIA 1 asks in the dialog again.
insert_up_to_the_attributes(&mut s);
assert!(s.attribute_entry().is_some(), "a typed INSERT asks in the dialog");
s.cancel();
// A LISP expression typed at the command line is the same program: no dialog.
s.cmdline("(command \"-INSERT\" \"T\" \"0,60\" 1 1 0)").unwrap();
assert_eq!(s.prompt_text(), "INSERT First <1>:");
assert!(s.attribute_entry().is_none(), "a typed (command …) never opens the dialog");
s.cancel();
}
/// A routine that types a command into a running LINE: `(command "LINE" "0,0" spelling …)`.
/// `extra` answers MINSERT's grid, and the arguments after it answer the attribute prompts.
fn lisp_token_replaces_line(spelling: &str, extra: &str) -> Session {
let mut s = session(None, Some(true));
let code = format!("(command \"LINE\" \"0,0\" \"{spelling}\" \"T\" \"0,50\" 1 1 0{extra})");
let r = s.execute("lisp", &json!({ "code": code })).unwrap();
assert!(r.get("error").is_none(), "{spelling}: {r}");
s
}
/// Answer the attribute prompts the routine's INSERT left waiting, as the person at the
/// command line would.
fn answer_the_routines_insert(s: &mut Session) {
s.input(Input::Text("a".into())).unwrap();
s.input(Input::Text("c".into())).unwrap();
s.input(Input::Text("a".into())).unwrap(); // A's Verify
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(s), pairs(&[("A", "a"), ("B", "two"), ("C", "c")]));
}
#[test]
fn a_lisp_insert_token_replacing_a_command_never_asks_in_the_dialog() {
// The token reaches the typed-input path while LINE runs, not the idle start: the INSERT
// that replaces LINE is still the routine's, so ATTDIA 1 opens no dialog nobody can click.
let mut s = lisp_token_replaces_line("'-INSERT", "");
assert_eq!(s.prompt_text(), "INSERT First <1>:", "asked at the command line");
assert!(s.attribute_entry().is_none(), "a LISP token never opens the dialog");
// The command keeps answering at the command line after the routine ended.
answer_the_routines_insert(&mut s);
}
#[test]
fn a_lisp_minsert_token_replacing_a_command_never_asks_in_the_dialog() {
let mut s = lisp_token_replaces_line("'MINSERT", " 1 1");
assert_eq!(s.prompt_text(), "MINSERT First <1>:", "asked at the command line");
assert!(s.attribute_entry().is_none(), "a LISP token never opens the dialog");
answer_the_routines_insert(&mut s);
}
#[test]
fn a_person_typing_a_transparent_insert_still_asks_in_the_dialog() {
// The tokens the routine feeds above, typed by a person: the INSERT that replaces LINE is
// theirs, so ATTDIA 1 asks in the dialog.
let mut s = session(None, Some(true));
s.cmdline("LINE 0,0 '-INSERT T 0,50 1 1 0").unwrap();
assert!(s.running.is_some(), "{}", s.prompt_text());
assert!(s.attribute_entry().is_some(), "a typed transparent INSERT asks in the dialog");
s.cancel();
}
/// A person typing `'NAME T …` while a routine waits in `(command "LINE" "0,0" pause)`
/// cancels it; the routine's `*error*` handler then starts a LINE of its own. The handler's
/// command is the program's, and it must not take the origin or number of the person's start.
/// `extra` answers MINSERT's rows and columns.
fn person_replaces_paused_lisp(spelling: &str, extra: &str) -> Session {
let mut s = session(None, Some(true));
s.cmdline("(defun *error* (msg) (command \"LINE\" \"1,1\" \"2,2\" \"\"))").unwrap();
s.cmdline("(command \"LINE\" \"0,0\" pause)").unwrap();
assert!(s.running.is_some(), "the routine's LINE waits for the person: {}", s.prompt_text());
// The person replaces the waiting routine with their own command.
s.cmdline(&format!("'{spelling} T 0,50 1 1 0{extra}")).unwrap();
assert!(s.running.is_some(), "{}", s.prompt_text());
// The handler's LINE is the only one drawn: the paused LINE was cancelled at its first
// point, and the handler's own command ran as the program's (nobody typed 1,1 or 2,2).
let lines: Vec<(Vec2, Vec2)> = s
.doc()
.unwrap()
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(l) => Some((l.a.xy(), l.b.xy())),
_ => None,
})
.collect();
assert_eq!(lines, vec![(Vec2::new(1.0, 1.0), Vec2::new(2.0, 2.0))], "the error handler's LINE is drawn, and the paused one added nothing");
s
}
#[test]
fn a_person_replacing_paused_lisp_keeps_their_insert_dialog() {
let s = person_replaces_paused_lisp("-INSERT", "");
assert_eq!(s.command_origin(), Origin::Person, "the person's INSERT is not the handler's command");
let e = s.attribute_entry().expect("ATTDIA 1: the person's INSERT asks in the dialog");
// The handler's LINE finished as a command of its own; the INSERT's answers belong to a
// later number, so the dialog a cancelled command left behind is not taken.
assert_eq!(s.last_finished.map(|(command, _)| command), Some(e.command.wrapping_sub(1)), "the handler's LINE keeps its own number");
}
#[test]
fn a_person_replacing_paused_lisp_keeps_their_minsert_dialog() {
let s = person_replaces_paused_lisp("MINSERT", " 1 1");
assert_eq!(s.command_origin(), Origin::Person, "the person's MINSERT is not the handler's command");
let e = s.attribute_entry().expect("ATTDIA 1: the person's MINSERT asks in the dialog");
assert_eq!(s.last_finished.map(|(command, _)| command), Some(e.command.wrapping_sub(1)), "the handler's LINE keeps its own number");
}
#[test]
fn an_entry_belongs_to_the_drawing_and_command_that_asked() {
let mut s = session(None, Some(true));
insert_up_to_the_attributes(&mut s);
let first = s.attribute_entry().expect("asks");
assert_eq!(first.drawing, s.state().unwrap().uid);
assert_eq!(first.command, s.commands_started);
// Asked again in a later frame: the same owner.
assert_eq!(s.attribute_entry().map(|e| (e.drawing, e.command)), Some((first.drawing, first.command)));
// Cancelled and started again: a new number, so the old dialog's draft is not taken.
s.cancel();
insert_up_to_the_attributes(&mut s);
let second = s.attribute_entry().expect("asks again");
assert_eq!(second.block, "T");
assert_ne!((second.drawing, second.command), (first.drawing, first.command));
// Another drawing's INSERT is another owner too.
let mut other = session(None, Some(true));
insert_up_to_the_attributes(&mut other);
let third = other.attribute_entry().expect("asks there");
assert_eq!(third.drawing, other.state().unwrap().uid);
assert_ne!(third.drawing, first.drawing);
}
#[test]
fn two_definitions_with_one_tag_are_both_asked_once() {
// INSERT counted its answers by tag: the second X was asked for ever.
let mut d = cadcraft_engine::doc::Drawing::new_imperial();
let mut b = Block::new("DUP");
for (prompt, y) in [("first", 0.0), ("second", 2.0)] {
let h = d.new_handle();
b.entities.push(Entity::new(h, EntityKind::AttDef(def("X", prompt, "d", y, false, AttribModes::default()))));
}
d.blocks.insert("DUP".into(), Arc::new(b));
let mut s = Session::empty();
s.open_drawing(d, "dup", None);
s.settings.attdia = false;
s.script("-INSERT DUP 0,0 1 1 0\na\nb\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s).len(), 2);
}
@@ -0,0 +1,44 @@
//! A dimension kept as read (LARGE_RADIAL_DIMENSION, ARC_DIMENSION) draws its `*D` block through
//! a reference in its graphics (#3438); object snaps reach the objects inside that block.
use cadcraft_engine::doc::Space;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::snap::{self, mode};
#[test]
fn a_kept_dimension_snaps_to_its_blocks_objects() {
// The block's base point isn't the origin; its line is where the dimension draws it.
let dxf = "0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n8\n0\n2\n*D1\n70\n1\n10\n100\n20\n50\n3\n*D1\n0\nLINE\n8\n0\n10\n110\n20\n60\n11\n120\n21\n70\n0\nENDBLK\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n0\nLARGE_RADIAL_DIMENSION\n5\n41\n100\nAcDbEntity\n8\n0\n100\nAcDbDimension\n2\n*D1\n0\nENDSEC\n0\nEOF\n";
let d = cadcraft_io::read_dxf(dxf.as_bytes()).expect("read");
let at = |p: Vec2, m: u32| snap::osnap(&d, &Space::Model, p + Vec2::new(0.02, -0.01), 0.1, m, None, false).map(|h| (h.point, h.mode));
let end = Vec2::new(120.0, 70.0);
assert!(at(end, mode::END).is_some_and(|(p, m)| m == mode::END && p.dist(end) < 1e-9), "{:?}", at(end, mode::END));
let mid = Vec2::new(115.0, 65.0);
assert!(at(mid, mode::MID).is_some_and(|(p, m)| m == mode::MID && p.dist(mid) < 1e-9), "{:?}", at(mid, mode::MID));
}
/// A DIMENSION inside a block snaps to the objects of its own `*D` block, as it is drawn; so does
/// one moved by an older AutoCAD (group 12), translated by the move as the renderer draws it.
#[test]
fn dimensions_in_blocks_snap_to_their_blocks_objects() {
let dim = |handle: &str, offset: (f64, f64)| {
format!(
"0\nDIMENSION\n5\n{handle}\n100\nAcDbEntity\n8\n0\n100\nAcDbDimension\n2\n*D2\n10\n5\n20\n7\n30\n0\n11\n5\n21\n8\n31\n0\n12\n{}\n22\n{}\n32\n0\n70\n1\n100\nAcDbAlignedDimension\n13\n0\n23\n7\n33\n0\n14\n10\n24\n7\n34\n0\n",
offset.0, offset.1
)
};
let dxf = format!(
"0\nSECTION\n2\nBLOCKS\n\
0\nBLOCK\n8\n0\n2\n*D2\n70\n1\n10\n0\n20\n0\n3\n*D2\n0\nLINE\n8\n0\n10\n0\n20\n7\n11\n10\n21\n7\n0\nENDBLK\n\
0\nBLOCK\n8\n0\n2\nNEST\n70\n0\n10\n0\n20\n0\n3\nNEST\n{}0\nENDBLK\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n0\nINSERT\n5\n70\n8\n0\n2\nNEST\n10\n100\n20\n0\n{}0\nENDSEC\n0\nEOF\n",
dim("60", (0.0, 0.0)),
dim("61", (0.0, 50.0)),
);
let d = cadcraft_io::read_dxf(dxf.as_bytes()).expect("read");
let at = |p: Vec2, m: u32| snap::osnap(&d, &Space::Model, p + Vec2::new(0.02, -0.01), 0.1, m, None, false).map(|h| (h.point, h.mode));
for (p, m) in [(Vec2::new(110.0, 7.0), mode::END), (Vec2::new(105.0, 7.0), mode::MID), (Vec2::new(10.0, 57.0), mode::END)] {
assert!(at(p, m).is_some_and(|(q, k)| k == m && q.dist(p) < 1e-9), "{p:?}: {:?}", at(p, m));
}
}
+7
View File
@@ -5,6 +5,7 @@ mod annotative;
mod arc_ctrl_direction;
mod array_commands;
mod array_key_point;
mod array_live;
mod assoc_array;
mod attdef_command;
mod attdisp_attsync;
@@ -57,6 +58,7 @@ mod dynamic_grips;
mod explode_stretched;
mod extend_polyline_arc_end;
mod extend_polyline_end_choice;
mod extrim;
mod fillet_chamfer;
mod fix_holds_grips;
mod followups_626;
@@ -76,12 +78,14 @@ mod hidden_grip_targets;
mod inquiry_keywords;
mod inquiry_variables;
mod inquiry_z;
mod insert_attrib_entry;
mod insert_attribute_prompts;
mod insert_enter;
mod insert_prompts;
mod isometric;
mod join_close;
mod json_param_validation;
mod kept_dimension_snaps;
mod layer_cmdline;
mod layer_merge_delete;
mod layer_state_cmdline;
@@ -134,6 +138,7 @@ mod properties_set_locked;
mod properties_set_text_dims;
mod props_bad_lineweight;
mod props_insert_scale_attribs;
mod purge_kept_dimension_blocks;
mod purge_mlinestyles;
mod purge_prompts;
mod qdim;
@@ -147,6 +152,7 @@ mod refedit;
mod region;
mod rename_cmdline;
mod rotate_reference;
mod rotation_grip_input;
mod scale_offset_z;
mod select_keywords;
mod select_similar;
@@ -182,6 +188,7 @@ mod trim_cut_at_the_pick;
mod trim_cut_where_an_arc_span_starts;
mod trim_extend_json_pick;
mod trim_extend_options;
mod trim_highlight;
mod trim_keeps_z_and_width;
mod undo_count;
mod undo_layout_tab;
@@ -0,0 +1,31 @@
//! PURGE keeps the `*D` block a dimension kept as read names (LARGE_RADIAL_DIMENSION,
//! ARC_DIMENSION): the dimension draws it, and AutoCAD needs it to read the file (#3438, #1161).
use std::sync::Arc;
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Block, Common, Entity, EntityKind, Handle, Line, RawTag, Space, Unknown};
use cadcraft_engine::geom::Vec3;
use serde_json::json;
#[test]
fn purge_keeps_the_block_a_kept_dimension_names() {
let mut s = Session::new();
let d = s.doc_mut().unwrap();
for name in ["*D1", "*D2"] {
let mut b = Block::new(name);
b.entities.push(Entity::new(Handle(0x9000), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 1.0, 0.0) })));
d.blocks.insert(name.into(), Arc::new(b));
}
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let dim = Unknown {
dxf_type: "ARC_DIMENSION".into(),
tags: vec![tag(100, "AcDbEntity"), tag(8, "0"), tag(100, "AcDbDimension"), tag(2, "*D1"), tag(100, "AcDbArcDimension")],
graphics: Vec::new(),
};
d.add(&Space::Model, Common::default(), EntityKind::Unknown(dim)).unwrap();
s.execute("purge", &json!({})).unwrap();
let d = s.doc().unwrap();
assert!(d.block("*D1").is_some(), "the kept dimension's block stays");
assert!(d.block("*D2").is_none(), "an unused one goes");
}
@@ -0,0 +1,44 @@
//! The rotation grip of a dynamic block asks for an angle: Dynamic Input shows one angle box,
//! holding the angle the cursor would give as Properties will show it. The drawing is the
//! synthetic Symbol block of the io tests (Angle1 about its base, its grip at the radius' end).
use cadcraft_engine::Session;
use cadcraft_engine::doc::Handle;
use cadcraft_engine::doc::dynblock::GripPart;
use cadcraft_engine::geom::Vec2;
use serde_json::json;
fn dxf(src: &str) -> String {
src.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.map(|l| {
let (code, value) = l.split_once(' ').unwrap_or((l, ""));
format!("{code}\n{value}\n")
})
.collect()
}
/// A session with Symbol and a reference to it at (100, 100).
fn session() -> (Session, Handle) {
let src = include_str!("../../../io/tests/data/dynblock_symbol.txt").replace("\r\n", "\n");
let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap();
let mut s = Session::empty();
s.open_drawing(d, "symbol", None);
let r = s.execute("insert", &json!({ "name": "Symbol", "at": [100, 100] })).unwrap();
(s, Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap())
}
#[test]
fn the_rotation_grip_asks_for_an_angle_and_shows_it_live() {
let (mut s, h) = session();
s.start_dyn_grip(h, 15, GripPart::End).unwrap();
assert!(s.current_prompt().is_some_and(|p| p.angle), "{:?}", s.current_prompt());
// The grip is at (102, 100); straight above the base is a quarter turn.
assert_eq!(s.live_value(Vec2::new(100.0, 102.0)).as_deref(), Some("90°"));
assert_eq!(s.live_value(Vec2::new(98.0, 100.0)).as_deref(), Some("180°"));
// Nothing is changed by looking.
let props = s.execute("blocks.reference", &json!({ "handle": h.hex() })).unwrap();
let angle = props["properties"].as_array().unwrap().iter().find(|p| p["name"] == "Angle1").unwrap()["value"].clone();
assert_eq!(angle, json!("0"));
}
+16
View File
@@ -30,3 +30,19 @@ fn programmatic_spline_control_count_is_limited() {
s.execute("spline", &json!({ "control": control(20_000) })).unwrap();
assert_eq!(s.doc().unwrap().model.len(), 1);
}
#[test]
fn cv_degree_prompt_retries_a_fractional_degree() {
for command in ["spline.cv d", "spline m cv d"] {
let mut s = Session::new();
s.cmdline(command).unwrap();
let degree_prompt = s.current_prompt().unwrap();
assert!(degree_prompt.accept.number);
s.cmdline("2.5").unwrap();
assert_eq!(s.current_prompt().unwrap().message, degree_prompt.message, "{command}");
s.cmdline("2 0,0 1,1 2,0 3,1").unwrap();
s.input(cadcraft_engine::Input::Enter).unwrap();
let d = s.doc().unwrap();
assert!(matches!(&d.model.iter().last().unwrap().kind, EntityKind::Spline(sp) if sp.degree == 2));
}
}
+34
View File
@@ -171,3 +171,37 @@ fn json_form_takes_the_fit_options() {
assert_eq!(sp.fit_opts.start_tangent, None);
assert_eq!(sp.fit_opts.end_tangent, Some(-Vec2::Y));
}
#[test]
fn cv_method_keeps_cv_on_enter_and_can_switch_back_to_fit() {
for entry in ["spline.cv", "spline m cv"] {
let mut s = Session::new();
s.cmdline(&format!("{entry} d 2 m")).unwrap();
s.cmdline("").unwrap();
s.cmdline("m fit 0,0 1,2 3,1").unwrap();
s.cmdline("").unwrap();
assert_eq!(last_spline(&s).fit.len(), 3, "{entry}");
s.cmdline(&format!("{entry} d 2 m")).unwrap();
s.cmdline("").unwrap();
s.cmdline("0,0 1,2 3,1 4,0").unwrap();
s.cmdline("").unwrap();
let cv = last_spline(&s);
assert!(cv.fit.is_empty() && cv.degree == 2, "{entry}");
}
}
#[test]
fn cv_object_converts_the_picked_polyline() {
for entry in ["spline.cv", "spline m cv"] {
let mut s = Session::new();
s.execute("pline", &json!({"vertices":[[0,0],[1,2],[3,1]]})).unwrap();
let h = s.doc().unwrap().model.iter().next().unwrap().handle;
s.cmdline(&format!("{entry} o")).unwrap();
assert!(s.current_prompt().unwrap().picks_objects(), "{entry}");
s.input(cadcraft_engine::Input::Pick(vec![h])).unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none() && s.doc().unwrap().model.len() == 1);
assert_eq!(last_spline(&s).fit.len(), 3);
}
}
+312
View File
@@ -0,0 +1,312 @@
//! #1118: at TRIM's and EXTEND's "Select object" prompt the rollover highlight shows what a click
//! there changes (the piece a trim removes, the stretch an extend adds), worked out by the same
//! code as the click itself, and leaves the drawing alone.
use cadcraft_engine::doc::{Entity, EntityKind, Handle};
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::{Input, Session};
use serde_json::json;
/// The object a command made: its `handle`, or the first of its `handles`.
fn h(v: &serde_json::Value) -> Handle {
let hex = v["handle"].as_str().or_else(|| v["handles"][0].as_str()).unwrap_or_else(|| panic!("{v}"));
Handle::parse_hex(hex).unwrap()
}
fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle {
h(&s.execute("line", &json!({ "points": [a, b] })).unwrap())
}
/// The outlines of `ents`, flattened finely.
fn outline(s: &Session, ents: &[Entity]) -> Vec<Vec<Vec2>> {
let d = s.doc().unwrap();
ents.iter().flat_map(|e| cadcraft_engine::select::hit_polylines(d, e, 1e-4)).collect()
}
fn length(pls: &[Vec<Vec2>]) -> f64 {
pls.iter().flat_map(|pl| pl.windows(2).map(|w| w[0].dist(w[1]))).sum()
}
/// The highlighted part, as outlines: `None` when the whole object is highlighted.
fn highlight(s: &Session, h: Handle, at: [f64; 2]) -> Option<Vec<Vec<Vec2>>> {
let ents = s.highlight(h, Vec2::new(at[0], at[1]))?;
Some(outline(s, &ents))
}
/// The highlighted part, as the ends of each stretch rounded to 1e-6.
fn ends(s: &Session, h: Handle, at: [f64; 2]) -> Option<Vec<[[i64; 2]; 2]>> {
let r = |p: Vec2| [(p.x * 1e6).round() as i64, (p.y * 1e6).round() as i64];
let mut v: Vec<[[i64; 2]; 2]> = highlight(s, h, at)?
.iter()
.map(|pl| {
let (a, b) = (r(pl[0]), r(*pl.last().unwrap()));
if a <= b { [a, b] } else { [b, a] }
})
.collect();
v.sort();
Some(v)
}
fn seg(a: [f64; 2], b: [f64; 2]) -> [[i64; 2]; 2] {
let r = |p: [f64; 2]| [(p[0] * 1e6).round() as i64, (p[1] * 1e6).round() as i64];
let (a, b) = (r(a), r(b));
if a <= b { [a, b] } else { [b, a] }
}
/// Two vertical edges at x = 0 and x = 10 and a horizontal line across both, from -5 to 15.
fn ladder() -> (Session, Handle) {
let mut s = Session::new();
line(&mut s, [0.0, -5.0], [0.0, 5.0]);
line(&mut s, [10.0, -5.0], [10.0, 5.0]);
let l = line(&mut s, [-5.0, 0.0], [15.0, 0.0]);
s.zoom_extents().unwrap();
(s, l)
}
#[test]
fn trim_highlights_only_the_piece_a_click_there_removes() {
let (mut s, l) = ladder();
s.start("trim").unwrap();
assert_eq!(ends(&s, l, [5.0, 0.0]), Some(vec![seg([0.0, 0.0], [10.0, 0.0])]), "between the edges");
assert_eq!(ends(&s, l, [-3.0, 0.0]), Some(vec![seg([-5.0, 0.0], [0.0, 0.0])]), "past the first edge");
assert_eq!(ends(&s, l, [12.0, 0.0]), Some(vec![seg([10.0, 0.0], [15.0, 0.0])]), "past the second edge");
}
#[test]
fn the_highlight_leaves_the_drawing_and_its_undo_alone() {
let (mut s, l) = ladder();
s.start("trim").unwrap();
let before = s.state().unwrap().doc.clone();
for x in [-3.0, 5.0, 12.0, 5.0] {
assert!(highlight(&s, l, [x, 0.0]).is_some());
}
assert!(std::sync::Arc::ptr_eq(&before, &s.state().unwrap().doc), "the drawing is the same object");
s.input(Input::Enter).unwrap();
s.execute("undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().model.iter().count(), 2, "the one undo step is the last line drawn");
}
#[test]
fn quick_mode_highlights_the_whole_object_no_edge_crosses() {
let (mut s, _) = ladder();
let lone = line(&mut s, [20.0, 20.0], [25.0, 20.0]);
s.start("trim").unwrap();
assert_eq!(ends(&s, lone, [22.0, 20.0]), Some(vec![seg([20.0, 20.0], [25.0, 20.0])]), "a click erases it");
}
#[test]
fn a_click_removes_exactly_what_was_highlighted() {
// Each kind of object crossed twice by the vertical lines x = -1 and x = 1.
let shapes: Vec<(&str, serde_json::Value)> = vec![
("line", json!({ "points": [[-5, 0.5], [5, 0.5]] })),
("arc", json!({ "center": [0, -3], "radius": 4, "start": 20, "end": 160 })),
("circle", json!({ "center": [0, 0], "radius": 3 })),
("pline", json!({ "points": [[-5, 0], [-2, 2], [2, 2], [5, 0]] })),
("pline", json!({ "points": [[-4, -2], [4, -2], [4, 2], [-4, 2]], "closed": true })),
("ellipse", json!({ "center": [0, 0], "major": [4, 0], "ratio": 0.5 })),
("spline", json!({ "control": [[-5, 0], [-2, 3], [2, -3], [5, 0]] })),
];
for (cmd, p) in shapes {
let mut s = Session::new();
line(&mut s, [-1.0, -10.0], [-1.0, 10.0]);
line(&mut s, [1.0, -10.0], [1.0, 10.0]);
let o = h(&s.execute(cmd, &p).unwrap());
s.zoom_extents().unwrap();
let whole = length(&outline(&s, &[(**s.doc().unwrap().entity(o).unwrap()).clone()]));
// A point on the object between the two edges.
let on = cadcraft_engine::select::hit_polylines(s.doc().unwrap(), s.doc().unwrap().entity(o).unwrap(), 1e-4)
.iter()
.flat_map(|pl| pl.windows(2).map(|w| (w[0], w[1])).collect::<Vec<_>>())
.find(|(a, b)| a.x * b.x <= 0.0 && a.x != b.x)
.map(|(a, b)| a + (b - a) * (-a.x / (b.x - a.x)))
.unwrap_or_else(|| panic!("{cmd}: it doesn't cross x = 0"));
s.start("trim").unwrap();
let shown = length(&highlight(&s, o, [on.x, on.y]).unwrap_or_else(|| panic!("{cmd}: no part highlighted")));
let total = |s: &Session| length(&outline(s, &s.doc().unwrap().model.iter().map(|e| (**e).clone()).collect::<Vec<_>>()));
let before = total(&s);
s.input(Input::Point(on)).unwrap();
let removed = before - total(&s);
assert!(removed > 1e-3, "{cmd}: the click trimmed nothing");
assert!((shown - removed).abs() < 2e-3 * whole, "{cmd}: highlighted {shown}, removed {removed}");
}
}
#[test]
fn extend_highlights_only_the_stretch_it_adds() {
let mut s = Session::new();
line(&mut s, [10.0, -5.0], [10.0, 5.0]);
let l = line(&mut s, [0.0, 0.0], [4.0, 0.0]);
s.zoom_extents().unwrap();
s.start("extend").unwrap();
assert_eq!(ends(&s, l, [3.0, 0.0]), Some(vec![seg([4.0, 0.0], [10.0, 0.0])]));
s.input(Input::Point(Vec2::new(3.0, 0.0))).unwrap();
let EntityKind::Line(x) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!() };
assert_eq!((x.b.x, x.b.y), (10.0, 0.0), "the click extends it as shown");
}
#[test]
fn the_whole_object_is_highlighted_where_a_click_does_nothing_special() {
let (mut s, l) = ladder();
// No command: the ordinary rollover highlight.
assert!(s.highlight(l, Vec2::new(5.0, 0.0)).is_none());
// At another of TRIM's prompts.
s.start("trim").unwrap();
s.input(Input::Keyword("Fence".into())).unwrap();
assert!(s.highlight(l, Vec2::new(5.0, 0.0)).is_none());
s.cancel();
// On a locked layer, which TRIM refuses.
s.execute("layer.set", &json!({ "name": "0", "locked": true })).unwrap();
s.start("trim").unwrap();
let k = l;
assert!(s.highlight(k, Vec2::new(5.0, 0.0)).is_none());
}
#[test]
fn the_edges_are_gathered_again_once_the_drawing_changes() {
let (mut s, l) = ladder();
s.start("trim").unwrap();
assert_eq!(ends(&s, l, [5.0, 0.0]), Some(vec![seg([0.0, 0.0], [10.0, 0.0])]));
// Trimming the right edge's lower half away leaves the line crossed by the left edge only.
let right = s.doc().unwrap().model.iter().find(|e| matches!(&e.kind, EntityKind::Line(x) if x.a.x == 10.0)).unwrap().handle;
s.input(Input::Point(Vec2::new(10.0, -3.0))).unwrap();
let still = matches!(&s.doc().unwrap().entity(right).unwrap().kind, EntityKind::Line(x) if x.a.y.min(x.b.y) >= 0.0);
assert!(still, "the right edge now starts on the line");
assert_eq!(ends(&s, l, [12.0, 0.0]), Some(vec![seg([10.0, 0.0], [15.0, 0.0])]), "it still meets the line at its end");
assert_eq!(ends(&s, l, [-3.0, 0.0]), Some(vec![seg([-5.0, 0.0], [0.0, 0.0])]));
}
/// The highlight while a fence or a crossing window is drawn, as outlines.
fn highlight_all(s: &Session, at: [f64; 2]) -> Option<Vec<Vec<Vec2>>> {
let ents = s.highlight_all(Vec2::new(at[0], at[1]))?;
Some(outline(s, &ents))
}
/// The total length of every object's outline.
fn drawn(s: &Session) -> f64 {
length(&outline(s, &s.doc().unwrap().model.iter().map(|e| (**e).clone()).collect::<Vec<_>>()))
}
#[test]
fn a_fence_highlights_every_piece_it_will_remove() {
let (mut s, _) = ladder();
let upper = line(&mut s, [-5.0, 2.0], [15.0, 2.0]);
s.start("trim").unwrap();
s.input(Input::Keyword("Fence".into())).unwrap();
assert!(s.highlight_all(Vec2::new(5.0, 3.0)).is_none(), "nothing before the fence's first point");
s.input(Input::Point(Vec2::new(5.0, -3.0))).unwrap();
let before = s.state().unwrap().doc.clone();
let shown = highlight_all(&s, [5.0, 3.0]).unwrap();
let mut spans: Vec<[[i64; 2]; 2]> = shown
.iter()
.map(|pl| {
let r = |p: Vec2| [(p.x * 1e6).round() as i64, (p.y * 1e6).round() as i64];
let (a, b) = (r(pl[0]), r(*pl.last().unwrap()));
if a <= b { [a, b] } else { [b, a] }
})
.collect();
spans.sort();
assert_eq!(spans, vec![seg([0.0, 0.0], [10.0, 0.0]), seg([0.0, 2.0], [10.0, 2.0])], "both lines between the edges");
assert!(std::sync::Arc::ptr_eq(&before, &s.state().unwrap().doc), "the drawing is left alone");
// Short of the upper line, only the lower one.
assert_eq!(highlight_all(&s, [5.0, 1.0]).unwrap().len(), 1);
assert!(s.highlight(upper, Vec2::new(5.0, 2.0)).is_none(), "no single-object highlight while fencing");
}
#[test]
fn a_fence_removes_exactly_what_it_highlighted() {
// A grid of lines and a circle, with a fence through several of them: some of what it trims
// is an edge of what it trims next, so the preview must follow the run trim by trim.
let mut s = Session::new();
for x in [0.0, 10.0, 20.0] {
line(&mut s, [x, -10.0], [x, 10.0]);
}
for y in [0.0, 5.0] {
line(&mut s, [-5.0, y], [25.0, y]);
}
s.execute("circle", &json!({ "center": [10, 2.5], "radius": 4 })).unwrap();
s.zoom_extents().unwrap();
let fence = [[3.0, -4.0], [12.0, 3.0], [17.0, 8.0]];
s.start("trim").unwrap();
s.input(Input::Keyword("Fence".into())).unwrap();
for p in &fence[..2] {
s.input(Input::Point(Vec2::new(p[0], p[1]))).unwrap();
}
let shown = length(&highlight_all(&s, fence[2]).unwrap());
let before = drawn(&s);
s.input(Input::Point(Vec2::new(fence[2][0], fence[2][1]))).unwrap();
s.input(Input::Enter).unwrap();
let removed = before - drawn(&s);
assert!(removed > 1.0, "the fence trimmed something");
assert!((shown - removed).abs() < 1e-3 * before, "highlighted {shown}, removed {removed}");
}
#[test]
fn a_quick_fence_and_a_crossing_window_are_previewed_too() {
// Quick mode: a pick in empty space starts a two-point fence.
let (mut s, _) = ladder();
s.start("trim").unwrap();
s.input(Input::Point(Vec2::new(5.0, -3.0))).unwrap();
let shown = highlight_all(&s, [5.0, 3.0]).expect("the two-point fence is previewed");
assert!((length(&shown) - 10.0).abs() < 1e-6, "{}", length(&shown));
s.cancel();
// A crossing window round the middle of the line.
s.start("trim").unwrap();
s.input(Input::Keyword("Crossing".into())).unwrap();
s.input(Input::Point(Vec2::new(4.0, -1.0))).unwrap();
let shown = highlight_all(&s, [6.0, 1.0]).expect("the window is previewed");
assert!((length(&shown) - 10.0).abs() < 1e-6, "{}", length(&shown));
}
#[test]
fn an_extend_fence_highlights_the_stretches_it_adds() {
let mut s = Session::new();
line(&mut s, [10.0, -5.0], [10.0, 5.0]);
line(&mut s, [0.0, 0.0], [4.0, 0.0]);
line(&mut s, [0.0, 2.0], [6.0, 2.0]);
s.zoom_extents().unwrap();
s.start("extend").unwrap();
s.input(Input::Keyword("Fence".into())).unwrap();
s.input(Input::Point(Vec2::new(4.0, -1.0))).unwrap();
let shown = length(&highlight_all(&s, [4.0, 3.0]).unwrap());
assert!((shown - (6.0 + 4.0)).abs() < 1e-6, "both lines run on to x = 10: {shown}");
// And the fence extends them by just that.
let before = drawn(&s);
s.input(Input::Point(Vec2::new(4.0, 3.0))).unwrap();
s.input(Input::Enter).unwrap();
assert!((drawn(&s) - before - shown).abs() < 1e-6);
}
#[test]
fn a_fence_across_more_objects_than_the_preview_cap_shows_no_part() {
use cadcraft_engine::cmd::TRIM_PREVIEW_MAX_PICKS as CAP;
// Rungs crossed by one fence, between two rails that cut them. Each rung is one pick.
let mut s = Session::new();
line(&mut s, [0.0, 0.0], [0.0, 100.0]);
line(&mut s, [10.0, 0.0], [10.0, 100.0]);
let rung = |s: &mut Session, i: usize| {
let y = 1.0 + i as f64;
line(s, [-5.0, y], [15.0, y]);
};
for i in 0..CAP {
rung(&mut s, i);
}
s.zoom_extents().unwrap();
let fence = |s: &mut Session| {
s.start("trim").unwrap();
s.input(Input::Keyword("Fence".into())).unwrap();
s.input(Input::Point(Vec2::new(5.0, 0.5))).unwrap();
};
// The fence runs up between the rails, crossing every rung: CAP picks, the most the preview takes.
fence(&mut s);
let shown = highlight_all(&s, [5.5, 99.0]).expect("up to the cap, the fence is previewed");
assert!((length(&shown) - CAP as f64 * 10.0).abs() < 1e-6, "{}", length(&shown));
s.cancel();
// One more rung: past the cap there is no part highlight, and the fence still trims them all.
rung(&mut s, CAP);
fence(&mut s);
assert!(s.highlight_all(Vec2::new(5.5, 99.0)).is_none(), "past the cap nothing is previewed");
let before = drawn(&s);
s.input(Input::Point(Vec2::new(5.5, 99.0))).unwrap();
s.input(Input::Enter).unwrap();
assert!((before - drawn(&s) - (CAP + 1) as f64 * 10.0).abs() < 1e-6, "every rung lost its middle");
}
@@ -0,0 +1,135 @@
//! MIRROR retains a hatch pattern's direction by default, while reflecting its boundary.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{EntityKind, Handle, Hatch};
use cadcraft_engine::geom::Vec2;
use serde_json::{Value, json};
/// Create a rectangular hatch with an oblique pattern direction for reflection checks.
fn fixture() -> (Session, Handle) {
fixture_with(json!({"pattern": "ANSI31", "angle": 30}))
}
/// Create a nonassociative rectangular hatch with the supplied synthetic fill parameters.
fn fixture_with(mut params: Value) -> (Session, Handle) {
let mut s = Session::new();
let outline = s.execute("rectang", &json!({"p1": [2, 1], "p2": [8, 4]})).unwrap()["handle"].clone();
params["handles"] = json!([outline]);
params["associative"] = json!(false);
let result = s.execute("hatch", &params).unwrap();
let h = result["handles"][0].as_str().unwrap();
let h = Handle::parse_hex(h).unwrap();
(s, h)
}
/// Clone the asserted hatch so its geometry and fill can be compared across edits.
fn hatch(s: &Session, h: Handle) -> Hatch {
match &s.doc().unwrap().entity(h).unwrap().kind {
EntityKind::Hatch(h) => h.clone(),
_ => panic!("expected hatch"),
}
}
/// A diagonal mirror reflects the boundary while retaining the fill direction through DXF readback.
#[test]
fn diagonal_mirror_keeps_pattern_direction_and_reflects_boundary() {
let (mut s, source) = fixture();
let before = hatch(&s, source);
let result = s.execute("mirror", &json!({"handles": [source.hex()], "p1": [0, 0], "p2": [10, 10]})).unwrap();
let mirrored = Handle::parse_hex(result["handles"][0].as_str().unwrap()).unwrap();
let after = hatch(&s, mirrored);
assert!((after.angle - before.angle).abs() < 1e-12, "pattern turned from {} to {} degrees", before.angle.to_degrees(), after.angle.to_degrees());
for (a, b) in before.loops[0].vertices.iter().zip(&after.loops[0].vertices) {
assert!((a.p.x - b.p.y).abs() < 1e-12);
assert!((a.p.y - b.p.x).abs() < 1e-12);
}
assert_eq!(hatch(&s, source), before, "retained source is unchanged");
let saved = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap();
let EntityKind::Hatch(saved) = &saved.entity(mirrored).unwrap().kind else { panic!("hatch lost on save") };
assert!((saved.angle - before.angle).abs() < 1e-12);
}
/// Typed MIRROR previews and committed geometry agree, including undo and redo.
#[test]
fn typed_mirror_previews_match_the_result_and_undo_redo() {
let (mut s, h) = fixture();
let before = hatch(&s, h);
s.set_selection(vec![h]);
s.cmdline("MIRROR 0,0").unwrap();
let cursor = Vec2::new(10., 10.);
let previews = s.preview(cursor);
let preview = previews
.iter()
.find_map(|e| match &e.kind {
EntityKind::Hatch(h) => Some(h),
_ => None,
})
.unwrap();
assert_eq!(preview.angle, before.angle);
let (drag, _) = s.drag(cursor).unwrap();
assert!(!drag.handles.contains(&h), "GPU reflection would turn the hatch pattern");
let drag_hatch = drag
.extra
.iter()
.find_map(|k| match k {
EntityKind::Hatch(h) => Some(h),
_ => None,
})
.unwrap();
assert_eq!(drag_hatch, preview);
s.cmdline("10,10").unwrap();
s.cmdline("Y").unwrap();
assert!(s.running.is_none());
let after = hatch(&s, h);
assert_eq!(&after, preview);
s.execute("undo", &json!({})).unwrap();
assert_eq!(hatch(&s, h), before);
s.execute("redo", &json!({})).unwrap();
assert_eq!(hatch(&s, h), after);
}
/// Patterned and gradient fills keep their definitions when the mirrored result replaces its source.
#[test]
fn another_pattern_and_gradient_directions_are_retained() {
for gradient in [false, true] {
let (mut s, h) = fixture();
if gradient {
s.execute("hatchedit", &json!({"handles": [h.hex()], "gradient": {"name": "LINEAR", "angle": 20}})).unwrap();
} else {
s.execute("hatchedit", &json!({"handles": [h.hex()], "pattern": "ANSI32"})).unwrap();
}
let before = hatch(&s, h);
s.execute("mirror", &json!({"handles": [h.hex()], "p1": [1, 2], "p2": [5, -1], "erase": true})).unwrap();
let after = hatch(&s, h);
assert_eq!(after.angle, before.angle);
assert_eq!(after.pattern, before.pattern);
assert_eq!(after.pattern_lines, before.pattern_lines);
assert_eq!(after.gradient, before.gradient);
}
}
/// Original asymmetric pattern families retain their line definitions under reflection.
#[test]
fn custom_pattern_line_families_are_not_reflected() {
let (mut s, h) = fixture_with(json!({
"pattern": "ORIGINAL", "angle": 30,
"patternText": "*ORIGINAL,Original asymmetric regression pattern\n17,0.2,0.4,0.3,0.8,0.5,-0.2\n67,0.1,0.3,0.2,0.9,0.1,-0.4\n"
}));
let before = hatch(&s, h);
assert_eq!(before.pattern_lines.len(), 2);
s.execute("mirror", &json!({"handles": [h.hex()], "p1": [0, 0], "p2": [10, 10], "erase": true})).unwrap();
let after = hatch(&s, h);
assert_eq!(after.angle, before.angle);
assert_eq!(after.pattern_lines, before.pattern_lines);
}
/// Solid hatches remain eligible for the shared GPU reflection preview.
#[test]
fn solid_fills_can_still_use_the_gpu_preview() {
let (mut s, h) = fixture_with(json!({"pattern": "SOLID"}));
s.set_selection(vec![h]);
s.cmdline("MIRROR 0,0").unwrap();
let (drag, _) = s.drag(Vec2::new(10., 10.)).unwrap();
assert!(drag.handles.contains(&h));
assert!(!drag.extra.iter().any(|k| matches!(k, EntityKind::Hatch(_))));
}
+2 -1
View File
@@ -17,7 +17,8 @@ fn read_file_refuses_a_name_that_is_not_unicode() {
let good = dir.join("good.dxf");
let bad = dir.join(OsString::from_vec(b"bad-\xff.dxf".to_vec()));
std::fs::write(&good, b"0\nEOF\n").unwrap();
std::fs::write(&bad, b"0\nEOF\n").unwrap();
// Validation precedes filesystem access; macOS filesystems may reject this name.
assert!(!bad.exists());
let e = read_file(&bad).err().expect("a non-Unicode name is refused");
assert!(e.contains("not valid Unicode") && e.contains("bad-"), "{e}");
assert!(read_file(&good).is_ok());
+6 -5
View File
@@ -3,10 +3,10 @@
//! empty, `CRAFT_FONTS` is empty and the build is unchanged. It only reads the local checkout
//! (no network). A bad checkout is a warning, or an error with `CRAFT_FONTS_REQUIRED=1`.
//!
//! On wasm32 it embeds only `BIZ UDPGothic` Regular, the `Arab` and `Geor` faces and the `Thai`
//! Regular faces (about 6.1 MB), to keep the web build within hosting limits (Cloudflare Pages:
//! 25 MiB per file). The web build has no system fonts, so these are its only fallback for
//! Japanese, Arabic-script, Georgian and Thai text.
//! On wasm32 it embeds only `BIZ UDPGothic` Regular, the `Arab`, `Geor` and `Taml` faces and the
//! `Thai` Regular faces (about 6.4 MB), to keep the web build within hosting limits (Cloudflare
//! Pages: 25 MiB per file). The web build has no system fonts, so these are its only fallback for
//! Japanese, Arabic-script, Georgian, Tamil and Thai text.
use std::fmt::Write as _;
use std::path::PathBuf;
@@ -59,7 +59,8 @@ fn craft_fonts(dir: &std::path::Path) -> Result<String, String> {
continue;
}
let has = |script: &str| scripts.split(',').any(|s| s.trim() == script);
let web_face = (*family == "BIZ UDPGothic" && *style == "Regular") || has("Arab") || has("Geor") || (has("Thai") && *style == "Regular");
let web_face =
(*family == "BIZ UDPGothic" && *style == "Regular") || has("Arab") || has("Geor") || has("Taml") || (has("Thai") && *style == "Regular");
if wasm && !web_face {
continue;
}
+124 -27
View File
@@ -134,10 +134,10 @@ fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64
*point += Vec2::new(offset_y * shear, offset_y);
}
let origin = Vec2::new(pen_x + glyph.dx * glyph_scale + offset_y * shear, offset_y);
let text = shows.get(n).copied().flatten().filter(|character| !character.is_whitespace()).and_then(|character| {
ttf::text_glyph_at(&outline, character, origin, normalized_height / outline.cap, scale_x, shear)
let texts = shows.get(n).into_iter().flatten().filter(|character| !character.is_whitespace()).filter_map(|character| {
ttf::text_glyph_at(&outline, *character, origin, normalized_height / outline.cap, scale_x, shear)
});
shaped.push_glyph(contours, text);
shaped.push_glyph(contours, texts);
}
let advance = glyph.advance * glyph_scale;
let (underline, overline) = flags(glyph.cluster);
@@ -249,46 +249,99 @@ fn shape_run(face: &Face, cs: &[char], r: Range<usize>, rtl: bool) -> Vec<Glyph>
/// longer one (a hostile run of thousands of stacked marks) take its characters in order.
const MAX_MATCHED_CLUSTER: usize = 32;
/// The character each glyph of a left-to-right run shows, for output that keeps text as text
/// The characters each glyph of a left-to-right run shows, for output that keeps text as text
/// ([`crate::TextGlyph`]). The shaper reorders, splits and substitutes glyphs inside a cluster
/// (a letter with its marks), so within each cluster a glyph that is a character's own glyph
/// takes that character first, then the other glyphs take the cluster's remaining characters in
/// order. Each character is shown once: a glyph left over (the second half of a split Thai sara
/// am) shows none and is drawn as an outline only.
fn glyph_chars(face: &Face, cs: &[char], glyphs: &[Glyph], end: usize) -> Vec<Option<char>> {
let mut out: Vec<Option<char>> = vec![None; glyphs.len()];
/// order, and characters left over (a ligature such as ฐ with sara u below) are shown by the
/// glyph before them. Each character is shown once, and the glyphs show the characters in typed
/// order wherever that leaves no fewer glyphs showing one, so text read back in drawing order is
/// the typed text: a split Thai sara am is drawn as nikhahit, then any tone mark, then sara aa,
/// so in น้ำ the sara aa shows ำ and the nikhahit, moved before the tone mark, shows none and is
/// drawn as an outline only.
fn glyph_chars(face: &Face, cs: &[char], glyphs: &[Glyph], end: usize) -> Vec<Vec<char>> {
let mut out: Vec<Vec<char>> = vec![Vec::new(); glyphs.len()];
let mut i = 0;
while let Some(cluster) = glyphs.get(i).map(|g| g.cluster) {
let j = glyphs.iter().skip(i).position(|g| g.cluster != cluster).map_or(glyphs.len(), |n| i + n);
// Clusters ascend in a left-to-right run: this one's characters end where the next starts.
let to = glyphs.get(j).map_or(end, |g| g.cluster).clamp(cluster, end.max(cluster));
let chars = cs.get(cluster..to).unwrap_or_default();
let mut free: Vec<Option<char>> = chars.iter().copied().map(Some).collect();
if chars.len() <= MAX_MATCHED_CLUSTER {
let ids = face.glyph_ids(chars);
for n in i..j {
let gid = glyphs.get(n).map(|g| g.gid);
let own = ids.iter().zip(&free).position(|(id, f)| f.is_some() && *id == gid);
if let (Some(p), Some(o)) = (own, out.get_mut(n)) {
*o = free.get_mut(p).and_then(Option::take);
}
}
}
let mut rest = free.into_iter().flatten();
for o in out.iter_mut().take(j).skip(i).filter(|o| o.is_none()) {
*o = rest.next();
let ids = if chars.len() <= MAX_MATCHED_CLUSTER { face.glyph_ids(chars) } else { Vec::new() };
let gids: Vec<u32> = glyphs.get(i..j).unwrap_or_default().iter().map(|g| g.gid).collect();
let any = cluster_chars(chars, &ids, &gids, false).unwrap_or_default();
// Output that keeps one character per glyph (render, PDF) writes each glyph's first: typed
// order must not leave fewer of them than the plain assignment.
let firsts = |s: &[Vec<char>]| s.iter().filter(|c| !c.is_empty()).count();
let shows = cluster_chars(chars, &ids, &gids, true).filter(|t| firsts(t) >= firsts(&any)).unwrap_or(any);
for (o, s) in out.iter_mut().skip(i).zip(shows) {
*o = s;
}
i = j;
}
out
}
/// The characters each glyph `gids` of one cluster shows, of the cluster's characters `chars`
/// with their own glyph ids `ids` (empty: none matched): a glyph that is a character's own glyph
/// takes that character first, then the other glyphs take the remaining characters in order,
/// and the cluster's last glyph takes those left over. `typed`: own glyphs are matched in typed
/// order only and a character with no glyph of its own between them goes with the glyph before
/// it, so the glyphs show the characters in typed order; `None` when a character comes before
/// every glyph that shows one (a vowel sign drawn before its consonant).
fn cluster_chars(chars: &[char], ids: &[Option<u32>], gids: &[u32], typed: bool) -> Option<Vec<Vec<char>>> {
let mut taken = vec![false; chars.len()];
let mut at: Vec<Vec<usize>> = vec![Vec::new(); gids.len()];
let mut from = 0;
for (a, gid) in at.iter_mut().zip(gids) {
let own = ids.iter().zip(&taken).enumerate().skip(from).find(|(_, (id, t))| !**t && **id == Some(*gid)).map(|(p, _)| p);
if let Some(p) = own {
a.push(p);
taken.get_mut(p).into_iter().for_each(|t| *t = true);
from = if typed { p + 1 } else { 0 };
}
}
// The characters before `next` are shown; `last` is the glyph that shows the latest one.
let (mut next, mut last): (usize, Option<usize>) = (0, None);
for k in 0..at.len() {
match at.get(k).and_then(|a| a.first()).copied() {
Some(p) if typed => {
if next < p {
at.get_mut(last?)?.extend(next..p);
}
(next, last) = (p + 1, Some(k));
}
Some(_) => {}
None => {
while !typed && taken.get(next) == Some(&true) {
next += 1;
}
if taken.get(next) == Some(&false) {
at.get_mut(k)?.push(next);
(next, last) = (next + 1, Some(k));
}
}
}
}
let rest: Vec<usize> = (next..chars.len()).filter(|p| taken.get(*p) == Some(&false)).collect();
if !rest.is_empty() {
at.last_mut()?.extend(rest);
}
Some(at.into_iter().map(|a| a.into_iter().filter_map(|p| chars.get(p).copied()).collect()).collect())
}
#[cfg(test)]
mod tests {
use super::*;
/// A single empty glyph with a positive advance, without relying on installed fonts.
fn empty_glyph_face() -> Face {
mapped_face(&[])
}
/// [`empty_glyph_face`] with a character map: each character to its glyph id (all ids draw
/// the one empty glyph).
fn mapped_face(map: &[(char, u32)]) -> Face {
let mut head = vec![0_u8; 54];
head[..4].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
head[18..20].copy_from_slice(&1000_u16.to_be_bytes());
@@ -297,7 +350,16 @@ mod tests {
hhea[4..6].copy_from_slice(&800_i16.to_be_bytes());
hhea[6..8].copy_from_slice(&(-200_i16).to_be_bytes());
hhea[34..36].copy_from_slice(&1_u16.to_be_bytes());
let mut cmap = Vec::from([0, 0, 0, 1, 0, 3, 0, 10, 0, 0, 0, 12, 0, 12, 0, 0]); // Format 12 at 12.
let len = u32::try_from(16 + 12 * map.len()).unwrap();
cmap.extend(len.to_be_bytes().into_iter().chain([0; 4]).chain(u32::try_from(map.len()).unwrap().to_be_bytes()));
let mut map = map.to_vec();
map.sort_unstable();
for (c, gid) in map {
cmap.extend([u32::from(c), u32::from(c), gid].into_iter().flat_map(u32::to_be_bytes));
}
let tables = [
(*b"cmap", cmap),
(*b"head", head),
(*b"hhea", hhea),
(*b"hmtx", vec![1, 244, 0, 0]), // Advance 500, left side bearing 0.
@@ -305,7 +367,7 @@ mod tests {
];
let mut bytes = vec![0_u8; 12 + tables.len() * 16];
bytes[..4].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
bytes[4..6].copy_from_slice(&4_u16.to_be_bytes());
bytes[4..6].copy_from_slice(&u16::try_from(tables.len()).unwrap().to_be_bytes());
bytes[6..8].copy_from_slice(&64_u16.to_be_bytes());
bytes[8..10].copy_from_slice(&2_u16.to_be_bytes());
for (i, (tag, data)) in tables.into_iter().enumerate() {
@@ -446,6 +508,38 @@ mod tests {
assert!(!needed("50x50 mm.") && !needed("Ünïcödé %%c25") && !needed(""));
}
/// The shaper splits sara am (ำ) into nikhahit and sara aa and draws the nikhahit before a
/// tone mark: in drawing order the glyphs still show the typed text, each character on a
/// glyph of its own, of its parts or before it (issue #2899). A glyph drawn before the
/// character it stands for (a vowel sign before its consonant) keeps its own character: no
/// character is moved onto another glyph to keep the order.
#[test]
fn reordered_glyphs_show_their_cluster_in_typed_order() {
let (no, mai_tho, sara_am, nikhahit, sara_aa) = ('\u{0E19}', '\u{0E49}', '\u{0E33}', '\u{0E4D}', '\u{0E32}');
let (deva_ka, deva_i, sara_u) = ('\u{0915}', '\u{093F}', '\u{0E38}');
let face = mapped_face(&[(no, 1), (mai_tho, 2), (sara_am, 3), (nikhahit, 4), (sara_aa, 5), (deva_ka, 6), (deva_i, 7), (sara_u, 8)]);
let with_gids = |gids: &[u32]| gids.iter().map(|gid| Glyph { gid: *gid, ..glyph(0) }).collect::<Vec<_>>();
let cs = [no, mai_tho, sara_am];
// What the shaper draws for น้ำ: no, nikhahit, mai tho, sara aa.
let shows = glyph_chars(&face, &cs, &with_gids(&[1, 4, 2, 5]), cs.len());
assert_eq!(shows.iter().flatten().collect::<String>(), "น้ำ");
assert_eq!(shows.get(2), Some(&vec![mai_tho]), "the tone mark's glyph shows the tone mark: {shows:?}");
// A sara u drawn into the letter's glyph goes with it, before the tone mark.
let cs = [no, sara_u, mai_tho];
let shows = glyph_chars(&face, &cs, &with_gids(&[1, 2]), cs.len());
assert_eq!(shows, [vec![no, sara_u], vec![mai_tho]]);
// Typed with the tone mark before sara u but drawn after it: in typed order the tone mark
// would only follow no on its glyph, and output that writes a glyph's first character
// would lose it, so each glyph keeps its own character.
let cs = [no, mai_tho, sara_u];
let shows = glyph_chars(&face, &cs, &with_gids(&[1, 8, 2]), cs.len());
assert_eq!(shows, [vec![no], vec![sara_u], vec![mai_tho]]);
// Devanagari ki: the vowel sign is drawn first.
let cs = [deva_ka, deva_i];
let shows = glyph_chars(&face, &cs, &with_gids(&[7, 6]), cs.len());
assert_eq!(shows, [vec![deva_i], vec![deva_ka]]);
}
fn glyph(cluster: usize) -> Glyph {
Glyph { gid: 0, cluster, advance: 500.0, dx: 0.0, dy: 0.0 }
}
@@ -459,17 +553,20 @@ mod tests {
// A run from index 1: cluster 1 has "ab" (two glyphs), cluster 3 has "cd" and a split
// character's extra glyph, which shows nothing.
let gs = Vec::from([1, 1, 3, 3, 3].map(glyph));
assert_eq!(glyph_chars(&face, &cs, &gs, 5), vec![Some('a'), Some('b'), Some('c'), Some('d'), None]);
assert_eq!(glyph_chars(&face, &cs, &gs, 5), vec![vec!['a'], vec!['b'], vec!['c'], vec!['d'], vec![]]);
// A ligature (ฐ with sara u below as one glyph) shows every character of its cluster.
let gs = Vec::from([1, 3].map(glyph));
assert_eq!(glyph_chars(&face, &cs, &gs, 5), vec![vec!['a', 'b'], vec!['c', 'd']]);
// Clusters out of order, past the run or past the line show nothing and don't panic.
let gs = Vec::from([3, 1, usize::MAX, 9].map(glyph));
assert_eq!(glyph_chars(&face, &cs, &gs, 5), vec![None, Some('a'), None, None]);
assert_eq!(glyph_chars(&face, &cs, &gs, 5), vec![vec![], vec!['a', 'b', 'c', 'd'], vec![], vec![]]);
assert!(glyph_chars(&face, &cs, &[], 5).is_empty());
// A cluster longer than the matching limit still shows each character once, in order.
let long: Vec<char> = std::iter::once('ก').chain(std::iter::repeat_n('\u{0E48}', MAX_CHARS)).collect();
let gs: Vec<Glyph> = (0..long.len()).map(|_| glyph(0)).collect();
let shows = glyph_chars(&face, &long, &gs, long.len());
assert_eq!(shows.first(), Some(&Some('ก')));
assert!(shows.iter().all(Option::is_some));
assert_eq!(shows.first(), Some(&vec!['ก']));
assert!(shows.iter().all(|s| s.len() == 1));
}
/// An installed font with Thai, or `None` (the tests then skip).
+3 -2
View File
@@ -1,8 +1,8 @@
//! Fonts from the optional craft-fonts build input (<https://github.com/storytold/craft-fonts>).
//!
//! Built with `CRAFT_FONTS_DIR=<craft-fonts checkout>`, `build.rs` embeds the fonts listed in its
//! `fonts/manifest.txt` (web builds: only `BIZ UDPGothic` Regular, the `Arab` and `Geor` faces and
//! the Thai Regular faces). Without it [`CRAFT_FONTS`] is empty and nothing changes. The font table ([`crate::ttf`])
//! `fonts/manifest.txt` (web builds: only `BIZ UDPGothic` Regular, the `Arab`, `Geor` and `Taml`
//! faces and the Thai Regular faces). Without it [`CRAFT_FONTS`] is empty and nothing changes. The font table ([`crate::ttf`])
//! lists the embedded fonts with the installed ones, under [`CraftFont::stem`]. A text style
//! can name one (`BIZ UDPGothic`), and they are fallbacks for characters a text's font lacks.
//! They are copied out of the binary only when first used.
@@ -86,6 +86,7 @@ mod tests {
Some("Thai") => '\u{0E01}',
Some("Hang" | "Kore") => '가',
Some("Geor") => 'ა',
Some("Taml") => 'த',
_ => 'A',
};
assert!(face.is_some_and(|x| x.has_glyph(sample)), "{} lacks {sample}", f.family);
+7 -7
View File
@@ -408,15 +408,15 @@ pub struct TextGlyph {
}
impl Shaped {
/// Add a glyph outline and, when it is a font glyph, its [`TextGlyph`].
/// An empty outline is retained only when text metadata needs its slot.
pub(crate) fn push_glyph(&mut self, contours: Vec<Vec<Vec2>>, text: Option<TextGlyph>) {
if contours.is_empty() && text.is_none() {
/// Add a glyph outline and, when it is a font glyph, its [`TextGlyph`] (one per character it
/// shows: a ligature shows several). An empty outline is retained only when text metadata
/// needs its slot.
pub(crate) fn push_glyph(&mut self, contours: Vec<Vec<Vec2>>, text: impl IntoIterator<Item = TextGlyph>) {
let (outline, before) = (self.glyphs.len(), self.text.len());
self.text.extend(text.into_iter().map(|t| TextGlyph { outline, ..t }));
if contours.is_empty() && self.text.len() == before {
return;
}
if let Some(t) = text {
self.text.push(TextGlyph { outline: self.glyphs.len(), ..t });
}
self.glyphs.push(contours);
}
/// Apply a point transform to every vertex (an affine map: text glyphs keep their axes).
+4 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "cadcraft-io"
description = "CADCraft file formats: DXF read/write mapping, SVG, PNG and PDF export"
description = "CADCraft file formats: DXF/DWG, SVG and PDF import, SVG/PNG/PDF export"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -21,7 +21,9 @@ cadcraft-fonts = { workspace = true }
thiserror = { workspace = true }
serde_json = { workspace = true }
serde = { workspace = true }
craft-pdf = { workspace = true, features = ["write"] }
craft-pdf = { workspace = true, features = ["write", "interpret"] }
kurbo = { workspace = true }
lyon_tessellation = { workspace = true }
[dev-dependencies]
miniz_oxide = "0.9"
+144 -4
View File
@@ -903,6 +903,73 @@ pub fn object_records(d: &Drawing) -> Vec<ObjectRecord> {
.collect()
}
/// The `dependentOnObject` handle (first group 330 inside the `AcDbAssocDependency` subclass) of
/// a kept associative dependency, when it is non-null.
fn assoc_dependency_target(o: &ForeignObject) -> Option<String> {
let mut in_dep = false;
for r in &o.tags {
if r.code == 100 {
if in_dep {
break;
}
in_dep = r.value.trim().eq_ignore_ascii_case("AcDbAssocDependency");
} else if in_dep && r.code == 330 {
let v = norm(&r.value);
return (!v.is_empty() && v != "0").then_some(v);
}
}
None
}
/// The groups of an `AcDbAssocAction` subclass before its dependency count: `100 AcDbAssocAction`,
/// `90` version, `90` status, `330` network, `360` body, `90` index and `90` highest dependency index.
const ASSOC_ACTION_HEADER: [i32; 7] = [100, 90, 90, 330, 360, 90, 90];
/// If `tags[at]` is the dependency count (group 90) of an `AcDbAssocAction` subclass, returns the count.
/// The count is followed by one group per dependency: 360 for an owned dependency, 330 for one the
/// action does not own. acadrust writes this layout (`write_assoc_action` in acadrust 0.6.6's
/// `io/dxf/writer/section_writer/associative.rs`) and reads it back (`read_action` in
/// `io/dxf/reader/section_reader/associative.rs`). A DWG reaches this code through that writer, so a
/// kept action from a DWG has this form too.
///
/// The match is positional on purpose. When the class version is above 1, the list is followed by
/// `90 0`, `90 n` and n group-360 owned parameters. A loose match on a group 90 before handles also
/// takes that second list.
fn assoc_action_dep_count(tags: &[RawTag], at: usize) -> Option<usize> {
if at < ASSOC_ACTION_HEADER.len() || tags.get(at)?.code != 90 {
return None;
}
let start = at - ASSOC_ACTION_HEADER.len();
if !tags[start].value.trim().eq_ignore_ascii_case("AcDbAssocAction") {
return None;
}
if !ASSOC_ACTION_HEADER.iter().enumerate().all(|(k, &c)| tags[start + k].code == c) {
return None;
}
let count = usize::try_from(tags[at].value.trim().parse::<i64>().ok()?).ok()?;
let deps = tags.get(at + 1..at + 1 + count)?;
deps.iter().all(|t| matches!(t.code, 330 | 360)).then_some(count)
}
/// The index of a kept object's `100 AcDbAssocAction` marker. An associative network derives from
/// an action, so it has one too.
fn assoc_action_marker(tags: &[RawTag]) -> Option<usize> {
tags.iter().position(|t| t.code == 100 && t.value.trim().eq_ignore_ascii_case("AcDbAssocAction"))
}
/// The dependency list of a kept action that [`assoc_action_dep_count`] recognizes: the index of
/// its count group and the count.
fn assoc_action_list(tags: &[RawTag]) -> Option<(usize, usize)> {
let at = assoc_action_marker(tags)? + ASSOC_ACTION_HEADER.len();
Some((at, assoc_action_dep_count(tags, at)?))
}
/// Whether a kept object is an action whose dependency list has a form we do not know. Its list
/// cannot be rewritten, so the dependencies it owns are not pruned.
fn is_unknown_assoc_action(tags: &[RawTag]) -> bool {
assoc_action_marker(tags).is_some() && assoc_action_list(tags).is_none()
}
/// Remaps the kept data's handles onto a written file.
struct Map<'a> {
f: &'a Foreign,
@@ -954,6 +1021,7 @@ impl Map<'_> {
fn object(&self, o: &ForeignObject, out: &mut Vec<Tag>) {
out.push(Tag::s(0, o.kind.clone()));
let dict = is_dictionary(&o.kind);
let list = assoc_action_list(&o.tags);
let mut i = 0;
while let Some(r) = o.tags.get(i) {
i += 1;
@@ -997,6 +1065,16 @@ impl Map<'_> {
}
continue;
}
if let Some((_, count)) = list.filter(|&(at, _)| at == i - 1) {
// An entry keeps its own group code. A null entry stays null, because [`Map::get`]
// gives "0" only for a null handle. An entry whose object is gone is left out, and
// the count follows.
let live: Vec<Tag> = o.tags[i..i + count].iter().filter_map(|n| self.get(&n.value).map(|h| Tag::s(n.code, h))).collect();
out.push(Tag::i(90, i64::try_from(live.len()).unwrap_or(i64::MAX)));
out.extend(live);
i += count;
continue;
}
if r.code == 5 {
out.push(Tag::s(5, self.get(&r.value).unwrap_or_else(|| "0".into())));
continue;
@@ -1166,7 +1244,7 @@ pub(crate) fn finish(
(o.handle.hex(), head(&t).owner)
})
.collect();
let alive_memo = settle(&hard, |kept: &HashMap<String, bool>| {
let mut alive_memo = settle(&hard, |kept: &HashMap<String, bool>| {
// Keep established live paths available to descendants during this pass as well.
let mut alive_memo: HashMap<String, bool> = kept.iter().filter(|(_, live)| **live).map(|(h, &live)| (h.clone(), live)).collect();
let kept = |h: &str| kept.get(h) == Some(&true);
@@ -1207,6 +1285,64 @@ pub(crate) fn finish(
}
alive_memo
});
// Drop kept AcDbAssocDependency objects whose dependentOnObject is no longer written. Also drop
// the kept objects whose owner, as [`owner_of`] finds it, is a dropped dependency. Leaving an
// active dependency with its group 330 remapped to "0" breaks the associative reactor invariant.
let entities: HashSet<String> = all_entities(d).map(|e| e.handle.hex()).filter(|h| written.contains(h)).collect();
// A dependency stays when an action of unknown form names it by group 330 or 360, or is its
// owner. That action's list and count stay as read, and only the dangling target becomes null.
// Each kept action is classified once, here.
let unknown_actions: Vec<&ForeignObject> = f.objects.iter().filter(|o| is_unknown_assoc_action(&o.tags)).collect();
let unknown_handles: HashSet<String> = unknown_actions.iter().map(|o| o.handle.hex()).collect();
let unknown_refs: HashSet<String> = unknown_actions
.iter()
.flat_map(|o| o.tags.iter().take_while(|t| t.code < 1000).filter(|t| matches!(t.code, 330 | 360)).map(|t| norm(&t.value)))
.collect();
let in_unknown_action =
|h: &str| unknown_refs.contains(h) || own.get(h).and_then(Option::as_deref).is_some_and(|owner| unknown_handles.contains(owner));
// Each pass that changes something drops at least one live object, so the loop ends.
loop {
let mut changed = false;
for o in &f.objects {
let h = o.handle.hex();
if alive_memo.get(&h) != Some(&true) || in_unknown_action(&h) {
continue;
}
let dead_target = assoc_dependency_target(o).is_some_and(|t| {
if objs.contains_key(&t) {
alive_memo.get(&t) != Some(&true)
} else if let Some(role) = handle(&t).and_then(|th| f.targets.get(&th)) {
!roles.contains_key(role)
} else {
!entities.contains(&t)
}
});
if dead_target {
alive_memo.insert(h, false);
changed = true;
}
}
if !changed {
break;
}
// The owner is found as for the first liveness pass ([`owner_of`]). A null-owner child goes
// with its hard owner, and a child with another live hard owner stays.
let mut cascade = true;
while cascade {
cascade = false;
for o in &f.objects {
let h = o.handle.hex();
if alive_memo.get(&h) != Some(&true) {
continue;
}
let owner = owner_of(own.get(&h).cloned().flatten(), &h, &hard, |x| alive_memo.get(x) == Some(&true));
if owner.is_some_and(|owner| objs.contains_key(&owner) && alive_memo.get(&owner) != Some(&true)) {
alive_memo.insert(h, false);
cascade = true;
}
}
}
}
// New handles for the written kept objects, above every written handle and the seed.
let mut fresh = Fresh::new(tags);
// The entities of unmodeled types join the records only below, so their handles are not in
@@ -1224,7 +1360,6 @@ pub(crate) fn finish(
}
}
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>());
let mut block = String::new();
@@ -1263,7 +1398,9 @@ pub(crate) fn finish(
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() {
out.extend(b.iter().cloned());
out.extend(b.iter().map(|tag| {
if r.kind == "LAYOUT" && tag.code == 333 { Tag::s(333, map.get(&tag.str()).unwrap_or_else(|| "0".into())) } else { tag.clone() }
}));
continue;
}
record(&map, r, b, x.as_deref(), None, Some(r.start) == root, &mut out);
@@ -1379,6 +1516,8 @@ fn plan_unknown(
};
let br = |name: &str| roles.get(&("BLOCK_RECORD".to_string(), up(name))).cloned();
let first_at = |s: &cadcraft_doc::EntityStore| s.iter().find_map(|e| at.get(&e.handle.hex()).copied());
// The LAYER table as written: proxy graphics name layers by their index in it (#3094).
let written_layers: Vec<String> = recs.iter().filter(|r| r.sec == "TABLES" && r.kind == "LAYER").filter_map(|r| val(body(r), 2)).collect();
let layouts = d.paper_space_layouts();
// (entities, owner, paper space, end of the space, section)
let mut stores: Vec<(&cadcraft_doc::EntityStore, Option<String>, bool, Option<usize>, &str)> = Vec::new();
@@ -1406,7 +1545,8 @@ fn plan_unknown(
{
continue;
}
let t = unknown_entity(u, e, &owner, paper);
let remapped = u.with_proxy_layers(&d.proxy_layers, &written_layers).map(|tags| Unknown { tags, ..u.clone() });
let t = unknown_entity(remapped.as_ref().unwrap_or(u), e, &owner, paper);
if !t.is_empty() {
pending.push((sec.to_string(), t));
}
+62
View File
@@ -98,6 +98,64 @@ fn keep_file_order<T>(items: &mut [T], name: impl Fn(&T) -> &str, order: &[Strin
});
}
/// A dimension kept as read (LARGE_RADIAL_DIMENSION, ARC_DIMENSION) draws its `*D` block, as
/// AutoCAD does, in place of the proxy graphics it may carry: those can differ from what AutoCAD
/// shows (an exporter's picture without the arrowheads; #3438). Its graphics become one reference
/// to that block, with the dimension's handle, so it is drawn, measured and picked like a proxy.
/// A reference, not a copy of the contents: nested dimensions, the block's draw order and the
/// renderer's depth and size limits all apply as for any block reference.
fn draw_kept_dimensions_from_their_blocks(d: &mut Drawing) {
let pictures = |store: &cadcraft_doc::EntityStore, d: &Drawing| -> Vec<(Handle, Entity)> {
store
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Unknown(u) => {
let block = d.block(u.dimension_block()?)?;
// The block holds the dimension as drawn, in the dimension's coordinates: placed
// at its base point it draws where it is, as a DIMENSION's block does.
let reference = Insert { block: block.name.clone(), insert: block.base, ..Insert::default() };
// Everything ByBlock, so what the block gives ByBlock is the dimension's own.
let common = Common {
layer: "0".into(),
color: Color::ByBlock,
linetype: "ByBlock".into(),
lineweight: Lineweight::ByBlock,
transparency: Transparency::ByBlock,
plot_style: "ByBlock".into(),
..Common::default()
};
(!block.entities.is_empty()).then(|| (e.handle, Entity { handle: e.handle, common, kind: EntityKind::Insert(reference) }))
}
_ => None,
})
.collect()
};
let apply = |store: &mut cadcraft_doc::EntityStore, found: Vec<(Handle, Entity)>| {
for (h, reference) in found {
store.modify(h, |e| {
if let EntityKind::Unknown(u) = &mut e.kind {
u.graphics = vec![reference];
}
});
}
};
let found = pictures(&d.model, d);
apply(&mut d.model, found);
for i in 0..d.layouts.len() {
let found = pictures(&d.layouts[i].entities, d);
apply(&mut d.layouts[i].entities, found);
}
let names: Vec<String> = d.blocks.keys().cloned().collect();
for name in names {
let found = d.blocks.get(&name).map(|b| pictures(&b.entities, d)).unwrap_or_default();
if !found.is_empty()
&& let Some(b) = d.blocks.get_mut(&name)
{
apply(&mut std::sync::Arc::make_mut(b).entities, found);
}
}
}
/// Read a DXF file into a drawing.
pub fn read(bytes: &[u8]) -> Result<Drawing> {
read_budgeted(bytes, 4_000_000, hatch::MAX_READ_CURVE_POINTS)
@@ -205,6 +263,9 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
// Proxy graphics name layers and linetypes by their place in the file's tables, and saving
// writes them unchanged: the tables keep the file's order, with what CADCraft adds after it.
keep_file_order(&mut d.layers, |l| &l.name, &rx.proxy_tables.layers, &[]);
// Saving turns the graphics' layer indices from this order into the written table's, so
// removing or adding layers doesn't move them (#3094).
d.proxy_layers.clone_from(&rx.proxy_tables.layers);
keep_file_order(&mut d.linetypes, |l| &l.name, &rx.proxy_tables.linetypes, &["ByBlock", "ByLayer"]);
// A proxy text takes the first style on its font, so the styles keep the file's order too.
let styles: Vec<String> = rx.proxy_tables.styles.iter().map(|(n, _)| n.clone()).collect();
@@ -215,6 +276,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
let (paper_block_for, first_layout) = setup_layouts(&mut d, &mut layout_objs, &rx);
place_blocks(&mut d, blocks, &mut rx, &paper_block_for, &first_layout);
place_entities(&mut d, entities, &rx, &paper_block_for, &first_layout);
draw_kept_dimensions_from_their_blocks(&mut d);
number_unknown_viewport_ids(&mut d, &dropped_paper_views(&rx, &paper_block_for, &first_layout));
apply_sortents(&mut d, &objs.sortents, &rx.brs, &paper_block_for, &first_layout);
objs.apply(&mut d, &rx);
+29 -4
View File
@@ -119,15 +119,17 @@ pub(super) fn ocs_n(n: Vec3, p: Vec3) -> Vec3 {
/// billionth of the object's size and distance from the origin. A normal that is the Z axis
/// or the Z axis turned over moves nothing, and noise in one moves points by a negligible
/// amount, so those objects keep their arcs; however small the tilt, an object far enough from
/// the origin to be moved visibly is projected.
pub(super) fn tilted(n: Vec3, pts: impl IntoIterator<Item = Vec3>) -> bool {
if !n.is_finite() || n.len() < 1e-12 {
/// the origin to be moved visibly is projected. The points are only gathered for a normal off
/// the Z axis: along it (x and y exactly 0, as in nearly every drawing) nothing moves, and
/// sampling every arc of every object for that would be wasted.
pub(super) fn tilted<I: IntoIterator<Item = Vec3>>(n: Vec3, pts: impl FnOnce() -> I) -> bool {
if !n.is_finite() || n.len() < 1e-12 || (n.x == 0.0 && n.y == 0.0) {
return false;
}
let m = cadcraft_geom::Mat4::ocs(n);
let flip = if n.z < 0.0 { -1.0 } else { 1.0 };
let (mut moved, mut reach) = (0.0f64, 1.0f64);
for p in pts.into_iter().filter(|p| p.is_finite()) {
for p in pts().into_iter().filter(|p| p.is_finite()) {
let shown = Vec2::new(flip * p.x, p.y);
moved = moved.max((m.apply(p).xy() - shown).len());
reach = reach.max(p.x.abs()).max(p.y.abs()).max(p.z.abs());
@@ -204,3 +206,26 @@ pub(super) fn plan_of_tilted(n: Vec3, elevation: f64, vertices: &[PolyVertex], c
let z = if local.is_empty() { elevation } else { local.iter().map(|v| to_plan(v.p).z).sum::<f64>() / local.len() as f64 };
(local.into_iter().map(|v| PolyVertex { p: to_plan(v.p).xy(), ..v }).collect(), z)
}
#[cfg(test)]
mod tests {
use super::*;
/// A normal on the Z axis, either way up and of any length, moves no point, so [`tilted`]
/// answers without sampling the object's arcs; any other normal gathers them.
#[test]
fn a_normal_on_the_z_axis_gathers_no_points() {
let gathered = std::cell::Cell::new(0);
let pts = || {
gathered.set(gathered.get() + 1);
vec![Vec3::new(1.0, 2.0, 3.0)]
};
for n in [Vec3::Z, Vec3::new(0.0, 0.0, -1.0), Vec3::new(0.0, 0.0, 2.5), Vec3::new(-0.0, 0.0, -0.1)] {
assert!(!tilted(n, pts), "{n:?}");
}
assert_eq!(gathered.get(), 0);
assert!(tilted(Vec3::new(0.0, 0.5, -0.75f64.sqrt()), pts));
assert!(!tilted(Vec3::new(0.0, 1e-15, 1.0), pts), "noise in a plan normal still moves nothing visible");
assert_eq!(gathered.get(), 2);
}
}

Some files were not shown because too many files have changed in this diff Show More