Compare commits

...
Author SHA1 Message Date
skylar taylor-barrick f7adf3ad56 Prepare CADCraft nightly signing and Mac archive layout (#3598) 2026-11-27 15:19:23 -06:00
Dylan M. TaylorandFredApps 1981067187 ci: notify artcraft-services on release state changes (#3581)
* ci: notify artcraft-services on release state changes

* ci: pass only the dispatch token to the notify-services workflow

secrets: inherit hands the called workflow every repository secret, including
the signing credentials. The reusable workflow only reads
ARTCRAFT_SERVICES_DISPATCH_TOKEN, so map just that one.

---------

Co-authored-by: FredApps <[email protected]>
2026-11-27 09:44:56 -05:00
FredApps 717f9520d3 Merge pull request #3564 from 2ez4gcx/fix/linetype-dash-budget
Linetypes: a dash budget per build, and say when a run is drawn continuous
2026-11-27 14:43:50 +01:00
FredApps ff4de54a14 Merge remote-tracking branch 'origin/main' into real-3564
# Conflicts:
#	crates/render/src/lib.rs
#	crates/render/src/pipeline.rs
#	crates/render/src/viewports.rs
2026-11-27 20:23:57 +07:00
FredApps dd423db3a8 Merge pull request #3572 from 2ez4gcx/fix/lisp-blocking-run
LISP: an expression typed at a prompt gets a short step allowance
2026-11-27 14:23:02 +01:00
FredApps fa6e282d16 Merge pull request #3562 from 2ez4gcx/fix/table-record-dedup
fix(io): read VIEW and UCS records, and each layout's named UCS, without scanning, so crafted files don't open in quadratic time
2026-11-27 14:22:56 +01:00
FredApps 59efc33013 Merge pull request #3561 from 2ez4gcx/fix/datalink-stored-paths
Data links: read a link saved in a drawing only from its folder
2026-11-27 14:22:50 +01:00
FredApps e3418eddbc Merge pull request #3560 from 2ez4gcx/fix/dimension-block-render-cycle
fix(render): a dimension whose block leads back to its own block is drawn once, not down to the depth limit
2026-11-27 14:22:45 +01:00
FredApps 1c45f0e307 Merge remote-tracking branch 'origin/main' into pr-3572
# Conflicts:
#	crates/engine/src/lisp/tests.rs
2026-11-27 20:06:58 +07:00
FredApps 456fdacf01 Merge pull request #3589 from 2ez4gcx/fix/hatch-edge-path-chaining
DXF/DWG: chain HATCH edge-path edges that are out of order or reversed
2026-11-27 14:06:09 +01:00
FredApps 1b48b22546 Merge pull request #3588 from 2ez4gcx/fix/control-preauth-bound
Bound what the control server reads before the token check (part of #1925, F-12)
2026-11-27 14:06:04 +01:00
FredApps 1858b04c2f Merge pull request #3582 from 2ez4gcx/fix/attdef-ocs-plane
Read a tilted ATTDEF or ATTRIB at its world point (#3541)
2026-11-27 14:05:59 +01:00
FredApps 86731b23e4 Merge pull request #3576 from 2ez4gcx/fix/lisp-integer-wrap
LISP: gcd and atoi give a real past 32 bits instead of wrapping
2026-11-27 14:05:35 +01:00
2ez4gcxandClaude Opus 5.5 1aa8d9db9c Keep the lost-reply warning on the control client's retry
exchange() retries once when the first attempt was not sent (or is
read-only), but the retry dropped `sent`: a mutation the retry sent and
whose reply was lost came back as a plain transport error, without the
"may or may not have been applied" warning. The new ping before long
requests adds a way into that retry (a lost ping reply counts as not
sent). The retry now keeps `sent` and returns the same warning for
mutations; read-only methods keep the plain error.

Test: a_lost_reply_on_the_retry_still_says_a_mutation_may_have_been_applied.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 17:18:56 +07:00
2ez4gcxandClaude Opus 5.5 364881867c Hatch edge chaining: close each later outline at its exact start
A later outline was closed back to its start only when its end lay farther
than the tolerance from it (review). With the end within the tolerance but
not equal, the jump back to the first outline left from the end while the
jump out arrived at the start, so the two did not cancel under even-odd
fill and a sliver between them was filled. The start is now added whenever
the end differs from it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 16:17:07 +07:00
2ez4gcxandClaude Opus 5.5 3da5c2c319 Hatch edge chaining: ends meet only within the tolerance
The end lookup took any unused end in the 3x3 grid cells around a point,
so ends up to about 2.8 tolerances apart could be joined (review). The grid
now only gives candidates; each is checked with Vec2::near against the
tolerance and the lowest eligible end wins, as the "runs on" and closed-run
checks already did. A cell's scan stops at the best match so far, and the
ends visited are capped at 32 per end of the loop: past that, a crafted
loop is read in file order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 15:36:01 +07:00
2ez4gcxandClaude Opus 5.5 02ea1d1c31 DXF/DWG: chain HATCH edge-path edges that are out of order or reversed
An edge path was read in file order, so an edge listed elsewhere or stored
end to start made the vertex list jump, and the even-odd fill filled the
polygon of the jumps (a square listed AB, DC, BC, AD filled as an hourglass).

Each edge is now read on its own and hatch/chain.rs joins them. A path whose
edges already run on is joined in file order as before. Otherwise edges are
chained into runs by their ends (within a millionth of the loop's extent,
at least 1e-9), turned around when needed (points reversed, bulges negated
and moved). Closed runs fill as loops of their own; open runs are joined in
order, as a path read in file order is. Ends are looked up in a sorted grid,
O(n log n).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 14:11:23 +07:00
2ez4gcxandClaude Opus 5.5 db0a4aca42 Bound what the control server reads before the token check (#1925)
The control server checks a request's token only after reading the whole
line, and clients send the token last, so a local peer without it could
make the app buffer a line of up to 256 MiB (512 MiB across connections).

Until a request on a connection has passed the token check, a request
line may be at most 64 KiB (control_token::MAX_UNAUTHENTICATED_LINE); a
longer one gets an error reply and the connection is closed. After that
the usual 256 MiB limit applies.

The MCP bridge sends a short ping with the token before a longer request
on a new connection, and sends the request only when the ping's reply
shows the token check passed; a refused or lost ping leaves the request
unsent and safe to retry. docs/control-protocol.md describes the limit.

Part of #1925 (F-12).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 14:09:23 +07:00
2ez4gcxandClaude Opus 5.5 293d79fac8 Read a tilted ATTDEF or ATTRIB at its world point (#3541)
An ATTDEF or ATTRIB in a tilted plane facing up holds its insertion
point, alignment point and rotation in that plane's OCS (DXF Reference,
ATTDEF and ATTRIB groups 10 and 11 "in OCS"; "Object Coordinate Systems
(OCS)"). The reader took them as world coordinates, and the writer saves
attributes with no group 210, so a save moved the attribute millions of
units in a drawing near survey coordinates.

flatten_tilted maps them through Mat4::ocs and turns group 50 into the
plane's direction in plan, as tilted LWPOLYLINE and HATCH are drawn
flat; an ATTDEF's extrusion is then spent. ATTRIBs of a reference that
is itself left in its tilted plane (#1158) stay as read with it; the
INSERT arm and that check share mirrored_reference. Planes facing down
(mirror_text), flat attributes and TEXT (#3296) are unchanged.

Fixes #3541

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 11:11:12 +07:00
2ez4gcxandClaude Opus 5.5 7b482c5e3b render: a pattern of gaps only draws no line on any run
e9e4b0e1f made a gaps-only pattern draw nothing past the per-run limit, but
it was still drawn as one continuous line where a pattern with a dash falls
back to continuous: a run shorter than one period, a pattern under
`min_pattern` (sub-pixel), past 50,000 periods with a level of detail, and
a run of one point (review of #3564). On screen that also differed from the
plot of the same run.

apply, apply_as and ranges now return no dashes for a pattern whose elements
are all gaps, before any of those fallbacks. Patterns with a dash or a dot
keep every fallback, and an empty (continuous) pattern is drawn whole. Texts
and shapes in a gaps-only pattern are placed as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 09:05:09 +07:00
2ez4gcxandClaude Opus 5.5 e9e4b0e1ff render: charge a closed run for the periods it walks; gaps only draw nothing at any length
Review of #3564:

- A closed run is stretched to round(L / period) periods and laid out from
  the period before its anchor to the one after its last, up to half a
  period more than the (L / period + 2) elements it was charged. A run of
  192 on 127 dashes and a gap (period 128) walked 508 elements for a charge
  of 448. It is now charged (round(L / period) + 2) x the pattern's length.
  The per-run limit keeps its formula, so runs under it keep their output.
- A pattern of gaps only was refused past the per-run limit, drawn as one
  continuous line and counted as undashed, while below the limit it draws
  nothing. It now draws nothing at any length, uncharged and unreported.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 01:19:53 +07:00
2ez4gcxandClaude Opus 5.5 7dfb39d3db LISP: gcd and atoi give a real past 32 bits instead of wrapping
`(gcd -2147483648 0)` gave 2147483647 (the divisor clamped to the
largest integer), and `atoi` cast its digits with `as i32`, so
"99999999999" gave 1215752191 and "99999999999999999999" gave 0.

They now follow what the reader, `fix` and JSON inputs already do with
a whole number that doesn't fit 32 bits: it is a real. `gcd` gives
2147483648.0 for its one such result; `atoi` gives the real `atof`
reads from the digits, the number the reader makes of them. Results
that fit are the same integers as before. Integer arithmetic still
wraps.

Part of #1933.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 00:47:43 +07:00
2ez4gcxandClaude Opus 5.5 a44fcd4fce engine: EXPORT, PLOT and SAVEAS to an image say when dashes were drawn continuous
The first commit made `cadcraft-cli convert` print the note, but the app's
own commands write images through IoHooks::write and ::plot, which return
bytes only, so the desktop and web apps and LISP stayed silent (#1069).

- cmd::file::set_noted_io(NotedIo { write, plot }): an optional hook beside
  IoHooks (which is built by struct literal in ~70 places), installed by the
  CLI, desktop and web apps with cadcraft_io::write_framed_noted and the new
  cadcraft_io::plotter::plot_noted / pdf::plot_noted.
- EXPORT, PLOT (so EXPORTPDF, PUBLISH and PDFBOOK per sheet), QSAVE and
  SAVEAS to an image and document.bytes echo the note and add it to the
  result's `warnings`. An image written with a `version` option goes through
  the same writer (same bytes), so it is noted too.
- report_notes adds to `warnings` instead of replacing them;
  report_dwg_notes uses it (no result had `warnings` before it, so DWG
  results don't change). Without the hook nothing changes.

Not covered: the plot preview and the canvas show no message.

Fixes #1069.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 00:11:22 +07:00
2ez4gcxandClaude Opus 5.5 ef42a37dcb LISP: an expression typed at a prompt gets a short step allowance
An expression typed at a command's prompt (CIRCLE, then `(while T)` as
the radius) is the prompt's answer, so it ran as a blocking run with the
500,000,000-step cap meant for programmatic calls: about 17 s on a dev
build with no frame drawn and Esc not handled.

It now runs through `lisp_eval_answer` with a 20,000,000-step cap, and
the callbacks it runs (`vl-sort`'s comparator and the other synchronous
callbacks) share what is left of that allowance instead of each taking
the 500,000,000-step callback allowance inside one step. The error says
the expression was stopped and to run long routines at Command:, where
they run a slice per frame and Esc stops them. Routines at Command:,
`c:` commands, APPLOAD, dropped files, the `lisp`/`appload` JSON calls
and startup files are unchanged.

Part of #1926 (item 3).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 23:32:33 +07:00
2ez4gcxandClaude Opus 5.5 861223423d Data links: drop the file linked longest ago at the bound
DATALINK remembers up to 1000 linked files per open drawing. At the
bound a new file dropped an arbitrary entry of a HashSet, which could be
the file linked just before it. Each remembered file now carries when it
was last linked: linking it again moves it to the newest, and a new file
at the bound drops the one linked longest ago.

Test: remembered_links_are_the_most_recent_ones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 22:27:50 +07:00
FredApps a3ed0682ab Merge pull request #1633 from KnottyDyes/squad/docs-dxf-dwg-write-version
Docs: describe DXF and DWG save-version selection
2026-11-26 15:12:38 +01:00
FredApps b1340f0697 Merge main into docs/save-version (keep main's craft-dwg and acadrust 0.6.6 text; this PR's version-selection rules) 2026-11-26 20:48:14 +07:00
2ez4gcxandClaude Opus 5.5 c824e5e96a render: a dash budget per build, and say when a run is drawn continuous
A dashed run is laid out over at most two million pattern elements, but
nothing bounded the total, and a pattern of mostly gaps visits many elements
for each point it draws, so the 64M-point display budget never stopped it:
1,000 lines on a 256-element pattern of gaps and one dash (a 58 KB DXF) took
11.6 s to PNG and 12.7 s to a 69 MB PDF on a dev build. A run past the
per-run limit was also drawn continuous without a word (#1069).

- MAX_DASH_ELEMENTS (64M, as many as the list's points) is charged by
  linetype::layout before a run is laid out, on a counter shared like the
  point budget's (parallel parts, XCLIP parts, viewport contents). Once a run
  does not fit, the rest of the build's dashed runs are drawn continuous.
  The per-run limit is MAX_RUN_DASH_ELEMENTS, unchanged.
- A run drawn continuous because of either limit sets DisplayList::truncated
  and counts in the new DisplayList::undashed, merged where lists are joined.
  Runs drawn continuous by rule (short, sub-pixel, the screen's 50,000-period
  level of detail) are not counted.
- cadcraft_io::write_framed_noted (and png/svg/pdf "noted" variants) return
  the note; cadcraft-cli convert and run --export print it.
- Linetype texts are placed only on a run whose dashes were laid out; phase
  checks the limits without laying the run out again.

On 11 real drawings the most a complete plot asked was 26.5M elements; a
16M total would have drawn 8,241 runs of that drawing solid. With 64M the
gap-pattern file takes 0.8 s / 0.4 s, the #1069 controls and three real
drawings export byte-identical, and the audit's dense dash/gap file stays as
on main (it fills the point budget at the same time).

Part of #1923 (F-05 f). Part of #1069: the app's EXPORT and PLOT don't show
the note yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 20:13:14 +07:00
FredApps b3bc4a7618 Merge pull request #997 from aldozar/perf/cjk-text
Faster CJK-heavy drawings: per-thread font caches, offscreen glyphs left out (#666, #662)
2026-11-26 13:43:40 +01:00
FredApps e66cdcec29 Merge main into perf/cjk-text
Conflicts: crates/fonts/src/ttf.rs (main made OutlineMesh's points pub(crate); kept that and this PR's bounds field) and crates/render/src/tests.rs (kept this PR's #666 view test and main's fixture-font section).

Main also added a public font-set GENERATION/generation() for redraws (2c979eb1), which clashed by name with this PR's private lookup-cache counter. Renamed this PR's counter to LOOKUP_GENERATION/lookup_generation(), and set_font_dirs now also calls changed() so the per-thread caches drop fonts from removed folders.

cargo test -p cadcraft-fonts -p cadcraft-render and cargo fmt --check pass locally.
2026-11-26 19:31:45 +07:00
2ez4gcxandClaude Opus 5.5 077a5fd247 fix(io): read VIEW and UCS records and each layout's named UCS without scans
The DXF reader looked for an earlier VIEW or UCS of the same name by
scanning the records read so far, and found each layout's named UCS by
scanning every UCS, on read and on save. A crafted file of N VIEW or N UCS
records, or of N layouts each naming one of N UCSs, cost N^2 name
comparisons (#1924, F-04 item 3): at N = 40 000 it took 67 s and 194 s to
open on main.

- ByName: the records of a table read so far by lower-cased name; a later
  record of a name replaces the first, which keeps its place and takes the
  later record's name, as before. DIMSTYLE records use it too.
- UcsNames: the drawing's UCSs by lower-cased name with their positions in
  table order; a layout's named UCS is the first of that name whose frame
  is the layout's, as named_ucs finds it. Built once per read and per save.

Tests: VIEW/UCS records (main 118.9 s, now 0.23 s) and layouts naming
UCSs, read and saved (39.9 s, now 1.6 s), against a 10 s bound; a
behaviour test compares UcsNames with named_ucs. Follows #3539.

Part of #1924

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 18:55:44 +07:00
2ez4gcxandClaude Opus 5.5 8f4f06b9fb Data links: read a link saved in a drawing only from its folder
A table's data link path is stored in the drawing, and DATALINKUPDATE
copies the linked file's text into the table, where the next save keeps
it. A stored path could name any local file (by `..` or an absolute
path), so a drawing could pull any readable file into itself.

A link the drawing itself names is now read only when its file, resolved
by the file system (`..`, symbolic links and junctions followed), lies in
the drawing's folder or a folder below it, compared by whole components;
the resolved path is the one read. A file the user links with DATALINK
is remembered for that open drawing (never saved, at most 1000, newest
kept), so it keeps updating until the drawing is opened again. Refused
links are listed in DATALINKUPDATE's errors; the other links update. The
automation roots are still checked first.

Part of #1929 (F-08).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 18:48:34 +07:00
2ez4gcxandClaude Opus 5.5 851d154843 fix(render): draw a dimension whose block leads back to its own block from its definition points
A dimension block holding dimensions of itself, directly or through block references, other
dimension blocks, multileader blocks or proxy graphics, was drawn again for every such dimension at
every level down to MAX_BLOCK_DEPTH: k of them made up to k^16 copies, a loop through many
distinct blocks one copy per ordering of them, cut only by the 2M expansion budget. A crafted
490-byte DXF took 79 s to export to PNG (dev build), 602 bytes over 300 s.

A dimension inside block C is now drawn from its own block T only if T does not lead back to C.
A short search from T (16 blocks, 256 objects) settles ordinary blocks; past it the strongly
connected components of the block graph are found once per build (iterative Tarjan, shared through
a OnceLock). A dimension on a loop is drawn from its definition points, as one whose block is
missing is. Loops made only of block references are unchanged.

Part of #1923 (F-05).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 17:45:00 +07:00
FredApps e59031a441 Merge pull request #2782 from 2ez4gcx/fix/arraypath-closed-spacing
ARRAYPATH: no extra item where a closed path closes, by spacing
2026-11-26 10:39:43 +01:00
FredApps e0d64c676d Merge pull request #2705 from 2ez4gcx/fix/spline-closed-autocad
SPLINE: closed fit-point splines built as AutoCAD 2024 builds them
2026-11-26 10:29:22 +01:00
FredApps a46923c96d Merge remote-tracking branch 'origin/main' into ic45-2782 2026-11-26 16:20:50 +07:00
FredApps 61f4632e60 Merge pull request #2762 from 2ez4gcx/fix/arraypath-item-count
ARRAYPATH: the item count takes a whole number as AutoCAD 2024 does
2026-11-26 10:20:35 +01:00
FredApps 28fd71600c Merge pull request #2778 from 2ez4gcx/fix/splinedit-elevate-order-integer
SPLINEDIT: take a whole number as typed for Elevate order
2026-11-26 10:20:17 +01:00
FredApps 6525de811e Merge pull request #2784 from 2ez4gcx/fix/insert-points-at-scale-prompts
INSERT/MINSERT: take points at the scale, rotation and spacing prompts
2026-11-26 10:20:00 +01:00
FredApps daa6bf9063 Merge main into fix/spline-closed-autocad 2026-11-26 16:09:42 +07:00
FredApps b4ad0f3800 Merge pull request #2703 from 2ez4gcx/fix/spline-file-tangent-length
SPLINE: a file's end tangents count with their length, as in AutoCAD 2024
2026-11-26 10:09:24 +01:00
FredApps 5096e1503f Merge pull request #3500 from 2ez4gcx/feat/vi-catalog-phase1
Vietnamese catalog: approved terminology and the 249 missing strings (craft-i18n#401 phase 1)
2026-11-26 10:09:06 +01:00
FredApps bcfc9a0786 Merge pull request #2780 from 2ez4gcx/fix/divide-count-integer
DIVIDE: take a whole number as typed for the number of segments
2026-11-26 10:04:21 +01:00
FredApps 9df34c448c Merge remote-tracking branch 'origin/main' into ic45-2762 2026-11-26 16:00:43 +07:00
FredApps edbdf0dd8f Merge pull request #2774 from 2ez4gcx/fix/arraypath-json-params
ARRAYPATH: refuse a JSON count or spacing it can't use
2026-11-26 10:00:31 +01:00
FredApps 60ca94cd7a Merge commit 'bb3b0cd5' into ic46-2705 2026-11-26 16:00:25 +07:00
FredApps 02bc55aaaa Merge remote-tracking branch 'origin/main' into ic45-2778
# Conflicts:
#	crates/engine/tests/it/pedit_splinedit.rs
2026-11-26 15:56:21 +07:00
FredApps 66d92125f1 Merge pull request #2772 from 2ez4gcx/fix/splinedit-precision-integer
SPLINEDIT: take a whole number as typed for the polyline precision
2026-11-26 09:54:22 +01:00
FredApps 40c4c7dac1 Merge main into feat/vi-catalog-phase1 2026-11-26 15:52:44 +07:00
FredApps bb3b0cd5cd Merge main into fix/spline-file-tangent-length 2026-11-26 15:52:12 +07:00
FredApps efa617fcd5 Merge remote-tracking branch 'origin/main' into ic45-2784
# Conflicts:
#	crates/engine/tests/it/minsert.rs
2026-11-26 15:51:50 +07:00
FredApps 19290804a1 Merge pull request #2699 from 2ez4gcx/fix/spline-fit-autocad
SPLINE: open fit-point splines built as AutoCAD 2024 builds them
2026-11-26 09:51:49 +01:00
FredApps bb375992f4 Merge pull request #2789 from 2ez4gcx/fix/minsert-json-counts
MINSERT: JSON rows and columns are whole numbers
2026-11-26 09:51:23 +01:00
FredApps f2d1845aee Merge pull request #2205 from 2ez4gcx/fix/pline-undo-plinewid
PLINE: Undo returns to the last segment's mode, and PLINEWID is the width
2026-11-26 09:48:33 +01:00
FredApps 2c4ab18255 Merge pull request #2761 from 2ez4gcx/fix/array-count-integer
ARRAY: counts take a whole number as typed, as AutoCAD 2024 does
2026-11-26 09:48:12 +01:00
FredApps a37797484d Merge pull request #2204 from 2ez4gcx/fix/rectang-autocad-vertices
RECTANG: Area with cut corners, oversized corners and Rotation as AutoCAD takes them
2026-11-26 09:48:01 +01:00
FredApps 900ed557f1 Merge pull request #2726 from 2ez4gcx/feat/copy-autocad
COPY as AutoCAD 2024: COPYMODE, mOde/Multiple, Array with Fit, Undo, and Enter for a displacement
2026-11-26 09:47:40 +01:00
FredApps d7ea0ede4c Merge pull request #2209 from 2ez4gcx/fix/stretch-arcs-bulges-splines
STRETCH: arcs and polyline arc segments keep their height; spline control points move
2026-11-26 09:47:17 +01:00
FredApps 0e3a58418f Merge remote-tracking branch 'origin/main' into ic45-2780 2026-11-26 15:44:23 +07:00
FredApps 6a3199d5a4 Merge pull request #3539 from 2ez4gcx/fix/style-name-lookups
fix(doc, io): look linetypes, text and dimension styles and layouts up by name through an index, so crafted files don't open or draw in quadratic time
2026-11-26 09:42:20 +01:00
FredApps c352afc399 Merge remote-tracking branch 'origin/main' into ic45-2774 2026-11-26 15:40:39 +07:00
FredApps 292b6bc7ce Merge remote-tracking branch 'origin/main' into ic45-2772 2026-11-26 15:38:23 +07:00
FredApps 45b20c6470 Merge remote-tracking branch 'origin/main' into ic45-2789 2026-11-26 09:35:09 +01:00
FredApps fbea6d1ffc Merge pull request #2766 from 2ez4gcx/fix/minsert-count-integer
MINSERT: take a whole number as typed for the rows and columns
2026-11-26 09:34:52 +01:00
FredApps 22ba34c123 Merge main into feat/vi-catalog-phase1 2026-11-26 09:32:53 +01:00
FredApps 331c867476 Merge main into fix/array-count-integer 2026-11-26 09:28:41 +01:00
FredApps bddbf390f7 Merge main into fix/rectang-autocad-vertices 2026-11-26 09:28:12 +01:00
FredApps 5f24b4b667 Merge main into fix/pline-undo-plinewid 2026-11-26 09:28:06 +01:00
FredApps 6b403674ed Merge main into fix/stretch-arcs-bulges-splines 2026-11-26 09:27:59 +01:00
FredApps 2485c2e758 Merge main into feat/copy-autocad 2026-11-26 09:17:23 +01:00
FredApps 2ca9557d2c Merge remote-tracking branch 'origin/main' into ic45-2766 2026-11-26 09:16:22 +01:00
FredApps ea66defc0d Merge main into fix/spline-fit-autocad 2026-11-26 09:12:33 +01:00
FredApps 2e9fe9462c Merge main into fix/style-name-lookups 2026-11-26 09:10:47 +01:00
2ez4gcxandClaude Opus 5.5 4c1ea7d320 Merge main (ba344a89) into feat/copy-autocad
One conflict, in crates/engine/src/cmd/modify/select_then.rs: this branch
adds COPY's copy_prompt, copy_input and copy_done just above join_now, and
main (#2725) rewrote join_now's doc comment. Kept both: the COPY methods,
then main's two-line doc. The struct fields (copy_single, copies,
copy_array, ask_circle), SelectThen::new and the match arms merged without
conflict. No behaviour changed on either side.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:39:48 +07:00
2ez4gcxandClaude Opus 5.5 d290fc886f fix(doc, io): look linetypes, styles and layouts up by name through an index
Drawing::linetype, text_style, dim_style and layout scanned their table,
once per entity while a drawing is drawn, measured or saved, and once
per layout after every command. The DXF reader also scanned the
dimension styles once per DIMSTYLE record and the layouts by exact name
once per paper-space object. So a crafted file of N records and N
entities naming one it lacks, N DIMSTYLE records, or N layouts with N
objects in the last of them cost N^2 name comparisons (#1924, F-04
item 3): at N = 40 000 a PNG export took 23 s, opening 107-151 s or
more than 300 s on main.

- linetypes, text_styles, dim_styles and layouts are NamedLists (from
  #3484) and the four lookups use its index: the first entry of a name
  in list order, ASCII case folded, as the scan returned.
- NamedList::by_name_mut: the first entry of a name to change.
- Scans with the same answer go through the lookup (STYLE, DIMSTYLE,
  RENAME, -DIMSTYLE, .lin loading, COMPARE, COUNT, UCS, plotter, DXF
  header, Layers panel).
- The DXF reader indexes DIMSTYLE records by lower-cased name, and maps
  layout names (exact) to the first layout of that name once per pass.

Cost tests (doc: one per table; io: DIMSTYLE records and layouts) fail
on main at 66-421 s and pass within 3 s; a behaviour test compares
every lookup with a scan.

Part of #1924

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:02:33 +07:00
skylar taylor-barrick 12eef22768 Nightly: stop blocking a refused launch on macOS (#3537)
Nightly launch fix under Skylar's Exec 454: the Launcher's trailing `--` no longer reaches the file list where that applied, and a refused launch no longer blocks on macOS (the reason goes to stderr and the app exits 2).
2026-11-26 00:46:02 -06:00
FredApps 7c8f8ada92 Merge pull request #3536 from 2ez4gcx/fix/dwg-ltype-dash-count
DWG save: keep the first 255 dash elements of a linetype, and say so (part of #1923)
2026-11-26 07:43:27 +01:00
FredApps ba344a894b Merge pull request #2790 from 2ez4gcx/fix/join-other-height
JOIN: ends meet at the same height; objects facing the other way stay out
2026-11-26 06:13:20 +01:00
2ez4gcxandClaude Opus 5.5 b861b6c0a5 DWG save: keep the first 255 dash elements of a linetype, and say so
acadrust 0.6.6 writes and reads a DWG linetype's element count as one
byte, so a linetype of 256 elements came back from a DWG save with none
(continuous) and one of 300 with 44. The DXF read cap of #3482 lets 256
through, so every capped DXF linetype hit the 256 -> 0 case.

The DWG bridge text now writes at most 255 elements per linetype (the
first ones, with group 40 totalling them); DXF output is unchanged.
cadcraft_io::dwg_notes gives one note counting the linetypes cut, counted
by the writer so an xref linetype the file leaves out is not counted. An
engine hook installed by the apps echoes it and returns it in `warnings`
on every DWG write: QSAVE/SAVEAS, document.bytes, EXPORT, WBLOCK,
-WBLOCK, LAYOUT SAVEAS; cadcraft-cli convert prints it.

Part of #1923 (F-05).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 12:07:14 +07:00
FredApps c9260d1b59 Merge pull request #2740 from 2ez4gcx/feat/qleader
QLEADER at the command line, as AutoCAD 2024 runs it
2026-11-26 06:06:19 +01:00
FredApps d2587c694e Merge pull request #2487 from 2ez4gcx/fix/linetype-dash-layout
Linetypes: lay dashes out as AutoCAD does
2026-11-26 06:05:59 +01:00
FredApps a06b236f0c Merge branch 'main' into fix/join-other-height 2026-11-26 05:34:33 +01:00
FredApps 4a4b1e2339 Merge pull request #2906 from 2ez4gcx/fix/pedit-heights
PEDIT: polylines at their objects' height; Join only at the same height
2026-11-26 05:32:57 +01:00
FredApps b5481e3bbf Merge pull request #2725 from 2ez4gcx/feat/join-autocad
JOIN onto the source object as AutoCAD 2024 does: lines, arcs, and a polyline that keeps its handle
2026-11-26 05:32:42 +01:00
FredApps 7244d2bc96 Note QLEADER in the Leaders, tables, fields parity row
The command-line form lands in #2740 / #3532; the Settings dialog is still open.
Percentages and hours are not re-measured.
2026-11-26 05:30:16 +01:00
FredApps d8aa2c60dc Merge main into feat/qleader 2026-11-26 05:30:16 +01:00
FredApps b38215b7cf Merge main into fix/linetype-dash-layout 2026-11-26 05:30:04 +01:00
FredApps d955a3ccfc Clamp gap-first open-run dashes to the start of the run
In the x < 0 branch, a dash that starts slightly before p0 could push a
negative range. Keep the start at p0 (and the existing end cap at p0 + len).
2026-11-26 05:30:04 +01:00
aiongg b55abde2a8 Merge pull request #3449 from aiongg/minimal-port-next
CadCraft: move to craft-libs next (minimal port)
2026-11-25 23:16:50 -05:00
aiongg a3640199b6 Quit CADCraft asks about unsaved drawings again
muda's predefined Quit ends the process through terminate: without asking. The menu item
is craft-quit's Quit, a close request of the main window, so the close path asks first
as the close button does (#2157).
2026-11-26 03:48:00 +00:00
FredApps 91966ccc9d Classify qleader under NO_FILES for automation roots 2026-11-26 10:15:15 +07:00
FredApps 414e544282 Merge pull request #2760 from 2ez4gcx/fix/options-reset-profile
OPTIONS: reset restores every profile variable; a refused change leaves the drawing's snap and grid
2026-11-26 03:58:53 +01:00
FredApps b255d58275 Merge pull request #3491 from 2ez4gcx/fix/attrib-tag-matching
fix(doc,render,io,engine): match attributes to their definitions by tag in one lookup (part of #1923)
2026-11-26 03:54:12 +01:00
FredApps 1fb86ec415 Merge remote-tracking branch 'origin/main' into ic40-2740 2026-11-26 09:50:41 +07:00
FredApps 8a5bd99e46 Merge pull request #3482 from 2ez4gcx/fix/ltype-element-cap
DXF read: keep at most 256 dash elements per linetype (part of #1923)
2026-11-26 03:45:04 +01:00
skylar taylor-barrick cad62242eb Switch on supervised nightlies on the nightly-signer branch (#3522)
Supervised nightly switch-on, merged under Skylar's explicit Nightly 758 override after green CI, CodeRabbit on this head with no open threads, Sonar passing, and an independent adversarial review with no blockers.
2026-11-25 20:43:56 -06:00
FredApps bc5749ec18 fix(doc): order attribute tags instead of hashing them, so crafted tags can't collide on the web build
The web build's RandomState keys come from addresses, not entropy, so a
file could pick tags whose hashes collide and bring back the A x K cost
this change removes. Key the by-tag maps by the tag's ASCII-folded bytes
in a BTreeMap, as the layer and block name index (#3484) does. Matching
is unchanged: TagKey's order is consistent with eq_ignore_ascii_case.

Part of #1923.
2026-11-26 09:42:42 +07:00
FredApps 4cc0e1f19a Merge main into fix/attrib-tag-matching 2026-11-26 09:34:25 +07:00
FredApps 927108262a Merge pull request #3484 from 2ez4gcx/fix/open-name-lookups
fix(doc): look layers and blocks up by name through an index, so crafted files don't open in quadratic time
2026-11-26 03:33:57 +01:00
aiongg f99ae6956c A copy fired in a floating panel keeps the modifiers it was pressed with 2026-11-25 20:11:31 +00:00
aiongg b844248903 Floating windows carry the running channel's app id 2026-11-25 20:09:16 +00:00
aiongg 1cff8cd681 Repin craft-libs to storytold next 8fa4db64a9 and egui to b9770908e 2026-11-25 19:15:09 +00:00
aiongg 09944da2a4 Repin craft-libs to the hidden-window and modal-focus fixes (next + float-fixes) 2026-11-25 18:45:26 +00:00
aiongg 433e51abc4 Reset Panel Layout cancels a panel drag in progress again
As before the move to the craft-ui dock, a tab held while the layout
resets is not dropped into the reset layout. The reset replaces the
workspace, so its generation changes.
2026-11-25 18:29:18 +00:00
aiongg 53d1790348 Close tests: a close that goes ahead is checked without quitting
The tests assert CADCraft's own close decision for a saved drawing and
for a programmatic quit, as they did before the platform's quit joined
the close path, so they pass on macOS, where that quit cancels the window
close. Unsaved drawings still run the whole close frame.
2026-11-25 18:24:58 +00:00
aiongg f4c3018003 An opened panel's floating window comes to the front again
As before the move to the craft-ui dock, opening or activating a panel
with a command raises the floating window that holds it, once. Docked
panels only become the front tab.
2026-11-25 18:24:58 +00:00
aiongg 239f8a32f0 Repin craft-libs to the fix for windows that stay hidden (next + float-menu) 2026-11-25 18:19:04 +00:00
aiongg 9d214d6e88 Drawing focus comment: a click on a palette leaves the drawing focused 2026-11-25 15:50:21 +00:00
aiongg d26d9ca01f Repin craft-libs to storytold next aa401985d 2026-11-25 15:50:21 +00:00
aiongg c9286726ab Copy, Cut and Paste pressed in a floating panel reach the app 2026-11-25 15:15:06 +00:00
aiongg 138f447988 Ctrl+=, Ctrl++, Ctrl+- and Ctrl+0 change the interface scale
The keys (Cmd on macOS) step the Options interface scale by a tenth, within its limits, and Ctrl+0 sets it back to 100 %. They work while a text field or the command line has the keyboard, and a key the user gave to a command runs the command. In the browser they zoom the page.
2026-11-25 14:35:42 +00:00
aiongg e425c71c44 Enter and Space leave the drawing's right-click menus open 2026-11-25 14:20:12 +00:00
aiongg c3f691264a Repin craft-libs to storytold next d1bdf8e5da 2026-11-25 13:44:10 +00:00
aiongg aac7ae1cf2 A running command keeps Tab after a click on the palette or the status bar 2026-11-25 13:24:08 +00:00
aiongg 849e6fd5c4 The drawing takes the keyboard focus and keeps Tab while the command line has work for it
A press in the drawing, and a drawing that opens or becomes active, give the drawing the focus; a text field, a dialog
or a menu keeps it. The focused drawing keeps Tab (KeepKeys::Tab) only while a command runs, text is typed, value boxes
are live or a snap marker is under the cursor. A bare Tab with nothing focused is the framework's: capture_tab is gone.
2026-11-25 13:06:11 +00:00
aiongg 9e5889b782 Tab reaches the palettes from the document tabs
The drawing's host canvas is declared with the id of the drawing's own widget, so egui keeps the focus Tab gives it.
While the drawing is the focused Tab stop, the command line and the shortcuts take the keyboard as with nothing focused.
2026-11-25 12:38:02 +00:00
2ez4gcxandClaude Opus 5.5 3439895ec3 Vietnamese catalog: approved terminology and the 249 missing strings
Phase 1 of storytold/craft-i18n#401 for CADCraft's own vi.tsv.

- 44 existing rows: the 8 terms raised in #401 (14 rows), "nạp" for
  loading into CADCraft (8 rows), Boundary as "Đường bao" (2), the 17
  rows left in English (Find and Replace, Magenta, Working Set, Feet)
  and 3 rows kept consistent with them. "tỉ lệ" stays as spelled.
- 249 new rows, one for each string the translation_gaps report listed
  (Dimension Style Manager and dimension properties, keyboard shortcuts,
  right-click customization, Array dialog, UCS, ALIASEDIT, commands),
  grouped under comments. The report now prints "vi: nothing missing".
- ATTRIBUTION.md: the phase 1 changes were reviewed by a native
  Vietnamese speaker; older rows are not yet proofread in full.

Translations are written from the meaning of the English strings and
their use in the code (clean room).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 17:58:46 +07:00
2ez4gcxandClaude Opus 5.5 04c880e96f fix(doc): key the layer and block name index by the folded name, not a hash
The index mapped a hash of the case-folded name to the first entry of that hash, and scanned the
table when the entry's name differed. On wasm32-unknown-unknown, std's RandomState takes its keys
from a stack and a heap address (library/std/src/sys/random/unsupported.rs), so a crafted file
could pick colliding names and keep every lookup a full scan on the web build (review of #3484).

The index is now a BTreeMap from the name's bytes with ASCII letters lower-cased to the first
entry of that name. eq_ignore_ascii_case compares exactly those bytes, so a lookup returns what the
scan returns without a fallback, and costs O(log N) comparisons whatever the names are. Short
names are folded on the stack. Measured, one search costs about a scan of 100 names and a build
about 100-350 scans, so tables are indexed from 128 entries and after 256 scans since their last
change.

A new test builds the index alone and finds the first entry of every name: case variants, names
that differ after a long shared prefix, names of 64 bytes and longer, non-ASCII names and the empty
name. The cost test now uses 60 000 names and a 10 s bound (166.6 s on main).

Part of #1924 (F-04).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 16:39:36 +07:00
2ez4gcxandClaude Opus 5.5 a34ebd0bd0 Match attributes to their definitions by tag in one lookup (part of #1923)
One block reference with A attributes of a block with K attribute
definitions cost A x K tag comparisons wherever they are matched: the
extents (constant values a reference carries, the layer of an attribute
without its own), the renderer's constant values (per MINSERT copy), the
DXF writer (ATTRIB properties, MULTILEADER block-content values), BURST,
ATTSYNC/BLOCKREPLACE and the dynamic-grip preview. Crafted 16k x 16k and
32k x 32k files took 2-28 s to open, draw or save in a dev build.

TagKey compares and hashes a tag without ASCII case, as
eq_ignore_ascii_case does; Block::attdefs_by_tag and
Insert::attribs_by_tag keep the first definition or attribute of a tag,
as the scans' find/any did. Each site builds the map once and looks each
tag up once. Outputs of the crafted files are byte-identical.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 15:26:03 +07:00
aiongg c089fdff1a Paste tests that run only the shortcut table don't install the runtime (no drawing keeps the clipboard events in egui) 2026-11-25 07:19:23 +00:00
2ez4gcxandClaude Opus 5.5 3532ddf65e fix(doc): look layers and blocks up by name through an index, so crafted files don't open in quadratic time
Drawing::layer scanned every layer, and Drawing::block scanned every block when the exact name
missed. Both run once per entity while a drawing is read, measured and inspected, so a file with N
layers, or with N blocks and N references to blocks it doesn't have, opened in N² comparisons
(40 000 missing-block references: 75.7 s in a dev build; 40 000 layers: 6.8 s).

Drawing::layers is now a NamedList<Layer> and Drawing::blocks a NamedMap<Arc<Block>>. They read
and change as the Vec and BTreeMap they wrap, and keep an index from a keyed hash of the
case-folded name to the first entry of that hash. A hit is checked against the name and falls back
to the scan, so results are the same as before: same case rule, first match in table order, exact
block name first. Every change goes through DerefMut, which drops the index; a clone (undo
snapshot) shares it. The index is built only for tables of 64 entries or more, after 32 scans
since the last change, so code that changes a table between lookups costs what it did.

Part of #1924 (F-04).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 14:07:49 +07:00
2ez4gcxandClaude Opus 5.5 7867366a14 DXF read: keep at most 256 dash elements per linetype
An LTYPE record kept every dash element a DXF listed, while a .lin file
is capped at MAX_LINETYPE_ELEMENTS (256). The renderer clones the whole
linetype for every object drawn with it and walks the pattern on every
run, so a crafted 400,000-element pattern made a PNG export of 250
lines take 18-22 s on a dev build (8 s or less with this change; the
rest is the renderer walking 1M gap steps per line).

ltype_pattern now stops at the 257th element: the linetype keeps its
first 256 elements, the text and shapes of the dropped ones are not read,
and one read note counts the linetypes cut. Saving writes the elements
kept. A DWG reaches the reader as DXF but cannot carry more than 255
elements (one-byte count), so the cap does not fire there.

Part of #1923 (F-05).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 13:49:49 +07:00
aiongg ad1446c302 Allow egui::ComboBox: craft-libs next has no craft_ui::ComboBox 2026-11-25 06:47:06 +00:00
aiongg 7eb9401f08 cargo fmt 2026-11-25 06:40:11 +00:00
aiongg 69a040acc6 Merge main into the minimal port
Conflicts: Cargo.toml (kept the next/egui pins for every craft-libs entry, including main's new craft-csv and hayro-interpret/cmap/postscript patches), apps/cadcraft/src/main.rs (port's framework frame decision and apply_frame with main's os_window identity, persistence path and exit hook), crates/ui-egui/src/updates_ui.rs (next's argument-free check calls with main's check_updates_at_start gate). Main's new tests and dialogs switched to install_headless and escape_pressed.
2026-11-25 06:38:00 +00:00
aiongg 2282d11b37 Repin egui to storytold b15ffe9bfc (what craft-libs next pins) 2026-11-25 06:32:55 +00:00
aiongg d659315743 Repin craft-libs to storytold next 16001e7210 and egui to storytold b15ffe9bfc 2026-11-25 06:31:24 +00:00
2ez4gcxandClaude Opus 5.5 5bff714e00 ARRAY counts: withdraw the ARRAYEDIT measurement claim
b781f047 said AutoCAD 2024 was measured at ARRAYEDIT's columns, rows
and items. That measurement was made after the clean-room standard of
20 November (one agent session must not both operate AutoCAD and write
code), so the claim is withdrawn.

The module doc now lists only ARRAYRECT's rows and columns,
ARRAYPOLAR's items and rows, and -ARRAY's rows and items as measured.
The arrayedit_counts doc says ARRAYEDIT's counts go through the same
count() parser in crates/engine/src/cmd/array.rs, so they refuse and
take the same texts; no AutoCAD measurement of ARRAYEDIT is claimed.
Comments only: the test logic and the engine code are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 10:41:49 +07:00
2ez4gcxandClaude Opus 5.5 c4f139ac50 Merge main into fix/spline-closed-autocad
Conflict in crates/engine/tests/it/spline_options.rs, where both sides
appended tests: keep reverse_keeps_a_closed_spline_seam and main's SPLINE
CV method tests (#3456).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 09:02:43 +07:00
aiongg 9ea307ede8 Capture tests: frames run the app's raw input hooks; one geometry for the admission test
The capture rig ran note_raw_geometry alone, so the framework never got
the Options interface scale (FrameInput's Scale, given in before_input)
and egui's zoom stayed 1: the settled-scale test saw 800×600. It now runs
raw_input_hook and before_input, as the desktop app does.

The admission test reseeded the geometry for each request, an identity
change that the next drain rejects queued requests for; it now admits
all four against one geometry, so all four issue and stay undrained.
2026-11-24 19:28:13 +00:00
aiongg c125e9ebb8 Repin craft-libs to 9fd8b0cdaa; frame-only work and captures skip passes that will run again 2026-11-24 19:08:26 +00:00
aiongg ddee4e5bec Tests on next: clipboard rig without the runtime, wheel rig with the frame input, QuickCalc field under its panel, traversal from a focused control, left-edge drop case 2026-11-24 17:40:53 +00:00
aiongg 092ab07e66 Repin craft-libs to next-host-input 3ad64a26ea 2026-11-24 17:06:04 +00:00
aiongg 5195d9e5c8 Screenshots need no egui import on the web; iconic-column test reads the icons right of the drawing 2026-11-24 16:57:16 +00:00
aiongg 4f4a3e94b6 Tests: install the runtime in harnesses that run the app's UI; dock tests on next's model
Harnesses and bare contexts that run CadApp::ui install the runtime headless; rigs that
run the raw hook also run before_input. Dock tests use the workspace accessors, next's
action constructors and the tabs' accessible names; tests of the old renderer's hit rects,
divider ids and drag bar are removed.
2026-11-24 16:47:31 +00:00
aiongg 68de3797cc Host the craft-ui runtime from CADCraft's eframe App on craft-libs next
The runtime is installed in the desktop and web shells, before_input runs in the raw hook,
the close path decides in embed::logic, and the interface scale is the runtime's RootEnv
scale. The dock is next's DockArea over the saved workspace with CADCraft's panel bodies
and the drawing as its canvas group; ui.dock keeps its JSON vocabulary. Update dialogs run
on a DialogHost, the macOS title row is shell::TitleBar, screenshots use the runtime's
screenshot slot, and Escape with nothing focused is read as the window's cancel.
2026-11-24 16:47:31 +00:00
aiongg b6ee77e3ac Cargo.lock for the next pins (rustix 1.1.6) 2026-11-24 16:35:24 +00:00
aiongg 180ff4471d minimal-port rewrite: 99 edits (dock rename 43, combo 40, dock 10, split rename 3, deps 2, split 1) 2026-11-24 16:27:10 +00:00
aiongg 8fe5682b63 minimal-port repin: 35 edits (revs 30, features 5) 2026-11-24 16:26:54 +00:00
2ez4gcxandClaude Opus 5.5 bc976e9bde Merge main into fix/pline-undo-plinewid
Conflict in crates/engine/src/cmd/draw/line_pline.rs PlineM::begin():
keep main's drawing elevation (#3423) and the branch's PLINEWID start
widths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 08:57:36 +07:00
2ez4gcxandClaude Opus 5.5 b781f04784 ARRAY counts: test ARRAYEDIT's counts and the MAXARRAY bounds
ARRAYEDIT's columns, rows and items, measured in AutoCAD 2024's core
console, refuse 5.0, 5., 4.5, 1e1 and 8/2 and take +5, 05 and 5, as the
other count prompts do. A count runs from 1 to the MAXARRAY limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 21:19:36 +07:00
2ez4gcxandClaude Opus 5.5 c40fc740ab Merge main into fix/array-count-integer
Conflict in crates/engine/tests/it/main.rs: keep both array_counts and
main's array_key_point (#2368).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 19:21:22 +07:00
2ez4gcxandClaude Opus 5.5 fb20f102df Merge main into fix/spline-closed-autocad
Conflict in crates/io/src/dxf_read/entities.rs: keep the branch's
keeps_closing_tangent() and main's hatch curve budget parameter (#3306).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 18:06:39 +07:00
2ez4gcxandClaude Opus 5.5 ee13c648df Merge main into fix/linetype-dash-layout
Conflict in crates/render/src/wide.rs dashed(): keep main's point budget
for segments() (#3306) and the branch's closed PLINEGEN anchor.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 17:34:35 +07:00
2ez4gcxandClaude Opus 5.5 62a1a23288 Prompt: declare NO_OR as a slice
This PR and #2915 each add a prompt to NO_OR and raise its array length
from 28 to 29, so with both merged the array holds 30 entries under a
length of 29 (E0308), whichever lands first. A slice has no length to
keep in step; both PRs make the same change to this line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 09:06:54 +07:00
2ez4gcxandClaude Opus 5.5 12b7742384 JOIN: set the new polyline's elevation without with_z
#2548 rewrites BREAK and deletes with_z; with both PRs in, this branch's
call to it no longer compiled (E0425), whichever landed first. Set the
elevation on the polyline lwpoly() makes instead: the same value, and
nothing of this branch depends on with_z any more.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 08:59:04 +07:00
2ez4gcxandClaude Opus 5.5 927a417255 Merge branch 'fix/spline-file-tangent-length' into fix/spline-closed-autocad
Brings chord_interpolate's start-condition row ahead of the fit-point
rows, so its system stays banded. chord_closed builds closed chord fits
through it: control points are bit-identical, and a closed fit of 1,000
points took 17.4 -> 3.2 ms (dev profile).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 08:02:36 +07:00
2ez4gcxandClaude Opus 5.5 fc838dce98 SPLINE: assemble the chord fit's start condition before its points
chord_interpolate added the start tangent or zero-curvature row after
all the fit-point rows, so its column-0 entry sat in row n and solve
swept the whole width. With the start row first, the system has a lower
and upper bandwidth of at most two. The control points come out
bit-identical; a fit took 17.5 -> 4.4 ms at 1,000 points and
414 -> 135 ms at 4,000 (natural ends, dev profile).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 07:58:59 +07:00
2ez4gcxandClaude Opus 5.5 a1142566b8 SPLINE: assemble the chord fit's start condition before its points
chord_interpolate added the start tangent or zero-curvature row after
all the fit-point rows, so its column-0 entry sat in row n and solve
swept the whole width. With the start row first, the system has a lower
and upper bandwidth of at most two. The control points come out
bit-identical; a fit took 17.5 -> 4.4 ms at 1,000 points and
414 -> 135 ms at 4,000 (natural ends, dev profile).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 07:28:58 +07:00
2ez4gcxandClaude Opus 5.5 db8f6cc6e4 Merge main into fix/spline-fit-autocad
Main's banded solve came with a dense-solver oracle test whose cases all
use chord-length knots; on this branch those go through
chord_interpolate, so the test no longer reached interpolate. Extend it
with square-root and uniform knots, with and without end tangents, and
a 1000-point square-root fit (the same change as on
fix/spline-file-tangent-length).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 07:08:12 +07:00
2ez4gcxandClaude Opus 5.5 4b76e4a305 Merge branch 'fix/spline-file-tangent-length' into fix/spline-closed-autocad
Brings in main f9c0c96e. Main's clippy-pedantic refactor of
spline_fit.rs conflicted in three places: fit_sanitized takes main's
if-let form and keeps closed_fit's tangent argument, closed_fit keeps
main's #[expect] on its four-parameter signature, and the closed
tolerance test keeps main's bit-exact assert with this branch's comment.

Closed chord-length fits go through chord_closed on this branch, so the
dense-solver oracle's comments say so, and an n=150 closed square-root
fit keeps the large cyclic matrix compared.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 06:24:09 +07:00
2ez4gcxandClaude Opus 5.5 17888ad5c6 Test the dense-solver oracle on interpolate's fits too
With chord-length knots, open fit-point splines are now built by
chord_interpolate, so fits_are_bit_identical_to_the_dense_solver no
longer reached interpolate (a panic there left the test passing). Add
square-root and uniform knots, with and without end tangents, and a
1000-point square-root fit, so interpolate's matrices, its tangent rows
and the closed cyclic interpolation stay compared with the dense solver.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 06:01:28 +07:00
2ez4gcxandClaude Opus 5.5 0edd056e8e Merge main into fix/spline-file-tangent-length
Main's clippy-pedantic refactor of spline_fit.rs restyled the body of
Spline::fit_with; this branch had moved that body into fit_sanitized.
Keep the split and apply main's if-let form inside fit_sanitized.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 05:30:27 +07:00
2ez4gcxandClaude Opus 5.5 74c183415b Merge main into fix/linetype-dash-layout
Brings the branch up to main ca87680f. The one conflict is in
crates/render/src/linetype_text.rs, texts(): main's #2744 adds a point
allowance for the labels of a run, and this branch starts the run a period
before its start. Both are kept: the allowance is charged for each label
placed, and elements before the run's start are skipped before any charge.
Main's new test placed_labels_stop_at_the_point_allowance now passes the
Layout argument this branch added to texts().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 11:54:27 +07:00
2ez4gcxandClaude Opus 5.5 67c78743dd DXF: write the closing fit point after a closed list ending with its first
The reader drops one closing fit point from a closed spline, so the writer
now adds one whenever the reader will drop one: also after a list that
already ends with its first point (a kink where it closes, as a file can
give it). Before, [A, B, C, A, A] came back as [A, B, C, A], and a later
fit-point edit smoothed the seam. Three points ending with the first are
still written as they are, since the reader keeps them so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 13:56:20 +07:00
2ez4gcxandClaude Opus 5.5 45300ee3a2 Merge main into fix/pedit-heights
Brings the branch up to main 6d744887, which has #2954's fix for
mtext::tests::strips_formatting, so the gate runs on a main that passes.
No conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 12:52:16 +07:00
2ez4gcxandClaude Opus 5.5 d6dc7131c3 Merge main into fix/spline-closed-autocad
Brings the branch up to main 6d744887, which has #2954's fix for
mtext::tests::strips_formatting. The one conflict is in
crates/geom/src/nurbs.rs, where main makes the derivative allocation-free
(#2434, basis_pair_into) and this branch adds reversed_loop. The merged
file is main's plus exactly this branch's own lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 11:08:03 +07:00
2ez4gcxandClaude Opus 5.5 96e62b4632 PEDIT Join: only objects in one plane with the polyline, as AutoCAD 2024
AutoCAD 2024 joins only objects that lie in one plane with the polyline:
the plane the polyline and every line picked share, if they share one,
else the polyline's own. Measured: a triangle at Z 5 whose last side slopes
to Z 0 leaves that side out; a sloped line followed by a line turning off
their vertical plane joins neither; a sloped line followed by an arc joins
the line only. Before, a sloped line joined wherever its end met the chain
at the same height.

Also, after review: tests for the sloped line drawn either way, a chain
meeting its start at another height, arcs below Z 0 and mirrored above it,
thickness, the joined polyline's normal and bulges, fuzz in plan only, and
an exact pick on the arc; doc comments for the plane rule, the height
tolerance and tilted arcs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 04:04:46 +07:00
2ez4gcxandClaude Opus 5.5 e20f5ed590 PEDIT: polylines at their objects' height; Join only at the same height
PEDIT turned a line or an arc into a polyline at elevation 0, so a line at
Z 5 dropped to Z 0, and its Join took any object meeting the polyline in
plan. As AutoCAD 2024 does (measured):

- Convert puts the polyline at the line's height or the arc's centre
  height and keeps the thickness; a line's polyline faces up whatever the
  line's normal, a mirrored arc's keeps its normal and runs as the arc
  does in its own coordinates.
- PEDIT's Join takes an object only where the ends meet at the same
  height, and none facing the other way (an arc or polyline whose normal
  points down Z where the polyline's points up, or the other way round;
  a line counts as facing up). After a sloped line, the chain continues
  from its far end's height.
- Multiple's Join leaves out objects facing the other way too, but takes
  them at any height.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 21:19:21 +07:00
2ez4gcxandClaude Opus 5.5 6133dc60bb JOIN: a new polyline stays at the source's height
JOIN made the new polyline from a line or arc source at elevation 0, so
lines at Z 5 moved down to Z 0. It now takes the source's height, as a
polyline source keeps its elevation with a sloped line joined to it
(AutoCAD 2024, measured), negated when the polyline inherits a normal
pointing down Z. The new polyline itself wasn't measured: the core
console's JOIN never makes one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 09:02:04 +07:00
2ez4gcxandClaude Opus 5.5 8b1adcd8d5 MINSERT: test that JSON null counts and distances are taken as missing
A null rows or columns is 1 and a null rowSpacing or columnSpacing is 0,
as when the key is missing. Each count is tested null on its own; the
distances on a 2 x 2 grid, since one row or column drops its distance
anyway.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 23:39:33 +07:00
2ez4gcxandClaude Opus 5.5 19dcf74419 JOIN: ends meet at the same height; objects facing the other way stay out
JOIN compared chain ends in plan only, so an end meeting another only in
plan at another height was joined and collapsed onto the source's
elevation. Each piece now carries its ends' world heights (a line's own
Z, an arc's centre Z, a polyline's elevation, negated when its normal
points down Z), turned round with the piece, and ends must meet at the
same height too.

Onto a polyline source, an object facing the other way stays out: an arc
or a polyline faces its normal, a line always counts as facing up.
AutoCAD 2024 (accoreconsole, measured) joins a line with normal 0,0,-1
to a polyline facing up, no line to a polyline facing down, and an arc
or polyline only when it faces the polyline's way. A line or arc source
keeps the old behaviour: the core console can't measure it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 23:18:18 +07:00
KnottyDyesandClaude Opus 5.5 b573490901 Docs: qualify the README DWG read claims
The format-parity table marks R13 and R14 DWG reading as untested and
2018 as tested only on synthetic files; say the same in the README.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:13:35 -07:00
KnottyDyesandClaude Opus 5.5 5f4c2ed819 Docs: SAVEAS version overrides the kept version and is remembered
Say so wherever the docs describe a drawing keeping its own version,
as file-format-parity.md already does: save_as writes an explicit
version into $ACADVER, so later saves use it too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:13:35 -07:00
KnottyDyes 203ed93f51 Docs: describe DXF and DWG save-version selection 2026-11-04 09:13:35 -07:00
2ez4gcxandClaude Opus 5.5 20a9ac7433 MINSERT: JSON rows and columns are whole numbers
The JSON form read rows and columns as numbers with no fraction, so 2.0 and
1e2 were counts. They must now be JSON whole numbers from 1 to 32767, as the
array commands' JSON counts already are; missing or null is still 1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 22:08:20 +07:00
2ez4gcxandClaude Opus 5.5 22b2f7a5a9 Merge main into feat/copy-autocad; NO_OR is 29 long
main and this branch each added a row to NO_OR in prompt.rs ("Enter
option" and "Enter a copy mode option") on top of the same 27, and both
declared 28; the merge has 29 rows, so the declared length is now 29.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 20:51:41 +07:00
2ez4gcxandClaude Opus 5.5 ca3ff7997f INSERT/MINSERT: take points at the scale, rotation and spacing prompts
These prompts ignored a point. AutoCAD 2024 (measured on INSERT and
MINSERT) takes one as the first of two at the Scale, X, Y, Z and Rotate
presets and at MINSERT's column spacing, asking "Specify second point:"
(the distance is the scale or spacing, the direction the rotation; Enter
there keeps a preset's default); at XYZ's Z a point gives its distance from
the insertion point; Y scale refuses a point. They now do the same, with
AutoCAD's messages at each prompt ("Value must be nonzero.", "Requires
numeric distance or two points.", "Requires valid numeric angle or two
points.", "Requires numeric distance or second point.", "Requires numeric
value."). Exploded INSERT's scale takes a positive number only ("Value must
be positive and nonzero."). The Rotate preset still reads typed text as an
angle, so <<45 stays 45 degrees.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 20:33:17 +07:00
2ez4gcxandClaude Opus 5.5 a113667951 ARRAYPATH: no extra item where a closed path closes, by spacing
The JSON spacing form made floor(length / spacing) + 1 items on every path,
so on a closed one the last sat on top of the first (or nearer to it than
the spacing). AutoCAD 2024 fills a closed path with floor(length / spacing)
items and an open one with one more, at its end (measured with Fill entire
path on a closed and an open square and a circle). The spacing form now does
the same, letting length / spacing fall 1e-9 short for rounding.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 19:46:34 +07:00
2ez4gcxandClaude Opus 5.5 8af4b8a61b DIVIDE: take a whole number as typed for the number of segments
The count was read as a number with no fraction, so 5.0, 5. and 1e1 were
taken; a point gave its distance from the pick as the count; and Enter ended
DIVIDE. AutoCAD 2024 takes +5, 05 and 2 to 32767, and refuses all of those,
and 4.5, 1, 32768 and x, with "Requires an integer between 2 and 32767, or
option keyword." ("...32767." once Block has been chosen) and asks again
(measured). DIVIDE now does the same. MEASURE, which shares the prompt
machine, is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 19:05:56 +07:00
2ez4gcxandClaude Opus 5.5 223beb2fb8 SPLINEDIT: take a whole number as typed for Elevate order
"Enter new order" took a number with no fraction from 1 to 1000, so 5.0 and
1e1 were taken, and a point went back to the vertex menu without a word.
AutoCAD 2024 takes +5 and 05, keeps the order on 4 (a cubic's), and refuses
5.0, 5., 1e1, 4.5, 3, 27 and a point with "Requires an integer between 4
and 26."; the range starts at the spline's own order (measured at orders 4
and 5). The prompt now does the same, and the JSON form's elevate uses the
same wording. The prompt's logic moves to input_order(), which keeps
SplineditM::input under clippy's complexity limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 19:02:20 +07:00
2ez4gcxandClaude Opus 5.5 20463574de COPY: MAXARRAY doesn't limit Array; refuse a point at the count
AutoCAD 2024 doesn't apply MAXARRAY to COPY's Array: with MaxArray 100000,
four lines and 26000 items made 104000 lines. The count is now 2 to 32767
whatever the selection, as AutoCAD asks it. A point at "Enter number of
items to array:" was ignored; AutoCAD refuses it with "Requires an integer
between 2 and 32767." (measured with a LISP point), and so does COPY now.

So that a large selection can't run out of memory, the copies (items after
the first, times the objects) stay within MAX_ARRAY_ITEMS, ARRAY's own limit
whatever MAXARRAY says, checked before anything is made.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 17:35:30 +07:00
2ez4gcxandClaude Opus 5.5 b44d5c3588 ARRAYPATH: refuse a JSON count or spacing it can't use
The JSON form read `count` with as_u64 and `spacing` with as_f64 and quietly
dropped what didn't fit: a count of 4.5, "8" or -3 made the default 6 items,
0 made 1, and a spacing of 0, -5 or "10" fell back to the count. They are now
refused as the other arrays' JSON forms refuse them: the count goes through
count_or (a whole number of at least 1) and the spacing through size_param (a
positive number). Missing or null keeps the defaults.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 16:50:40 +07:00
2ez4gcxandClaude Opus 5.5 35462869e6 SPLINEDIT: take a whole number as typed for the polyline precision
"Specify a precision <10>:" read a number from 0 to 99 and rounded it, so
5.0, 5. and 4.5 were taken. AutoCAD 2024 refuses those, and 1e1, 8/2, 100,
-1 and a point, with "Requires an integer between 0 and 99." and takes +5
and 05 (measured). A point used to convert with precision 10; it is now
refused too.

The JSON form clamped `precision` to 99 and read any other value as 10. It
now refuses a precision that isn't a whole number from 0 to 99; absent or
null is still 10.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 16:15:17 +07:00
2ez4gcxandClaude Opus 5.5 cf90a60626 MINSERT: take a whole number as typed for the rows and columns
The row and column counts were read as a number with no fraction, so 5.0,
5. and 1e1 were taken. AutoCAD 2024 refuses those with "Requires an integer
between 1 and 32767." and asks again, and takes +3 and 03 (measured at the
rows, and 5.0 and +3 at the columns). A point at these prompts was ignored
without a message; AutoCAD refuses it with the same message (measured with
a LISP point at the rows).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 15:39:35 +07:00
2ez4gcxandClaude Opus 5.5 81f8032255 OPTIONS: a refused change puts the same drawing back
Writing the header entries back went through doc_mut, whose copy on
write gave a clean drawing a new Arc, so a refused OPTIONS call marked
it changed. apply now keeps the drawing's Arc when SNAPUNIT or GRIDUNIT
is among the values and puts that same Arc back on a refusal; a call
that names neither never touches the drawing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 13:43:33 +07:00
2ez4gcxandClaude Opus 5.5 1d16e82a49 ARRAYPATH: the item count takes a whole number as AutoCAD 2024 does
"Enter number of items along path" read the count as a distance and cut
it to an integer, so 4.5 gave 4 items and 1e1, 8/2 and 3' were taken.
AutoCAD 2024 takes a whole number from 1 to 32767 in plain decimals
there (5, +5, 05, 5., 5.0) and refuses 4.5, 1e1, 8/2, 3', 0 and 32768
(measured); the count is now read the same way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 13:02:19 +07:00
2ez4gcxandClaude Opus 5.5 8ecf3e6cac ARRAY: counts take a whole number as typed, as AutoCAD 2024 does
The ARRAYRECT, ARRAYPOLAR, -ARRAY and ARRAYEDIT count prompts read a
number with no fraction, so they took 5.0, 4. and 1e1. AutoCAD 2024
refuses those, and 8/2, 3' and 4.5, and takes +3 and 03 (measured at
ARRAYRECT's rows and columns, ARRAYPOLAR's items and rows, and -ARRAY's
rows and items). The count is now read as a whole number.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 12:22:19 +07:00
2ez4gcxandClaude Opus 5.5 ab71b353d5 OPTIONS: reset puts every profile variable back; a refused change leaves the drawing's snap and grid
options::reset missed 15 profile variables (the Dynamic Input, selection
preview and area, grip, PICKSTYLE and MEASUREINIT settings), so a reset
left them as they were. It now restores all of them; SNAPUNIT and
GRIDUNIT, which the drawing keeps in its header, are still left alone.

apply is all or nothing, but a refused value left SNAPUNIT and GRIDUNIT
written to the drawing's header. Their raw header entries are now put
back as they were, or removed when the drawing didn't have them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 11:54:04 +07:00
2ez4gcxandClaude Opus 5.5 02dfd37d14 Merge main into fix/linetype-dash-layout
main added SHX shapes to complex linetypes in linetype_text.rs; this
branch lays linetype elements out with Layout and phase. Both are kept:
shapes go where texts and dashes go (centred on an open run), and
main's point budget counts only the elements placed. main's shape test
now expects the centred positions, as the text test does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:35:44 +07:00
2ez4gcxandClaude Opus 5.5 43207db68e QLEADER: refuse a width that overflows; name an unreadable JSON point
A width given by a point far enough away to overflow is refused with the
message typed text gets, and the width is asked again. In the JSON form, a
point that can't be read says so instead of saying `points` is missing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 05:02:43 +07:00
2ez4gcxandClaude Opus 5.5 69b214743d COPY: pin +3 and 03 at the array count, as AutoCAD 2024 takes them
AutoCAD 2024 takes "+3" and "03" at "Enter number of items to array:"
(measured: three items each), which the count's integer parse already
does. Say so in the comment and test it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 04:38:00 +07:00
2ez4gcxandClaude Opus 5.5 3c9b4be339 JOIN: whole objects by their ends, the circle question, the source's space
Measured in AutoCAD 2024's core console:
- Objects join whole, by their end points; a polyline is never split, and
  one met only at an inner vertex stays as it is. The source is the first
  pick JOIN can take (a circle picked first is passed over).
- Where an object meeting the chain at more than one place goes: a
  polyline by its first vertex if it can, before the chain rather than
  after; a line or an arc turned round if it can. A source that already
  ends where it starts still takes more; a join that closes the chain
  stops it; a source of no length takes nothing; a lone polyline whose
  ends meet stays open.
- Arcs that come round make a circle with no tolerance at the source's
  start, and the command line asks "Combined arc segments form a circle.
  Convert to circle? [Yes/No] <Yes>:" first; No leaves the arcs. The JSON
  form takes the default.
- A new polyline keeps another polyline's widths, and what JOIN makes
  goes in the source's space.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 04:36:45 +07:00
2ez4gcxandClaude Opus 5.5 762b64268b QLEADER at the command line, as AutoCAD 2024 runs it with its default settings
Up to three leader points, a text width (not remembered; a point gives its
distance from the leader's end), then lines of multiline text. The text
sits DIMGAP past the end: with the middle of its first line level with it
when the leader runs right (attachment 1), of its last line when it runs
left (attachment 9), whatever DIMTAD. A hook line DIMASZ long is added when
the last segment slopes and text follows. Enter at the first line leaves
the leader alone. Measured in AutoCAD 2024's core console. Alias LE, and a
JSON form.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 03:32:55 +07:00
2ez4gcxandClaude Opus 5.5 c2b2545d0a COPY: the array count takes digits only; mOde Enter keeps the mode shown; reset COPYMODE
AutoCAD 2024 refuses 4.0, 1e1, 8/2, 1' and 3" at "Enter number of items
to array:" (measured), so the count is read as digits, not as a number
with no fraction. Enter at the mOde prompt now runs COPY in the mode the
prompt shows, and OPTIONS reset puts COPYMODE back to 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 02:55:48 +07:00
2ez4gcxandClaude Opus 5.5 c36cc6af34 SPLINE: a closed spline keeps its seam and its tangent where it closes
Review of #2705: REVERSE turned a closed spline's whole fit list round
while the curve still started at the old first fit point. The DXF
writer, which writes a closed spline's fit points from the first one,
then wrote another seam, and the next fit-point edit moved it.

Measured with AutoCAD 2024 (accoreconsole) on SPLINE (0,0) (4,0) (6,3)
(1,4) Close:
- REVERSE keeps the first fit point first and turns the others round
  ([f0, f3, f2, f1]); it turns the tangent where the curve closes
  (12/13) round and reverses the control points and knots;
- SPLINEDIT Fit data Move, Delete (of the first fit point too) and
  Open keep that tangent instead of working it out again from the
  points.

So a closed fit spline with chord-length knots now keeps its tangent
where it closes as both end tangents, as AutoCAD keeps 12/13:
- refits, grips and SPLINEDIT take it;
- `Spline::reversed` keeps the seam first and turns the tangent round;
- the DXF reader keeps it for such a spline, and drops the curve's own
  tangents that the writer gives the others (periodic knots, a fit
  tolerance, a kink);
- SPLINEDIT Close still gives the closed curve its own tangent.
A new closed spline still ignores the tangents given with it.

Also:
- a closed kinked fit stores its fit points from the kink where the
  curve starts;
- the closing tangent is divided by its length, not normalised, so a
  short one is not a zero tangent;
- AutoCAD's 44 = 1e-10 (no fit tolerance) is read as 0, and a tolerance
  too tight to approximate with gives AutoCAD's chord-length build, as
  for an open spline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 01:54:22 +07:00
2ez4gcxandClaude Opus 5.5 03c8bac609 SPLINE: two fit points with a fit tolerance make the same cubic
AutoCAD 2024 builds a chord-length spline through two points as the cubic
with control points at the thirds whatever the fit tolerance (measured with
tolerance 1: the same control points and knots as with 0, only group 44
differs). The tolerance no longer turns it into a line. The comment on the
interpolation fallback now says what was measured, and the test compares
the result with the tolerance-0 fit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 01:36:48 +07:00
2ez4gcxandClaude Opus 5.5 a9a3b35c91 feat(engine): COPY with COPYMODE, Multiple/mOde, Array and Fit as AutoCAD 2024
COPYMODE (profile, 0 copies until Exit, 1 makes one copy) and the base point
options mOde (sets it) and Multiple (this command only). Enter at the first
second point copies by the base point taken as a displacement. Array asks for
2 to 32767 items, the original included, and spaces them a second point apart
or, with Fit, up to it; Undo takes back the last placement, an array at once.
MAXARRAY caps an array's copies as it caps ARRAY's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 23:38:46 +07:00
2ez4gcxandClaude Opus 5.5 6c81995e03 fix(engine): JOIN onto the source object as AutoCAD 2024 does
Lines on the source's line make it one longer line and arcs on its circle
join counterclockwise from its start, both keeping the source's handle;
arcs that come round to within 1e-6 rad of its start make a circle on the
source's layer. An open polyline source keeps its handle, its own vertices,
elevation, PLINEGEN and (with only lines and arcs) constant width; other
polylines keep their bulges and widths, lines and arcs take the widths of
the source's vertex at that end. The tolerance is AutoCAD's measured 1e-6,
absolute at any coordinate size. The message names a line, arc or circle.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 23:23:26 +07:00
2ez4gcxandClaude Opus 5.5 99ae84f39c SPLINE: the preview adds no fit point with the cursor on the last one
A click on the last fit point adds nothing, but the preview still added
the cursor there, so it showed a corner the command would not make.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 21:34:08 +07:00
2ez4gcxandClaude Opus 5.5 04b56c4f4a Test the fit-option DXF roundtrip over the whole spline
Chord-length knots now run to the fit points' length rather than 1, so the
roundtrip check sampled only the first part of those splines. It now
samples the spline's own domain and checks the domain survives the file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 20:53:28 +07:00
2ez4gcxandClaude Opus 5.5 cbf79599e2 STRETCH: a fit-point spline moves its fit points and is fitted again
AutoCAD 2024 (accoreconsole, entget after STRETCH of a spline stored with
fit points only) moves the fit points inside the area and fits the spline
through them again, keeping its fit data (70 = 1064, 74 = 4); with all of
them inside, it moves whole. Here such a spline moved whole by its first
grip, or not at all. The test pins AutoCAD's fit points for three windows:
the last fit point, a middle one, and the whole spline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 20:38:34 +07:00
2ez4gcxandClaude Opus 5.5 de9f9ccc93 RECTANG: test corners at the limit where they still fit
AutoCAD 2024 (accoreconsole, entget of a 4 by 2 rectangle) keeps corners
exactly as long as the shorter side allows: fillet 1, and chamfer 1 + 1 or
1.2 + 0.8, still fit. A hair longer (fillet 1.0001, chamfer 1.2 + 0.81) and
the corners stay square, each still written twice. The rule already matches;
this pins the six measured rectangles, including which way the two chamfer
distances run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 20:35:08 +07:00
2ez4gcxandClaude Opus 5.5 25afec0fa9 Merge main into fix/stretch-arcs-bulges-splines
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 19:53:36 +07:00
2ez4gcxandClaude Opus 5.5 1b16f3caeb Merge branch 'fix/spline-file-tangent-length' into fix/spline-closed-autocad
Stacks the closed fit-spline change on the DXF tangent-length one (#2703).
Both change the SPLINE reader; the merged reader keeps both rules:

- an open spline keeps a file's 12/13 tangents with their length and is
  rebuilt from fit data with them as the end derivatives (#2703);
- a closed spline drops AutoCAD's closing fit point and takes its
  closing tangent from the curve, not from 12/13.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 18:48:24 +07:00
2ez4gcxandClaude Opus 5.5 8178e578c2 SPLINE: a small uniform scale keeps a spline's end tangents
`transform` dropped a tangent that the map shrank to under EPS of the
tangent's own length. So SCALE 1e-10 lost a (100, 0) tangent, although
the map is invertible.

The check now compares with the map's largest axis scale. An invertible
uniform scale, however small, keeps the tangent. A singular map, or one
that squashes the direction to under EPS of that scale, still drops it.
`scale_factor` (sqrt |det|) would not do: it is 0 for a singular map, so
rounding noise would survive as a direction.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 18:46:22 +07:00
2ez4gcxandClaude Opus 5.5 fe1c3eeeab SPLINE: a tangent too short to normalise is dropped, not zero
`sanitized` kept tangents longer than 1e-12, but `Vec2::normalized`
returns zero up to 1e-9, so a direction between the two was stored as
Some(ZERO): a zero end derivative instead of no tangent. Such a direction
is now dropped.

`transform` scales a tangent by the lengths instead of going through
`normalized`, so a short tangent from a file survives MOVE, ROTATE, SCALE
and MIRROR. A map that flattens its direction still drops it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 18:00:43 +07:00
2ez4gcxandClaude Opus 5.5 93e2255722 SPLINE: closed fit-point splines built as AutoCAD 2024 builds them
A closed spline through fit points with chord-length knots and no fit
tolerance is now the cubic AutoCAD 2024 builds (measured with
accoreconsole): the open chord-length interpolation through the fit
points and back to the first, clamped, with the same unit first
derivative at both ends. That tangent is the derivative at the first
point of the cubic through the first four points of the loop, with
square-root-of-chord parameters.

AutoCAD flags this spline periodic (group 70 bit 2) although its knots
are clamped: it sets the bit from the curve, the same first derivative
where it closes. `Spline::is_periodic` now means that (closed and smooth
where it closes); the knot shape it meant before is `Spline::wraps`
(unclamped knots, control points wrapping round), which SPLINEDIT uses
for its control-point edits.

DXF: AutoCAD rebuilds a spline with fit data from its fit points and end
tangents, and opened a closed spline written with its fit points once
as an open spline. The writer now adds the first fit point again at the
end and the tangent where the curve closes as 12 and 13, as AutoCAD
writes it; the reader drops the closing point and takes the tangent from
the curve. AutoCAD reads the written spline back as its own (70 = 1067,
the same control points).

Closed splines with square-root or uniform knots, or a fit tolerance,
are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 17:44:41 +07:00
2ez4gcxandClaude Opus 5.5 5513565da9 SPLINE: a file's end tangents count with their length, as in AutoCAD 2024
A DXF SPLINE stored with fit points and 12/13 tangents only is rebuilt
with each stored vector as its end derivative, length included: AutoCAD
2024 does so (12 = (0, 3) gives control points 2.67 from those of the
unit (0, 1)). The spline keeps the vector, so it is written back as read.
Refits (grips, SPLINEDIT, STRETCH) use it as stored, and transforms turn
it and keep its length, as AutoCAD's MOVE, ROTATE, SCALE, MIRROR and
SPLINEDIT Fit data Move do.

SPLINE, SPLINEDIT and the JSON options still take tangents as unit
directions: fit_with normalises them, and SPLINEDIT's input is already
normalised.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 17:13:41 +07:00
2ez4gcxandClaude Opus 5.5 9a6f025c47 SPLINE: open fit-point splines built as AutoCAD 2024 builds them
An open spline through fit points with chord-length knots and no fit
tolerance is now the cubic AutoCAD 2024 builds (measured with
accoreconsole, `entget` of the control points and knots):

- the knots are the running chord length, not normalised, with the fit
  points' own parameters as the interior knots;
- there are two control points more than fit points: an end with a
  tangent has it as its first derivative, an end without one has no
  second derivative (with one tangent too);
- two fit points without tangents make a cubic with its control points
  at the thirds, no longer a line.

SPLINE also leaves out a click on the point before, as AutoCAD does,
instead of storing a repeated fit point (a kink).

Closed splines, the other knot parametrisations and fit tolerance are
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 16:28:16 +07:00
Aldo ZarateandClaude Opus 5.5 06491fc757 Merge upstream/main into perf/cjk-text
ttf.rs keeps both test modules: the thread cache's and main's font
directory scan.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 22:03:34 -06:00
2ez4gcxandClaude Opus 5.5 897f53c7b3 Merge main into fix/linetype-dash-layout
After #2603, dashes are laid out only with Options::linetypes on: the
runs stroked with a layout (open, or closed from an anchor) and the
polyline centre line keep that check, so hit tests still draw lines
whole.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 07:40:25 +07:00
2ez4gcxandClaude Opus 5.5 97b531eaae RECTANG: Area with cut corners, oversized corners, Rotation as AutoCAD takes it
Three rules measured in AutoCAD 2024 that main's RECTANG does not follow:

- Area sizes the rectangle so that its outline, corners cut, encloses the
  area: _C 1.5 2.5 ... _A 1442.93 _W 35.535 has length 40.817, the
  area plus 2 x 1.5 x 2.5 over the width; a fillet adds (4 - pi) r^2.
  When the corners then don't fit, they stay square and the area is
  the full rectangle's.
- A fillet or chamfer too large for the shorter side leaves each corner
  as two coincident vertices, eight in all, as AutoCAD stores them.
- A typed Rotation is an amount turned in the ANGDIR sense from +X,
  ANGBASE aside: with ANGBASE 90 and ANGDIR 1, 30 turns the rectangle
  30 degrees clockwise. The modes line and the prompt's default show it
  as the drawing shows angles: "Rotation=120.00", "30d30'" with AUNITS 1.

The fit test is one function, shared by the vertices and Area. Of the
40 measured cases that set every mode, main's RECTANG matches 33; this
matches all 40.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 10:59:37 +07:00
2ez4gcxandClaude Opus 5.5 b872742e42 Merge main into the RECTANG fix, keeping #2554's RECTANG
#2554, now in main, rewrote RECTANG's vertex order, corners and
remembered modes along the same measurements as this branch. The
conflicts are resolved by taking main's RECTANG as it is. The next commit
brings back, on top of it, the rules this branch measured that #2554
left out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 10:59:30 +07:00
2ez4gcxandClaude Opus 5.5 b91fa88224 Linetypes: a plot or export keeps the dashes of a run over 50,000 periods
The 50,000-period guard is for a display zoomed out a lot, so it now applies only where there
is a level of detail (min_pattern above 0). A plot or export has none and keeps the pattern on a
run of any length, bounded by the two-million-element work limit; linetype text follows, through
phase. This is the plot exemption of #1277 (#1069) in the new layout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-31 08:41:26 +07:00
2ez4gcxandClaude Opus 5.5 3e8f468fe3 Linetypes: anchor a closed PLINEGEN run at its second vertex when it coincides with the first
The anchor was the length of the first drawn segment, so when the first two
vertices coincide (Polyline::segments leaves that pair out) the pattern was
anchored at the third vertex. It is now the chord length from the first
vertex to the second (wide::second_vertex_at), 0 for that pair, and the
thin run and the wide band share it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 22:57:33 +07:00
2ez4gcxandClaude Opus 5.5 cc69082a85 PLINE test: check PLINEWID after Width before Halfwidth
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 19:46:51 +07:00
2ez4gcxandClaude Opus 5.5 e6f2ea0405 Linetypes: keep the cap on pattern elements laid out
The rewritten layout capped runs at 50,000 periods but dropped the
earlier limit of 2,000,000 pattern elements, so a long pattern repeated
that often could produce millions of ranges. A run past either limit is
drawn continuous again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 19:21:33 +07:00
2ez4gcxandClaude Opus 5.5 d56ead7ca4 PLINE: the JSON form starts at PLINEWID too
A JSON pline without a width now takes PLINEWID, as the command does,
unless its vertices give their own widths; an explicit width, 0
included, is kept. FILLET and CHAMFER's JSON forms already fall back on
their variables the same way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 18:49:00 +07:00
2ez4gcxandClaude Opus 5.5 dc07a1032d Linetypes: anchor a closed run at its second vertex as it is drawn
The anchor of a closed PLINEGEN polyline is now the length of its first
segment tessellated at the drawing tolerance, as the run is measured,
not the arc length. With an arc first, a dash now starts right at the
second vertex, matching the filled band, which already measured it so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 18:46:54 +07:00
2ez4gcxandClaude Opus 5.5 6c2d37983e Linetypes: a wide polyline's centre line is dashed as a thin one
With fill off, a polyline with width draws its centre line. It now goes
through the same layout as a polyline without width: stretched around a
closed PLINEGEN one from its second vertex, along the whole of an open
PLINEGEN one, and restarted at each vertex otherwise.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 18:15:45 +07:00
2ez4gcxandClaude Opus 5.5 45f9b5653e Merge main into fix/pline-undo-plinewid
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 17:46:30 +07:00
2ez4gcxandClaude Opus 5.5 d79185ed8d RECTANG: take Rotation as AutoCAD does and show it in the drawing's units
Measured in AutoCAD 2024 with ANGBASE 90 and ANGDIR 1: Rotation 30 turns
the rectangle 30 degrees clockwise from +X (ANGBASE aside), and the next
RECTANG shows "Current rectangle modes:  Rotation=120.00", the rotation
from ANGBASE in the ANGDIR sense; the rotation prompt's default reads
<120.00>. With AUNITS 1, 30.5 shows as "Rotation=30d30'". The typed
rotation is now an amount turned in the ANGDIR sense, and both the
modes line and the default use the drawing's angle settings and units.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 17:17:16 +07:00
2ez4gcxandClaude Opus 5.5 6d3f63752b Linetypes: one ranges function that takes the layout
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 15:28:29 +07:00
2ez4gcxandClaude Opus 5.5 3944717ca2 Merge main into fix/linetype-dash-layout
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:54:02 +07:00
2ez4gcxandClaude Opus 5.5 c319cd7ae4 Linetypes: closed wide bands and gap-first phase follow the dashes
A closed PLINEGEN polyline with width now lays its pattern out like a
thin one: stretched around the run from the second vertex
(linetype::ranges_as with Layout::Closed), not centred as an open run.

phase() now gives where the periods of a gap-first pattern start when
the run leaves room for a piece of dash at its start: a gap before the
second element at x, as gap_first lays them, so text in the linetype
sits with its dashes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:54:01 +07:00
2ez4gcxandClaude Opus 5.5 a303ff433c Linetypes: lay dashes out as AutoCAD does
Patterns were laid out from the start of every run with the first dash
whole. AutoCAD 2024 plots, read back stroke by stroke, show otherwise:
an open run is drawn continuous when shorter than one period, and
otherwise the pattern is centred (n = floor(L / period),
p0 = (n·period + first − L) / 2), the first dash starting at the run's
start and the last ending at its end; a pattern opening with a dot puts
dots at both ends, and one opening with a gap has a rule of its own. A
closed run (a circle, a whole ellipse, a closed PLINEGEN polyline) is
stretched to round(L / period) periods from its anchor (angle 0, or the
second vertex).

linetype::layout makes the drawn stretches for both; apply, apply_as
and ranges use it, the draw code picks the closed layout for circles,
whole ellipses and closed PLINEGEN polylines, and text in complex
linetypes follows the same phase. The measured lines, dots, circle,
rectangles and 33 gap-first cases are pinned in the linetype tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 13:11:38 +07:00
2ez4gcxandClaude Opus 5.5 f126a24c42 Merge main into the RECTANG fix
Picks up #2302, which formats crates/render/src/dim/linear.rs; the
gate's fmt step failed on that file, not on this branch's changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 09:06:54 +07:00
2ez4gcxandClaude Opus 5.5 55d8db69dc STRETCH: an arc with both ends inside moves whole
A full-sweep arc (start = end) has a zero chord, so rebuilding it from
the moved ends gave nothing and STRETCH left it in place even when the
window held all of it. When both ends move, translate the arc instead;
rebuild from the ends only when one of them moves.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 09:06:34 +07:00
2ez4gcxandClaude Opus 5.5 b3ff5505c5 Merge main into the STRETCH fix; import Arc explicitly
#2239 replaced stretch.rs's glob import with an explicit list, and the
new arc rule names cadcraft_geom::Arc, which only the glob brought in, so
the branch no longer compiled on main. `use cadcraft_geom::Arc;` after
the use super::{…} block is the only change the merge needs. Reported in
review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 08:45:45 +07:00
2ez4gcxandClaude Opus 5.5 bc36b99152 Merge main into the RECTANG fix; drop the rect_with_corners import
#2239 replaced rect.rs's glob import with an explicit list that names
rect_with_corners, which this PR removes (the new vertex builder replaces
it), so the branch no longer compiled on main. Dropping the name from the
list is the only change the merge needs. Reported in review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 08:41:55 +07:00
Aldo ZarateandClaude Opus 5.5 d8c37cc6c1 Format dim/linear.rs as rustfmt does
Main's fmt check fails on it since #2302; this keeps the PR's gate green.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 19:40:18 -06:00
Aldo Zarate 8391c1f0de Merge remote-tracking branch 'upstream/main' into perf/cjk-text 2026-10-29 19:39:48 -06:00
Aldo ZarateandClaude Opus 5.5 7941757ed3 Check every placed glyph corner before building its bounds
Bounds2 skips non-finite points, so a glyph with one overflowing corner
could be culled from the few corners left. Any non-finite corner now
leaves the glyph to the mesh code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 19:36:45 -06:00
Aldo Zarate d325681051 Merge remote-tracking branch 'upstream/main' into perf/cjk-text
# Conflicts:
#	crates/render/src/text.rs
2026-10-29 19:25:42 -06:00
Aldo ZarateandClaude Opus 5.5 e5dd7290e9 Cull glyphs by their own ink box, not a fixed em margin
Screen builds left out a filled glyph when a fixed font-unit box
(-1000..2000) placed by its transform missed the view, so ink reaching
more than an em past its box (flourishes, long ligatures, tall stacks,
large operators) vanished when the view saw only that part. Each
outline now records its font-unit bounds once as it is built, exposed
as ttf::glyph_bounds through the same per-thread and shared outline
caches, and may_show places those four corners instead: exact, and
still four points per glyph however long its outline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 10:53:41 -06:00
Aldo Zarate 000dbb4383 Merge remote-tracking branch 'upstream/main' into perf/cjk-text 2026-10-29 10:41:47 -06:00
2ez4gcxandClaude Opus 5.5 508c28654d STRETCH: pin the spline selection AutoCAD makes, and note the collapsed arc
Two review questions, answered by measuring AutoCAD 2024 (accoreconsole,
read back with entget):

- A crossing window that holds a spline's control point but misses the
  drawn curve selects nothing in AutoCAD ("0 found"), so the spline stays
  put; CADCraft does the same. Only a window that also crosses the curve
  moves the control point, (10,100) to (15,103). Both cases join the test.
- An arc end stretched onto the other end: AutoCAD collapses the arc into
  a zero-radius arc at that point (radius 6e-16). CADCraft keeps the arc
  rather than make an object nothing can draw or pick; the code says so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:59:07 +07:00
2ez4gcxandClaude Opus 5.5 b57647de0a PLINEWID is an ordinary system variable
PLINE now starts at PLINEWID and stores its widths back, but the
variable itself was out of reach: typing PLINEWID was an unknown command
and GETVAR an unknown variable until a Width answer happened to set it.
It joins the header-variable table (a real of at least 0, default 0, as
in AutoCAD), so GETVAR reports 0, SETVAR and the typed name set it, and
SETVAR ? lists it. Suggested in review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:45:54 +07:00
2ez4gcxandClaude Opus 5.5 12e56da913 RECTANG names the modes it carries over, as AutoCAD does
With chamfer, fillet, width, elevation, thickness and rotation carried
over, a plain RECTANG can draw something its own command never asked for,
and nothing said so. It now opens with AutoCAD's line, in AutoCAD's words
and order: "Current rectangle modes:  Chamfer=1.6574 x 2.8497  Rotation=50.50",
"Current rectangle modes:  Elevation=7.5000  Thickness=2.2500  Rotation=30.96"
(both from AutoCAD 2024's log for the same inputs); no line when every
mode is off. POINT already echoes its modes the same way. Suggested in
review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:39:33 +07:00
2ez4gcxandClaude Opus 5.5 a819d82028 Merge main (the module layout of #2220) into the STRETCH fix
#2220 moved STRETCH to cmd/modify/stretch.rs; keep_height and the arc,
polyline-bulge and spline rules move with it, unchanged, below the doc
comment #2220 gave stretch_entity.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 11:51:12 +07:00
2ez4gcxandClaude Opus 5.5 9ce57972c8 Merge main (the module layout of #2220) into the PLINE fix
#2220 moved PLINE's prompt machine to cmd/draw/line_pline.rs; the fix
(PLINEWID as the starting width, Undo returning to the last segment's
mode) moves with it, unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 10:52:10 +07:00
2ez4gcxandClaude Opus 5.5 f49355f6c2 Merge main (the module layout of #2220) into the RECTANG fix
#2220 moved RECTANG from cmd/draw2.rs to cmd/draw2/rect.rs and LastUsed
from lib.rs to last_used.rs. The fix moves with them: rect.rs carries the
AutoCAD vertex rules, draw2 re-exports RectangModes, and LastUsed keeps
the remembered RECTANG options.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 10:28:32 +07:00
2ez4gcxandClaude Opus 5.5 99e973f71f RECTANG: Area adds the corner cut back only when the corners fit
Area sized the rectangle so that its cut corners take nothing off the
area asked for, but it did so even when the fillet or chamfer turned out
too large for the resulting sides and the corners stayed square: Area 4,
length 4, fillet 2 drew a square-cornered 4 x 1.858 rectangle. When the
corners don't fit, the sides now come from the area alone (4 x 1), in the
JSON form and at the prompt. Pointed out in review.

The fit test now lives in one place (corners_fit, with corner_cuts) and
is shared by the vertex builder and the Area sizing. All 64 measured
AutoCAD cases still match vertex for vertex.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:54:20 +07:00
2ez4gcxandClaude Opus 5.5 230d5107fb STRETCH: a collapsed arc segment loses its bulge
When a stretch brings both ends of a polyline arc segment together, the
chord is zero and there is no arc height left to keep; keep_height still
returned the old bulge, which then sat on a zero-length segment. It now
returns 0 (also for a NaN chord). Pointed out in review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:40:33 +07:00
2ez4gcxandClaude Opus 5.5 23a973edfa STRETCH: arcs and polyline arc segments keep their height; spline control points move
STRETCH was checked against AutoCAD 2024 black-box: 36 crossing-window
cases run in accoreconsole (lines, polylines, arcs, circles, text,
ellipses, splines, points, block references), each object read back with
entget. Lines, straight polylines, circles, text, full ellipses, points
and block references already matched; three kinds of object did not.

- Arcs moved whole when their centre was inside the window and were left
  alone otherwise. AutoCAD moves the ends that are inside and keeps the
  arc's height, bulge x chord / 2: the arc (0,0) r20 0-90 deg with its
  start stretched by (5,3) becomes centre (3.1798, -2.2061), radius
  22.4326. The centre alone moves nothing.
- Polyline arc segments kept their bulge, so they ballooned or flattened
  as a vertex moved. AutoCAD keeps their height too: bulge 0.5 over a
  chord of 25 becomes 0.6338 when the chord shrinks to 19.72 (and -1.5
  becomes -1.2303 over a longer one).
- Splines moved whole when their first grip was inside, and stayed put
  otherwise. AutoCAD moves the control points inside the window. Splines
  built from fit points keep the old behaviour, which was not measured.

An elliptical arc with one end inside is still left as it was: AutoCAD
changes the whole ellipse there by a rule one measurement does not pin.

The new test stretch_arcs_bulges_and_splines_match_autocad pins nine of
the measured cases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:22:43 +07:00
2ez4gcxandClaude Opus 5.5 95429bb286 PLINE: Undo returns to the last segment's mode, and PLINEWID is the width
PLINE was checked against AutoCAD 2024 black-box: 76 typed inputs run in
accoreconsole, read back with entget and GETVAR. 72 matched; with this
change all 76 do.

- Undo after an arc segment stayed in arc mode, so a following `_L` was
  arc mode's Line instead of line mode's Length and the point became a
  plain vertex. AutoCAD returns to the mode of the segment now last:
  `_A` point `_U` `_L` point continues the last line by the point's
  distance, ending at (64.48701958199356, 48.21692560701169) in the
  measured case.
- PLINEWID was ignored: AutoCAD starts every polyline at that width
  ("Current line-width is 0.7500") and stores the ending width of the
  last Width or Halfwidth answer back into it (`_H 0.5 0.5` leaves
  PLINEWID 1).

The new test pline_undo_mode_and_plinewid_match_autocad pins both with
the measured numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 15:55:12 +07:00
2ez4gcxandClaude Opus 5.5 54e34b02ba RECTANG draws the vertices AutoCAD stores
RECTANG was checked against AutoCAD 2024 black-box: 64 typed inputs run
in accoreconsole, each polyline read back with entget. 18 matched; with
this change all 64 match vertex for vertex.

- Vertex order: AutoCAD starts at the first corner and runs along the
  first axis towards the other corner, so a rectangle is clockwise when
  the corners are picked down-right or up-left. CADCraft always started at
  the lower-left corner and ran counterclockwise.
- Chamfer: the first distance is cut on the edge into each corner and the
  second on the edge out of it, in drawing order. CADCraft cut the first
  along x and the second along y, which mirrors the corners whenever the
  two distances differ.
- Fillet bulges follow the drawing direction: negative on a clockwise
  rectangle.
- A fillet or chamfer too large for the shorter side leaves each corner
  as two coincident vertices (8 vertices, no arcs), not 4 vertices.
- Chamfer and Fillet replace each other: the option set last wins.
  CADCraft kept the fillet when a chamfer was set after it.
- Area sizes the rectangle so that the outline, with its corners cut
  off, encloses the area given: L = (A + 2*d1*d2) / W for a chamfer and
  (A + (4 - pi)*r^2) / W for a fillet. This applies to the JSON form too.
- Chamfer, fillet, width, elevation, thickness and rotation carry over to
  the next RECTANG (AutoCAD opens it with "Current rectangle modes:
  Fillet=2.0000" or "Elevation=7.5000  Thickness=2.2500  Rotation=30.96").
  They are kept in LastUsed; the JSON form stays stateless.

The new test rectang_vertices_match_autocad pins 12 of the measured
cases, one or more per rule. Three older tests change with the measured
behaviour: an oversized fillet now gives 8 coincident-pair vertices, and
two tests that draw several rectangles in one session set the remembered
rotation or fillet back explicitly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 15:43:58 +07:00
Aldo ZarateandClaude Opus 5.5 9a1bd48a26 Per-thread glyph outlines: bound them by points
Each thread kept up to 8192 glyph outlines in front of the shared cache with no size limit, and
held them after the shared cache let them go. They are now held within MAX_SHAPED_POINTS / 16
points per thread, and an outline above a quarter of that is read from the shared cache instead.
The generation test reads the cache before checking the generation, so another test's change in
between can't fail it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 08:10:30 -06:00
Aldo ZarateandClaude Opus 5.5 e57786e726 Per-thread caches: bound meshes by bytes; don't keep a stale font lookup
Each thread's text meshes were capped at 4096 entries but not by size; CJK text at full detail
could hold hundreds of MB per core. They are now capped at 16 MiB per thread (with the shared
cache's size estimate), and a mesh above a quarter of that is read from the shared cache instead.

A font lookup that ran while a font was being registered could keep the old answer (a "not
found") on that thread until the next change. The generation is read before the lookup, and the
answer is kept only under that generation, so a lookup overtaken by a change starts over.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 07:44:08 -06:00
Aldo ZarateandClaude Opus 5.5 4d3ceea73b Merge upstream/main into perf/cjk-text
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 19:41:29 -06:00
Aldo ZarateandClaude Opus 5.5 38e98e43c0 Faster CJK-heavy drawings: per-thread font caches, offscreen glyphs left out
Display lists are built on all cores, but every text looked its font up,
and every character its font lacks (all of a CJK text's) its fallback
font, glyph outline and glyph mesh, through shared tables behind global
locks; text-heavy drawings spent most of the build waiting on them.
Font lookups, fallback faces, FONTALT, glyph outlines and glyph meshes
now have per-thread caches in front of the shared ones (a generation
counter empties them when fonts or FONTALT/FONTFALLBACK change).

On screen, filled glyphs outside the area being looked at are left out,
as hatch patterns already are (the canvas builds again when the view
leaves that area); plots and exports keep every glyph. Zoomed in, every
glyph of every text was filled at that zoom's detail and drawn each
frame, i.e. on every mouse move.

Synthetic 3.8 MB drawing (24,000 TEXT and 2,500 MTEXT in Chinese, 30,000
lines), macOS, Apple silicon: display list at fit 335 -> 103 ms;
triangles at 16x zoom 11.2 M -> 0.44 M, at 64x 19.0 M -> 45 k.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 09:58:53 -06:00
281 changed files with 16099 additions and 2147 deletions
+5 -5
View File
@@ -2,13 +2,13 @@
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/cadcraft",
"repository_id": 1408289866,
"producer_workflow_id": null,
"producer_workflow_id": 429719786,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
"producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
+24 -7
View File
@@ -1,7 +1,8 @@
name: CADCraft release-ref nightly signer
# Enabled for supervised manual dispatch on release. Main/release contents must match.
# A reusable callee does not change context; this must be a real top-level release dispatch.
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
on:
workflow_dispatch:
inputs:
@@ -22,21 +23,37 @@ concurrency:
jobs:
release:
# Actual context guards: official repository, manual dispatch, real release branch.
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
if: >-
github.repository == 'storytold/cadcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
app-name: cadcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the existing release environment and export keys in its signing step.
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
+4 -4
View File
@@ -22,13 +22,13 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
app-name: cadcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
# Linux/macOS signer (#342).
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
+20
View File
@@ -0,0 +1,20 @@
name: Notify Services on Release Change
on:
release:
types:
- published
- unpublished
- created
- edited
- deleted
- prereleased
- released
permissions: {}
jobs:
notify:
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
secrets:
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+1 -1
View File
@@ -87,7 +87,7 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted) | Original Turkish 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; the running app reviewed by a native speaker |
| `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/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 and the craft-i18n#401 phase 1 changes reviewed by a native Vietnamese speaker; older rows not yet proofread in full |
| `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) |
Generated
+1272 -86
View File
File diff suppressed because it is too large Load Diff
+36 -32
View File
@@ -14,11 +14,11 @@ repository = "https://github.com/storytold/cadcraft"
# internal
cadcraft-geom = { path = "crates/geom" }
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "219c1d0b14177af6f291395d6587f61a5e09043a" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
cadcraft-color = { path = "crates/color" }
cadcraft-doc = { path = "crates/doc" }
cadcraft-constraints = { path = "crates/constraints" }
@@ -28,19 +28,19 @@ cadcraft-io = { path = "crates/io" }
cadcraft-engine = { path = "crates/engine" }
cadcraft-ui-egui = { path = "crates/ui-egui" }
cadcraft-mcp = { path = "crates/mcp" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# SVG/SVGZ import and export geometry (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# Which paths stored in a drawing (xrefs, data links) may be opened.
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", 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 }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
# Delimited text (CSV/TSV) parsing (shared Craft library).
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4.6.11"
clap_mangen = { version = "0.3.3", features = ["env"] }
@@ -74,8 +74,12 @@ encoding_rs = "0.8.35"
quick-xml = "0.42"
# ui
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["serde"] }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
@@ -85,7 +89,7 @@ egui-wgpu = "0.37"
# Monotonic time on native and web (performance.now on wasm).
web-time = "1.1"
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
rfd = "0.17"
arboard = { version = "3.6", default-features = false }
@@ -117,23 +121,23 @@ debug = 0
# PDF backends for craft-pdf: pinned to the same reviewed craft-libs revision as craft-pdf itself
# (Cargo ignores dependency-local patches).
[patch.crates-io]
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" }
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# Keep the complete egui family and native event bridge on reviewed fork commits.
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+10 -4
View File
@@ -89,9 +89,15 @@
line, prompts with clickable `[Keywords]`, AutoComplete, object snaps, polar tracking, ortho,
direct distance entry, window and crossing selection, grips, and right-click-to-repeat behave
the way decades of drafting habit expect.
- **Open files.** DXF is read and written natively (ASCII and binary, R12 through 2018), and DWG
files (R13 through 2018) open and save through the open-source acadrust library. Export to SVG
and PNG today.
- **Open files.** DXF is read natively (R12 through 2018, with binary support from R13) and
written as 2000 through 2018 (ASCII and binary). DWG files (R13 through 2018; R13 and R14
untested, 2018 tested only on synthetic files) open through the open-source acadrust library
and save as 2000 through 2018. New drawings default to
2018 (AC1032) in both formats. In the app's Save dialog, File ▸ Default Save Format
(also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version for untitled
drawings; drawings with a file keep their own version, subject to supported-version mapping
and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later
saves. Export to SVG and PNG today.
- **Fast and native.** Pure Rust and egui, no Electron, no web view. One binary on macOS
(universal), Windows, Linux and FreeBSD, plus a WebAssembly build for the browser.
- **Built for agents.** Every menu item, tool and prompt is a command. Agents can type at the
@@ -114,7 +120,7 @@ numbers):
| Layers & properties | Layers palette and Layer Properties Manager (on/off, freeze, lock, plot, colour, linetype), layer tools (isolate, freeze, off, lock, match, previous), Properties palette with per-object editing, linetypes, lineweights, colour index and true colour |
| Annotation | All DIM* commands with full DIMSTYLE variables, overrides and every arrowhead, associative dimensions that follow geometry, MLEADER, TABLE, TrueType fonts (`.ttf`, `.otf`, `.ttc` collections), MTEXT formatting codes (fonts, heights, colours, stacked fractions), our own single-stroke drafting font |
| Hatch & blocks | Pick-point hatch boundaries with islands, pattern, solid and gradient fills from our own pattern library, BLOCK/INSERT, attributes and nested blocks |
| Files | DXF read (R12–2018, ASCII and binary) and write (R2000), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library) and write (R2000); PDF plotting, SVG and PNG export. Entities CADCraft doesn't model yet are not kept on save: see [file-format parity](docs/file-format-parity.md) |
| Files | DXF read (R12–2018, binary from R13) and write (2000–2018, ASCII and binary), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library; R13 and R14 untested, 2018 tested only on synthetic files) and write (2000–2018). New drawings save as 2018 (AC1032); opened drawings keep their supported version, except DWG defaults to at least 2004. In the app's Save dialog, File ▸ Default Save Format (also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version for untitled drawings; drawings with a file keep their own version, subject to supported-version mapping and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later saves. DXF uses R2000 structure with the chosen `$ACADVER`. PDF plotting, SVG and PNG export. Entities CADCraft doesn't model yet are not kept on save: see [file-format parity](docs/file-format-parity.md) for version selection and fidelity |
| 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 |
+7
View File
@@ -45,6 +45,12 @@ fn install_io() {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
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())
@@ -60,6 +66,7 @@ fn install_io() {
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
}
/// `path` as text, for the engine and io calls that take a file name as a string.
+8 -1
View File
@@ -145,15 +145,22 @@ pub(crate) fn export(s: &Session, out: &Path, io: &mut Streams) -> Result {
pub(crate) fn export_framed(s: &Session, out: &Path, window: Option<Bounds2>, io: &mut Streams) -> Result {
let d = s.doc()?;
let bytes = cadcraft_io::write_framed(d, out, window)?;
let (bytes, notes) = cadcraft_io::write_framed_noted(d, out, window)?;
let folder = write_atomic(out, &bytes)?;
report_new_folder(folder, io);
io.errln(format_args!("wrote {} ({} bytes)", out.display(), bytes.len()));
// What the image draws short of the drawing (dashed runs past a dash limit drawn continuous).
for note in notes {
io.errln(format_args!("{}: {note}", out.display()));
}
if cadcraft_engine::cmd::file::drops_unknown(out) {
let lost = cadcraft_engine::cmd::file::not_saved(d);
if let Some(m) = cadcraft_engine::cmd::file::not_saved_message(&lost) {
io.errln(format_args!("{m}"));
}
for note in cadcraft_engine::cmd::file::dwg_notes(d) {
io.errln(format_args!("{note}"));
}
}
Ok(())
}
@@ -0,0 +1,144 @@
//! `convert` to an image says how many dashed runs it drew continuous because of a dash limit
//! (#1069): a line whose DASHED pattern repeats past what one run may be laid out over. A line of
//! 50,001 periods, which an export keeps dashed, gets no note.
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A DXF of one line `periods` DASHED (0.5, -0.25) periods long.
fn dashed_line(periods: f64) -> String {
format!(
"0
SECTION
2
TABLES
0
TABLE
2
LTYPE
70
1
0
LTYPE
2
DASHED
70
0
3
Dashed
72
65
73
2
40
0.75
49
0.5
74
0
49
-0.25
74
0
0
ENDTAB
0
ENDSEC
0
SECTION
2
ENTITIES
0
LINE
8
0
6
DASHED
10
0
20
0
11
{}
21
0
0
ENDSEC
0
EOF
",
periods * 0.75
)
}
#[test]
fn convert_to_an_image_notes_dashed_runs_drawn_continuous_past_the_dash_limit() {
let dir = std::env::temp_dir().join(format!("cc-cli-dash-limit-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
// (1,000,001 + 2) periods × 2 elements: past the two million one run may be laid out over.
let long = dir.join("long.dxf");
std::fs::write(&long, dashed_line(1_000_001.0)).unwrap();
let control = dir.join("control.dxf");
std::fs::write(&control, dashed_line(50_001.0)).unwrap();
let notes = |out: &Output| {
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stderr).lines().filter(|l| l.contains("drawn continuous")).map(str::to_string).collect::<Vec<_>>()
};
for ext in ["png", "svg", "pdf"] {
let image = dir.join(format!("long.{ext}"));
let image = image.to_str().unwrap();
let got = notes(&cli(&["convert", long.to_str().unwrap(), image]));
assert!(matches!(got.as_slice(), [note] if note.starts_with(&format!("{image}: 1 dashed run "))), "{ext}: {got:?}");
let got = notes(&cli(&["convert", control.to_str().unwrap(), dir.join(format!("control.{ext}")).to_str().unwrap()]));
assert!(got.is_empty(), "{ext}: {got:?}");
}
// A DXF copy draws nothing, so there is nothing to note.
assert!(notes(&cli(&["convert", long.to_str().unwrap(), dir.join("copy.dxf").to_str().unwrap()])).is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
/// The engine's commands that write an image say it too, on the command line and in the result's
/// `warnings`: EXPORT, PLOT (PDF, PNG, SVG, to a file or as data), QSAVE and SAVEAS to an image and
/// `document.bytes`.
#[test]
fn image_commands_warn_about_dashed_runs_drawn_continuous() {
let dir = std::env::temp_dir().join(format!("cc-cli-dash-limit-cmds-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let out = |name: &str| serde_json::to_string(dir.join(name).to_str().unwrap()).unwrap();
let cmds = [
format!("export {{\"path\": {}}}", out("export.png")),
format!("plot {{\"path\": {}}}", out("plot.pdf")),
format!("plot {{\"path\": {}, \"output\": \"png\", \"resolution\": 50}}", out("plot.png")),
format!("plot {{\"path\": {}, \"output\": \"svg\"}}", out("plot.svg")),
format!("saveas {{\"path\": {}}}", out("saved.svg")),
format!("qsave {{\"path\": {}}}", out("saved.pdf")),
"plot {\"output\": \"svg\"}".to_string(),
"document.bytes {\"format\": \"pdf\"}".to_string(),
format!("saveas {{\"path\": {}, \"version\": 2018}}", out("versioned.png")),
];
for (periods, warned) in [(1_000_001.0, true), (50_001.0, false)] {
let input = dir.join(format!("line-{periods}.dxf"));
std::fs::write(&input, dashed_line(periods)).unwrap();
let mut args = vec!["run".to_string(), input.to_str().unwrap().to_string()];
for c in &cmds {
args.extend(["--cmd".to_string(), c.clone()]);
}
let run = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(&args).output().unwrap();
assert!(run.status.success(), "{:?}: {}", run.status, String::from_utf8_lossy(&run.stderr));
let results: Vec<serde_json::Value> = String::from_utf8_lossy(&run.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(results.len(), cmds.len(), "{results:?}");
for (c, r) in cmds.iter().zip(&results) {
let notes: Vec<&str> = r["warnings"].as_array().into_iter().flatten().filter_map(|w| w.as_str()).collect();
let noted = matches!(notes.as_slice(), [n] if n.starts_with("1 dashed run ") && n.contains("drawn continuous"));
assert_eq!(noted, warned, "{periods} periods, {c}: {r}");
assert_eq!(r.get("warnings").is_some(), warned, "{periods} periods, {c}: {r}");
}
// Said on the command line once for each command.
let echoed = String::from_utf8_lossy(&run.stderr).lines().filter(|l| l.starts_with("1 dashed run ")).count();
assert_eq!(echoed, if warned { cmds.len() } else { 0 }, "{}", String::from_utf8_lossy(&run.stderr));
}
let _ = std::fs::remove_dir_all(&dir);
}
@@ -0,0 +1,41 @@
//! `convert` to DWG says, in one warning, how many linetypes the DWG keeps with only their first
//! 255 dash elements (#1923, F-05); converting to DXF keeps them whole and says nothing.
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A DXF with a 256-element linetype and a line drawn with it.
fn dxf() -> String {
let mut s = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLTYPE\n70\n1\n0\nLTYPE\n2\nLONG\n70\n0\n3\nLong\n72\n65\n73\n256\n40\n192\n");
for i in 0..256 {
s.push_str(if i % 2 == 0 { "49\n1\n74\n0\n" } else { "49\n-0.5\n74\n0\n" });
}
s.push_str("0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n6\nLONG\n10\n0\n20\n0\n11\n10\n21\n0\n0\nENDSEC\n0\nEOF\n");
s
}
#[test]
fn convert_to_dwg_notes_the_linetypes_it_cuts() {
let dir = std::env::temp_dir().join(format!("cc-cli-ltype-dwg-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let source = dir.join("long.dxf");
std::fs::write(&source, dxf()).unwrap();
let source = source.to_str().unwrap();
let notes =
|out: &Output| String::from_utf8_lossy(&out.stderr).lines().filter(|l| l.contains("dash elements")).map(str::to_string).collect::<Vec<_>>();
let out = cli(&["convert", source, dir.join("long.dwg").to_str().unwrap()]);
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
assert!(
matches!(notes(&out).as_slice(), [note] if note.contains("1 linetype") && note.contains("255")),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let out = cli(&["convert", source, dir.join("copy.dxf").to_str().unwrap()]);
assert!(out.status.success() && notes(&out).is_empty(), "{}", String::from_utf8_lossy(&out.stderr));
let _ = std::fs::remove_dir_all(&dir);
}
+4
View File
@@ -1,6 +1,10 @@
mod cli;
mod dash_limit_note;
mod drafting_spacing;
mod help;
// DWG output needs craft-dwg's bridge.
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
mod ltype_dwg_note;
mod mcp_connect;
mod pdf_import;
mod skipped_records;
+2 -2
View File
@@ -21,8 +21,8 @@ cadcraft-io = { workspace = true }
cadcraft-fonts = { workspace = true }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
# The page command API (storytold/craft-libs#413): window.cadcraft over the control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
+11 -2
View File
@@ -54,11 +54,12 @@ mod web {
if let Some(bridge) = &self.2 {
bridge.report_dirty(&self.0);
}
self.0.close_path(ctx);
}
/// Forward raw input to the web `CadApp` and capture Tab at the command line.
/// Forward raw input to the web `CadApp` and hand the frame's root values to the UI runtime.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.0.raw_input_hook(ctx, raw);
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
self.0.before_input(ctx);
}
/// Preferences and validated panel placement survive reloads; egui memory is not kept.
fn save(&mut self, storage: &mut dyn eframe::Storage) {
@@ -119,6 +120,12 @@ mod web {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
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())
@@ -134,6 +141,7 @@ mod web {
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
let Some(canvas) = app_canvas() else {
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
return;
@@ -166,6 +174,7 @@ mod web {
canvas,
options,
Box::new(move |cc| {
cadcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
// Embedded, the host sends the drawing: start on the Start tab, not Drawing1.
let session = if app_bridge.is_some() { Session::empty() } else { Session::new() };
let control = crate::api::install(cc.egui_ctx.clone());
+1 -1
View File
@@ -94,7 +94,7 @@ mod tests {
let mut ui = UiState::default();
let before = serde_json::to_value(&ui).unwrap();
let mut invalid = ui.clone();
invalid.docking.layout.root = None;
invalid.docking = cadcraft_ui_egui::docking::Workspace::default();
assert!(save(&invalid).is_err());
let mut record: Value = serde_json::from_str(&save(&ui).unwrap()).unwrap();
record["docking"] = serde_json::to_value(&invalid.docking).unwrap();
+3 -7
View File
@@ -41,22 +41,18 @@ winit = { version = "0.30", default-features = false, features = ["x11"] }
zbus = { version = "=5.19.0", default-features = false, features = ["async-io", "blocking-api"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# Floating panels open in their own OS windows on the desktop; the web build keeps them in the page.
craft-ui = { workspace = true, features = ["native-windows"] }
craft-update = { workspace = true }
rfd = { workspace = true }
sys-locale = "0.3"
[target.'cfg(target_os = "macos")'.dependencies]
# `title_bar::sync_movable`: AppKit's title-band drag leaves the window still under the row's
# controls and under floating panels.
craft-window = { workspace = true }
muda = { version = "0.21", default-features = false }
# Quit CADCraft as a close request of the main window, so the unsaved-changes question runs (#2157).
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
# View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: the system's Reduce motion
# (system_animations.rs). Already in Cargo.lock through muda.
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility"] }
# The same winit eframe uses (the storytold fork, patched in the workspace): its opt-in that turns
# AppKit's terminate (Cmd+Q, Dock Quit) into a close request, so unsaved changes are asked about.
# The same winit eframe uses (the storytold fork, patched in the workspace).
# `rwh_06`: the window handle a file dialog shown as a sheet attaches to (src/sheet.rs).
winit = { version = "0.30", default-features = false, features = ["rwh_06"] }
# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already
+78 -4
View File
@@ -4,8 +4,9 @@
//! The server only reads requests: a line that is not a JSON object with a string `method` (an
//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is
//! closed, so nothing sent after it runs. Every resource a client can hold is bounded
//! ([`Limits`]): simultaneous connections, request line length, queued requests, and how long a
//! socket may sit idle or blocked on a write.
//! ([`Limits`]): simultaneous connections, request line length (shorter until a request on the
//! connection has carried the token), queued requests, and how long a socket may sit idle or
//! blocked on a write.
use std::io::{BufRead, BufReader, ErrorKind, Write};
use std::net::{TcpListener, TcpStream};
@@ -24,6 +25,9 @@ struct Limits {
max_clients: usize,
/// Longest request line in bytes (newline excluded); a longer one closes the connection.
max_line: usize,
/// Longest request line until a request on the connection has carried the right token; a
/// longer one closes the connection (#1925).
preauth_line: usize,
/// Request-line bytes buffered at once across all connections; a request that would pass it
/// is refused with an error reply.
total_bytes: usize,
@@ -43,6 +47,7 @@ impl Default for Limits {
max_clients: 16,
// Generous, so requests that carry whole drawings or images as base64 still fit.
max_line: 256 * 1024 * 1024,
preauth_line: cadcraft_mcp::control_token::MAX_UNAUTHENTICATED_LINE,
// Room for one maximal request plus smaller ones, not `max_clients` maximal ones.
total_bytes: 512 * 1024 * 1024,
queue: 64,
@@ -344,12 +349,21 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
let mut reader = BufReader::new(read);
let mut buf = Vec::new();
let mut held = Held::new(budget);
// The token is checked only after the whole line is read, so until a request here has carried
// it a line is kept short: a peer without it can't make the app buffer `max_line` (#1925).
let mut authenticated = false;
loop {
let reject = match read_bounded_line(&mut reader, &mut buf, limits.max_line, &mut held) {
let max = if authenticated { limits.max_line } else { limits.preauth_line.min(limits.max_line) };
let reject = match read_bounded_line(&mut reader, &mut buf, max, &mut held) {
Ok(false) => break,
// Nothing of a line arrived (idle timeout, or the peer is gone): close without a word.
// A line nobody asked for would be read as the reply to the client's next request.
Err(_) if buf.is_empty() => break,
// Only an overlong line leaves more than `max` bytes buffered.
Err(_) if !authenticated && buf.len() > max => format!(
"request line longer than {max} bytes before a request with the control token on this connection; \
send a short request with the token (such as `ping`) first; closing the connection"
),
Err(e) => e,
Ok(true) => match parse_line(&buf) {
Line::Blank => continue,
@@ -366,6 +380,7 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
let _ = writeln!(out, "{r}");
break;
}
authenticated = true;
// Absent `params` is `{}`; ones that cannot be decoded (an unpaired surrogate escape) are an
// error, not a request run with defaults.
let params = match params.map(|r| serde_json::from_str::<Value>(r.get())) {
@@ -499,7 +514,12 @@ mod tests {
/// The control server on a loopback port, with a stand-in UI that echoes each method.
fn serve_echo() -> std::net::SocketAddr {
let (addr, rx) = serve_with(Limits::default());
serve_echo_with(Limits::default())
}
/// [`serve_echo`] under `limits`.
fn serve_echo_with(limits: Limits) -> std::net::SocketAddr {
let (addr, rx) = serve_with(limits);
std::thread::spawn(move || {
for req in rx {
let _ = req.reply.send(json!({"ok": true, "method": req.method}));
@@ -612,6 +632,60 @@ mod tests {
drop(first);
}
/// Small bounds for the pre-authentication tests: lines up to 1000 bytes until the connection
/// has shown the token, up to 100 000 after.
fn preauth() -> Limits {
Limits { max_line: 100_000, preauth_line: 1000, idle_timeout: Duration::from_secs(5), ..short() }
}
/// A request line carrying the test token whose parameters make it `len` bytes or longer.
fn long_req_line(id: i64, len: usize) -> String {
json!({"id": id, "method": "long", "params": {"text": "x".repeat(len)}, "token": TEST_TOKEN}).to_string() + "\n"
}
/// A peer without the token is refused once its line passes the pre-authentication bound,
/// while it is still sending: the app doesn't buffer the rest of the line to find the token
/// at its end (#1925).
#[test]
fn an_unauthenticated_long_line_is_refused_at_the_preauth_bound() {
let (addr, rx) = serve_with(preauth());
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
// Well under `max_line`, and unfinished: without the pre-authentication bound the server
// keeps reading and waiting for the rest of it. One write, so it all reaches the server's
// buffer at once and the close after the refusal leaves nothing unread to reset the reply.
let unfinished = format!(r#"{{"id":1,"method":"m","params":"{}"#, "x".repeat(5000));
c.write_all(unfinished.as_bytes()).unwrap();
let mut line = String::new();
BufReader::new(&mut c).read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!(v["ok"], json!(false));
assert!(v["error"].as_str().unwrap_or("").contains("longer than 1000 bytes before a request with the control token"), "{line}");
assert!(rx.try_recv().is_err(), "nothing was dispatched");
}
/// A long request with the token is taken once a shorter request with the token has been
/// answered on the same connection; as a connection's first line it is refused, since its
/// token comes only at the end.
#[test]
fn a_long_request_is_taken_once_the_connection_has_shown_the_token() {
let addr = serve_echo_with(preauth());
let long = long_req_line(2, 5000);
let first = exchange(addr, long.as_bytes());
assert_eq!(first.len(), 1, "{first:?}");
assert!(first[0]["error"].as_str().unwrap_or("").contains("before a request with the control token"), "{first:?}");
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
c.write_all(format!("{}{long}", req_line(1, "ping")).as_bytes()).unwrap();
let mut r = BufReader::new(c);
for (id, method) in [(1, "ping"), (2, "long")] {
let mut line = String::new();
r.read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!((v["id"].as_i64(), v["ok"].as_bool(), v["method"].as_str()), (Some(id), Some(true), Some(method)), "{line}");
}
}
#[test]
fn the_budget_is_given_back_when_the_connection_ends() {
let budget = Budget::new(100);
+58 -40
View File
@@ -61,9 +61,6 @@ struct App {
/// `CADCRAFT_NO_NATIVE_MENU`: the menus stay inside the window.
#[cfg(target_os = "macos")]
menus_in_window: bool,
/// The `movable` flag last set on the main window.
#[cfg(target_os = "macos")]
movable: Option<bool>,
/// Drawings and quit requests from Finder, the Dock and `open -a` (see `apple_events`).
#[cfg(target_os = "macos")]
apple_events: fmv_macos_events::Inbox,
@@ -141,17 +138,18 @@ impl eframe::App for App {
if std::mem::take(&mut self.cad.quit_requested) {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
self.cad.close_path(ctx);
}
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and capture Tab at the command line.
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and hand the frame's root values to the UI
/// runtime.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
follow_desktop(raw, self.desktop_theme.current());
self.cad.raw_input_hook(ctx, raw);
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
self.cad.before_input(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
cadcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
self.cad.guarded_ui(ui);
#[cfg(target_os = "macos")]
craft_window::title_bar::sync_movable(ui.ctx(), &mut self.movable);
}
/// A normal exit: the workspace is saved, and this run's autosave files are not needed (a
/// crash leaves them for recovery).
@@ -184,6 +182,12 @@ pub fn install_io() {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
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())
@@ -199,6 +203,7 @@ pub fn install_io() {
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
}
fn services() -> Services {
@@ -302,17 +307,15 @@ const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0];
/// The main window: its size, title bar, placement and rendering needs. `restoring`: a window state
/// saved by the last session is restored instead of opening centred. `stencil`: the stencil bits of
/// its render pass ([`stencil_bits`]).
fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
fn window_options(restoring: bool, stencil: u8, frame: Option<&cadcraft_ui_egui::framework::Decision>) -> eframe::NativeOptions {
let viewport = egui::ViewportBuilder::default()
.with_title(os_window::name_for(os_window::identity()))
.with_inner_size([1600.0, 1000.0])
.with_min_inner_size(MIN_INNER_SIZE)
.with_drag_and_drop(true)
.with_app_id(os_window::app_id());
eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title(os_window::name_for(os_window::identity()))
.with_inner_size([1600.0, 1000.0])
.with_min_inner_size(MIN_INNER_SIZE)
.with_drag_and_drop(true)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false)
.with_app_id(os_window::app_id()),
viewport: cadcraft_ui_egui::framework::apply_frame(viewport, frame),
// The size, position and maximized state are kept between sessions (#2595); eframe keeps a
// restored window on the monitors that are connected now.
persist_window: true,
@@ -390,14 +393,23 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1))
}
/// A refused launch profile ends with a native dialog on a desktop, and with the reason on standard
/// error everywhere else (a headless runner must never wait for a modal).
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
build_flavor::needs_native_error(flavor, desktop_session) && !macos
}
/// A refused launch profile ends with a native dialog where a modal renders without the app's run
/// loop (Windows, X11/Wayland), and with the reason on standard error everywhere else: a headless
/// runner must never wait for a modal, and on macOS one opened before the event loop never appears.
fn report_launch_profile_error(error: &str) {
eprintln!("CADCraft launch profile: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("CADCraft launch profile: {error}");
return;
@@ -544,6 +556,9 @@ fn main() -> eframe::Result {
if stencil == 0 {
log::warn!("CADCRAFT_STENCIL is off: the window has no stencil buffer; clipped layout viewports draw unclipped");
}
// XWayland when it's there (see below), unless CADCRAFT_WAYLAND=1 keeps the native Wayland backend.
let forced_x11 = cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On;
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11);
let persistence_path = vars
.portable_storage_file
.clone()
@@ -553,7 +568,7 @@ fn main() -> eframe::Result {
// swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync).
wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface),
persistence_path: persistence_path.clone(),
..window_options(restores_window(persistence_path.as_deref()), stencil)
..window_options(restores_window(persistence_path.as_deref()), stencil, frame.as_ref())
};
if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon);
@@ -576,22 +591,12 @@ fn main() -> eframe::Result {
// manager showed a "no" cursor. Run through XWayland when it's there; CADCRAFT_WAYLAND=1
// keeps the native Wayland backend.
#[cfg(all(unix, not(target_os = "macos")))]
if std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On {
if forced_x11 {
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::x11::EventLoopBuilderExtX11;
b.with_x11();
}));
}
// macOS: Quit CADCraft (Cmd+Q), the Dock's Quit and logout end the app through AppKit's
// terminate, which would skip the unsaved-changes prompt (#2157). winit turns each into a
// close request for the window instead, so it asks first, as the close button does.
#[cfg(target_os = "macos")]
{
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::macos::EventLoopBuilderExtMacOS;
b.with_close_requested_on_terminate(true);
}));
}
// Registered before the event loop starts, so it catches the Finder event that launched us as
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
#[cfg(target_os = "macos")]
@@ -604,6 +609,7 @@ fn main() -> eframe::Result {
os_window::name_for(os_window::identity()),
options,
Box::new(move |cc| {
cadcraft_ui_egui::framework::install(&cc.egui_ctx, forced_x11, frame.clone())?;
let mut app = CadApp::new(Session::empty(), services());
// The exit hook runs in `on_exit`: macOS ends the process inside AppKit's terminate after
// it, so nothing after `run_native` can be relied on there.
@@ -666,7 +672,7 @@ fn main() -> eframe::Result {
}
app.session.set_lisp_support_dir(Some(support));
}
app.integrated_titlebar = cfg!(target_os = "macos");
app.integrated_titlebar = cadcraft_ui_egui::framework::draws_title_row(frame.as_ref());
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
}
@@ -717,8 +723,6 @@ fn main() -> eframe::Result {
#[cfg(target_os = "macos")]
menus_in_window: vars.no_native_menu == Switch::On,
#[cfg(target_os = "macos")]
movable: None,
#[cfg(target_os = "macos")]
apple_events,
}))
}),
@@ -756,7 +760,7 @@ mod tests {
/// #1129: the first launch opens centred, not cascaded from the top-left corner.
#[test]
fn the_first_launch_opens_centred() {
let o = window_options(false, STENCIL_BITS);
let o = window_options(false, STENCIL_BITS, None);
assert!(o.centered, "centred on launch");
assert!(o.persist_window, "the window state is saved for the next launch");
}
@@ -764,7 +768,7 @@ mod tests {
/// #2595: a saved window state (size, position, maximized) is restored, not centred over.
#[test]
fn a_saved_window_reopens_where_it_was() {
let o = window_options(true, STENCIL_BITS);
let o = window_options(true, STENCIL_BITS, None);
assert!(!o.centered, "centring would move a restored window");
assert!(o.persist_window);
}
@@ -789,8 +793,8 @@ mod tests {
#[test]
fn the_window_carries_the_chosen_stencil_bits() {
for bits in [0, STENCIL_BITS] {
assert_eq!(window_options(false, bits).stencil_buffer, bits);
assert_eq!(window_options(true, bits).stencil_buffer, bits);
assert_eq!(window_options(false, bits, None).stencil_buffer, bits);
assert_eq!(window_options(true, bits, None).stencil_buffer, bits);
}
let format = |bits| eframe::egui_wgpu::depth_format_from_bits(0, bits);
assert_eq!(format(0), None, "no stencil: the canvas builds no clip pipelines");
@@ -844,3 +848,17 @@ mod tests {
assert_eq!(raw.system_theme, None);
}
}
#[cfg(test)]
mod refusal_dialog_tests {
use super::refusal_dialog;
use crate::build_flavor::BuildFlavor;
#[test]
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
}
}
+10 -2
View File
@@ -15,6 +15,9 @@ pub struct NativeMenu {
items: HashMap<String, (String, String, MenuItem)>,
submenus: Vec<(String, Submenu)>,
predefined: Vec<(&'static str, PredefinedMenuItem)>,
/// Quit CADCraft: a close request of the main window, so unsaved drawings are asked about first.
/// muda's predefined Quit ends the process through `terminate:` without asking.
quit: MenuItem,
language: &'static str,
/// Monotonic time of the last enablement refresh. `NEG_INFINITY` makes the first poll refresh
/// immediately: `now_ms` starts near zero, so the old `0.0` sentinel suppressed the first
@@ -58,7 +61,6 @@ impl NativeMenu {
("Hide CADCraft", PredefinedMenuItem::hide(Some(i18n::tr(language, "Hide CADCraft")))),
("Hide Others", PredefinedMenuItem::hide_others(Some(i18n::tr(language, "Hide Others")))),
("Show All", PredefinedMenuItem::show_all(Some(i18n::tr(language, "Show All")))),
("Quit CADCraft", PredefinedMenuItem::quit(Some(i18n::tr(language, "Quit CADCraft")))),
];
// The Mac place for preferences: CADCraft ▸ Settings… (⌘,) opens the Options dialog.
let settings = MenuItem::with_id("cc-settings", i18n::tr(language, "Settings..."), true, accel("Cmd+Comma"));
@@ -69,6 +71,8 @@ impl NativeMenu {
let _ = app_menu.append(&PredefinedMenuItem::separator());
}
}
let quit = MenuItem::with_id(craft_quit::QUIT_MENU_ID, i18n::tr(language, "Quit CADCraft"), true, accel("Cmd+Q"));
let _ = app_menu.append(&quit);
items.insert("cc-about".into(), ("ui.dialog.about".into(), "About CADCraft".into(), about));
items.insert("cc-discord".into(), ("ui.discord".into(), "Join the ArtCraft Discord…".into(), discord));
items.insert("cc-settings".into(), ("options".into(), "Settings...".into(), settings));
@@ -85,6 +89,7 @@ impl NativeMenu {
items,
submenus,
predefined,
quit,
language,
last_refresh: f64::NEG_INFINITY,
recent: app.ui.recent_files.clone(),
@@ -114,7 +119,9 @@ impl NativeMenu {
/// Drain queued menu events into commands (Discord opens externally), rebuild Open Recent, retranslate on a language change and refresh enablement when 300 ms have elapsed.
pub fn poll(&mut self, app: &mut CadApp, ctx: &egui::Context) {
while let Ok(ev) = self.events.try_recv() {
if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
if craft_quit::on_menu_event(ctx, ev.id.as_ref()) {
ctx.request_repaint();
} else if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
if cmd == "ui.discord" {
ctx.open_url(egui::OpenUrl::new_tab("https://discord.gg/artcraft"));
} else {
@@ -133,6 +140,7 @@ impl NativeMenu {
for (label, item) in &self.predefined {
item.set_text(i18n::tr(language, label));
}
self.quit.set_text(i18n::tr(language, "Quit CADCraft"));
for (label, submenu) in &self.submenus {
submenu.set_text(i18n::tr_menu(language, label));
}
+5 -5
View File
@@ -252,7 +252,7 @@ mod tests {
app.run("ui.dock", json!({"operation":"move", "panel":"layers", "target":"properties", "zone":"left"})).unwrap();
app.run("ui.dock", json!({"operation":"float", "panel":"properties", "rect":[120,90,340,410]})).unwrap();
ui.docking = app.ui.docking;
ui.docking.set_visible(Panel::ToolSets, false, None, permissions).unwrap();
ui.docking.set_visible(Panel::ToolSets, false, None, false, permissions).unwrap();
ui.show_toolsets = false;
store.save_if_changed(&ui, Instant::now()).unwrap();
let saved: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
@@ -263,9 +263,9 @@ mod tests {
assert_eq!(serde_json::to_value(&reloaded.docking).unwrap(), serde_json::to_value(&ui.docking).unwrap());
assert!(!reloaded.show_toolsets);
reveal_panel(&mut reloaded.docking, Panel::ToolSets).unwrap();
let tools = reloaded.docking.layout.location(&Panel::ToolSets).unwrap();
let tools = reloaded.docking.layout().location(&Panel::ToolSets).unwrap();
assert_eq!(serde_json::to_value(&tools.group).unwrap()["column"]["side"], json!("Start"), "{tools:?}");
assert_eq!(reloaded.docking.layout.floating[0].rect, [120.0, 90.0, 340.0, 410.0]);
assert_eq!(reloaded.docking.layout().floating[0].rect, egui::Rect::from_min_size(egui::pos2(120.0, 90.0), egui::vec2(340.0, 410.0)));
fs::remove_dir_all(directory).unwrap();
}
@@ -293,8 +293,8 @@ mod tests {
assert_eq!(ui.toolset_tab, "Modeling");
assert_eq!(ui.history_lines, 4);
assert!(!ui.show_toolsets && ui.show_palettes && !ui.show_toolbar);
assert_eq!(ui.docking.layout, default_workspace().layout);
assert!(ui.docking.hidden.is_empty(), "{:?}", ui.docking.hidden);
assert_eq!(ui.docking.layout(), default_workspace().layout());
assert!(ui.docking.hidden().is_empty(), "{:?}", ui.docking.hidden());
fs::remove_dir_all(directory).unwrap();
}
-3
View File
@@ -2,7 +2,4 @@ allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true
allow-indexing-slicing-in-tests = true
disallowed-types = [
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
]
cognitive-complexity-threshold = 30
+4 -3
View File
@@ -238,8 +238,9 @@ mod tests {
assert!(f.t.near(g.t, 1e-3), "{f:?} {g:?}");
assert!((f.k - g.k).abs() < 1e-2, "{f:?} {g:?}");
}
// An unclamped (periodic) spline has no ends.
let closed = GSpline::from_fit_points_closed(&[Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)]);
assert!(spline_end(&closed, false).is_none());
// An unclamped spline has no ends: one whose control points wrap round.
let fit = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)];
let closed = GSpline::fit_with(&fit, true, cadcraft_geom::FitOptions { knots: cadcraft_geom::KnotParam::Uniform, ..Default::default() });
assert!(closed.wraps() && spline_end(&closed, false).is_none());
}
}
+1 -1
View File
@@ -47,7 +47,7 @@ mod proxy;
mod text;
mod wipeout;
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, mtext_literal};
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, TagKey, mtext_literal};
pub use common::{Common, Handle, Lineweight, RawTag, Transparency};
pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, PolyfaceMesh, Polyline3d, RayLine, Solid};
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
+67
View File
@@ -1,3 +1,6 @@
use std::cmp::Ordering;
use std::collections::BTreeMap;
use super::common::{Common, Lineweight};
use super::text::{MText, Text};
use super::{Color, Deserialize, EntityKind, Mat3, Serialize, Vec2, Vec3};
@@ -142,6 +145,43 @@ impl AttribProps {
}
}
/// An attribute tag as attributes are matched to their definitions and to each other: ASCII
/// letters in either case are the same tag, other characters must be equal. As an ordered map key
/// it finds the match in a logarithmic number of comparisons, where comparing each attribute with
/// each definition costs their product on a block with many of both (#1923). It orders, rather
/// than hashes, so the cost doesn't depend on hash keys a crafted file could predict (the web
/// build's `RandomState`), as in the layer and block name index.
#[derive(Clone, Copy, Debug)]
pub struct TagKey<'a>(pub &'a str);
impl TagKey<'_> {
/// The tag's bytes with ASCII letters in lower case: equal for the tags `eq_ignore_ascii_case`
/// finds equal.
fn folded(&self) -> impl Iterator<Item = u8> + '_ {
self.0.bytes().map(|b| b.to_ascii_lowercase())
}
}
impl PartialEq for TagKey<'_> {
fn eq(&self, other: &Self) -> bool {
self.0.eq_ignore_ascii_case(other.0)
}
}
impl Eq for TagKey<'_> {}
impl Ord for TagKey<'_> {
fn cmp(&self, other: &Self) -> Ordering {
self.folded().cmp(other.folded())
}
}
impl PartialOrd for TagKey<'_> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Insert {
@@ -204,4 +244,31 @@ impl Insert {
.then_before(Mat3::scale(self.scale.x, self.scale.y))
.then_before(Mat3::translate(-base))
}
/// The reference's attributes by tag: of several with one tag (in any ASCII case), the first.
/// Built once, it tells whether the reference carries a definition's tag, and its value, in
/// one lookup instead of a pass over the attributes per definition (#1923).
pub fn attribs_by_tag(&self) -> BTreeMap<TagKey<'_>, &Attrib> {
let mut by_tag = BTreeMap::new();
for a in &self.attribs {
by_tag.entry(TagKey(a.tag.as_str())).or_insert(a);
}
by_tag
}
}
impl crate::Block {
/// The block's attribute definitions by tag: of several with one tag (in any ASCII case), the
/// first in the block's order, the one an attribute of that tag takes its properties from.
/// Built once for all of a reference's attributes, it matches each in one lookup instead of a
/// pass over the block per attribute (#1923).
pub fn attdefs_by_tag(&self) -> BTreeMap<TagKey<'_>, &crate::Entity> {
let mut by_tag = BTreeMap::new();
for e in self.entities.iter() {
if let EntityKind::AttDef(a) = &e.kind {
by_tag.entry(TagKey(a.tag.as_str())).or_insert(e.as_ref());
}
}
by_tag
}
}
+20 -17
View File
@@ -1,10 +1,10 @@
//! Approximate entity bounds (used for extents, zoom and selection pre-filtering).
use std::collections::HashMap;
use std::collections::{BTreeMap, HashMap};
use cadcraft_geom::{Arc, Bounds2, EPS, Polyline, Vec2, bulge_to_arc};
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim};
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim, TagKey};
/// Nested block references deeper than this are ignored (cyclic or hostile files).
pub const MAX_BLOCK_DEPTH: usize = 16;
@@ -283,33 +283,33 @@ fn layer_counts(d: &Drawing, layer: &str, off_counts: bool) -> bool {
}
/// The layer an insert's attribute draws on, as the renderer takes it: its own, else its
/// definition's (layer "0" being the insert's).
fn attrib_layer<'a>(d: &'a Drawing, ins: &crate::Insert, a: &'a crate::Attrib) -> &'a str {
a.props.layer.as_deref().unwrap_or_else(|| {
d.block(&ins.block)
.and_then(|blk| blk.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag))))
.map_or("0", |be| be.common.layer.as_str())
})
/// definition's, from the block's definitions by tag `defs` (layer "0" being the insert's).
fn attrib_layer<'a>(defs: Option<&BTreeMap<TagKey<'a>, &'a Entity>>, a: &'a crate::Attrib) -> &'a str {
a.props.layer.as_deref().unwrap_or_else(|| defs.and_then(|defs| defs.get(&TagKey(&a.tag))).map_or("0", |be| be.common.layer.as_str()))
}
/// 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.
/// reference, whichever asks first. Also the block's attribute definitions by tag, for the layer
/// of an attribute that has none of its own.
struct Contents<'a> {
geometry: Bounds2,
constants: Vec<(&'a str, Bounds2)>,
defs: BTreeMap<TagKey<'a>, &'a Entity>,
}
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))
if self.constants.is_empty() {
return self.geometry;
}
// The reference's tags are gathered once, not scanned again for each constant (#1923).
let carried = ins.attribs_by_tag();
self.constants.iter().filter(|(tag, _)| !carried.contains_key(&TagKey(tag))).fold(self.geometry, |b, (_, c)| b.union(c))
}
}
@@ -323,7 +323,7 @@ fn contents<'a, 'm>(
) -> 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() };
let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new(), defs: blk.attdefs_by_tag() };
// 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);
@@ -487,9 +487,12 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
// one draws nothing, so it contributes nothing: ZOOM Extents must not fly off to its
// insertion point. Attributes below still count.
let mut b = Bounds2::EMPTY;
let mut defs = None;
if let Some(blk) = d.block(&ins.block) {
let m = ins.transform(blk.base.xy());
let inner = contents(d, blk, depth, blocks, off_counts).map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
let c = contents(d, blk, depth, blocks, off_counts);
defs = c.map(|c| &c.defs);
let inner = c.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).
@@ -511,7 +514,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
}
}
for a in &ins.attribs {
if !a.invisible && layer_counts(d, attrib_layer(d, ins, a), off_counts) {
if !a.invisible && layer_counts(d, attrib_layer(defs, a), off_counts) {
b = b.union(&match a.multiline_text() {
Some(m) => mtext_box(&m),
None => text_box(&a.text, a.text.value.chars().count()),
+35 -19
View File
@@ -14,6 +14,7 @@ mod format;
mod gdt;
mod header;
pub mod library;
mod names;
mod plotstyle;
mod plotter;
mod raster;
@@ -36,6 +37,7 @@ pub use extents::{
pub use format::Format;
pub use gdt::*;
pub use header::{HVal, Header};
pub use names::{Named, NamedList, NamedMap};
pub use plotstyle::*;
pub use plotter::*;
pub use raster::{Raster, Rasters};
@@ -101,19 +103,25 @@ pub struct Drawing {
pub header: Header,
/// File data CADCraft does not model, written back on save.
pub foreign: std::sync::Arc<foreign::Foreign>,
pub layers: Vec<Layer>,
pub linetypes: Vec<Linetype>,
pub text_styles: Vec<TextStyle>,
pub dim_styles: Vec<DimStyle>,
/// Layers in table order; [`Drawing::layer`] looks them up by name.
pub layers: NamedList<Layer>,
/// Linetypes in table order; [`Drawing::linetype`] looks them up by name.
pub linetypes: NamedList<Linetype>,
/// Text styles in table order; [`Drawing::text_style`] looks them up by name.
pub text_styles: NamedList<TextStyle>,
/// Dimension styles in table order; [`Drawing::dim_style`] looks them up by name.
pub dim_styles: NamedList<DimStyle>,
pub mleader_styles: Vec<MLeaderStyle>,
pub table_styles: Vec<TableStyle>,
/// Multiline styles (MLSTYLE); STANDARD is always there.
pub mline_styles: Vec<MLineStyle>,
pub blocks: BTreeMap<String, std::sync::Arc<Block>>,
/// Block definitions by name; [`Drawing::block`] looks them up.
pub blocks: NamedMap<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>,
/// Layouts in list order (`tab_order` orders the tabs); [`Drawing::layout`] looks them up by name.
pub layouts: NamedList<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.
pub active_layout: Option<String>,
@@ -195,21 +203,22 @@ impl Drawing {
Drawing {
header: Header::default(),
foreign: std::sync::Arc::default(),
layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }],
layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }].into(),
linetypes: vec![
Linetype { name: "ByBlock".into(), description: String::new(), pattern: Vec::new() },
Linetype { name: "ByLayer".into(), description: String::new(), pattern: Vec::new() },
Linetype::continuous(),
],
text_styles: vec![TextStyle::default()],
dim_styles: vec![DimStyle::default()],
]
.into(),
text_styles: vec![TextStyle::default()].into(),
dim_styles: vec![DimStyle::default()].into(),
mleader_styles: vec![MLeaderStyle::default()],
table_styles: vec![TableStyle::default()],
mline_styles: vec![MLineStyle::default()],
blocks: BTreeMap::new(),
blocks: NamedMap::default(),
model: EntityStore::new(),
model_page: None,
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)],
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)].into(),
active_layout: None,
views: Vec::new(),
vports: Vec::new(),
@@ -313,20 +322,25 @@ impl Drawing {
}
}
/// The first layer named `name`, without case.
pub fn layer(&self, name: &str) -> Option<&Layer> {
self.layers.iter().find(|l| l.name.eq_ignore_ascii_case(name))
self.layers.by_name(name)
}
/// The first layer named `name`, without case, to change.
pub fn layer_mut(&mut self, name: &str) -> Option<&mut Layer> {
self.layers.iter_mut().find(|l| l.name.eq_ignore_ascii_case(name))
self.layers.by_name_mut(name)
}
/// The first linetype named `name`, without case.
pub fn linetype(&self, name: &str) -> Option<&Linetype> {
self.linetypes.iter().find(|l| l.name.eq_ignore_ascii_case(name))
self.linetypes.by_name(name)
}
/// The first text style named `name`, without case.
pub fn text_style(&self, name: &str) -> Option<&TextStyle> {
self.text_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
self.text_styles.by_name(name)
}
/// The first dimension style named `name`, without case.
pub fn dim_style(&self, name: &str) -> Option<&DimStyle> {
self.dim_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
self.dim_styles.by_name(name)
}
/// The DIM* variables in the header that differ from the current dimension style, as
@@ -394,11 +408,13 @@ impl Drawing {
}
}
}
/// The block named exactly `name`, else the first by name order named `name` without case.
pub fn block(&self, name: &str) -> Option<&std::sync::Arc<Block>> {
self.blocks.get(name).or_else(|| self.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v))
self.blocks.by_name(name)
}
/// The first layout named `name`, without case.
pub fn layout(&self, name: &str) -> Option<&Layout> {
self.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(name))
self.layouts.by_name(name)
}
/// Add a layer if missing; returns whether it was created.
+575
View File
@@ -0,0 +1,575 @@
//! The drawing's tables of named entries (layers, blocks, linetypes, text styles, dimension styles
//! and layouts), whose names are looked up without case through an index instead of a scan once a
//! table is large and looked up often.
//!
//! [`Drawing::layer`](crate::Drawing::layer), [`Drawing::block`](crate::Drawing::block) and the
//! other lookups by name run for every entity while a drawing is read, measured and drawn, and
//! every layout is looked up on each change. Scanning the table on each made a file of N layers,
//! or of N blocks, linetypes or styles and N objects naming ones it does not have, cost N² name
//! comparisons: tens of seconds to open or draw at a few tens of thousands (#1924, F-04).
//!
//! Each table keeps an index from a name with its ASCII letters lower-cased to the table's first
//! entry of that name, so a lookup returns what a scan in table order returns. The index is ordered
//! by those bytes, not hashed: a lookup costs a logarithmic number of name comparisons whatever
//! the names are, also where a file could predict a hash's keys (the web build's `RandomState`).
//! Every change to a table goes through `DerefMut`, which drops the index, so it can never be
//! stale. The index is built only once a table has been scanned [`SCANS_BEFORE_INDEX`] times since
//! it last changed: a table changed between every few hundred lookups costs at most about 2.5 times
//! what scanning it always did, and one looked up many times in between is indexed once.
use std::collections::{BTreeMap, btree_map};
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, OnceLock};
/// Tables with fewer entries than this are always scanned: a search of the index costs about what a
/// scan of 100 names does (measured), so a smaller table gains nothing from one.
const MIN_INDEXED: usize = 128;
/// Lookups that scan a table after it changed before its index is built. A build costs about 100
/// to 350 scans (measured on tables of 100 to 40 000 names), so a table changed after every few
/// hundred lookups costs at most about 2.5 times what scanning it always did.
const SCANS_BEFORE_INDEX: u32 = 256;
/// From a name with its ASCII letters lower-cased to the first entry, in table order, of that name.
struct Index<V>(BTreeMap<Box<[u8]>, V>);
impl<V> Index<V> {
fn build<'a>(entries: impl Iterator<Item = (&'a str, V)>) -> Self {
let mut map = BTreeMap::new();
for (name, v) in entries {
map.entry(name.to_ascii_lowercase().into_bytes().into_boxed_slice()).or_insert(v);
}
Index(map)
}
/// The first entry named `name`, without case.
fn get(&self, name: &str) -> Option<&V> {
with_folded(name, |folded| self.0.get(folded))
}
}
/// `f` of the bytes of `name` with its ASCII letters lower-cased, which are equal for the names
/// `eq_ignore_ascii_case` finds equal. A short name is folded on the stack.
fn with_folded<R>(name: &str, f: impl FnOnce(&[u8]) -> R) -> R {
let mut buf = [0u8; 64];
match buf.get_mut(..name.len()) {
Some(short) => {
short.copy_from_slice(name.as_bytes());
short.make_ascii_lowercase();
f(short)
}
None => f(name.to_ascii_lowercase().as_bytes()),
}
}
/// A table's index: built on demand, shared by copies of the unchanged table (an undo snapshot),
/// dropped when the table changes.
struct Lazy<V> {
index: OnceLock<Arc<Index<V>>>,
/// Lookups that scanned the table since it last changed.
scans: AtomicU32,
}
impl<V> Lazy<V> {
/// The index of a table of `len` entries, built with `build` once the table has been scanned
/// often enough since it changed; `None` while it is to be scanned.
fn get(&self, len: usize, build: impl FnOnce() -> Index<V>) -> Option<&Index<V>> {
if let Some(ix) = self.index.get() {
return Some(ix);
}
if len < MIN_INDEXED || self.scans.fetch_add(1, Ordering::Relaxed) < SCANS_BEFORE_INDEX {
return None;
}
Some(self.index.get_or_init(|| Arc::new(build())))
}
/// Forget the index: the table may change.
fn clear(&mut self) {
self.index = OnceLock::new();
*self.scans.get_mut() = 0;
}
}
impl<V> Default for Lazy<V> {
fn default() -> Self {
Lazy { index: OnceLock::new(), scans: AtomicU32::new(0) }
}
}
impl<V> Clone for Lazy<V> {
fn clone(&self) -> Self {
Lazy { index: self.index.clone(), scans: AtomicU32::new(0) }
}
}
/// An entry of a [`NamedList`]: what it is looked up by.
pub trait Named {
fn name(&self) -> &str;
}
/// Entries named by their `name` field.
macro_rules! named_by_field {
($($t:ty),*) => {$(
impl Named for $t {
fn name(&self) -> &str {
&self.name
}
}
)*};
}
named_by_field!(crate::Layer, crate::Linetype, crate::TextStyle, crate::DimStyle, crate::Layout);
/// A list of named entries in their own order (the drawing's layers, linetypes, text styles,
/// dimension styles and layouts). It reads and changes as a `Vec`; [`NamedList::by_name`] finds the
/// first entry of a name without case.
pub struct NamedList<T> {
list: Vec<T>,
index: Lazy<usize>,
}
impl<T: Named> NamedList<T> {
/// The position of the first entry named `name`, without case.
pub fn position_by_name(&self, name: &str) -> Option<usize> {
match self.index.get(self.list.len(), || Index::build(self.list.iter().enumerate().map(|(i, t)| (t.name(), i)))) {
Some(ix) => ix.get(name).copied(),
None => self.list.iter().position(|t| t.name().eq_ignore_ascii_case(name)),
}
}
/// The first entry named `name`, without case.
pub fn by_name(&self, name: &str) -> Option<&T> {
self.position_by_name(name).and_then(|i| self.list.get(i))
}
/// The first entry named `name`, without case, to change (which drops the index).
pub fn by_name_mut(&mut self, name: &str) -> Option<&mut T> {
let i = self.position_by_name(name)?;
self.get_mut(i)
}
}
impl<T> Deref for NamedList<T> {
type Target = Vec<T>;
fn deref(&self) -> &Vec<T> {
&self.list
}
}
impl<T> DerefMut for NamedList<T> {
fn deref_mut(&mut self) -> &mut Vec<T> {
self.index.clear();
&mut self.list
}
}
impl<T> Default for NamedList<T> {
fn default() -> Self {
Vec::new().into()
}
}
impl<T: Clone> Clone for NamedList<T> {
fn clone(&self) -> Self {
NamedList { list: self.list.clone(), index: self.index.clone() }
}
}
impl<T: std::fmt::Debug> std::fmt::Debug for NamedList<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.list.fmt(f)
}
}
impl<T: PartialEq> PartialEq for NamedList<T> {
fn eq(&self, other: &Self) -> bool {
self.list == other.list
}
}
impl<T> From<Vec<T>> for NamedList<T> {
fn from(list: Vec<T>) -> Self {
NamedList { list, index: Lazy::default() }
}
}
impl<T> From<NamedList<T>> for Vec<T> {
fn from(l: NamedList<T>) -> Self {
l.list
}
}
impl<T: serde::Serialize> serde::Serialize for NamedList<T> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
self.list.serialize(s)
}
}
impl<T> FromIterator<T> for NamedList<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
Vec::from_iter(iter).into()
}
}
impl<T> IntoIterator for NamedList<T> {
type Item = T;
type IntoIter = std::vec::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.list.into_iter()
}
}
impl<'a, T> IntoIterator for &'a NamedList<T> {
type Item = &'a T;
type IntoIter = std::slice::Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.list.iter()
}
}
impl<'a, T> IntoIterator for &'a mut NamedList<T> {
type Item = &'a mut T;
type IntoIter = std::slice::IterMut<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.deref_mut().iter_mut()
}
}
/// Entries by name, in name order (the drawing's block definitions). It reads and changes as a
/// `BTreeMap`; [`NamedMap::by_name`] finds an entry by its exact name, else the first in name
/// order whose name matches without case.
pub struct NamedMap<V> {
map: BTreeMap<String, V>,
index: Lazy<Box<str>>,
}
impl<V> NamedMap<V> {
/// The entry named exactly `name`, else the first in name order named `name` without case.
pub fn by_name(&self, name: &str) -> Option<&V> {
if let Some(v) = self.map.get(name) {
return Some(v);
}
match self.index.get(self.map.len(), || Index::build(self.map.keys().map(|k| (k.as_str(), Box::from(k.as_str()))))) {
Some(ix) => ix.get(name).and_then(|k| self.map.get(&**k)),
None => self.map.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v),
}
}
}
impl<V> Deref for NamedMap<V> {
type Target = BTreeMap<String, V>;
fn deref(&self) -> &BTreeMap<String, V> {
&self.map
}
}
impl<V> DerefMut for NamedMap<V> {
fn deref_mut(&mut self) -> &mut BTreeMap<String, V> {
self.index.clear();
&mut self.map
}
}
impl<V> Default for NamedMap<V> {
fn default() -> Self {
BTreeMap::new().into()
}
}
impl<V: Clone> Clone for NamedMap<V> {
fn clone(&self) -> Self {
NamedMap { map: self.map.clone(), index: self.index.clone() }
}
}
impl<V: std::fmt::Debug> std::fmt::Debug for NamedMap<V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.map.fmt(f)
}
}
impl<V: PartialEq> PartialEq for NamedMap<V> {
fn eq(&self, other: &Self) -> bool {
self.map == other.map
}
}
impl<V> From<BTreeMap<String, V>> for NamedMap<V> {
fn from(map: BTreeMap<String, V>) -> Self {
NamedMap { map, index: Lazy::default() }
}
}
impl<V> FromIterator<(String, V)> for NamedMap<V> {
fn from_iter<I: IntoIterator<Item = (String, V)>>(iter: I) -> Self {
BTreeMap::from_iter(iter).into()
}
}
impl<V> IntoIterator for NamedMap<V> {
type Item = (String, V);
type IntoIter = btree_map::IntoIter<String, V>;
fn into_iter(self) -> Self::IntoIter {
self.map.into_iter()
}
}
impl<'a, V> IntoIterator for &'a NamedMap<V> {
type Item = (&'a String, &'a V);
type IntoIter = btree_map::Iter<'a, String, V>;
fn into_iter(self) -> Self::IntoIter {
self.map.iter()
}
}
impl<'a, V> IntoIterator for &'a mut NamedMap<V> {
type Item = (&'a String, &'a mut V);
type IntoIter = btree_map::IterMut<'a, String, V>;
fn into_iter(self) -> Self::IntoIter {
self.deref_mut().iter_mut()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::{MIN_INDEXED, Named, NamedList};
use crate::{Block, DimStyle, Drawing, Layer, Layout, Linetype, TextStyle};
/// Names to look up: each given name as it is, upper-cased, lower-cased and with a character
/// added (a miss).
fn probes<'a>(names: impl Iterator<Item = &'a str>) -> Vec<String> {
names.flat_map(|n| [n.to_string(), n.to_ascii_uppercase(), n.to_ascii_lowercase(), format!("{n}?")]).collect()
}
fn layers_indexed(d: &Drawing) -> bool {
d.layers.index.index.get().is_some()
}
fn indexed<T>(list: &NamedList<T>) -> bool {
list.index.index.get().is_some()
}
/// Every lookup through `find` finds what a scan of `list` in table order finds (the first of a
/// name without case), by pointer, for the list's names and `extra`.
fn check_list<'a, T: Named>(list: &'a NamedList<T>, find: impl Fn(&str) -> Option<&'a T>, extra: &[&str]) {
let names: Vec<String> = list.iter().map(|t| t.name().to_string()).collect();
for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) {
let want = list.iter().find(|t| t.name().eq_ignore_ascii_case(&p)).map(std::ptr::from_ref);
assert_eq!(find(&p).map(std::ptr::from_ref), want, "{p}");
}
}
/// The linetype, text style, dimension style and layout lookups each find what a scan in table
/// order finds (the first of a name without case): while they scan, once the table is indexed,
/// and after `by_name_mut` (RENAME, STYLE, DIMSTYLE, a .lin file reloaded, a layout's UCS)
/// changed the first of a name and dropped the index.
#[test]
fn linetype_style_and_layout_lookups_find_the_first_of_a_name() {
let names: Vec<String> = (0..150).map(|i| format!("N{i}")).chain(["n7", "Dash", "DASH"].map(String::from)).collect();
let mut d = Drawing::new_imperial();
d.linetypes = names.iter().map(|n| Linetype::simple(n, "", &[0.5, -0.25])).collect();
d.text_styles = names.iter().map(|n| TextStyle { name: n.clone(), ..TextStyle::default() }).collect();
d.dim_styles = names.iter().map(|n| DimStyle { name: n.clone(), ..DimStyle::default() }).collect();
d.layouts = names.iter().zip(1..).map(|(n, tab)| Layout::new(n, tab)).collect();
let check = |d: &Drawing, extra: &[&str]| {
check_list(&d.linetypes, |n| d.linetype(n), extra);
check_list(&d.text_styles, |n| d.text_style(n), extra);
check_list(&d.dim_styles, |n| d.dim_style(n), extra);
check_list(&d.layouts, |n| d.layout(n), extra);
};
let all_indexed = |d: &Drawing| indexed(&d.linetypes) && indexed(&d.text_styles) && indexed(&d.dim_styles) && indexed(&d.layouts);
// The first round scans until the index is built; the second reads only the index.
check(&d, &["dash", "missing"]);
assert!(all_indexed(&d));
check(&d, &["dash", "missing"]);
// The first of a name changes, and the later one of that name is found after it.
d.linetypes.by_name_mut("n7").unwrap().name = "Seven".into();
d.text_styles.by_name_mut("n7").unwrap().name = "Seven".into();
d.dim_styles.by_name_mut("n7").unwrap().name = "Seven".into();
d.layouts.by_name_mut("n7").unwrap().name = "Seven".into();
assert!(!indexed(&d.linetypes) && !indexed(&d.text_styles) && !indexed(&d.dim_styles) && !indexed(&d.layouts));
assert_eq!(d.linetype("N7").map(|l| l.name.as_str()), Some("n7"));
assert_eq!(d.text_style("N7").map(|s| s.name.as_str()), Some("n7"));
assert_eq!(d.dim_style("N7").map(|s| s.name.as_str()), Some("n7"));
assert_eq!(d.layout("N7").map(|l| (l.name.as_str(), l.tab_order)), Some(("n7", 151)));
assert_eq!(d.linetypes.get(7).map(|l| l.name.as_str()), Some("Seven"));
check(&d, &["SEVEN", "n7"]);
assert!(all_indexed(&d));
// A miss changes nothing and keeps the index.
assert!(d.dim_styles.by_name_mut("none").is_none());
assert!(indexed(&d.dim_styles));
check(&d, &["dash"]);
}
fn blocks_indexed(d: &Drawing) -> bool {
d.blocks.index.index.get().is_some()
}
/// `layer_mut` finds the first layer of a name and drops the index, as the table may change
/// through it. Then every layer lookup finds what a scan in table order finds (the first of a
/// name without case), and a large table looked up this often is left indexed.
fn check_layers(d: &mut Drawing, extra: &[&str]) {
let p = extra.first().copied().unwrap_or("L1");
let want = d.layers.iter().position(|l| l.name.eq_ignore_ascii_case(p)).and_then(|i| d.layers.get(i)).map(std::ptr::from_ref);
assert_eq!(d.layer_mut(p).map(|l| std::ptr::from_ref(&*l)), want, "{p}");
assert!(want.is_none() || !layers_indexed(d));
let names: Vec<String> = d.layers.iter().map(|l| l.name.clone()).collect();
for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) {
let want = d.layers.iter().position(|l| l.name.eq_ignore_ascii_case(&p));
assert_eq!(d.layers.position_by_name(&p), want, "{p}");
let at = want.and_then(|i| d.layers.get(i)).map(std::ptr::from_ref);
assert_eq!(d.layer(&p).map(std::ptr::from_ref), at, "{p}");
}
assert_eq!(layers_indexed(d), d.layers.len() >= MIN_INDEXED);
}
/// Every block lookup finds what `Drawing::block` always found: the block of that exact name,
/// else the first in name order of that name without case. Only names that miss an exact name
/// count towards building the index, so the names are looked up twice.
fn check_blocks(d: &Drawing, extra: &[&str]) {
let names: Vec<String> = d.blocks.keys().cloned().collect();
for p in probes(names.iter().chain(&names).map(String::as_str).chain(extra.iter().copied())) {
let want = d.blocks.get(&p).or_else(|| d.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(&p)).map(|(_, v)| v));
assert_eq!(d.block(&p).map(std::ptr::from_ref), want.map(std::ptr::from_ref), "{p}");
}
assert_eq!(blocks_indexed(d), d.blocks.len() >= MIN_INDEXED);
}
/// The index answers by itself, with no scan to fall back on: every name finds the first entry
/// of its name without case, also names that differ only after a long shared prefix, names
/// that fill the stack buffer or are longer, and names with non-ASCII letters (which keep their
/// case). Names are compared, not hashed, so no two names can share a slot.
#[test]
fn the_index_alone_finds_the_first_entry_of_every_name() {
let long = "x".repeat(100);
let names: Vec<String> = vec![
"Door".into(),
"DOOR".into(),
"door2".into(),
format!("{long}A"),
format!("{long}a"),
format!("{long}B"),
format!("{}b", "P".repeat(63)),
format!("{}B", "p".repeat(63)),
"Ärea".into(),
"ärea".into(),
"ÄREA".into(),
String::new(),
];
let ix = super::Index::build(names.iter().enumerate().map(|(i, n)| (n.as_str(), i)));
for p in names.iter().flat_map(|n| [n.clone(), n.to_ascii_uppercase(), n.to_ascii_lowercase(), format!("{n}?")]) {
let want = names.iter().position(|n| n.eq_ignore_ascii_case(&p));
assert_eq!(ix.get(&p).copied(), want, "{p:?}");
}
assert_eq!(ix.get(&format!("{long}a")), Some(&3));
assert_eq!(ix.get("ärea"), Some(&9));
}
#[test]
fn layer_lookups_find_the_first_of_a_name_through_every_change() {
let mut d = Drawing::new_imperial();
d.layers = (0..200).map(|i| Layer::new(&format!("L{i}"))).chain([Layer::new("l5"), Layer::new("Doors")]).collect();
check_layers(&mut d, &["l5", "missing"]);
// Renamed through layer_mut (RENAME).
d.layer_mut("l7").unwrap().name = "Seven".into();
assert!(!layers_indexed(&d));
assert!(d.layer("L7").is_none());
check_layers(&mut d, &["SEVEN", "L7"]);
// Added (LAYER New, or a file's later record of a name it already has).
d.layers.push(Layer::new("SEVEN"));
assert!(!layers_indexed(&d));
check_layers(&mut d, &["seven"]);
// Removed (PURGE, LAYDEL): the later `l5` becomes the first of that name.
d.layers.retain(|l| l.name != "L5");
assert!(!layers_indexed(&d));
assert_eq!(d.layer("L5").map(|l| l.name.as_str()), Some("l5"));
check_layers(&mut d, &["L5"]);
// Inserted before an earlier layer of the same name.
d.layers.insert(0, Layer::new("l9"));
assert!(!layers_indexed(&d));
assert_eq!(d.layer("L9").map(|l| l.name.as_str()), Some("l9"));
check_layers(&mut d, &["L9"]);
// Changed by position, and by a loop over all of them.
d.layers[3].name = "Third".into();
assert!(!layers_indexed(&d));
check_layers(&mut d, &["third"]);
for l in &mut d.layers {
l.name.make_ascii_uppercase();
}
assert!(!layers_indexed(&d));
check_layers(&mut d, &["doors"]);
// Undo: a snapshot keeps the table it was taken with, and its index.
let names = |d: &Drawing| d.layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();
assert!(layers_indexed(&d));
let (snap, before) = (d.clone(), names(&d));
d.layers.clear();
d.layers.push(Layer::new("Only"));
check_layers(&mut d, &["only", "L1"]);
d = snap;
assert!(layers_indexed(&d));
assert_eq!(names(&d), before);
check_layers(&mut d, &["THIRD"]);
// The whole table replaced (LAYERP, LAYUNISO).
d.layers = vec![Layer::new("0"), Layer::new("A"), Layer::new("a")].into();
check_layers(&mut d, &["a"]);
}
#[test]
fn block_lookups_find_an_exact_name_else_the_first_without_case_through_every_change() {
let block = |name: &str| Arc::new(Block::new(name));
let mut d = Drawing::new_imperial();
for name in (0..150).map(|i| format!("B{i}")).chain(["Door", "DOOR", "door"].map(String::from)) {
d.blocks.insert(name.clone(), block(&name));
}
check_blocks(&d, &["dOOR", "missing"]);
// An exact name wins; otherwise the first in name order ("DOOR" < "Door" < "door").
assert_eq!(d.block("door").map(|b| b.name.as_str()), Some("door"));
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("DOOR"));
// Removed (PURGE, a definition replaced under another name).
d.blocks.remove("DOOR");
assert!(!blocks_indexed(&d));
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("Door"));
check_blocks(&d, &["dOOR"]);
// Added before the first of that name.
d.blocks.insert("DoOr".into(), block("DoOr"));
assert!(!blocks_indexed(&d));
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("DoOr"));
check_blocks(&d, &["dOOR"]);
// Renamed (RENAME takes the definition out and puts it back under the new name).
let b1 = d.blocks.remove("B1").unwrap();
d.blocks.insert("Renamed".into(), b1);
assert!(d.block("b1").is_none() && d.block("RENAMED").is_some());
check_blocks(&d, &["b1", "RENAMED"]);
// Redefined in place, and changed through get_mut: the names stay.
d.blocks.insert("Door".into(), block("Door"));
assert!(!blocks_indexed(&d));
check_blocks(&d, &["DOOR"]);
Arc::make_mut(d.blocks.get_mut("B2").unwrap()).description = "changed".into();
assert!(!blocks_indexed(&d));
check_blocks(&d, &["b2"]);
// Many removed at once.
d.blocks.retain(|k, _| !k.starts_with("B9"));
assert!(!blocks_indexed(&d));
check_blocks(&d, &["b9", "b90"]);
// A loop over all of them.
for (_, b) in &mut d.blocks {
Arc::make_mut(b).description = "looped".into();
}
assert!(!blocks_indexed(&d));
check_blocks(&d, &["b3"]);
// Undo: a snapshot keeps the table it was taken with, and its index.
let snap = d.clone();
d.blocks.clear();
d.blocks.insert("Only".into(), block("Only"));
check_blocks(&d, &["only", "door"]);
d = snap;
assert!(blocks_indexed(&d));
check_blocks(&d, &["DOOR", "only"]);
}
}
+2 -2
View File
@@ -1018,8 +1018,8 @@ impl LayerState {
pub const ALL: u32 = 2047;
/// A state of every property of `layers`, with `current` the layer restoring makes current.
pub fn new(name: impl Into<String>, layers: Vec<Layer>, current: impl Into<String>) -> Self {
LayerState { name: name.into(), layers, current: current.into(), ..LayerState::default() }
pub fn new(name: impl Into<String>, layers: impl Into<Vec<Layer>>, current: impl Into<String>) -> Self {
LayerState { name: name.into(), layers: layers.into(), current: current.into(), ..LayerState::default() }
}
}
+155
View File
@@ -890,3 +890,158 @@ fn constant_values_count_in_extents_as_attmode_shows_them() {
assert!(top(1, true) < 40.0);
assert!(top(2, true) > 40.0, "ATTMODE 2 shows an invisible one");
}
#[test]
fn an_attribute_lies_on_the_layer_of_the_first_definition_of_its_tag() {
// Two definitions of one tag, in different case, on a frozen layer and on layer 0: an
// attribute without a layer of its own (in a third case) lies on the first one's.
let top = |defs: [(&str, &str); 2]| {
let mut d = Drawing::new_imperial();
let mut frozen = Layer::new("AFRZ");
frozen.frozen = true;
d.layers.push(frozen);
let mut blk = Block::new("B");
blk.entities.push(on_layer("0", line((0.0, 0.0), (1.0, 1.0)), 1));
for (h, (layer, tag)) in (2..).zip(defs) {
blk.entities.push(on_layer(layer, EntityKind::AttDef(plain_attrib(tag)), h));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
let mut a = plain_attrib("Tag");
a.text.insert = Vec3::new(0.0, 500.0, 0.0);
ins.attribs.push(a);
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
extents_pair(&d).1.y
};
assert!(top([("AFRZ", "TAG"), ("0", "tag")]) < 100.0, "on the first definition's frozen layer");
assert!(top([("0", "tag"), ("AFRZ", "TAG")]) > 400.0, "on the first definition's layer 0");
}
#[test]
fn constant_definitions_of_one_tag_all_count_unless_the_reference_carries_the_tag() {
// Two constant definitions of one tag, in different case: a reference draws both values,
// unless it carries an attribute of that tag (in a third case), which stands for both.
let max = |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))));
for (h, tag, at) in [(2, "C", Vec3::new(0.0, 5000.0, 0.0)), (3, "c", Vec3::new(7000.0, 0.0, 0.0))] {
let mut a = plain_attrib(tag);
a.text.insert = at;
a.constant = true;
blk.entities.push(Entity::new(Handle(h), 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
};
for shown in [max(vec![]), max(vec![plain_attrib("D")])] {
assert!(shown.x > 6000.0 && shown.y > 4000.0, "both values count: {shown:?}");
}
let carried = max(vec![plain_attrib("D"), plain_attrib("Cc"), plain_attrib("C")]);
assert!(carried.x < 100.0 && carried.y < 100.0, "neither value counts: {carried:?}");
}
#[test]
fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() {
// #1923: one reference with N attributes (none with a layer of its own) of a block with N
// constant definitions, the tags N long ones alike up to their last characters, no attribute's
// a definition's. Comparing each attribute with each definition, for its layer and for which
// constant values the reference carries, cost N x N comparisons of whole tags (many seconds
// here); one lookup per attribute or definition costs milliseconds.
const N: usize = 4000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
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))));
for (h, i) in (2..).zip(0..N) {
let mut a = plain_attrib(&tag('D', i));
a.constant = true;
blk.entities.push(Entity::new(Handle(h), 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 = (0..N).map(|i| plain_attrib(&tag('A', i))).collect();
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let t = std::time::Instant::now();
assert!(!d.extents(&Space::Model).is_empty());
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
}
/// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N
/// blocks and N references to blocks it does not have, opened in N² name comparisons (#1924).
#[test]
fn layer_and_block_lookups_by_name_cost_about_the_same_for_any_table_size() {
const N: usize = 60_000;
let mut d = Drawing::new_imperial();
d.layers = (0..N).map(|i| Layer::new(&format!("L{i}"))).collect();
for i in 0..N {
let name = format!("B{i}");
d.blocks.insert(name.clone(), std::sync::Arc::new(Block::new(&name)));
}
let started = std::time::Instant::now();
for i in 0..N {
assert!(d.layer(&format!("l{i}")).is_some() && d.layer(&format!("M{i}")).is_none());
assert!(d.block(&format!("b{i}")).is_some() && d.block(&format!("Z{i}")).is_none());
}
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
}
/// Table entries for the cost tests below.
const NAMED: usize = 40_000;
/// A name of 54 bytes whose first 48 every such name of `kind` shares, so comparing two costs
/// about 50 bytes and not a length check, as in a crafted file.
fn long_name(kind: &str, tail: &str) -> String {
format!("{kind}{}{tail}", "x".repeat(48 - kind.len()))
}
/// The [`NAMED`] names `long_name(kind, "000000")`, `..."000001"`, ...
fn long_names(kind: &str) -> impl Iterator<Item = String> + '_ {
(0..NAMED).map(move |i| long_name(kind, &format!("{i:06}")))
}
/// Each of a table's [`NAMED`] names is looked up in other case (found) and as a missing name of
/// the same length, well within a bound that scanning the table for each lookup misses: a file of
/// N entries and N objects naming one it lacks, or names in other case, drew in N² name
/// comparisons (#1924).
fn lookups_by_name_are_quick(kind: &str, found: impl Fn(&str) -> bool) {
let started = std::time::Instant::now();
for i in 0..NAMED {
assert!(found(&long_name(kind, &format!("{i:06}")).to_ascii_uppercase()), "{kind} {i}");
assert!(!found(&long_name(kind, &format!("z{i:05}"))), "{kind} {i}");
}
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
}
#[test]
fn linetype_lookups_by_name_cost_about_the_same_for_any_table_size() {
let mut d = Drawing::new_imperial();
d.linetypes = long_names("LT").map(|n| Linetype::simple(&n, "", &[0.5, -0.25])).collect();
lookups_by_name_are_quick("LT", |n| d.linetype(n).is_some());
}
#[test]
fn text_style_lookups_by_name_cost_about_the_same_for_any_table_size() {
let mut d = Drawing::new_imperial();
d.text_styles = long_names("S").map(|name| TextStyle { name, ..TextStyle::default() }).collect();
lookups_by_name_are_quick("S", |n| d.text_style(n).is_some());
}
#[test]
fn dim_style_lookups_by_name_cost_about_the_same_for_any_table_size() {
let mut d = Drawing::new_imperial();
d.dim_styles = long_names("D").map(|name| DimStyle { name, ..DimStyle::default() }).collect();
lookups_by_name_are_quick("D", |n| d.dim_style(n).is_some());
}
/// Each change to a drawing looks up every layout of the drawing before it by name (the check for
/// non-finite results), so a drawing of N layouts cost N² name comparisons per command.
#[test]
fn layout_lookups_by_name_cost_about_the_same_for_any_table_size() {
let mut d = Drawing::new_imperial();
d.layouts = long_names("L").zip(1..).map(|(n, tab)| Layout::new(&n, tab)).collect();
lookups_by_name_are_quick("L", |n| d.layout(n).is_some());
}
+7 -1
View File
@@ -1,5 +1,5 @@
//! Dimensions and leaders: DIMLINEAR, DIMALIGNED, DIMRADIUS, DIMDIAMETER, DIMANGULAR, DIMARC,
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, DIMOVERRIDE,
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, QLEADER, DIMOVERRIDE,
//! DIMREASSOCIATE / DIMDISASSOCIATE, DIMTEDIT, DIMSPACE; DIMEDIT, DIMJOGGED, DIMJOGLINE,
//! DIMBREAK and DIMINSPECT in `annotate_dimedit.rs`.
@@ -19,6 +19,7 @@ mod edit;
mod leader;
mod linear;
mod mleader;
mod qleader;
mod radial;
use angular::{AngularM, ArcLenM, run_angular, run_arclen};
@@ -27,6 +28,7 @@ use common::{DimText, add_dim, assoc_enabled, circle_of, dim, pick_at};
use edit::{DimSpaceM, OverrideM, dims_of, run_dimspace, run_dimtedit, run_disassociate, run_override, run_reassociate, run_tedit, run_update};
use linear::{ChainM, LinearM, MAX_CHAIN, OrdinateM, run_aligned, run_baseline, run_continue, run_linear, run_ordinate};
use mleader::{MLeaderM, run_leader, run_mleader};
use qleader::{QLeaderM, run_qleader};
use radial::{RadialM, run_diameter, run_radius};
pub fn specs() -> Vec<CommandSpec> {
@@ -93,6 +95,10 @@ pub fn specs() -> Vec<CommandSpec> {
.alias(&["lead"])
.params("{points: [[x,y]...], text?}")
.interactive(|_| Ok(Box::new(leader::LeaderM::default()))),
CommandSpec::new("qleader", "Quick Leader", run_qleader)
.alias(&["le"])
.params("{points: [[x,y], [x,y], [x,y]?] (2 or 3), width?: text width (default 0), text?: lines split at \\n}")
.interactive(|_| Ok(Box::new(QLeaderM::default()))),
CommandSpec::new("dimstyle.update", "Update", run_update)
.menu(&["Dimension", "Update"])
.params("{handles?}")
+25 -3
View File
@@ -42,8 +42,13 @@ pub(super) struct LeaderM {
}
/// What follows the leader.
enum Annotation {
pub(super) enum Annotation {
Text(Vec<String>),
/// QLEADER's text: its lines and its width.
Quick {
lines: Vec<String>,
width: f64,
},
/// A copy of a text or multiline text: its contents, height, width and style.
Copy(MText),
None,
@@ -263,13 +268,13 @@ pub(super) fn json_leader(s: &mut Session, pts: &[Vec2], text: Option<&str>) ->
}
/// Draw the leader through `pts` and its annotation, as AutoCAD 2024 places them; their handles.
fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
let (Some(&end), Some(&before)) = (pts.last(), pts.len().checked_sub(2).and_then(|i| pts.get(i))) else { return Ok(Vec::new()) };
let z = sizes(s);
// The side the leader runs to: right unless its last segment runs left.
let dir = if end.x < before.x { -1.0 } else { 1.0 };
let mut vertices = pts.to_vec();
if let Annotation::Text(_) | Annotation::Copy(_) = ann {
if let Annotation::Text(_) | Annotation::Quick { .. } | Annotation::Copy(_) = ann {
let d = end - before;
// A copied text is centred on its line, and with DIMTAD on that line is above the leader:
// the leader ends half the text height lower.
@@ -310,6 +315,23 @@ fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Ann
columns: None,
}))?)
}
Annotation::Quick { lines, width } => {
// The middle of the first line level with the end on the right, of the last line on
// the left, whatever DIMTAD.
let (attach, lift) = if dir > 0.0 { (1, z.text / 2.0) } else { (9, -z.text / 2.0) };
Some(s.add_entity(EntityKind::MText(MText {
insert: v3(end + Vec2::new(dir * z.gap, lift)),
height: z.text,
width,
attach,
rotation: 0.0,
style: z.text_style,
contents: lines.join("\\P"),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
}))?)
}
Annotation::Copy(m) => {
let lift = if z.above { z.gap } else { 0.0 };
let attach = if dir > 0.0 { 4 } else { 6 };
+121
View File
@@ -0,0 +1,121 @@
//! QLEADER at the command line, as AutoCAD 2024 runs it with its default settings (accoreconsole,
//! synthetic drawings): up to three points, a text width, then lines of text.
//!
//! The leader is LEADER's, with an arrow and a hook line DIMASZ long when its last segment is more
//! than 15° off horizontal and text follows. The multiline text sits DIMGAP past the leader's end,
//! as wide as the width given: with the middle of its first line level with the end when the
//! leader runs right, and of its last line when it runs left, whatever DIMTAD. Enter at the first
//! line of text leaves the leader without text. The Settings dialog isn't available yet.
use serde_json::{Value, json};
use super::leader::{Annotation, add_leader};
use super::{Accept, Input, Interactive, Prompt, Result, Session, Step, Vec2, bad, points_param, str_param};
use crate::cmd::size_param;
/// QLEADER's default number of leader points.
const MAX_POINTS: usize = 3;
#[derive(Clone, Copy, Default, PartialEq)]
enum Ask {
#[default]
Points,
Width,
FirstLine,
NextLine,
}
#[derive(Default)]
pub(super) struct QLeaderM {
ask: Ask,
pts: Vec<Vec2>,
width: f64,
lines: Vec<String>,
}
impl Interactive for QLeaderM {
fn name(&self) -> &'static str {
"QLEADER"
}
fn prompt(&self, _s: &Session) -> Prompt {
let last = self.pts.last().copied();
match self.ask {
Ask::Points if self.pts.is_empty() => Prompt::new("Specify first leader point,", Accept::POINT).kw(&["Settings"]).default("Settings"),
Ask::Points => Prompt::new("Specify next point", Accept::POINT).base_opt(last),
// The width isn't remembered: AutoCAD 2024 offers 0 again after a width of 20.
Ask::Width => Prompt::new("Specify text width", Accept::POINT_OR_NUMBER).distance().default("0").base_opt(last),
Ask::FirstLine => Prompt::new("Enter first line of annotation text", Accept::TEXT).default("Mtext"),
Ask::NextLine => Prompt::new("Enter next line of annotation text", Accept::TEXT),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match self.ask {
Ask::Points => match i {
Input::Point(p) => {
self.pts.push(p);
if self.pts.len() == MAX_POINTS {
self.ask = Ask::Width;
}
}
Input::Enter | Input::Keyword(_) if self.pts.is_empty() => s.echo("The QLEADER Settings dialog is not available yet."),
// Enter after one point: no leader.
Input::Enter if self.pts.len() < 2 => return Ok(Step::Done),
Input::Enter => self.ask = Ask::Width,
_ => {}
},
Ask::Width => {
// A point gives the width as its distance from the leader's end; a negative
// width is none.
let width = match i {
Input::Point(p) => self.pts.last().map(|e| e.dist(p)),
Input::Text(t) => crate::units::parse_distance(&t),
Input::Enter => Some(0.0),
_ => return Ok(Step::Continue),
};
let finite = width.filter(|w| w.is_finite());
self.width = finite.ok_or_else(|| crate::EngineError::Other("Requires numeric distance or two points.".into()))?.max(0.0);
self.ask = Ask::FirstLine;
}
// Only typed text and Enter: a click in the drawing is no line of text, as at TEXT's.
Ask::FirstLine | Ask::NextLine => match i {
Input::Text(t) if !t.is_empty() => {
self.lines.push(t);
self.ask = Ask::NextLine;
}
Input::Text(_) | Input::Enter => {
let lines = std::mem::take(&mut self.lines);
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width: self.width } };
add_leader(s, &std::mem::take(&mut self.pts), false, true, ann)?;
return Ok(Step::Done);
}
_ => {}
},
}
Ok(Step::Continue)
}
}
/// QLEADER's JSON form: a leader through 2 or 3 `points`, with `text` (one line per line of it) as wide
/// as `width`, placed as the command line places them. The handles of the leader and its text.
pub(super) fn run_qleader(s: &mut Session, p: &Value) -> Result<Value> {
if p.get("points").is_none_or(Value::is_null) {
return Err(bad("qleader", "`points` is required"));
}
let pts = points_param(p, "points").ok_or_else(|| bad("qleader", "`points` must be a list of [x, y] points"))?;
if !(2..=MAX_POINTS).contains(&pts.len()) {
return Err(bad("qleader", "`points` takes 2 or 3 points"));
}
let width = size_param("qleader", p, "width", true)?.unwrap_or(0.0);
if p.get("text").is_some_and(|t| !t.is_null() && !t.is_string()) {
return Err(bad("qleader", "`text` must be a string"));
}
// Empty lines at the end are dropped, as the command line ends at one: a left-running leader
// would otherwise sit level with a blank last line. Text with nothing left is no text.
let mut lines: Vec<String> = str_param(p, "text").map(|t| t.lines().map(str::to_string).collect()).unwrap_or_default();
while lines.last().is_some_and(String::is_empty) {
lines.pop();
}
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width } };
let hs = add_leader(s, &pts, false, true, ann)?;
Ok(json!({ "handles": hs.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
+7 -5
View File
@@ -386,16 +386,18 @@ fn fmt(v: f64) -> String {
format!("{v:.4}")
}
/// A count typed at a prompt (Enter keeps `cur`); `None` for inputs the prompt ignores.
/// A count typed at a prompt (Enter keeps `cur`); `None` for inputs the prompt ignores. A whole
/// number as typed: AutoCAD 2024 takes +3 and 03 at its array counts and refuses 5.0, 1e1, 8/2
/// and 3' (measured at ARRAYRECT's rows and columns, ARRAYPOLAR's items and rows, and -ARRAY).
fn count(i: &Input, cur: u64, max: u64) -> Result<Option<u64>> {
match i {
Input::Enter => Ok(Some(cur)),
Input::Text(t) => t
.trim()
.parse::<f64>()
.parse::<u64>()
.ok()
.filter(|v| v.fract() == 0.0 && *v >= 1.0 && *v <= max as f64)
.map(|v| Some(v as u64))
.filter(|v| (1..=max).contains(v))
.map(Some)
.ok_or_else(|| other(format!("Requires an integer between 1 and {max} (MAXARRAY limits the size of the array)."))),
_ => Ok(None),
}
@@ -437,7 +439,7 @@ fn run_array(s: &mut Session, p: &Value) -> Result<Value> {
}
/// A count parameter (at least 1); a missing key gives the default, an invalid value is refused.
fn count_or(cmd: &str, p: &Value, key: &str, default: u64) -> Result<u64> {
pub(crate) fn count_or(cmd: &str, p: &Value, key: &str, default: u64) -> Result<u64> {
match p.get(key) {
None | Some(Value::Null) => Ok(default),
Some(v) => v.as_u64().filter(|n| *n >= 1).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of at least 1"))),
+183 -60
View File
@@ -403,13 +403,14 @@ fn run_insert(s: &mut Session, p: &Value) -> Result<Value> {
/// MINSERT's JSON form: INSERT's parameters and the grid.
fn run_minsert(s: &mut Session, p: &Value) -> Result<Value> {
// A whole number, as the array commands' JSON counts are: 2.0 and 1e2 are refused too.
let count = |key: &str| -> Result<u32> {
match p.get(key) {
None | Some(Value::Null) => Ok(1),
Some(v) => v
.as_f64()
.filter(|n| n.fract() == 0.0 && *n >= 1.0 && *n <= f64::from(Grid::MAX))
.map(|n| n as u32)
.as_u64()
.and_then(|n| u32::try_from(n).ok())
.filter(|n| (1..=Grid::MAX).contains(n))
.ok_or_else(|| bad("minsert", format!("`{key}` must be an integer between 1 and {}", Grid::MAX))),
}
};
@@ -833,11 +834,35 @@ enum InsStage {
/// rows).
Cell(Vec2),
ColSpacing,
/// The second of two points a preset or the column spacing takes after a point (AutoCAD 2024
/// asks "Specify second point:"), from the first.
Second(TwoPoints, Vec2),
Attribs,
/// A Verify attribute asked again.
Verify,
}
/// What two points give: a preset scale factor (all axes, or one) or the column spacing by their
/// distance, the preset rotation by their direction.
#[derive(Clone, Copy, Debug, PartialEq)]
enum TwoPoints {
Scale,
Axis(usize),
Rotation,
ColSpacing,
}
// AutoCAD 2024's messages at INSERT's and MINSERT's scale, rotation and spacing prompts (measured):
// a scale factor of 0; anything else that isn't a number where two points give a distance or an
// angle, where a point gives the distance from the insertion point, and where only a number does.
const NONZERO: &str = "Value must be nonzero.";
/// Exploded INSERT's scale factor, which must be positive.
const POSITIVE: &str = "Value must be positive and nonzero.";
const TWO_POINTS: &str = "Requires numeric distance or two points.";
const ANGLE_TWO_POINTS: &str = "Requires valid numeric angle or two points.";
const SECOND_POINT: &str = "Requires numeric distance or second point.";
const NUMERIC: &str = "Requires numeric value.";
#[derive(Default)]
struct InsertM {
stage: InsStage,
@@ -1018,6 +1043,66 @@ impl InsertM {
}
Ok(d)
}
/// The Scale preset `f` for every axis.
fn preset_scale(&mut self, s: &mut Session, f: f64) -> Result<Step> {
self.scale = Some(Vec2::new(f, f));
self.z_scale = Some(f.abs());
// An axis preset after it changes that axis alone (Scale -3 then X 2: 2/-3/3).
self.axes = [Some(f), Some(f), Some(f.abs())];
// Exploded insertion asks its one scale factor after the insertion point.
if self.at.is_some() {
return self.advance(s);
}
self.stage = InsStage::Point;
Ok(Step::Continue)
}
/// One axis preset: the others are 1, and no scale factors are asked after the point.
fn preset_axis(&mut self, ax: usize, f: f64) -> Result<Step> {
if let Some(a) = self.axes.get_mut(ax) {
*a = Some(f);
}
let [x, y, z] = self.axes.map(|a| a.unwrap_or(1.0));
self.scale = Some(Vec2::new(x, y));
self.z_scale = Some(z.abs());
self.stage = InsStage::Point;
Ok(Step::Continue)
}
fn preset_rotation(&mut self, r: f64) -> Result<Step> {
self.rotation = Some(r);
self.stage = InsStage::Point;
Ok(Step::Continue)
}
/// The second of two points (AutoCAD 2024, measured): their distance is a preset scale factor
/// (0 refused) or the column spacing (0 taken), their direction the preset rotation. Enter
/// keeps a preset's default and is refused for the spacing, as anything else is; a refusal asks
/// the first prompt again.
fn second_point(&mut self, s: &mut Session, what: TwoPoints, a: Vec2, i: Input) -> Result<Step> {
let (first, refused) = match what {
TwoPoints::Scale => (InsStage::PresetScale, TWO_POINTS),
TwoPoints::Axis(ax) => (InsStage::PresetAxis(ax), TWO_POINTS),
TwoPoints::Rotation => (InsStage::PresetRotation, ANGLE_TWO_POINTS),
TwoPoints::ColSpacing => (InsStage::ColSpacing, TWO_POINTS),
};
self.stage = first;
match (what, i) {
(TwoPoints::ColSpacing, Input::Point(b)) => {
self.col_spacing = Some(a.dist(b));
self.advance(s)
}
(TwoPoints::Rotation, Input::Point(b)) => self.preset_rotation(a.angle_to(b)),
(TwoPoints::Rotation, Input::Enter) => self.preset_rotation(0.0),
(TwoPoints::Scale | TwoPoints::Axis(_), Input::Point(b)) if a.dist(b) == 0.0 => Err(EngineError::Other(NONZERO.into())),
(TwoPoints::Scale, Input::Point(b)) => self.preset_scale(s, a.dist(b)),
(TwoPoints::Scale, Input::Enter) => self.preset_scale(s, 1.0),
(TwoPoints::Axis(ax), Input::Point(b)) => self.preset_axis(ax, a.dist(b)),
(TwoPoints::Axis(ax), Input::Enter) => self.preset_axis(ax, 1.0),
_ => Err(EngineError::Other(refused.into())),
}
}
}
/// A distance typed at MINSERT's grid prompts: any finite number, negative or 0 too.
@@ -1025,8 +1110,14 @@ fn distance(t: &str) -> Result<f64> {
number(t).filter(|v| v.is_finite()).ok_or_else(|| EngineError::Other("Requires a distance.".into()))
}
fn nonzero(t: &str) -> Result<f64> {
number(t).filter(|v| *v != 0.0).ok_or_else(|| EngineError::Other("Requires a non-zero number.".into()))
/// A scale factor typed at `t`: 0 gets AutoCAD 2024's "Value must be nonzero.", anything that
/// isn't a number the prompt's own message.
fn nonzero(t: &str, not_a_number: &str) -> Result<f64> {
let v = number(t).ok_or_else(|| EngineError::Other(not_a_number.into()))?;
if v == 0.0 {
return Err(EngineError::Other(NONZERO.into()));
}
Ok(v)
}
impl Interactive for InsertM {
@@ -1047,22 +1138,31 @@ impl Interactive for InsertM {
}
InsStage::Point => Prompt::new("Specify insertion point", Accept::POINT).kw(&["Basepoint", "Scale", "X", "Y", "Z", "Rotate"]),
InsStage::BasePoint => Prompt::new("Specify base point", Accept::POINT),
InsStage::PresetScale => Prompt::new("Specify scale factor for XYZ axes", Accept::NUMBER).default("1"),
InsStage::PresetAxis(i) => Prompt::new(format!("Specify {} scale factor", ["X", "Y", "Z"][i.min(2)]), Accept::NUMBER).default("1"),
// Exploded, after the insertion point, it takes a number only.
InsStage::PresetScale if self.at.is_some() => Prompt::new("Specify scale factor for XYZ axes", Accept::NUMBER).default("1"),
InsStage::PresetScale => Prompt::new("Specify scale factor for XYZ axes", Accept::POINT_OR_NUMBER).default("1"),
InsStage::PresetAxis(i) => {
Prompt::new(format!("Specify {} scale factor", ["X", "Y", "Z"][i.min(2)]), Accept::POINT_OR_NUMBER).default("1")
}
// Typed text is read as before (`<<45` the angle, not an override for a point); a point
// still comes from a click or LISP.
InsStage::PresetRotation => Prompt::new("Specify rotation angle", Accept::NUMBER).default("0"),
// Text is read here, not taken as a distance along the rubber band: the core console
// refuses 5 at this prompt (measured).
InsStage::Second(_, a) => Prompt::new("Specify second point", Accept::POINT_OR_NUMBER).base(a),
InsStage::XScale if self.xyz => Prompt::new("Specify X scale factor", Accept::POINT_OR_NUMBER).kw(&["Corner"]).default("1").base(at),
InsStage::XScale => {
Prompt::new("Enter X scale factor, specify opposite corner", Accept::POINT_OR_NUMBER).kw(&["Corner", "XYZ"]).default("1").base(at)
}
InsStage::Corner => Prompt::new("Specify opposite corner", Accept::POINT).base(at),
InsStage::YScale => Prompt::new("Enter Y scale factor", Accept::NUMBER).default("use X scale factor"),
InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::NUMBER).default("use X scale factor"),
InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::POINT_OR_NUMBER).default("use X scale factor").base(at),
InsStage::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER).default("0").base(at),
InsStage::Rows => Prompt::new("Enter number of rows (---)", Accept::NUMBER).default("1"),
InsStage::Cols => Prompt::new("Enter number of columns (|||)", Accept::NUMBER).default("1"),
InsStage::RowSpacing => Prompt::new("Enter distance between rows or specify unit cell (---)", Accept::POINT_OR_NUMBER),
InsStage::Cell(a) => Prompt::new("Specify opposite corner", Accept::POINT).corner(a),
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::NUMBER),
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::POINT_OR_NUMBER),
InsStage::Attribs => {
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);
@@ -1138,45 +1238,58 @@ impl Interactive for InsertM {
self.stage = InsStage::Point;
}
}
InsStage::PresetScale => {
let f = match i {
Input::Text(t) => nonzero(&t)?,
Input::Enter => 1.0,
_ => return Ok(Step::Continue),
// Exploded, after the insertion point: a positive number only (AutoCAD 2024 refuses a
// point and x with "Requires numeric value.", 0 and -2 with "Value must be positive and
// nonzero.", measured).
InsStage::PresetScale if self.at.is_some() => {
return match i {
Input::Text(t) => {
let f = number(&t).ok_or_else(|| EngineError::Other(NUMERIC.into()))?;
let f = Some(f).filter(|f| *f > 0.0).ok_or_else(|| EngineError::Other(POSITIVE.into()))?;
self.preset_scale(s, f)
}
Input::Enter => self.preset_scale(s, 1.0),
_ => Err(EngineError::Other(NUMERIC.into())),
};
self.scale = Some(Vec2::new(f, f));
self.z_scale = Some(f.abs());
// An axis preset after it changes that axis alone (Scale -3 then X 2: 2/-3/3).
self.axes = [Some(f), Some(f), Some(f.abs())];
// Exploded insertion asks its one scale factor after the insertion point.
if self.at.is_some() {
return self.advance(s);
}
self.stage = InsStage::Point;
}
// One axis preset: the others are 1, and no scale factors are asked after the point.
// A point at a preset is the first of two (AutoCAD 2024, measured).
InsStage::PresetScale => {
return match i {
Input::Point(p) => {
self.stage = InsStage::Second(TwoPoints::Scale, p);
Ok(Step::Continue)
}
Input::Text(t) => self.preset_scale(s, nonzero(&t, TWO_POINTS)?),
Input::Enter => self.preset_scale(s, 1.0),
_ => Err(EngineError::Other(TWO_POINTS.into())),
};
}
InsStage::PresetAxis(ax) => {
let f = match i {
Input::Text(t) => nonzero(&t)?,
Input::Enter => 1.0,
_ => return Ok(Step::Continue),
return match i {
Input::Point(p) => {
self.stage = InsStage::Second(TwoPoints::Axis(ax), p);
Ok(Step::Continue)
}
Input::Text(t) => self.preset_axis(ax, nonzero(&t, TWO_POINTS)?),
Input::Enter => self.preset_axis(ax, 1.0),
_ => Err(EngineError::Other(TWO_POINTS.into())),
};
if let Some(a) = self.axes.get_mut(ax) {
*a = Some(f);
}
let [x, y, z] = self.axes.map(|a| a.unwrap_or(1.0));
self.scale = Some(Vec2::new(x, y));
self.z_scale = Some(z.abs());
self.stage = InsStage::Point;
}
InsStage::PresetRotation => {
self.rotation = Some(match i {
Input::Text(t) => s.angle_settings().direction(&t).ok_or_else(|| EngineError::Other("Requires an angle.".into()))?,
Input::Enter => 0.0,
_ => return Ok(Step::Continue),
});
self.stage = InsStage::Point;
return match i {
Input::Point(p) => {
self.stage = InsStage::Second(TwoPoints::Rotation, p);
Ok(Step::Continue)
}
Input::Text(t) => {
let r = s.angle_settings().direction(&t).ok_or_else(|| EngineError::Other(ANGLE_TWO_POINTS.into()))?;
self.preset_rotation(r)
}
Input::Enter => self.preset_rotation(0.0),
_ => Err(EngineError::Other(ANGLE_TWO_POINTS.into())),
};
}
InsStage::Second(what, a) => return self.second_point(s, what, a, i),
InsStage::XScale => match i {
Input::Keyword(k) if k == "Corner" => self.stage = InsStage::Corner,
Input::Keyword(k) if k == "XYZ" => self.xyz = true,
@@ -1185,7 +1298,7 @@ impl Interactive for InsertM {
return self.corner_scale(s, sc);
}
Input::Text(t) => {
self.x_scale = Some(nonzero(&t)?);
self.x_scale = Some(nonzero(&t, "Requires a non-zero number.")?);
self.stage = InsStage::YScale;
}
Input::Enter => {
@@ -1202,10 +1315,11 @@ impl Interactive for InsertM {
}
InsStage::YScale => {
let x = self.x_scale.unwrap_or(1.0);
// A number only: AutoCAD 2024 refuses a point here (measured).
let y = match i {
Input::Text(t) => nonzero(&t)?,
Input::Text(t) => nonzero(&t, NUMERIC)?,
Input::Enter => x,
_ => return Ok(Step::Continue),
_ => return Err(EngineError::Other(NUMERIC.into())),
};
self.scale = Some(Vec2::new(x, y));
if self.xyz {
@@ -1214,11 +1328,15 @@ impl Interactive for InsertM {
}
return self.advance(s);
}
// A point gives its distance from the insertion point (AutoCAD 2024, measured).
InsStage::ZScale => {
self.z_scale = Some(match i {
Input::Text(t) => nonzero(&t)?,
Input::Text(t) => nonzero(&t, SECOND_POINT)?,
Input::Enter => self.x_scale.unwrap_or(1.0).abs(),
_ => return Ok(Step::Continue),
Input::Point(p) => {
Some(self.at.unwrap_or_default().dist(p)).filter(|d| *d != 0.0).ok_or_else(|| EngineError::Other(NONZERO.into()))?
}
_ => return Err(EngineError::Other(SECOND_POINT.into())),
});
return self.advance(s);
}
@@ -1232,17 +1350,14 @@ impl Interactive for InsertM {
return self.advance(s);
}
InsStage::Rows | InsStage::Cols => {
// A whole number as typed: AutoCAD 2024 takes +3 and 03 here and refuses 5.0, 5.,
// 1e1, 8/2, 3', 4.5 and a point (measured at the rows, and 5.0 and +3 at the columns).
let n = match i {
Input::Text(t) => t
.trim()
.parse::<f64>()
.ok()
.filter(|v| v.fract() == 0.0 && *v >= 1.0 && *v <= f64::from(Grid::MAX))
.map(|v| v as u32)
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 1 and {}.", Grid::MAX)))?,
Input::Enter => 1,
_ => return Ok(Step::Continue),
};
Input::Text(t) => t.trim().parse::<u32>().ok().filter(|v| (1..=Grid::MAX).contains(v)),
Input::Enter => Some(1),
_ => None,
}
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 1 and {}.", Grid::MAX)))?;
if self.stage == InsStage::Rows {
self.rows = Some(n);
} else {
@@ -1264,11 +1379,19 @@ impl Interactive for InsertM {
return self.advance(s);
}
}
// A distance, or two points (AutoCAD 2024, measured): Enter is refused too.
InsStage::ColSpacing => {
if let Input::Text(t) = i {
self.col_spacing = Some(distance(&t)?);
return self.advance(s);
}
return match i {
Input::Text(t) => {
self.col_spacing = Some(number(&t).filter(|v| v.is_finite()).ok_or_else(|| EngineError::Other(TWO_POINTS.into()))?);
self.advance(s)
}
Input::Point(p) => {
self.stage = InsStage::Second(TwoPoints::ColSpacing, p);
Ok(Step::Continue)
}
_ => Err(EngineError::Other(TWO_POINTS.into())),
};
}
InsStage::Attribs => {
let (tag, _, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
+4 -7
View File
@@ -3,7 +3,7 @@
use std::sync::Arc;
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert};
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert, TagKey};
use serde_json::{Value, json};
use crate::cmd::curves::KW;
@@ -102,17 +102,14 @@ impl Interactive for AttdispM {
/// Properties set on single attributes (layer, colour, …) go back to the definitions', as in AutoCAD.
pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec<Attrib> {
let m = ins.transform(blk.base.xy());
// The reference's attributes by tag, gathered once for all the definitions (#1923).
let carried = ins.attribs_by_tag();
defs.iter()
.map(|ad| {
let mut k = EntityKind::Text(ad.text.clone());
k.transform(&m);
let mut t = if let EntityKind::Text(t) = k { t } else { ad.text.clone() };
t.value = ins
.attribs
.iter()
.find(|a| a.tag.eq_ignore_ascii_case(&ad.tag))
.map(|a| a.text.value.clone())
.unwrap_or_else(|| ad.text.value.clone());
t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
Attrib {
tag: ad.tag.clone(),
text: t,
+8 -8
View File
@@ -2,7 +2,7 @@
//! become text with the values they show instead of the block's attribute definitions.
use cadcraft_color::Color;
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Insert};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, TagKey};
use serde_json::{Value, json};
use crate::cmd::machines::SelectRun;
@@ -28,22 +28,22 @@ fn run_burst(s: &mut Session, p: &Value) -> Result<Value> {
fn burst_pieces(d: &Drawing, e: &Entity) -> Option<Vec<Entity>> {
let EntityKind::Insert(ins) = &e.kind else { return None };
let mut out: Vec<Entity> = explode_kind(d, e)?.into_iter().filter(|p| !matches!(p.kind, EntityKind::AttDef(_))).collect();
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = d.block(&ins.block).map(|b| b.attdefs_by_tag()).unwrap_or_default();
for a in ins.attribs.iter().filter(|a| !a.invisible) {
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
None => EntityKind::Text(a.text.clone()),
};
out.push(Entity { handle: Handle(0), common: attrib_common(d, e, ins, &a.tag, &a.props), kind });
out.push(Entity { handle: Handle(0), common: attrib_common(e, defs.get(&TagKey(&a.tag)).copied(), &a.props), kind });
}
Some(out)
}
/// The properties an attribute is drawn with: its own, else its definition's; layer 0 is the
/// reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the block's
/// objects.
fn attrib_common(d: &Drawing, e: &Entity, ins: &Insert, tag: &str, props: &cadcraft_doc::AttribProps) -> Common {
let def =
d.block(&ins.block).and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(tag))));
/// The properties an attribute is drawn with: its own, else those of its definition `def`; layer
/// 0 is the reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the
/// block's objects.
fn attrib_common(e: &Entity, def: Option<&Entity>, props: &cadcraft_doc::AttribProps) -> Common {
// An attribute without a definition follows the reference.
let base = def.map(|de| de.common.clone()).unwrap_or_else(|| Common { color: Color::ByBlock, ..Common::default() });
let mut c = props.over(&base);
+52 -5
View File
@@ -5,7 +5,7 @@
use cadcraft_doc::color::Color;
use cadcraft_doc::dynblock::{self, GripPart, GripShape};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, Transparency};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, TagKey, Transparency};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
@@ -111,11 +111,10 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
.collect();
// An attribute draws with its definition's properties, except those set on it.
let by_block = Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..r.clone() };
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = b.attdefs_by_tag();
out.extend(ins.attribs.iter().filter(|a| !a.invisible).map(|a| {
let def = b.entities.iter().find_map(|e| match &e.kind {
EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag) => Some(&e.common),
_ => None,
});
let def = defs.get(&TagKey(&a.tag)).map(|e| &e.common);
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
@@ -248,3 +247,51 @@ impl Session {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn many_attributes_are_previewed_without_comparing_every_pair_with_the_definitions() {
// #1923: a reference with N attributes of a block with N definitions, the tags N long ones
// alike up to their last characters, no attribute's a definition's. Looking for each
// attribute's definition by comparing it with every one cost N x N comparisons of whole
// tags for each preview (many seconds here); the definitions gathered by tag once cost
// milliseconds.
const N: usize = 4000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let attrib = |tag: String| cadcraft_doc::Attrib {
tag,
text: cadcraft_doc::Text {
insert: cadcraft_geom::Vec3::ZERO,
align_pt: None,
height: 1.0,
value: "v".into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
},
invisible: false,
constant: false,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
};
let mut d = Drawing::new_metric();
let mut blk = cadcraft_doc::Block::new("B");
for (h, i) in (1..).zip(0..N) {
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(attrib(tag('D', i)))));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let ins = cadcraft_doc::Insert { block: "B".into(), attribs: (0..N).map(|i| attrib(tag('A', i))).collect(), ..Default::default() };
let h = d.add(&cadcraft_doc::Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let t = std::time::Instant::now();
assert_eq!(drawn(&d, h).len(), N);
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
}
}
+24 -15
View File
@@ -8,7 +8,9 @@ use cadcraft_geom::{Mat3, Vec2, Vec3};
use serde_json::{Value, json};
use super::super::curves::KW;
use super::super::file::{Version, lost_message, lost_writing, new_folder, own_version, report_lost, report_new_folder};
use super::super::file::{
Version, drops_unknown, dwg_notes, lost_message, lost_writing, new_folder, own_version, report_dwg_notes, report_lost, report_new_folder,
};
use super::super::machines::{SelOutcome, SelectPhase};
use super::super::modify::erase_kept;
use super::super::{CommandSpec, bad, point_param, str_param, targets};
@@ -46,7 +48,7 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("wblock", "`path` is required"))?.to_string();
let base = point_param(p, "base");
let folder = new_folder(&path);
let (entities, bytes, lost, version) = match str_param(p, "name") {
let (entities, bytes, lost, version, notes) = match str_param(p, "name") {
Some("*") => write(s, "wblock", &path, Source::Whole)?,
Some(name) => write(s, "wblock", &path, Source::Block(name, base))?,
None => write(s, "wblock", &path, Source::Objects(&targets(s, p)?, base.unwrap_or(Vec2::ZERO)))?,
@@ -54,6 +56,7 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
report_new_folder(s, &mut r, folder);
report_lost(s, &mut r, &path, version, &lost);
report_dwg_notes(s, &mut r, notes);
Ok(r)
}
@@ -64,7 +67,7 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("-wblock", "`path` is required"))?.to_string();
let base = point_param(p, "base");
let folder = new_folder(&path);
let (entities, bytes, lost, version) = match str_param(p, "name") {
let (entities, bytes, lost, version, notes) = match str_param(p, "name") {
Some(name) => write(s, "-wblock", &path, Source::Block(name, base))?,
None => {
let hs = targets(s, p)?;
@@ -80,16 +83,17 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
report_new_folder(s, &mut r, folder);
report_lost(s, &mut r, &path, version, &lost);
report_dwg_notes(s, &mut r, notes);
Ok(r)
}
/// Write `what` to `path` through the io hooks; the objects written, the file's size, what the
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams) and
/// the version it was written at, for the caller to report as a save does. The
/// written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK does: its units
/// ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in inches and
/// scaled on insert, and its defaults (text size, current styles, annotation scales).
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version)> {
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams), the
/// version it was written at and what a DWG keeps only in part, for the caller to report as a
/// save does. The written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK
/// does: its units ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in
/// inches and scaled on insert, and its defaults (text size, current styles, annotation scales).
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version, Vec<String>)> {
let src = s.doc()?;
// The base point becomes the written drawing's origin: by default 0,0 for objects and the
// block's base point for a block.
@@ -115,14 +119,19 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi
// The written drawing's own version: the writer is given no other.
let version = own_version(&d, path);
let lost = lost_writing(&d, path, version);
Ok((d.model.len(), bytes.len(), lost, version))
let notes = if drops_unknown(path) { dwg_notes(&d) } else { Vec::new() };
Ok((d.model.len(), bytes.len(), lost, version, notes))
}
/// Say on the command line what the file written at `path` and `version` left out.
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>) {
/// Say on the command line what the file written at `path` and `version` left out, and what a
/// DWG keeps only in part (`notes`).
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>, notes: Vec<String>) {
if let Some(msg) = lost_message(path, version, lost) {
s.echo(msg);
}
for note in notes {
s.echo(note);
}
}
/// A new drawing of `ents`, with `src`'s settings and the layers, linetypes, styles and blocks
@@ -341,7 +350,7 @@ impl DashWblockM {
fn write(&self, s: &mut Session, what: Source) -> Result<Step> {
match write(s, "-wblock", &self.path, what) {
Ok((.., lost, version)) => echo_not_saved(s, &self.path, version, &lost),
Ok((.., lost, version, notes)) => echo_not_saved(s, &self.path, version, &lost, notes),
Err(e) => s.echo(e.to_string()),
}
Ok(Step::Done)
@@ -352,8 +361,8 @@ impl DashWblockM {
return Ok(Step::Done);
}
match write(s, "-wblock", &self.path, Source::Objects(hs, self.base)) {
Ok((.., lost, version)) => {
echo_not_saved(s, &self.path, version, &lost);
Ok((.., lost, version, notes)) => {
echo_not_saved(s, &self.path, version, &lost, notes);
erase(s, hs)?;
}
Err(e) => s.echo(e.to_string()),
+4 -4
View File
@@ -265,10 +265,10 @@ fn defs_for(src: &Drawing, ents: &[Entity]) -> Drawing {
}
let mut d = Drawing::new_imperial();
d.header = src.header.clone();
d.layers = pick(&src.layers, &used.layers, |l| &l.name);
d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name);
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name);
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name);
d.layers = pick(&src.layers, &used.layers, |l| &l.name).into();
d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name).into();
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name).into();
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name).into();
d.mleader_styles = pick(&src.mleader_styles, &used.mleader_styles, |t| &t.name);
d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name);
d.blocks = src.blocks.iter().filter(|(k, _)| used.blocks.contains(&up(k))).map(|(k, b)| (k.clone(), b.clone())).collect();
+1 -1
View File
@@ -129,7 +129,7 @@ fn save(s: &mut Session, name: &str, annotative: Option<bool>, replace: bool) ->
if let Some(a) = annotative {
st.annotative = a;
}
let name = match d.dim_styles.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
let name = match d.dim_styles.by_name_mut(&name) {
Some(existing) if replace => {
let kept = existing.name.clone();
*existing = DimStyle { name: kept.clone(), ..st };
+2 -2
View File
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("pline", "Polyline", run_pline)
.menu(&["Draw", "Polyline"])
.alias(&["pl"])
.params("{vertices: [[x,y] | {p:[x,y], bulge, startWidth, endWidth}], closed?, width?}")
.params("{vertices: [[x,y] | {p:[x,y], bulge, startWidth, endWidth}], closed?, width? (default PLINEWID unless vertices give widths)}")
.interactive(|_| Ok(Box::new(PlineM::default()))),
CommandSpec::new("circle", "Circle", run_circle)
.menu(&["Draw", "Circle", "Center, Radius"])
@@ -62,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("rectang", "Rectangle", super::draw2::run_rectang2)
.menu(&["Draw", "Rectangle"])
.alias(&["rec", "rectangle"])
.params("{p1, p2 | dimensions: [l, w] (p2 picks the quadrant) | area + length|breadth, rotation? (deg), fillet?, chamfer?: [d1, d2], width?, elevation?, thickness?, center?: bool (p1 is the centre, not a corner; the size spans it evenly)}")
.params("{p1, p2 | dimensions: [l, w] (p2 picks the quadrant) | area + length|breadth (the outline encloses it, cut corners included), rotation? (deg), fillet? (wins over a chamfer), chamfer?: [d1, d2], width?, elevation?, thickness?, center?: bool (p1 is the centre, not a corner; the size spans it evenly)}")
.interactive(|_| Ok(Box::new(super::draw2::RectM2::default()))),
CommandSpec::new("polygon", "Polygon", run_polygon)
.menu(&["Draw", "Polygon"])
+21 -3
View File
@@ -45,15 +45,21 @@ fn current_elevation(s: &Session) -> Result<f64> {
pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
let raw = p.get("vertices").or_else(|| p.get("points")).and_then(Value::as_array);
let mut vertex_widths = false;
for v in raw.into_iter().flatten() {
size_param("pline", v, "startWidth", true)?;
size_param("pline", v, "endWidth", true)?;
vertex_widths |= size_param("pline", v, "startWidth", true)?.is_some() | size_param("pline", v, "endWidth", true)?.is_some();
}
let vs: Vec<PolyVertex> = raw.map(|a| a.iter().filter_map(vertex_value).collect()).unwrap_or_default();
if vs.len() < 2 {
return Err(bad("pline", "`vertices` needs at least 2 points"));
}
let width = size_param("pline", p, "width", true)?.unwrap_or(0.0);
// Without a width, the polyline starts at PLINEWID as the command does (unless its vertices
// give their own widths).
let width = match size_param("pline", p, "width", true)? {
Some(w) => w,
None if vertex_widths => 0.0,
None => Some(s.doc()?.header.f64("PLINEWID", 0.0)).filter(|w| w.is_finite() && *w > 0.0).unwrap_or(0.0),
};
let mut k = lwpoly(vs, bool_or(p, "closed", false));
if let EntityKind::LwPolyline(pl) = &mut k {
pl.const_width = width;
@@ -266,8 +272,11 @@ impl Interactive for PlineM {
fn name(&self) -> &'static str {
"PLINE"
}
/// Segments start at PLINEWID, the width the last Width or Halfwidth answer left.
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.elevation = current_elevation(s)?;
let w = s.doc()?.header.f64("PLINEWID", 0.0);
(self.start_w, self.end_w) = if w.is_finite() && w > 0.0 { (w, w) } else { (0.0, 0.0) };
Ok(Step::Continue)
}
fn prompt(&self, s: &Session) -> Prompt {
@@ -316,6 +325,11 @@ impl Interactive for PlineM {
self.end_w = self.start_w;
}
self.asking_width = if self.asking_width == 1 { 2 } else { 0 };
if self.asking_width == 0 {
// The ending width becomes PLINEWID, the next polyline's width (AutoCAD:
// Halfwidth 0.5 0.5 leaves PLINEWID 1).
s.doc_mut()?.header.set_f64("PLINEWID", self.end_w);
}
return Ok(Step::Continue);
}
if let (Some(a), Some(st)) = (self.ask, self.verts.last().map(|v| v.p)) {
@@ -379,6 +393,10 @@ impl Interactive for PlineM {
l.bulge = 0.0;
(l.start_width, l.end_width) = (0.0, 0.0);
}
// Back to the mode of the segment now last (AutoCAD: `_A` point `_U` returns
// to "Specify next point", where `_L` is Length, not arc mode's Line).
let n = self.verts.len();
self.arc_mode = n >= 2 && self.verts.get(n - 2).is_some_and(|v| v.bulge != 0.0);
self.sync(s, false)?;
Ok(Step::Continue)
}
+7 -1
View File
@@ -125,7 +125,11 @@ impl Interactive for SplineM {
}
match i {
Input::Point(p) => {
self.pts.push(p);
// The same point again is not a further fit point (AutoCAD 2024 leaves it out),
// nor a kink.
if self.pts.last() != Some(&p) {
self.pts.push(p);
}
Ok(Step::Continue)
}
Input::Keyword(k) if k == "Undo" => {
@@ -175,6 +179,8 @@ impl Interactive for SplineM {
}
Some(crate::cmd::spline_opts::SplineAsk::EndTangent) => opts.end_tangent = self.pts.last().map(|l| c - *l).filter(|d| d.len() > 1e-12),
Some(_) => {}
// The cursor on the last point adds nothing, as a click there doesn't.
None if pts.last() == Some(&c) => {}
None => pts.push(c),
}
if pts.len() < 2 {
+1 -1
View File
@@ -7,7 +7,7 @@ use cadcraft_geom::{Arc, Circle, Ellipse, Line, PolyVertex, Polyline, Spline, TA
use serde_json::{Value, json};
use super::curves::{self, Chain, MAX_GEN, TanObj};
use super::helpers::{arc, circle, line, lwpoly, rect_vertices, rect_with_corners, v3};
use super::helpers::{arc, circle, line, lwpoly, rect_corners_fit, rect_vertices, rect_with_corners, v3};
use super::machines::number;
use super::{CommandSpec, bad, bool_or, f64_or, f64_req, point_param, point_req, point_value, points_param, size_param, str_param, targets};
+33 -14
View File
@@ -139,6 +139,15 @@ impl DivideM {
pub(super) fn new(measure: bool) -> Self {
DivideM { measure, obj: None, phase: DivPhase::Object, block: None, align: true }
}
/// The JSON form's parameters for the picked object, before the count or length.
fn params(&self, h: Handle, pick: Vec2) -> Value {
let mut params = json!({ "handle": h.hex(), "align": self.align, "from": [pick.x, pick.y] });
if let Some(b) = &self.block {
params["block"] = json!(b);
}
params
}
}
impl Interactive for DivideM {
@@ -187,27 +196,37 @@ impl Interactive for DivideM {
self.phase = DivPhase::Value;
Ok(Step::Continue)
}
(DivPhase::Value, inp @ (Input::Text(_) | Input::Point(_))) => {
(DivPhase::Value, inp @ (Input::Text(_) | Input::Point(_))) if self.measure => {
let Some((h, pick)) = self.obj else { return Ok(Step::Cancel) };
let v = match inp {
Input::Text(t) => number(&t).ok_or_else(|| other("Requires a number."))?,
Input::Point(q) => pick.dist(q),
_ => return Ok(Step::Continue),
};
let mut params = json!({ "handle": h.hex(), "align": self.align, "from": [pick.x, pick.y] });
if let Some(b) = &self.block {
params["block"] = json!(b);
}
if self.measure {
params["length"] = json!(v);
run_measure(s, &params)?;
} else {
if !(2.0..=32767.0).contains(&v) || v.fract() != 0.0 {
return Err(other("Requires an integer between 2 and 32767."));
}
params["segments"] = json!(v as u64);
run_divide(s, &params)?;
let mut params = self.params(h, pick);
params["length"] = json!(v);
run_measure(s, &params)?;
Ok(Step::Done)
}
(DivPhase::Value, inp) if !self.measure => {
// A whole number as typed: AutoCAD 2024 takes +5 and 05 here and refuses 5.0, 5.,
// 1e1, 4.5, 1, 32768, x, Enter and a point, naming the Block keyword while the
// prompt still offers it (measured).
let n = match inp {
Input::Text(t) => t.trim().parse::<u64>().ok().filter(|n| (2..=32767).contains(n)),
_ => None,
}
.ok_or_else(|| {
other(if self.block.is_some() {
"Requires an integer between 2 and 32767."
} else {
"Requires an integer between 2 and 32767, or option keyword."
})
})?;
let Some((h, pick)) = self.obj else { return Ok(Step::Cancel) };
let mut params = self.params(h, pick);
params["segments"] = json!(n);
run_divide(s, &params)?;
Ok(Step::Done)
}
(_, Input::Enter) => Ok(Step::Cancel),
+42 -16
View File
@@ -1,6 +1,6 @@
use super::{
Accept, EntityKind, Input, Interactive, PolyVertex, Prompt, Result, Session, Step, Value, Vec2, added, bad, bool_or, curves, f64_or, lwpoly,
number, other, point_param, point_req, rect_with_corners, size_param,
number, other, point_param, point_req, rect_corners_fit, rect_with_corners, size_param,
};
use crate::last_used::RectangModes;
@@ -19,9 +19,30 @@ fn rect_kind(first: Vec2, (w, h): (f64, f64), rot: f64, fillet: f64, chamfer: (f
k
}
/// The area a fillet's or chamfer's four corners take off the full rectangle (a fillet wins).
fn corner_area(fillet: f64, chamfer: (f64, f64)) -> f64 {
if fillet > 0.0 {
(4.0 - std::f64::consts::PI) * fillet * fillet
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 {
2.0 * chamfer.0 * chamfer.1
} else {
0.0
}
}
/// The sides of the rectangle of `area` with one side `side`, its length (or with `breadth`,
/// its width). AutoCAD sizes it so that the outline, corners cut, encloses the area: the corners'
/// area is added back. When the corners then don't fit they stay square, and the area is the full
/// rectangle's.
fn area_sides(area: f64, side: f64, breadth: bool, fillet: f64, chamfer: (f64, f64)) -> (f64, f64) {
let sides = |a: f64| if breadth { (a / side, side) } else { (side, a / side) };
let (w, h) = sides(area + corner_area(fillet, chamfer));
if rect_corners_fit(Vec2::new(w, h), fillet, chamfer) { (w, h) } else { sides(area) }
}
/// The width and height of a rectangle from its `dimensions`, its `p2` corner, its `area` with
/// `length` or `breadth`, or its second corner `p2`, rotated by `rot` about `a`.
fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool) -> Result<(f64, f64)> {
fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool, fillet: f64, chamfer: (f64, f64)) -> Result<(f64, f64)> {
Ok(if let Some(d) = p.get("dimensions").and_then(Value::as_array) {
let l = d.first().and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad("rectang", "dimensions: [length, width]"))?;
let wd = d.get(1).and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad("rectang", "dimensions: [length, width]"))?;
@@ -38,8 +59,8 @@ fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool) -> Result<(f64, f64)>
return Err(bad("rectang", "area must be positive"));
}
match (p.get("length").and_then(Value::as_f64), p.get("breadth").and_then(Value::as_f64)) {
(Some(l), _) if l.is_finite() && l > 0.0 => (l, area / l),
(_, Some(b)) if b.is_finite() && b > 0.0 => (area / b, b),
(Some(l), _) if l.is_finite() && l > 0.0 => area_sides(area, l, false, fillet, chamfer),
(_, Some(b)) if b.is_finite() && b > 0.0 => area_sides(area, b, true, fillet, chamfer),
_ => return Err(bad("rectang", "area needs `length` or `breadth`")),
}
} else {
@@ -68,7 +89,7 @@ pub(crate) fn run_rectang2(s: &mut Session, p: &Value) -> Result<Value> {
}
let fillet = size_param("rectang", p, "fillet", true)?.unwrap_or(0.0);
let width = size_param("rectang", p, "width", true)?.unwrap_or(0.0);
let (w, h) = rect_size(p, a, rot, centered)?;
let (w, h) = rect_size(p, a, rot, centered, fillet, ch)?;
if w.abs() < 1e-12 || h.abs() < 1e-12 || !w.is_finite() || !h.is_finite() {
return Err(bad("rectang", "rectangle has no area"));
}
@@ -116,10 +137,13 @@ pub(crate) struct RectM2 {
asking: Option<RAsk>,
}
/// A rectangle's rotation as AutoCAD 2024 shows it: degrees from 0 to 360, two decimals.
fn rotation_text(rotation: f64) -> String {
let t = format!("{:.2}", rotation.to_degrees().rem_euclid(360.0));
if t == "360.00" { "0.00".into() } else { t }
/// A rectangle's rotation (radians counterclockwise from +X) as AutoCAD 2024 shows it: from
/// ANGBASE in the ANGDIR sense, in the drawing's angle units, to two places. Rotation 30 typed
/// with ANGBASE 90 and ANGDIR 1 shows as "120.00", and 30.5 in degrees/minutes/seconds as
/// "30d30'".
fn rotation_text(s: &Session, rotation: f64) -> String {
let au = s.angle_settings();
crate::units::format_angle(au.shown(rotation), au.aunits, 2)
}
/// AutoCAD 2024's line listing the RECTANG modes that are set, `None` when none is ("Current
@@ -144,9 +168,10 @@ fn modes_line(s: &Session, m: &RectangModes) -> Option<String> {
if m.width > 0.0 {
parts.push(format!("Width={}", d(m.width)));
}
let rot = rotation_text(m.rotation);
if rot != "0.00" {
parts.push(format!("Rotation={rot}"));
// Listed when the rectangle is turned from +X at all, to two places, whatever ANGBASE says.
let turned = format!("{:.2}", m.rotation.to_degrees().rem_euclid(360.0));
if turned != "0.00" && turned != "360.00" {
parts.push(format!("Rotation={}", rotation_text(s, m.rotation)));
}
(!parts.is_empty()).then(|| format!("Current rectangle modes: {}", parts.join(" ")))
}
@@ -219,7 +244,7 @@ impl Interactive for RectM2 {
}
/// Asks for the pending option's value, or for the first and second points; in centre mode
/// the first prompt asks for the centre instead of a corner.
fn prompt(&self, _s: &Session) -> Prompt {
fn prompt(&self, s: &Session) -> Prompt {
let num = |m: &str, d: f64| Prompt::new(m, Accept::NUMBER).default(format!("{d:.4}"));
if let Some(a) = self.asking {
return match a {
@@ -237,7 +262,7 @@ impl Interactive for RectM2 {
RAsk::DimW => num("Specify width for rectangles", self.dims.map(|d| d.1).unwrap_or(10.0)),
RAsk::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER)
.kw(&["Pick points"])
.default(rotation_text(self.rotation))
.default(rotation_text(s, self.rotation))
.base_opt(self.first),
RAsk::RotPick1 => Prompt::new("Specify first point", Accept::POINT),
RAsk::RotPick2(b) => Prompt::new("Specify second point", Accept::POINT).base(b),
@@ -299,7 +324,7 @@ impl Interactive for RectM2 {
self.asking = Some(a);
return Err(other("Value must be positive."));
}
let (w, h) = if a == RAsk::AreaLength { (v, self.area / v) } else { (self.area / v, v) };
let (w, h) = area_sides(self.area, v, a == RAsk::AreaWidth, self.fillet, self.chamfer);
return self.make(s, w, h);
}
RAsk::DimL => {
@@ -314,7 +339,8 @@ impl Interactive for RectM2 {
RAsk::Rotation => match i {
Input::Keyword(_) => self.asking = Some(RAsk::RotPick1),
Input::Point(p) => self.rotation = self.first.map(|f| f.angle_to(p)).unwrap_or(0.0),
Input::Text(t) => self.rotation = s.angle_settings().direction(&t).ok_or_else(|| other("Requires a valid angle."))?,
// An amount turned in the ANGDIR sense from +X, ANGBASE aside, as AutoCAD takes it.
Input::Text(t) => self.rotation = s.angle_settings().rotation(&t).ok_or_else(|| other("Requires a valid angle."))?,
_ => {}
},
RAsk::RotPick1 => {
+251 -5
View File
@@ -729,6 +729,57 @@ fn divide_and_measure_command_line() {
s.cancel();
}
#[test]
fn divide_takes_a_whole_number_as_typed() {
// AutoCAD 2024 at "Enter the number of segments or [Block]:": +5, 05, the LISP real 5.0 and
// 32767 are taken; 5.0, 5., 1e1, 4.5, 1, 0, -3, 32768, x, Enter and a point from LISP are
// refused and asked again (measured).
let points = |s: &Session| kinds(s).iter().filter(|k| **k == "Point").count();
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
s.cmdline("divide 5,0").unwrap();
let asked = s.prompt_text();
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter the number of segments or [Block]:"));
for bad in ["5.0", "5.", "1e1", "4.5", "1", "0", "-3", "32768", "x", "", "(list 1 2)"] {
let logged = s.log.len();
s.cmdline(bad).unwrap();
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
assert_eq!(said, ["Requires an integer between 2 and 32767, or option keyword."], "{bad:?}");
assert_eq!(s.prompt_text(), asked, "{bad:?}");
}
assert_eq!(points(&s), 0);
s.cmdline("+5").unwrap();
assert!(s.running.is_none());
assert_eq!(points(&s), 4);
for (typed, n) in [("05", 4), ("(+ 2.5 2.5)", 4), ("2", 1), ("32767", 32766)] {
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
s.cmdline("divide 5,0").unwrap();
s.cmdline(typed).unwrap();
assert!(s.running.is_none(), "{typed}: {}", s.prompt_text());
assert_eq!(points(&s), n, "{typed}");
}
// MEASURE shares the prompt machine and is unchanged: Enter at its length still ends it.
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
s.cmdline("measure 5,0").unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(points(&s), 0);
// After Block the prompt offers no keyword, and the message names none (AutoCAD 2024, measured).
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
let tick = s.execute("circle", &json!({"center": [50, 50], "radius": 0.1})).unwrap();
s.execute("block", &json!({"name": "DOT", "base": [50, 50], "handles": [h(&tick)], "keep": "delete"})).unwrap();
s.cmdline("divide 5,0 b DOT y").unwrap();
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter the number of segments:"));
s.cmdline("5.0").unwrap();
assert_eq!(s.log.last().map(String::as_str), Some("Requires an integer between 2 and 32767."));
s.cmdline("5").unwrap();
assert!(s.running.is_none());
assert_eq!(kinds(&s).iter().filter(|k| **k == "Block Reference").count(), 4);
}
// ---------------- REVCLOUD ----------------
#[test]
@@ -1101,6 +1152,198 @@ fn rectang_options_command_line() {
}
}
/// RECTANG against what AutoCAD 2024 stores for the same typed input (black-box: synthetic
/// input in accoreconsole, read back with `entget`): Area with the corners taken off, and
/// corners too large for the sides.
#[test]
fn rectang_area_and_oversized_corners_match_autocad() {
type Case = (&'static [&'static str], &'static [[f64; 3]], [f64; 3]);
// (typed input, vertices [x, y, bulge], [width, elevation, thickness])
let cases: [Case; 4] = [
// RECTANG-028: Area counts the chamfered corners off.
(
&["rectang _C 1.5 2.5 26.36462345136234,-19.7291241693893 _R 0 _A 1442.9297064464572 _W 35.53488991311575"],
&[
[26.36462345136234, -18.2291241693893, 0.0],
[28.86462345136234, -19.7291241693893, 0.0],
[65.68168268505678, -19.7291241693893, 0.0],
[67.18168268505678, -17.2291241693893, 0.0],
[67.18168268505678, 14.30576574372644, 0.0],
[64.68168268505678, 15.80576574372644, 0.0],
[27.86462345136234, 15.80576574372644, 0.0],
[26.36462345136234, 13.30576574372644, 0.0],
],
[0.0, 0.0, 0.0],
),
// RECTANG-035-VN: Area counts the fillets off, at survey coordinates.
(
&["rectang _F 2.0 612322.0691653182,2398792.948957577 _R 0 _A 592.8936847254046 _L 19.287858563349488"],
&[
[612322.0691653182, 2398794.948957577, 0.414213562373095],
[612324.0691653182, 2398792.948957577, 0.0],
[612339.3570238815, 2398792.948957577, 0.414213562373095],
[612341.3570238815, 2398794.948957577, 0.0],
[612341.3570238815, 2398821.866195597, 0.414213562373095],
[612339.3570238815, 2398823.866195598, 0.0],
[612324.0691653182, 2398823.866195598, 0.414213562373095],
[612322.0691653182, 2398821.866195597, 0.0],
],
[0.0, 0.0, 0.0],
),
// RECTANG-029: a fillet too large: each corner two coincident vertices.
(
&["rectang _F 11.37084114989061 -21.46774953784037,-0.023473793210982308 _R 0 -2.5163476213560187,49.88119923361903"],
&[
[-21.46774953784036, -0.0234737932109823, 0.0],
[-21.46774953784036, -0.0234737932109823, 0.0],
[-2.516347621356018, -0.0234737932109823, 0.0],
[-2.516347621356018, -0.0234737932109823, 0.0],
[-2.516347621356018, 49.88119923361903, 0.0],
[-2.516347621356018, 49.88119923361903, 0.0],
[-21.46774953784036, 49.88119923361903, 0.0],
[-21.46774953784036, 49.88119923361903, 0.0],
],
[0.0, 0.0, 0.0],
),
// RECTANG-039-VN: a chamfer too large, rotated, with Dimensions.
(
&[
"rectang _C 18.656567079201356 18.656567079201356 612317.9599920243,2398739.0200147885 _R 30 _D 26.652238684573366 32.64533161964191 612344.6122307089,2398771.6653464083",
],
&[
[612317.9599920243, 2398739.020014788, 0.0],
[612317.9599920243, 2398739.020014788, 0.0],
[612341.041507793, 2398752.34613413, 0.0],
[612341.041507793, 2398752.34613413, 0.0],
[612324.7188419831, 2398780.617820628, 0.0],
[612324.7188419831, 2398780.617820628, 0.0],
[612301.6373262145, 2398767.291701286, 0.0],
[612301.6373262145, 2398767.291701286, 0.0],
],
[0.0, 0.0, 0.0],
),
];
let same = |a: f64, b: f64| (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0);
for (input, want, [width, elevation, thickness]) in cases {
let mut s = Session::new();
for line in input {
s.cmdline(line).unwrap();
assert!(s.running.is_none(), "{line}: {}", s.prompt_text());
}
let e = s.doc().unwrap().model.last().unwrap().clone();
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{input:?}: {:?}", e.kind) };
let got: Vec<[f64; 3]> = p.vertices.iter().map(|v| [v.p.x, v.p.y, v.bulge]).collect();
let ok = got.len() == want.len() && got.iter().zip(want).all(|(g, w)| g.iter().zip(w).all(|(a, b)| same(*a, *b)));
assert!(
ok,
"{input:?}
got {got:?}
want {want:?}"
);
assert!(p.closed && same(p.const_width, width) && same(p.elevation, elevation) && same(e.common.thickness, thickness), "{input:?}");
}
// Rotation, elevation and thickness are remembered too: AutoCAD opens the next RECTANG with
// "Current rectangle modes: Elevation=7.5000 Thickness=2.2500 Rotation=30.96".
let mut s = Session::new();
s.cmdline("rectang _E 7.5 _T 2.25 0,0 _R _P 0,0 10,6 10,20").unwrap();
s.cmdline("rectang 100,100 110,105").unwrap();
let e = s.doc().unwrap().model.last().unwrap().clone();
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{:?}", e.kind) };
let edge = p.vertices[1].p - p.vertices[0].p;
assert!(p.vertices[0].p == Vec2::new(100.0, 100.0) && same(edge.angle(), 6f64.atan2(10.0)), "{p:?}");
assert!(p.elevation == 7.5 && e.common.thickness == 2.25);
}
/// RECTANG's Rotation follows the drawing's angle settings as AutoCAD 2024's does.
#[test]
fn rectang_rotation_follows_the_angle_settings() {
let modes = |s: &Session| s.log.iter().filter(|l| l.starts_with("Current rectangle modes:")).cloned().collect::<Vec<_>>();
// With ANGBASE 90 and ANGDIR 1, AutoCAD 2024 turns a rectangle given Rotation 30 clockwise
// by 30° from +X (ANGBASE aside), and shows that rotation from ANGBASE: "Rotation=120.00",
// and <120.00> as the next rotation default.
let mut s = Session::new();
s.cmdline("setvar angbase 90").unwrap();
s.cmdline("setvar angdir 1").unwrap();
s.cmdline("rectang 50,0 _R 30 60,5").unwrap();
let e = s.doc().unwrap().model.last().unwrap().clone();
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{:?}", e.kind) };
let edge = p.vertices[1].p - p.vertices[0].p;
assert!((edge.y.atan2(edge.x) + 30f64.to_radians()).abs() < 1e-9, "{p:?}");
s.start("rectang").unwrap();
assert_eq!(modes(&s), ["Current rectangle modes: Rotation=120.00"]);
s.cmdline("50,0").unwrap();
s.cmdline("_R").unwrap();
assert!(s.prompt_text().contains("<120.00>"), "{}", s.prompt_text());
s.cancel();
// In degrees/minutes/seconds: "Rotation=30d30'".
let mut s = Session::new();
s.cmdline("setvar aunits 1").unwrap();
s.cmdline("rectang 50,0 _R 30.5 60,5").unwrap();
s.start("rectang").unwrap();
assert_eq!(modes(&s), ["Current rectangle modes: Rotation=30d30'"]);
s.cancel();
}
/// Area allows for cut corners only while they fit: a fillet too large for the resulting sides
/// leaves square corners, so the rectangle is the full area asked for (4 × 1, not 4 × 1.858).
/// Corners exactly as long as the shorter side allows still fit; a hair longer and the corners
/// stay square, each still written twice (AutoCAD 2024, `entget` of a 4 x 2 rectangle).
#[test]
fn rectang_corners_at_the_limit_fit_and_just_over_stay_square() {
let b = (std::f64::consts::PI / 8.0).tan();
let fit: [(&str, &[(f64, f64, f64)]); 4] = [
(
"_F 0.9999",
&[
(0.0, 0.9999, b),
(0.9999, 0.0, 0.0),
(3.0001, 0.0, b),
(4.0, 0.9999, 0.0),
(4.0, 1.0001, b),
(3.0001, 2.0, 0.0),
(0.9999, 2.0, b),
(0.0, 1.0001, 0.0),
],
),
("_F 1", &[(0.0, 1.0, b), (1.0, 0.0, 0.0), (3.0, 0.0, b), (4.0, 1.0, 0.0), (4.0, 1.0, b), (3.0, 2.0, 0.0), (1.0, 2.0, b), (0.0, 1.0, 0.0)]),
(
"_C 1 1",
&[(0.0, 1.0, 0.0), (1.0, 0.0, 0.0), (3.0, 0.0, 0.0), (4.0, 1.0, 0.0), (4.0, 1.0, 0.0), (3.0, 2.0, 0.0), (1.0, 2.0, 0.0), (0.0, 1.0, 0.0)],
),
(
"_C 1.2 0.8",
&[(0.0, 1.2, 0.0), (0.8, 0.0, 0.0), (2.8, 0.0, 0.0), (4.0, 0.8, 0.0), (4.0, 0.8, 0.0), (3.2, 2.0, 0.0), (1.2, 2.0, 0.0), (0.0, 1.2, 0.0)],
),
];
let square =
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 2.0, 0.0), (4.0, 2.0, 0.0), (0.0, 2.0, 0.0), (0.0, 2.0, 0.0)];
let over: [(&str, &[(f64, f64, f64)]); 2] = [("_F 1.0001", &square), ("_C 1.2 0.81", &square)];
for (corners, want) in fit.into_iter().chain(over) {
let mut s = Session::new();
s.cmdline(&format!("rectang {corners} 0,0 4,2")).unwrap();
let EntityKind::LwPolyline(p) = last(&s) else { panic!("no polyline") };
let got: Vec<(f64, f64, f64)> = p.vertices.iter().map(|v| (v.p.x, v.p.y, v.bulge)).collect();
let ok = got.len() == want.len()
&& got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-9 && (g.1 - w.1).abs() < 1e-9 && (g.2 - w.2).abs() < 1e-6);
assert!(ok, "{corners}: {got:?}");
}
}
#[test]
fn rectang_area_with_corners_too_large_stays_exact() {
let check = |s: &Session| {
let pts = rect_pts(s);
let b = cadcraft_geom::Bounds2::from_points(pts.clone());
assert!(near(b.min, 0.0, 0.0) && near(b.max, 4.0, 1.0), "{pts:?}");
assert!(pts.len() == 8 && pts.chunks(2).all(|c| c[0] == c[1]), "{pts:?}");
};
let mut s = Session::new();
s.cmdline("rectang _F 2 0,0 _A 4 _L 4").unwrap();
check(&s);
s.execute("rectang", &json!({"p1": [0, 0], "area": 4, "length": 4, "fillet": 2})).unwrap();
check(&s);
}
/// Guards the JSON `center: true` form for every sizing route: a picked corner mirrored about
/// the centre, full-size `dimensions`, full `area`, rotation about the centre, that the default
/// corner mode is untouched, and that centre mode without a size is rejected.
@@ -1136,7 +1379,7 @@ fn rectang_center_mode_json() {
}
/// Guards that fillet, chamfer, width and thickness still apply in centre mode, and that an
/// oversized fillet falls back to sharp corners without moving the rectangle off centre.
/// oversized fillet leaves sharp corners without moving the rectangle off centre.
#[test]
fn rectang_center_mode_honours_options() {
let mut s = Session::new();
@@ -1153,9 +1396,11 @@ fn rectang_center_mode_honours_options() {
assert_eq!(rect_pts(&s).len(), 8);
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
// A fillet too large for the rectangle falls back to sharp corners, still centred.
// A fillet too large for the rectangle leaves sharp corners, each one two coincident vertices
// as in AutoCAD, still centred.
s.execute("rectang", &json!({"center": true, "p1": [10, 10], "p2": [14, 16], "fillet": 5})).unwrap();
assert_eq!(rect_pts(&s).len(), 4);
let pts = rect_pts(&s);
assert!(pts.len() == 8 && pts.chunks(2).all(|c| c[0] == c[1]), "{pts:?}");
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
}
@@ -1183,8 +1428,9 @@ fn rectang_center_mode_command_line() {
assert!(s.running.is_none(), "{}", s.prompt_text());
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
// Area too: the rectangle of that area is centred on the first point.
s.cmdline("rectang ce 10,10 a 96 l 8").unwrap();
// Area too: the rectangle of that area is centred on the first point (without the fillet
// remembered from above, which would take its corners off the area).
s.cmdline("rectang f 0 ce 10,10 a 96 l 8").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
+3 -2
View File
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("export", "Export...", run_export)
.menu(&["File", "Export..."])
.alias(&["exp"])
.params("{path? (else returns base64 `data`), format?: dxf|dwg|svg|png|pdf (default: the path's extension)} → {format, bytes, path? | data}")
.params("{path? (else returns base64 `data`), format?: dxf|dwg|svg|png|pdf (default: the path's extension)} → {format, bytes, path? | data, warnings?: what an image draws short of the drawing}")
.noundo(),
CommandSpec::new("preview", "Plot Preview", run_preview)
.menu(&["File", "Plot Preview"])
@@ -123,7 +123,7 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("export", "`format` must be dxf, dwg, svg, png or pdf (or give a `path` with one of those extensions)"));
}
let file = format!("export.{format}");
let bytes = (hooks.write)(s.doc()?, &file).map_err(|e| bad("export", e))?;
let (bytes, notes) = super::file::write_noted(hooks, s.doc()?, &file).map_err(|e| bad("export", e))?;
let folder = path.and_then(super::file::new_folder);
let mut r = match path {
Some(path) => {
@@ -134,6 +134,7 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
};
super::file::report_new_folder(s, &mut r, folder);
super::file::report_loss(s, &mut r, &file);
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
+126 -16
View File
@@ -49,6 +49,47 @@ pub fn io() -> Option<&'static IoHooks> {
IO.get()
}
/// [`IoHooks::write`] and [`IoHooks::plot`] that also return what an image (PNG, SVG, PDF) draws
/// short of the drawing because of a render limit, one note each, such as dashed lines drawn
/// continuous past the dash limit (installed by the app with the image writers, a lower layer;
/// see `cadcraft_io::write_framed_noted` and `cadcraft_io::plotter::plot_noted`). EXPORT, QSAVE
/// and SAVEAS to an image, `document.bytes` and PLOT (so PUBLISH and PDFBOOK, sheet by sheet)
/// report them; without the hooks they write through [`IoHooks`] with no such notes. The app
/// installs the same writers as its [`IoHooks`].
pub struct NotedIo {
pub write: fn(&Drawing, &str) -> std::result::Result<(Vec<u8>, Vec<String>), String>,
pub plot: fn(&Drawing, &cadcraft_doc::Space, &Value) -> std::result::Result<(Vec<u8>, Vec<String>), String>,
}
static NOTED_IO: OnceLock<NotedIo> = OnceLock::new();
pub fn set_noted_io(h: NotedIo) {
let _ = NOTED_IO.set(h);
}
/// `d` written as `name` with the image's notes ([`NotedIo::write`]), or through `hooks.write`
/// with none when the app installed no [`NotedIo`].
pub(crate) fn write_noted(hooks: &IoHooks, d: &Drawing, name: &str) -> std::result::Result<(Vec<u8>, Vec<String>), String> {
match NOTED_IO.get() {
Some(n) => (n.write)(d, name),
None => (hooks.write)(d, name).map(|bytes| (bytes, Vec::new())),
}
}
/// `d` plotted with the plot's notes ([`NotedIo::plot`]), or through `hook` with none when the
/// app installed no [`NotedIo`].
pub(crate) fn plot_noted(
hook: PlotHook,
d: &Drawing,
space: &cadcraft_doc::Space,
opts: &Value,
) -> std::result::Result<(Vec<u8>, Vec<String>), String> {
match NOTED_IO.get() {
Some(n) => (n.plot)(d, space, opts),
None => hook(d, space, opts).map(|bytes| (bytes, Vec::new())),
}
}
/// An entity as DXF groups and back, for AutoLISP's `entget`, `entmake` and `entmod`
/// (installed by the app with the DXF reader and writer, a lower layer).
pub struct EntityCodec {
@@ -104,6 +145,46 @@ pub fn set_dwg_compat_lost(f: DwgCompatLost) {
let _ = DWG_COMPAT_LOST.set(f);
}
/// Notes on what a DWG keeps of a drawing only in part, such as a linetype with more dash
/// elements than a DWG can count (installed by the app with the DWG writer, a lower layer; see
/// `cadcraft_io::dwg_notes`).
pub type DwgNotes = fn(&Drawing) -> Vec<String>;
static DWG_NOTES: OnceLock<DwgNotes> = OnceLock::new();
pub fn set_dwg_notes(f: DwgNotes) {
let _ = DWG_NOTES.set(f);
}
/// The [`DwgNotes`] of `d`, the drawing a DWG save writes: none without the hook.
pub fn dwg_notes(d: &Drawing) -> Vec<String> {
DWG_NOTES.get().map(|f| f(d)).unwrap_or_default()
}
/// Say on the command line what the DWG just written keeps only in part (`notes`, from
/// [`dwg_notes`]), and list it in the result's `warnings`.
pub(crate) fn report_dwg_notes(s: &mut Session, r: &mut Value, notes: Vec<String>) {
report_notes(s, r, notes);
}
/// Say each of `notes` on the command line and add them to the result's `warnings`.
pub(crate) fn report_notes(s: &mut Session, r: &mut Value, notes: Vec<String>) {
if notes.is_empty() {
return;
}
for note in &notes {
s.echo(note.clone());
}
if let Some(o) = r.as_object_mut() {
match o.get_mut("warnings").and_then(Value::as_array_mut) {
Some(list) => list.extend(notes.into_iter().map(Value::String)),
None => {
o.insert("warnings".into(), json!(notes));
}
}
}
}
/// What a DXF of `version` leaves out of `d` for its proxies' string streams (#3229): empty from
/// 2007 on. `d` is written as committed (a reference edit's working copies are not in the file).
fn proxies_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
@@ -208,9 +289,10 @@ fn is_dxf(path: &str) -> bool {
Format::from_path(path) == Some(Format::Dxf)
}
/// The drawing written to `path` with `opts`: through [`IoHooks::write`] when no option is set,
/// else through the [`write_as`] hook.
fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<Vec<u8>> {
/// The drawing written to `path` with `opts`: an image, or a drawing file with no option set,
/// through [`IoHooks::write`] (with an image's notes, [`write_noted`]); a drawing file at a
/// chosen version or as binary DXF through the [`write_as`] hook.
fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(Vec<u8>, Vec<String>)> {
let hooks = io().ok_or_else(|| bad(cmd, "file formats are not available in this build"))?;
if opts.binary && !is_dxf(path) {
return Err(bad(cmd, "binary applies to DXF files only"));
@@ -219,11 +301,12 @@ fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<Vec<
let d: &cadcraft_doc::Drawing = if is_drawing_file(path) { s.state()?.drawing() } else { s.doc()? };
let copy = (opts.portable_fonts && is_drawing_file(path)).then(|| Drawing { portable_fonts: true, ..d.clone() });
let d = copy.as_ref().unwrap_or(d);
let r = if opts.version.is_none() && !opts.binary {
(hooks.write)(d, path)
// An image has no version: `write_as` would write the same bytes without the notes.
let r = if !is_drawing_file(path) || (opts.version.is_none() && !opts.binary) {
write_noted(hooks, d, path)
} else {
let w = write_as().ok_or_else(|| bad(cmd, "saving at a chosen version or as binary DXF is not available in this build"))?;
w(d, path, opts)
w(d, path, opts).map(|bytes| (bytes, Vec::new()))
};
r.map_err(|e| bad(cmd, e))
}
@@ -255,7 +338,7 @@ pub fn specs() -> Vec<CommandSpec> {
.noundo(),
CommandSpec::new("document.switch", "Switch Drawing", run_switch).params("{index}").enabled(always).noundo(),
CommandSpec::new("document.bytes", "Drawing as bytes", run_bytes)
.params("{format?: dxf, version?: 2000…2018, binary?: bool, portableFonts?: bool} → {data: base64}")
.params("{format?: dxf, version?: 2000…2018, binary?: bool, portableFonts?: bool} → {data: base64, warnings?: what an image draws short of the drawing}")
.noundo(),
CommandSpec::new("script", "Run Script...", run_script)
.menu(&["Tools", "Run Script..."])
@@ -499,18 +582,19 @@ fn run_closeall(s: &mut Session, _p: &Value) -> Result<Value> {
ok()
}
pub(crate) fn save_to(s: &mut Session, path: &str) -> Result<usize> {
pub(crate) fn save_to(s: &mut Session, path: &str) -> Result<(usize, Vec<String>)> {
let opts = SaveAs { binary: s.state()?.binary_dxf && is_dxf(path), ..SaveAs::default() };
save_as(s, "save", path, &opts)
}
/// Save to `path` with `opts`. A drawing file then keeps the version and binary choice: the
/// version goes into the drawing's `$ACADVER`, so later saves (QSAVE) write it again.
fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<usize> {
/// version goes into the drawing's `$ACADVER`, so later saves (QSAVE) write it again. Also an
/// image's notes ([`write_noted`]).
fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(usize, Vec<String>)> {
if s.doc()?.refedit.is_some() {
return Err(bad(cmd, "A block reference is being edited in place: finish with REFCLOSE (Save or Discard) before saving."));
}
let bytes = write_bytes(s, cmd, path, opts)?;
let (bytes, notes) = write_bytes(s, cmd, path, opts)?;
let n = commit_save(s, path, &bytes, store)?;
if is_drawing_file(path) {
let st = s.state_mut()?;
@@ -522,7 +606,7 @@ fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<usiz
st.saved = st.drawing().clone();
}
}
Ok(n)
Ok((n, notes))
}
/// Put saved bytes where the user gets them: natively the file at `path`; on the web, which has
@@ -812,15 +896,18 @@ fn run_save(s: &mut Session, p: &Value) -> Result<Value> {
Some(p) => p.to_string(),
None => s.state()?.path.clone().ok_or_else(|| bad("qsave", "drawing has no file name yet; use saveas {path}"))?,
};
let n = save_to(s, &path)?;
Ok(saved(&path, n))
let (n, notes) = save_to(s, &path)?;
let mut r = saved(&path, n);
report_notes(s, &mut r, notes);
Ok(r)
}
fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("saveas", "`path` is required"))?.to_string();
let opts = save_options("saveas", p)?;
let n = save_as(s, "saveas", &path, &opts)?;
let (n, notes) = save_as(s, "saveas", &path, &opts)?;
let mut r = saved(&path, n);
report_notes(s, &mut r, notes);
if is_drawing_file(&path) {
r["version"] = json!(opts.version.unwrap_or_else(|| drawing_version(s, &path)).year());
r["binary"] = json!(opts.binary);
@@ -869,10 +956,13 @@ fn run_bytes(s: &mut Session, p: &Value) -> Result<Value> {
let opts = save_options("document.bytes", p)?;
let version = opts.version.unwrap_or_else(|| drawing_version(s, &format!("drawing.{fmt}")));
let lost = not_saved_as(s.doc()?, version);
let bytes = write_bytes(s, "document.bytes", &format!("drawing.{fmt}"), &opts)?;
let (bytes, notes) = write_bytes(s, "document.bytes", &format!("drawing.{fmt}"), &opts)?;
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len() });
report_notes(s, &mut r, notes);
if drops_unknown(format!("drawing.{fmt}")) {
report_not_saved(s, &mut r, &lost);
let notes = s.state().map(|st| dwg_notes(st.drawing())).unwrap_or_default();
report_dwg_notes(s, &mut r, notes);
} else if is_dxf_file(format!("drawing.{fmt}")) {
let lost = host_dxf_lost(s, version);
report_lost(s, &mut r, "drawing.dxf", version, &lost);
@@ -1005,7 +1095,9 @@ pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) {
let Ok(d) = s.doc() else { return };
let version = own_version(d, path);
let lost = lost_writing(d, path, version);
let notes = if drops_unknown(path) { dwg_notes(d) } else { Vec::new() };
report_lost(s, r, path, version, &lost);
report_dwg_notes(s, r, notes);
}
/// Say on the command line what the file `path`, written at `version`, couldn't keep (`lost`),
@@ -1112,6 +1204,8 @@ fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> R
report_new_folder(s, &mut r, folder);
if r.get("path").and_then(Value::as_str).is_some_and(drops_unknown) {
report_not_saved(s, &mut r, &lost);
let notes = s.state().map(|st| dwg_notes(st.drawing())).unwrap_or_default();
report_dwg_notes(s, &mut r, notes);
} else if r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) {
let lost = host_dxf_lost(s, version);
report_lost(s, &mut r, "drawing.dxf", version, &lost);
@@ -1179,6 +1273,22 @@ mod tests {
use crate::Session;
use crate::temp_dir::TempDir;
/// Notes join the warnings a result already has instead of replacing them, and are said on
/// the command line.
#[test]
fn notes_are_added_to_the_warnings_a_result_has() {
let mut s = Session::new();
let mut r = json!({ "warnings": ["kept"] });
super::report_notes(&mut s, &mut r, vec!["added".into()]);
assert_eq!(r["warnings"], json!(["kept", "added"]));
let mut r = json!({});
super::report_notes(&mut s, &mut r, Vec::new());
assert!(r.get("warnings").is_none());
super::report_notes(&mut s, &mut r, vec!["first".into()]);
assert_eq!(r["warnings"], json!(["first"]));
assert!(s.log.ends_with(&["added".to_string(), "first".to_string()]), "{:?}", s.log);
}
/// Whether the `.bak` name is taken is asked without following a link there: a dangling link
/// counts as taken, so a file that doesn't look like a drawing leaves it alone.
#[cfg(unix)]
+2 -8
View File
@@ -455,15 +455,9 @@ fn tinted_dim_style(d: &mut Drawing, name: &str, color: Color, tinted: &mut Tint
if let Some(n) = tinted.names.get(&key) {
return Some(n.clone());
}
let st = d.dim_styles.iter().find(|s| s.name.eq_ignore_ascii_case(name))?.clone();
let st = d.dim_style(name)?.clone();
let base = format!("COMPARE_{}_{}", tag(color), st.name);
let new = tinted.next.find(
"dimension style",
&base,
d.dim_styles.len(),
|i| suffixed(&base, i),
|n| d.dim_styles.iter().any(|s| s.name.eq_ignore_ascii_case(n)),
);
let new = tinted.next.find("dimension style", &base, d.dim_styles.len(), |i| suffixed(&base, i), |n| d.dim_style(n).is_some());
d.dim_styles.push(DimStyle {
name: new.clone(),
dim_line_color: Color::ByBlock,
+33 -14
View File
@@ -68,29 +68,48 @@ pub fn polygon_from_edge(p1: Vec2, p2: Vec2, sides: usize) -> Vec<PolyVertex> {
/// chamfer distances at every corner, in AutoCAD 2024's order: from `a` along X to `b`'s X, then
/// `b`, then back along Y. A chamfer cuts the edge into each corner by its first distance and the
/// edge out of it by its second; each fillet arc starts on the edge into its corner. A fillet or
/// chamfer that doesn't fit leaves the corners square.
/// chamfer too large for the shorter side leaves the corners square, each as two coincident
/// vertices, as AutoCAD stores them.
pub fn rect_with_corners(a: Vec2, b: Vec2, fillet: f64, chamfer: (f64, f64)) -> Vec<PolyVertex> {
let corners = [a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y)];
let short = (b.x - a.x).abs().min((b.y - a.y).abs());
let (d_in, d_out, bulge) = if fillet > 0.0 && fillet * 2.0 <= short + 1e-12 {
// Counter-clockwise round the corners (a positive bulge) when `b` is up and right of `a`, or
// down and left.
let sign = if (b.x - a.x) * (b.y - a.y) >= 0.0 { 1.0 } else { -1.0 };
(fillet, fillet, sign * cadcraft_geom::arc_to_bulge(std::f64::consts::FRAC_PI_2))
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 && chamfer.0 + chamfer.1 <= short + 1e-12 {
(chamfer.0, chamfer.1, 0.0)
} else {
return corners.into_iter().map(PolyVertex::new).collect();
};
let Some((d_in, d_out)) = rect_corner_cuts(fillet, chamfer) else { return corners.into_iter().map(PolyVertex::new).collect() };
let fits = rect_corners_fit(b - a, fillet, chamfer);
// Counter-clockwise round the corners (a positive bulge) when `b` is up and right of `a`, or
// down and left.
let sign = if (b.x - a.x) * (b.y - a.y) >= 0.0 { 1.0 } else { -1.0 };
let bulge = if fillet > 0.0 { sign * cadcraft_geom::arc_to_bulge(std::f64::consts::FRAC_PI_2) } else { 0.0 };
let mut out = Vec::with_capacity(8);
for (i, cur) in corners.iter().enumerate() {
let (Some(prev), Some(next)) = (corners.get((i + 3) % 4), corners.get((i + 1) % 4)) else { continue };
out.push(PolyVertex::with_bulge(*cur + (*prev - *cur).normalized() * d_in, bulge));
out.push(PolyVertex::new(*cur + (*next - *cur).normalized() * d_out));
if fits {
out.push(PolyVertex::with_bulge(*cur + (*prev - *cur).normalized() * d_in, bulge));
out.push(PolyVertex::new(*cur + (*next - *cur).normalized() * d_out));
} else {
out.extend([PolyVertex::new(*cur), PolyVertex::new(*cur)]);
}
}
out
}
/// How far a rectangle's fillet or chamfer cuts into the edges into and out of each corner, if
/// one is set: the fillet radius on both, or the two chamfer distances. A fillet wins over a
/// chamfer.
fn rect_corner_cuts(fillet: f64, chamfer: (f64, f64)) -> Option<(f64, f64)> {
if fillet > 0.0 {
Some((fillet, fillet))
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 {
Some(chamfer)
} else {
None
}
}
/// Whether a fillet or chamfer fits a rectangle of `size` (signed sides): its two cuts together
/// no longer than the shorter side. True when neither is set.
pub fn rect_corners_fit(size: Vec2, fillet: f64, chamfer: (f64, f64)) -> bool {
rect_corner_cuts(fillet, chamfer).is_none_or(|(d_in, d_out)| d_in + d_out <= size.x.abs().min(size.y.abs()) + 1e-12)
}
// ---------- the user's support files ----------
/// Largest support file (linetype, hatch pattern or alias file) read.
+1 -2
View File
@@ -62,8 +62,7 @@ impl Scope {
Some(_) => {
let name = given.unwrap_or_default();
let d = s.doc()?;
let l =
d.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(&name)).ok_or_else(|| bad(cmd, format!("no layout named \"{name}\"")))?;
let l = d.layout(&name).ok_or_else(|| bad(cmd, format!("no layout named \"{name}\"")))?;
Ok(Scope::Space(Space::Paper(l.name.clone())))
}
}
+2 -2
View File
@@ -297,7 +297,7 @@ fn run_layerp(s: &mut Session, _p: &Value) -> Result<Value> {
let d = s.doc_mut()?;
let snap = d.header.str("CADCRAFT_LAYERP", "");
let layers: Vec<Layer> = serde_json::from_str(&snap).map_err(|_| bad("layerp", "No previous layer state."))?;
d.layers = layers;
d.layers = layers.into();
Ok(json!({"message": "Restored previous layer states."}))
}
@@ -375,7 +375,7 @@ fn run_layuniso(s: &mut Session, _p: &Value) -> Result<Value> {
let d = s.doc_mut()?;
let snap = d.header.str("CADCRAFT_LAYISO", "");
let layers: Vec<Layer> = serde_json::from_str(&snap).map_err(|_| bad("layuniso", "No isolated layers."))?;
d.layers = layers;
d.layers = layers.into();
ok()
}
+11 -4
View File
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("layout.copy", "Copy Layout", run_copy).params("{from, to?}"),
CommandSpec::new("layout.list", "List Layouts", run_list).params("→ [{name, tabOrder, page, viewports}]").noundo(),
CommandSpec::new("layout.saveas", "Save Layout as Template", saveas::run_saveas)
.params("{name?: layout (default: the current layout, else the first tab), path: .dwt (or .dwg, .dxf; no extension adds .dwt)} → {name, path, bytes, notSaved?}")
.params("{name?: layout (default: the current layout, else the first tab), path: .dwt (or .dwg, .dxf; no extension adds .dwt)} → {name, path, bytes, notSaved?, warnings?}")
.noundo(),
CommandSpec::new("mview", "Viewports", run_mview)
.alias(&["mv"])
@@ -890,7 +890,7 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
if is_image && sheets.as_ref().is_some_and(|names| names.len() > 1) {
return Err(bad(cmd, "`layouts` with several sheets needs PDF output; PNG and SVG hold one sheet, so plot each layout separately"));
}
let bytes = hook(s.doc()?, &space, &opts).map_err(|e| bad(cmd, e))?;
let (bytes, notes) = super::file::plot_noted(hook, s.doc()?, &space, &opts).map_err(|e| bad(cmd, e))?;
let layout = match &sheets {
Some(names) => names.first().cloned().unwrap_or_default(),
None => space.tab_name().to_string(),
@@ -909,15 +909,22 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
let mut r = json!({ "path": path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_new_folder(s, &mut r, folder);
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
#[cfg(target_arch = "wasm32")]
{
super::exchange::deliver_file(cmd, _path, &bytes, super::file::deliver())?;
Ok(json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format }))
let mut r = json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
}
None => Ok(json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format })),
None => {
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
}
}
+4 -1
View File
@@ -12,7 +12,7 @@ use cadcraft_doc::{Common, Drawing, Entity, EntityKind, EntityStore, Point};
use cadcraft_geom::Vec3;
use serde_json::{Value, json};
use super::super::file::{drops_unknown, io, not_saved, not_saved_message};
use super::super::file::{drops_unknown, dwg_notes, io, not_saved, not_saved_message, report_dwg_notes};
use super::super::{bad, str_param};
use super::layout_name;
use super::prompts::current_layout;
@@ -136,6 +136,9 @@ pub(super) fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
o.insert("notSaved".into(), json!(lost));
}
}
if drops_unknown(&path) {
report_dwg_notes(s, &mut r, dwg_notes(&t));
}
Ok(r)
}
+376 -50
View File
@@ -129,80 +129,406 @@ pub(crate) fn join(s: &mut Session, hs: &[Handle]) -> Result<Option<Handle>> {
if hs.iter().any(|h| crate::cmd::curves::is_locked(s, *h)) {
return Err(EngineError::Other("An object is on a locked layer.".into()));
}
let hs = joinable_picks(s.doc()?, hs);
let hs = &hs[..];
if let Some(h) = join_on_source(s, hs)? {
return Ok(Some(h));
}
let d = s.doc()?;
let mut segs: Vec<Segment> = Vec::new();
// Source entity of each segment in `segs`, so only entities that end up in the chain are removed.
let mut owners: Vec<Handle> = Vec::new();
let mut common = None;
// Each object JOIN can take, as the pieces it is made of: a line or an arc is one piece, an
// open polyline its segments in order, each keeping its vertices, bulge and widths exactly.
// Each also with whether it faces down: an arc or a polyline whose normal points down Z
// (measured with 0,0,-1; a tilted one is taken the same way). A line faces up whatever its
// normal (AutoCAD 2024 joins one with normal 0,0,-1 to a polyline facing up, and no line to a
// polyline facing down; measured).
let mut units: Vec<(bool, Vec<Piece>)> = Vec::new();
let down = |e: &Entity| !matches!(e.kind, EntityKind::Line(_)) && e.common.extrusion.z < 0.0;
for h in hs {
let Some(e) = d.entity(*h) else { continue };
common.get_or_insert_with(|| e.common.clone());
match &e.kind {
EntityKind::Line(l) => segs.push(Segment::Line(Line::new(l.a.xy(), l.b.xy()))),
EntityKind::Arc(a) => segs.push(Segment::Arc { arc: Arc::new(a.center.xy(), a.radius, a.start, a.end), ccw: true }),
EntityKind::LwPolyline(p) if !p.closed => segs.extend(Polyline { vertices: p.vertices.clone(), closed: false }.segments()),
_ => {}
let piece =
|ends: (Vec2, Vec2), heights: (f64, f64), bulge: f64, widths: Option<(f64, f64)>| Piece { owner: *h, ends, heights, bulge, widths };
let unit: Vec<Piece> = match &e.kind {
// A line of no length joins as AutoCAD 2024 joins it, a repeated vertex.
EntityKind::Line(l) => vec![piece((l.a.xy(), l.b.xy()), (l.a.z, l.b.z), 0.0, None)],
EntityKind::Arc(a) => {
let arc = Arc::new(a.center.xy(), a.radius, a.start, a.end);
vec![piece((arc.start_point(), arc.end_point()), (a.center.z, a.center.z), cadcraft_geom::arc_to_bulge(arc.sweep()), None)]
}
// Repeated vertices included: AutoCAD 2024 keeps them.
EntityKind::LwPolyline(p) if !p.closed => {
// The elevation is along the polyline's normal: down Z for a mirrored one.
let z = if down(e) { -p.elevation } else { p.elevation };
p.vertices
.windows(2)
.map(|w| {
let widths = if p.const_width > 0.0 { (p.const_width, p.const_width) } else { (w[0].start_width, w[0].end_width) };
piece((w[0].p, w[1].p), (z, z), w[0].bulge, Some(widths))
})
.collect()
}
_ => Vec::new(),
};
if !unit.is_empty() {
units.push((down(e), unit));
}
owners.resize(segs.len(), *h);
}
if segs.len() < 2 {
if units.iter().map(|u| u.1.len()).sum::<usize>() < 2 {
return Err(EngineError::Other("Select at least two objects to join.".into()));
}
// Chain greedily from the first segment.
let mut chain = vec![segs.remove(0)];
let mut used = vec![owners.remove(0)];
// An object facing the other way from a polyline source stays out (AutoCAD 2024, measured: one
// facing up takes no arc facing down, and one facing down no arc or polyline facing up). Onto a
// line or an arc it wasn't measured (the core console's JOIN takes only collinear lines or arcs
// on one circle onto those), so objects facing either way still join there.
let polyline_source = units.first().filter(|u| u.1.first().is_some_and(|p| p.widths.is_some())).map(|u| u.0);
let units: Vec<Vec<Piece>> = units.into_iter().filter(|u| polyline_source.is_none_or(|down| u.0 == down)).map(|u| u.1).collect();
// A new polyline takes the source's properties.
let first = units.first().and_then(|u| u.first()).map(|p| p.owner);
let common = first.and_then(|h| d.entity(h)).map(|e| e.common.clone());
let tol = 1e-6;
loop {
let start = chain.first().map(Segment::start).unwrap_or_default();
let end = chain.last().map(Segment::end).unwrap_or_default();
let Some(i) =
segs.iter().position(|s| s.start().near(end, tol) || s.end().near(end, tol) || s.start().near(start, tol) || s.end().near(start, tol))
else {
break;
};
let s0 = segs.remove(i);
used.push(owners.remove(i));
if s0.start().near(end, tol) {
chain.push(s0);
} else if s0.end().near(end, tol) {
chain.push(s0.reversed());
} else if s0.end().near(start, tol) {
chain.insert(0, s0);
} else {
chain.insert(0, s0.reversed());
}
}
if chain.len() < 2 {
let links = chain_units(units, tol);
// One object alone joins nothing, even a polyline whose ends meet: AutoCAD 2024 leaves it open
// ("0 segments added to polyline").
let closed = links.first().zip(links.last()).is_some_and(|(a, b)| meet(a.start(), b.end(), tol));
let one_object = links.first().is_some_and(|f| links.iter().all(|l| l.owner == f.owner));
if links.len() < 2 || one_object {
return Err(EngineError::Other("Objects are not connected.".into()));
}
let closed = chain.first().zip(chain.last()).is_some_and(|(a, b)| a.start().near(b.end(), tol));
let mut vs: Vec<PolyVertex> = chain
let used = |h: &Handle| links.iter().any(|l| l.owner == *h);
// A polyline's own segments keep their widths.
let mut vs: Vec<PolyVertex> = links
.iter()
.map(|s| PolyVertex {
p: s.start(),
bulge: match s {
Segment::Line(_) => 0.0,
Segment::Arc { arc, ccw } => cadcraft_geom::arc_to_bulge(if *ccw { arc.sweep() } else { -arc.sweep() }),
},
..Default::default()
.map(|l| {
let (start_width, end_width) = l.widths.unwrap_or_default();
PolyVertex { p: l.ends.0, bulge: l.bulge, start_width, end_width }
})
.collect();
if !closed && let Some(l) = chain.last() {
vs.push(PolyVertex::new(l.end()));
if !closed && let Some(l) = links.last() {
vs.push(PolyVertex::new(l.ends.1));
}
let space = s.space();
// A new polyline goes in the source's space, whichever space is current.
let space = first.and_then(|h| d.space_of(h)).unwrap_or_else(|| s.space());
let doc = s.doc_mut()?;
for h in hs.iter().filter(|h| used.contains(*h)) {
// A polyline source takes the other pieces and keeps its handle (AutoCAD 2024: "1 segments
// added to polyline").
if let Some(src) = first
&& let Some(EntityKind::LwPolyline(sp)) = doc.entity(src).map(|e| &e.kind)
&& let Some(onto) = onto_polyline(sp, src, &links, closed)
{
for h in hs.iter().filter(|h| **h != src && used(h)) {
doc.remove_entity(*h);
}
doc.modify_entity(src, |e| e.kind = EntityKind::LwPolyline(onto))?;
s.set_selection(Vec::new());
return Ok(Some(src));
}
for h in hs.iter().filter(|h| used(h)) {
doc.remove_entity(*h);
}
// A new polyline stays at the source's height, as a polyline source keeps its elevation. The
// elevation runs along its normal: negated for one facing down. Not measured: the core
// console's JOIN makes no new polyline.
let height = links.iter().find(|l| Some(l.owner) == first).map_or(0.0, |l| l.heights.0);
let common = common.unwrap_or_default();
let elevation = if common.extrusion.z < 0.0 { -height } else { height };
let mut kind = lwpoly(vs, closed);
if let EntityKind::LwPolyline(p) = &mut kind {
p.elevation = elevation;
}
let nh = doc.new_handle();
if let Some(st) = doc.space_mut(&space) {
st.push(Entity { handle: nh, common: common.unwrap_or_default(), kind: lwpoly(vs, closed) });
st.push(Entity { handle: nh, common, kind });
}
s.set_selection(Vec::new());
Ok(Some(nh))
}
/// The picks JOIN can take, each once, in the order picked: lines, arcs and open polylines. The
/// first of them is the source (AutoCAD 2024 passes over a circle picked first and leaves it).
fn joinable_picks(d: &cadcraft_doc::Drawing, hs: &[Handle]) -> Vec<Handle> {
let mut seen = std::collections::HashSet::new();
let joinable = |h: &Handle| {
d.entity(*h).is_some_and(|e| match &e.kind {
EntityKind::Line(_) => true,
EntityKind::Arc(a) => a.radius > cadcraft_geom::EPS,
EntityKind::LwPolyline(p) => !p.closed,
_ => false,
})
};
hs.iter().copied().filter(|h| joinable(h) && seen.insert(*h)).collect()
}
/// Whether JOIN would make the picked arcs a circle. AutoCAD 2024 asks first ("Combined arc
/// segments form a circle. Convert to circle? [Yes/No] <Yes>:"), and No leaves every arc as it
/// is (measured).
pub(crate) fn join_makes_circle(s: &Session, hs: &[Handle]) -> bool {
let Ok(d) = s.doc() else { return false };
// Elliptical arcs and splines join another way, and a locked object stops the join.
let other_way = |h: &Handle| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Ellipse(_) | EntityKind::Spline(_)));
if hs.iter().any(|h| other_way(h) || crate::cmd::curves::is_locked(s, *h)) {
return false;
}
let picks = joinable_picks(d, hs);
let arcs: Vec<&cadcraft_doc::Arc> = picks
.iter()
.filter_map(|h| match d.entity(*h).map(|e| &e.kind) {
Some(EntityKind::Arc(a)) => Some(a),
_ => None,
})
.collect();
let tol = 1e-6;
match &arcs[..] {
[g, rest @ ..] if !rest.is_empty() && arcs.len() == picks.len() => arc_reach(g, rest, tol).is_some_and(|far| far > cadcraft_geom::TAU - tol),
_ => false,
}
}
/// How far round the source arc `g`'s circle, counterclockwise from its start, it and the
/// `others` reach; `None` when one of them isn't on that circle (less than `tol` off its centre
/// and radius). An arc that starts even a hair before the source's start reaches on round past
/// it: AutoCAD 2024 makes a circle of 7°-100° and an arc stored from 7° less 5e-16 rad, and
/// leaves 7°-100° with one from exactly 7° or 5e-7 rad after it.
fn arc_reach(g: &cadcraft_doc::Arc, others: &[&cadcraft_doc::Arc], tol: f64) -> Option<f64> {
let same_circle =
|o: &cadcraft_doc::Arc| o.center.xy().dist(g.center.xy()) < tol && (o.radius - g.radius).abs() < tol && (o.center.z - g.center.z).abs() < tol;
let reach = |o: &cadcraft_doc::Arc| norm_angle(o.start - g.start) + cadcraft_geom::ccw_sweep(o.start, o.end);
others.iter().all(|o| same_circle(o)).then(|| others.iter().map(|o| reach(o)).fold(reach(g), f64::max))
}
/// The chain JOIN builds from the first object: each next object with an end on one of the
/// chain's ends joins whole, turned round where needed, as AutoCAD 2024 joins them, until a join
/// closes the chain; one that the chain meets only at an inner vertex of a polyline stays out.
/// Ends are compared at the objects' own end points, not ones worked out again from arcs, and at
/// their heights.
fn chain_units(mut units: Vec<Vec<Piece>>, tol: f64) -> Vec<Piece> {
let ends = |u: &[Piece]| u.first().zip(u.last()).map(|(a, b)| (a.start(), b.end()));
let near = |p, q| meet(p, q, tol);
if units.is_empty() {
return Vec::new();
}
// A source that already ends where it starts still takes more, unless it has no length at all
// (AutoCAD 2024, measured with a polyline that ends where it starts and with a line of no
// length).
let mut chain: std::collections::VecDeque<Piece> = units.remove(0).into();
if chain.iter().all(|p| p.ends.0.near(p.ends.1, tol)) {
return chain.into();
}
while let (Some(start), Some(end)) = (chain.front().map(Piece::start), chain.back().map(Piece::end)) {
let meets = |u: &Vec<Piece>| ends(u).is_some_and(|(a, b)| near(a, end) || near(b, end) || near(a, start) || near(b, start));
let Some(i) = units.iter().position(meets) else { break };
let unit = units.remove(i);
let Some((a, b)) = ends(&unit) else { break };
// Where an object that meets the chain at more than one place goes, as AutoCAD 2024 puts
// it (measured): a polyline by its first vertex if it can, and before the chain rather
// than after it; a line or an arc turned round if it can, its end on the chain's end
// before its start on the chain's start.
let polyline = unit.first().is_some_and(|p| p.widths.is_some());
let (before, turned) = if polyline {
if near(a, start) {
(true, true)
} else if near(a, end) {
(false, false)
} else {
(near(b, start), !near(b, start))
}
} else if near(b, end) {
(false, true)
} else if near(a, start) {
(true, true)
} else {
(!near(a, end), false)
};
match (before, turned) {
(false, false) => chain.extend(unit),
(false, true) => chain.extend(unit.into_iter().rev().map(Piece::flipped)),
(true, false) => unit.into_iter().rev().for_each(|p| chain.push_front(p)),
(true, true) => unit.into_iter().for_each(|p| chain.push_front(p.flipped())),
}
// A chain that a join closes takes nothing more.
if chain.front().zip(chain.back()).is_some_and(|(f, l)| near(f.start(), l.end())) {
break;
}
}
chain.into()
}
/// A segment in the chain JOIN builds: the object it came from, its end points as the object has
/// them (turned round when it runs backwards in the chain) and their world heights (a line's own
/// Z, an arc's centre Z, a polyline's elevation, negated for one facing down), its bulge and, for a
/// polyline's own segment, its widths.
#[derive(Clone, Copy)]
struct Piece {
owner: Handle,
ends: (Vec2, Vec2),
heights: (f64, f64),
bulge: f64,
widths: Option<(f64, f64)>,
}
impl Piece {
fn flipped(self) -> Self {
Piece {
ends: (self.ends.1, self.ends.0),
heights: (self.heights.1, self.heights.0),
bulge: -self.bulge,
widths: self.widths.map(|(a, b)| (b, a)),
..self
}
}
fn start(&self) -> (Vec2, f64) {
(self.ends.0, self.heights.0)
}
fn end(&self) -> (Vec2, f64) {
(self.ends.1, self.heights.1)
}
}
/// Whether two ends meet: in plan and at the same height. AutoCAD 2024 leaves an end that meets
/// another only in plan apart (measured: a line or a polyline at 0 and a line at 5, or a polyline
/// at 5 and a line at 0, end to end in plan, stay as they are).
fn meet(p: (Vec2, f64), q: (Vec2, f64), tol: f64) -> bool {
p.0.near(q.0, tol) && (p.1 - q.1).abs() < tol
}
/// The open polyline `sp` (handle `src`) with the chain's other pieces added before and after
/// it, as AutoCAD 2024 JOIN makes it (measured with `entget`): its own vertices stay exactly as
/// they are, and so do its elevation, linetype generation and, when only lines and arcs join,
/// its constant width; another polyline's segments keep their bulges and widths; a line or arc
/// takes the widths of the source's vertex at the end it joins (first or last); and when another
/// polyline joins, the end vertex's widths are cleared.
///
/// `None` when the source's segments aren't one run of the chain (they always are: the chain
/// starts from the source and takes its segments in order).
fn onto_polyline(sp: &cadcraft_doc::LwPolyline, src: Handle, links: &[Piece], closed: bool) -> Option<cadcraft_doc::LwPolyline> {
let run: Vec<usize> = (0..links.len()).filter(|i| links[*i].owner == src).collect();
let (&first, &last) = (run.first()?, run.last()?);
if sp.closed || run.len() != last - first + 1 {
return None;
}
let other_polyline = links.iter().any(|l| l.owner != src && l.widths.is_some());
let mut own = sp.vertices.clone();
if other_polyline && sp.const_width > 0.0 {
// The constant width goes, so spell it out on the source's own segments.
for v in &mut own {
(v.start_width, v.end_width) = (sp.const_width, sp.const_width);
}
}
let widths = |v: &PolyVertex| (v.start_width, v.end_width);
let (head, tail) = (widths(own.first()?), widths(own.last()?));
let vertex = |i: usize, fill: (f64, f64)| {
let (start_width, end_width) = links[i].widths.unwrap_or(fill);
PolyVertex { p: links[i].ends.0, bulge: links[i].bulge, start_width, end_width }
};
let mut vs: Vec<PolyVertex> = (0..first).map(|i| vertex(i, head)).collect();
vs.extend(own);
if last + 1 < links.len() {
// The source's end vertex starts the first piece after it.
let v = vertex(last + 1, tail);
if let Some(end) = vs.last_mut() {
(end.bulge, end.start_width, end.end_width) = (v.bulge, v.start_width, v.end_width);
}
vs.extend((last + 2..links.len()).map(|i| vertex(i, tail)));
vs.push(PolyVertex { p: links.last()?.ends.1, start_width: tail.0, end_width: tail.1, ..Default::default() });
}
if other_polyline && let Some(end) = vs.last_mut() {
(end.start_width, end.end_width) = (0.0, 0.0);
}
if closed {
// The last vertex is the first one again.
vs.pop();
}
Some(cadcraft_doc::LwPolyline { vertices: vs, closed, const_width: if other_polyline { 0.0 } else { sp.const_width }, ..sp.clone() })
}
/// JOIN onto the first object (the source) as AutoCAD 2024 does when the others all lie on its
/// line or its circle: gaps and overlaps are bridged and the source keeps its handle.
///
/// - Lines on the source's line make one line, from the source's start end to the farthest
/// point the way it runs (and back past its start if one reaches behind it).
/// - Arcs on the source's circle join counterclockwise from the source's start to the farthest
/// end; arcs that reach all the way round make a circle, a new object in their place.
///
/// `None` when the objects aren't all of one of those kinds.
fn join_on_source(s: &mut Session, hs: &[Handle]) -> Result<Option<Handle>> {
let d = s.doc()?;
let ents: Vec<std::sync::Arc<Entity>> = hs.iter().filter_map(|h| d.entity(*h).cloned()).collect();
let [src, rest @ ..] = &ents[..] else { return Ok(None) };
if rest.is_empty() || ents.len() != hs.len() {
return Ok(None);
}
// AutoCAD 2024 takes lines less than 1e-6 off the source's line, and arcs less than 1e-6
// off its centre and radius, at any size of coordinates (measured at 0, 1000 and 2.4e6), and
// makes a circle of arcs that come round to less than 1e-6 radians from the source's start.
let tol = 1e-6;
let kind = match &src.kind {
EntityKind::Line(l) => {
let (a, b) = (l.a.xy(), l.b.xy());
let len = a.dist(b);
let lines: Vec<&cadcraft_doc::Line> = rest
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(o) => Some(o),
_ => None,
})
.collect();
let level = |z: f64| (z - l.a.z).abs() < tol;
if lines.len() != rest.len() || len <= 0.0 || !level(l.b.z) || !lines.iter().all(|o| level(o.a.z) && level(o.b.z)) {
return Ok(None);
}
let u = (b - a) * (1.0 / len);
let on_line = |p: Vec2| (p - a).cross(u).abs() < tol;
if !lines.iter().all(|o| on_line(o.a.xy()) && on_line(o.b.xy())) {
return Ok(None);
}
let ts = lines.iter().flat_map(|o| [o.a.xy(), o.b.xy()]).map(|p| (p - a).dot(u)).chain([0.0, len]);
let (t0, t1) = ts.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), t| (lo.min(t), hi.max(t)));
let at = |t: f64| (a + u * t).to3(l.a.z);
EntityKind::Line(cadcraft_doc::Line { a: at(t0), b: if t1 == len { l.b } else { at(t1) } })
}
EntityKind::Arc(g) => {
let arcs: Vec<&cadcraft_doc::Arc> = rest
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Arc(o) => Some(o),
_ => None,
})
.collect();
let Some(far) = arc_reach(g, &arcs, tol).filter(|_| arcs.len() == rest.len()) else { return Ok(None) };
if far > cadcraft_geom::TAU - tol {
let circle = Entity {
handle: Handle(0),
common: src.common.clone(),
kind: EntityKind::Circle(cadcraft_doc::Circle { center: g.center, radius: g.radius }),
};
// In the source's space, whichever space is current.
let space = d.space_of(src.handle).unwrap_or_else(|| s.space());
let doc = s.doc_mut()?;
for h in hs {
doc.remove_entity(*h);
}
let nh = doc.new_handle();
if let Some(st) = doc.space_mut(&space) {
st.push(Entity { handle: nh, ..circle });
}
s.set_selection(Vec::new());
return Ok(Some(nh));
}
let end = if far > cadcraft_geom::ccw_sweep(g.start, g.end) { norm_angle(g.start + far) } else { g.end };
EntityKind::Arc(cadcraft_doc::Arc { end, ..g.clone() })
}
_ => return Ok(None),
};
let src_h = src.handle;
let doc = s.doc_mut()?;
for h in hs.iter().filter(|h| **h != src_h) {
doc.remove_entity(*h);
}
doc.modify_entity(src_h, |e| e.kind = kind)?;
s.set_selection(Vec::new());
Ok(Some(src_h))
}
pub(super) fn run_join(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
if p.get("close").and_then(Value::as_bool) == Some(true) {
+193 -18
View File
@@ -1,4 +1,4 @@
use super::break_join::join;
use super::break_join::{join, join_makes_circle};
use super::explode::explode;
use super::transform::{at_elevation, erase, scale_entities, transform_entities};
use super::{
@@ -20,6 +20,18 @@ pub(super) enum Op {
Join,
}
/// COPY's Array option: asking how many items, then where the second one goes (or, with Fit, the
/// last one).
#[derive(Clone, Copy, PartialEq)]
enum CopyArray {
Off,
Count,
Items { n: u16, fit: bool },
}
/// The most items COPY's Array option makes, the original included, as in AutoCAD.
const MAX_COPY_ITEMS: u16 = 32767;
/// Select objects, then collect the points/values the operation needs.
pub(super) struct SelectThen {
op: Op,
@@ -37,9 +49,16 @@ pub(super) struct SelectThen {
/// SCALE Reference: the reference length, once known.
ref_len: Option<f64>,
copy_mode: bool,
/// COPY: one copy and done (COPYMODE 1, until the Multiple option), else copies until Exit.
copy_single: bool,
/// COPY: the objects each placement made, so Undo takes back the last one.
copies: Vec<Vec<Handle>>,
copy_array: CopyArray,
ask_erase: bool,
/// JOIN of a single arc or elliptical arc: the prompt asks for arcs to join to it, or cLose.
join_source: Option<Handle>,
/// JOIN of arcs that make a circle: asking whether to.
ask_circle: bool,
}
impl SelectThen {
@@ -55,8 +74,12 @@ impl SelectThen {
ref_from: None,
ref_len: None,
copy_mode: false,
copy_single: false,
copies: Vec::new(),
copy_array: CopyArray::Off,
ask_erase: false,
join_source: None,
ask_circle: false,
}
}
fn apply(&mut self, s: &mut Session) -> Result<Step> {
@@ -84,8 +107,120 @@ impl SelectThen {
}
}
/// JOIN the selected objects and report what they became.
/// COPY's prompt once the base point is known, as AutoCAD 2024 asks it.
fn copy_prompt(&self, base: Option<Vec2>) -> Prompt {
match self.copy_array {
CopyArray::Count => Prompt::new("Enter number of items to array", Accept::NUMBER),
CopyArray::Items { fit: false, .. } => Prompt::new("Specify second point", Accept::POINT).kw(&["Fit"]).base_opt(base),
CopyArray::Items { fit: true, .. } => Prompt::new("Specify second point", Accept::POINT).kw(&["Array"]).base_opt(base),
CopyArray::Off if self.copies.is_empty() => {
Prompt::new("Specify second point", Accept::POINT).kw(&["Array"]).default("use first point as displacement").base_opt(base)
}
CopyArray::Off => Prompt::new("Specify second point", Accept::POINT).kw(&["Array", "Exit", "Undo"]).default("Exit").base_opt(base),
}
}
/// COPY once the base point is known (AutoCAD 2024, measured): a point places a copy; Enter
/// at the first prompt copies by the base point taken as a displacement, and after a copy
/// ends the command; Array asks for a number of items, the original included, then puts
/// them a second point apart (or, with Fit, spread up to it, Enter keeping them at the
/// base); Undo takes back the last placement. One placement ends a single-copy COPY.
fn copy_input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let Some(base) = self.pts.first().copied() else { return Ok(Step::Continue) };
let placed = match (self.copy_array, i) {
(CopyArray::Count, Input::Enter) => return self.copy_done(s),
(CopyArray::Count, i) => {
// A whole number as typed, from 2 to 32767 whatever the selection: AutoCAD 2024 takes
// +3 and 03 here, refuses 4.0, 1e1, 8/2, 1', 3", 50002 and a point, and doesn't
// apply MAXARRAY (with MAXARRAY 100000, four lines and 26000 items made 104000
// lines; measured).
let n = match i {
Input::Text(t) => t.trim().parse::<u16>().ok().filter(|v| (2..=MAX_COPY_ITEMS).contains(v)),
_ => None,
}
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 2 and {MAX_COPY_ITEMS}.")))?;
// Not AutoCAD's: the copies (items after the first, times the objects) stay within
// ARRAY's own limit, whatever MAXARRAY says, so a large selection can't run out of
// memory.
let copies = u64::from(n - 1).saturating_mul(u64::try_from(self.objs.len()).unwrap_or(u64::MAX));
if copies > cadcraft_doc::MAX_ARRAY_ITEMS {
return Err(EngineError::Other(format!(
"The array would create {copies} objects; the limit is {}. Use fewer items or select fewer objects.",
cadcraft_doc::MAX_ARRAY_ITEMS
)));
}
self.copy_array = CopyArray::Items { n, fit: false };
return Ok(Step::Continue);
}
(CopyArray::Items { n, fit }, Input::Keyword(kw)) if kw == if fit { "Array" } else { "Fit" } => {
self.copy_array = CopyArray::Items { n, fit: !fit };
return Ok(Step::Continue);
}
(CopyArray::Items { n, fit }, i @ (Input::Point(_) | Input::Enter)) => {
let p = if let Input::Point(p) = i { p } else { base };
let step = if fit { (p - base) * (1.0 / f64::from(n - 1)) } else { p - base };
self.copy_array = CopyArray::Off;
let mut made = Vec::new();
for k in 1..n {
match transform_entities(s, &self.objs, &Mat3::translate(step * f64::from(k)), true) {
Ok(hs) => made.extend(hs),
Err(e) => {
// The items made so far are a placement Undo takes back.
self.copies.push(made);
return Err(e);
}
}
}
made
}
(CopyArray::Off, Input::Keyword(kw)) if kw == "Array" => {
self.copy_array = CopyArray::Count;
return Ok(Step::Continue);
}
(CopyArray::Off, Input::Keyword(kw)) if kw == "Undo" => {
if let Some(last) = self.copies.pop() {
let d = s.doc_mut()?;
for h in last {
d.remove_entity(h);
}
if self.copies.is_empty() {
s.echo("Command has been completely undone.");
}
}
return Ok(Step::Continue);
}
(CopyArray::Off, Input::Keyword(kw)) if kw == "Exit" => return self.copy_done(s),
(CopyArray::Off, Input::Enter) if !self.copies.is_empty() => return self.copy_done(s),
(CopyArray::Off, Input::Enter) => {
transform_entities(s, &self.objs, &Mat3::translate(base), true)?;
return self.copy_done(s);
}
(CopyArray::Off, Input::Point(p)) => transform_entities(s, &self.objs, &Mat3::translate(p - base), true)?,
_ => return Ok(Step::Continue),
};
self.copies.push(placed);
if self.copy_single {
return self.copy_done(s);
}
Ok(Step::Continue)
}
fn copy_done(&mut self, s: &mut Session) -> Result<Step> {
s.set_selection(Vec::new());
Ok(Step::Done)
}
/// JOIN the selected objects and report what they became. Arcs that make a circle ask first,
/// as AutoCAD 2024 does.
fn join_now(&mut self, s: &mut Session) -> Result<Step> {
if join_makes_circle(s, &self.objs) {
self.ask_circle = true;
return Ok(Step::Continue);
}
self.join_apply(s)
}
fn join_apply(&mut self, s: &mut Session) -> Result<Step> {
match join(s, &self.objs) {
Ok(h) => {
// Objects outside the joined chain are kept, so count only the ones JOIN consumed
@@ -95,6 +230,9 @@ impl SelectThen {
let what = match h.and_then(|h| d.entity(h)).map(|e| &e.kind) {
Some(EntityKind::Spline(_)) => "spline",
Some(EntityKind::Ellipse(_)) => "ellipse",
Some(EntityKind::Line(_)) => "line",
Some(EntityKind::Arc(_)) => "arc",
Some(EntityKind::Circle(_)) => "circle",
_ => "polyline",
};
s.echo(format!("{n} objects joined into 1 {what}"))
@@ -308,6 +446,9 @@ impl Interactive for SelectThen {
if self.ask_erase {
return Prompt::new("Erase source objects?", Accept::TEXT).kw(&["Yes", "No"]).default("No");
}
if self.ask_circle {
return Prompt::new("Combined arc segments form a circle. Convert to circle?", crate::cmd::curves::KW).kw(&["Yes", "No"]).default("Yes");
}
if let Some(src) = self.join_source {
let ellipse = s.doc().is_ok_and(|d| matches!(d.entity(src).map(|e| &e.kind), Some(EntityKind::Ellipse(_))));
let msg = if ellipse { "Select elliptical arcs to join to source" } else { "Select arcs to join to source" };
@@ -328,7 +469,7 @@ impl Interactive for SelectThen {
match (self.op, k) {
(Op::Move | Op::Copy, 0) => Prompt::new("Specify base point", Accept::POINT).kw(&["Displacement"]),
(Op::Move, _) => Prompt::new("Specify second point or <use first point as displacement>", Accept::POINT).base_opt(base),
(Op::Copy, _) => Prompt::new("Specify second point", Accept::POINT).kw(&["Array", "Exit", "Undo"]).base_opt(base),
(Op::Copy, _) => self.copy_prompt(base),
(Op::Rotate | Op::Scale, 0) => Prompt::new("Specify base point", Accept::POINT),
// ROTATE and SCALE offer the angle/factor used last time.
(Op::Rotate, _) => {
@@ -361,6 +502,14 @@ impl Interactive for SelectThen {
}
}
}
// No leaves every arc as it is (AutoCAD 2024, measured).
if self.ask_circle {
return match &i {
Input::Keyword(k) if k == "No" => Ok(Step::Done),
Input::Keyword(_) | Input::Enter => self.join_apply(s),
_ => Err(EngineError::Other("Invalid option keyword.".into())),
};
}
if let Some(src) = self.join_source {
return self.join_source_input(s, src, i);
}
@@ -388,10 +537,6 @@ impl Interactive for SelectThen {
self.reference = true;
Ok(Step::Continue)
}
(Op::Copy, _, Input::Keyword(kw)) if kw == "Exit" => {
s.set_selection(Vec::new());
Ok(Step::Done)
}
(_, 0, Input::Point(p)) => {
self.pts.push(p);
Ok(Step::Continue)
@@ -408,15 +553,7 @@ impl Interactive for SelectThen {
s.set_selection(Vec::new());
Ok(Step::Done)
}
(Op::Copy, _, Input::Point(p)) => {
let d = p - self.pts[0];
transform_entities(s, &self.objs, &Mat3::translate(d), true)?;
Ok(Step::Continue)
}
(Op::Copy, _, Input::Enter) => {
s.set_selection(Vec::new());
Ok(Step::Done)
}
(Op::Copy, _, i) => self.copy_input(s, i),
(Op::Rotate, 1, inp @ (Input::Point(_) | Input::Text(_) | Input::Enter)) => {
let a = match inp {
Input::Point(p) => self.pts[0].angle_to(p),
@@ -542,11 +679,13 @@ impl Interactive for SelectThen {
pub(super) struct DisplaceM {
inner: SelectThen,
displacement: bool,
/// COPY's mOde option: asking Single or Multiple.
ask_mode: bool,
}
impl DisplaceM {
pub(super) fn new(op: Op) -> Self {
DisplaceM { inner: SelectThen::new(op), displacement: false }
DisplaceM { inner: SelectThen::new(op), displacement: false, ask_mode: false }
}
/// At "Specify base point": objects selected, no point yet.
fn at_base(&self) -> bool {
@@ -559,14 +698,26 @@ impl Interactive for DisplaceM {
self.inner.name()
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.inner.copy_single = self.inner.op == Op::Copy && s.settings.copymode;
self.inner.begin(s)
}
fn prompt(&self, s: &Session) -> Prompt {
if self.displacement {
return Prompt::new("Specify displacement", Accept::POINT).default("0,0");
}
if self.ask_mode {
let current = if s.settings.copymode { "Single" } else { "Multiple" };
return Prompt::new("Enter a copy mode option", crate::cmd::curves::KW).kw(&["Single", "Multiple"]).default(current);
}
if self.at_base() {
return Prompt::new("Specify base point", Accept::POINT).kw(&["Displacement"]).default("Displacement");
// COPY: mOde sets COPYMODE; Multiple, offered while it is single, copies until Exit
// this once.
let kw: &[&str] = match self.inner.op {
Op::Copy if self.inner.copy_single => &["Displacement", "mOde", "Multiple"],
Op::Copy => &["Displacement", "mOde"],
_ => &["Displacement"],
};
return Prompt::new("Specify base point", Accept::POINT).kw(kw).default("Displacement");
}
self.inner.prompt(s)
}
@@ -583,10 +734,34 @@ impl Interactive for DisplaceM {
s.set_selection(Vec::new());
return Ok(Step::Done);
}
if self.ask_mode {
match &i {
Input::Keyword(k) if k == "Single" || k == "Multiple" => s.settings.copymode = k == "Single",
Input::Enter => {}
_ => return Ok(Step::Continue),
}
// The mode shown is the mode this COPY runs in, Enter keeping it.
self.inner.copy_single = s.settings.copymode;
self.ask_mode = false;
return Ok(Step::Continue);
}
if self.at_base() && (matches!(&i, Input::Enter) || matches!(&i, Input::Keyword(k) if k == "Displacement")) {
self.displacement = true;
return Ok(Step::Continue);
}
if self.at_base() && self.inner.op == Op::Copy {
match &i {
Input::Keyword(k) if k == "mOde" => {
self.ask_mode = true;
return Ok(Step::Continue);
}
Input::Keyword(k) if k == "Multiple" => {
self.inner.copy_single = false;
return Ok(Step::Continue);
}
_ => {}
}
}
self.inner.input(s, i)
}
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
+55 -4
View File
@@ -3,6 +3,7 @@ use super::{
Accept, Entity, EntityKind, Handle, Input, Interactive, Mat3, Prompt, Result, SelectKind, SelectMode, Session, Step, Value, Vec2, bad, json,
line, points_param,
};
use cadcraft_geom::Arc;
/// An area whose vertices STRETCH moves: a window's box, or a polygon closed back to its first
/// point.
@@ -40,6 +41,18 @@ fn add_mline_vertex_hits(s: &Session, area: &StretchArea, hs: &mut Vec<Handle>)
}
}
/// The bulge that keeps an arc's height (bulge × chord / 2) when its chord changes length; none
/// once the chord collapses to a point, which has no arc left to keep.
fn keep_height(bulge: f64, old_chord: f64, new_chord: f64) -> f64 {
if new_chord.is_nan() || new_chord <= 1e-12 {
0.0
} else if old_chord.is_finite() {
bulge * old_chord / new_chord
} else {
bulge
}
}
/// Move the vertices of `e` that lie inside any of the areas `wins` by `d` (STRETCH).
fn stretch_entity(e: &mut Entity, wins: &[StretchArea], d: Vec2) {
let inside = |p: Vec2| wins.iter().any(|a| a.contains(p));
@@ -55,18 +68,56 @@ fn stretch_entity(e: &mut Entity, wins: &[StretchArea], d: Vec2) {
mv(&mut l.b);
}
EntityKind::LwPolyline(pl) => {
let old: Vec<Vec2> = pl.vertices.iter().map(|v| v.p).collect();
for v in &mut pl.vertices {
if inside(v.p) {
v.p += d;
}
}
// An arc segment keeps its height (bulge × chord / 2) as its ends move, as in AutoCAD.
let n = pl.vertices.len();
let segs = if pl.closed { n } else { n.saturating_sub(1) };
for i in 0..segs {
let j = (i + 1) % n;
let (Some(a0), Some(b0), Some(b1)) = (old.get(i), old.get(j), pl.vertices.get(j).map(|v| v.p)) else { continue };
if let Some(v) = pl.vertices.get_mut(i)
&& v.bulge != 0.0
{
v.bulge = keep_height(v.bulge, a0.dist(*b0), v.p.dist(b1));
}
}
}
EntityKind::MLine(m) => m.vertices.iter_mut().for_each(|v| mv(&mut v.p)),
EntityKind::Arc(a) => {
// Arcs keep their shape: move when the centre is inside.
if inside(a.center.xy()) {
a.center.x += d.x;
a.center.y += d.y;
// AutoCAD moves the ends inside the area and keeps the arc's height (bulge × chord / 2);
// the centre alone moves nothing. An end stretched onto the other leaves the arc as it
// was: AutoCAD collapses it into a zero-radius arc at that point (radius 6e-16, start
// 180°, end 0°), an object nothing can draw or pick, which CADCraft does not make.
let g = Arc::new(a.center.xy(), a.radius, a.start, a.end);
let (s0, e0) = (g.start_point(), g.end_point());
let (s_in, e_in) = (inside(s0), inside(e0));
let (s1, e1) = (if s_in { s0 + d } else { s0 }, if e_in { e0 + d } else { e0 });
if s_in && e_in {
// Both ends move: the arc moves whole (a full sweep has no chord to rebuild from).
(a.center.x, a.center.y) = (a.center.x + d.x, a.center.y + d.y);
} else if (s_in || e_in)
&& let Some((r, _)) =
cadcraft_geom::bulge_to_arc(s1, e1, keep_height(cadcraft_geom::arc_to_bulge(g.sweep()), s0.dist(e0), s1.dist(e1)))
{
(a.center.x, a.center.y) = (r.center.x, r.center.y);
(a.radius, a.start, a.end) = (r.radius, r.start, r.end);
}
}
// Control points inside the area move (AutoCAD).
EntityKind::Spline(sp) if sp.fit.is_empty() => sp.control.iter_mut().filter(|p| inside(**p)).for_each(|p| *p += d),
// A spline built from fit points: the fit points inside the area move and it is fitted
// through them again, its fit data kept (AutoCAD 2024). All of them inside, it moves.
EntityKind::Spline(sp) => {
if sp.fit.iter().all(|p| inside(*p)) {
sp.transform(&Mat3::translate(d));
} else if sp.fit.iter().any(|p| inside(*p)) {
let fit: Vec<Vec2> = sp.fit.iter().map(|p| if inside(*p) { *p + d } else { *p }).collect();
*sp = sp.refit(&fit, sp.closed);
}
}
EntityKind::Solid(so) | EntityKind::Trace(so) => so.corners.iter_mut().for_each(mv),
+44 -2
View File
@@ -4,7 +4,8 @@
use cadcraft_doc::{Common, Entity, EntityKind, Handle, LwPolyline, MAX_BLOCK_DEPTH, Space};
use cadcraft_geom::{
Arc, Ellipse, Line, Mat3, PolyVertex, Polyline, Segment, Spline, TAU, Vec2, ccw_sweep, intersect_ext, line_circle, line_line_infinite, norm_angle,
Arc, Ellipse, Line, Mat3, PolyVertex, Polyline, Segment, Spline, TAU, Vec2, Vec3, ccw_sweep, intersect_ext, line_circle, line_line_infinite,
norm_angle,
};
use serde_json::{Value, json};
@@ -39,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
.params(
"{handle, option: close|open|join|reverse|refit|purge|polyline|move|fitmove|fitadd|fitdelete|kink|tangents|tolerance|vertexadd|vertexmove|vertexdelete|weight|elevate, \
handles2? (join), fit?, index?, to?, before?: bool (fitadd), at? (kink, vertexadd), start?, end? (tangent directions; null = default), tolerance?, weight?, \
order? (elevate), precision?}",
order? (elevate), precision?: 0..99 (polyline, default 10)}",
)
.interactive(|_| Ok(Box::new(SplineditM::default()))),
CommandSpec::new("lengthen", "Lengthen", run_lengthen)
@@ -122,6 +123,47 @@ pub(crate) fn as_lwpoly(k: &EntityKind) -> Option<LwPolyline> {
}
}
/// The polyline PEDIT turns a line or an arc into, and the normal it faces, as AutoCAD 2024 makes
/// them (measured): facing the way the arc faces, and up for a line whatever its normal; at the
/// line's height, or at the arc's centre height measured along its normal (a mirrored arc whose
/// centre is at world Z -5 gives elevation 5, one at Z 5 elevation -5); the thickness stays the
/// object's. A sloped line still comes out at elevation 0: AutoCAD makes a polyline in the line's
/// vertical plane, which a CADCraft polyline can't be. An arc in a tilted plane (normal neither up
/// nor down Z), which CADCraft keeps only approximately, keeps its normal and goes by the sign of
/// its Z as above; AutoCAD's result for one isn't measured. A polyline is returned as it is.
pub(crate) fn polyline_of(e: &Entity) -> Option<(LwPolyline, Vec3)> {
let mut pl = as_lwpoly(&e.kind)?;
let normal = e.common.extrusion;
match &e.kind {
EntityKind::Line(l) => {
if (l.a.z - l.b.z).abs() < 1e-9 {
pl.elevation = l.a.z;
}
Some((pl, Vec3::Z))
}
// The arc's centre is in world coordinates; a polyline's elevation runs along its normal.
// A mirrored arc runs clockwise in plan, and so does its polyline (AutoCAD 2024 starts it
// at the arc's start in the arc's own coordinates).
EntityKind::Arc(a) => {
pl.elevation = if normal.z < 0.0 { -a.center.z } else { a.center.z };
if normal.z < 0.0 {
pl.vertices = curves::reverse_vertices(&pl.vertices, false);
}
Some((pl, normal))
}
_ => Some((pl, normal)),
}
}
/// Puts the polyline `pl`, facing `normal`, in place of the object `h`.
fn set_polyline(s: &mut Session, h: Handle, pl: LwPolyline, normal: Vec3) -> Result<()> {
s.doc_mut()?.modify_entity(h, |e| {
e.kind = EntityKind::LwPolyline(pl);
e.common.extrusion = normal;
})?;
Ok(())
}
mod pedit_multi;
mod pedit_vertex;
+25 -6
View File
@@ -1,6 +1,6 @@
use super::{
Accept, Chain, Handle, Input, Interactive, Mat3, Prompt, Result, SelOutcome, SelectPhase, Session, Step, Value, bad, bool_or, curves, json,
number, other, targets,
other, targets,
};
// =====================================================================================
@@ -26,7 +26,13 @@ pub(crate) fn arraypath(
return Err(other("Select objects to array."));
}
let (n, step) = match (count, spacing) {
(_, Some(sp)) if sp.is_finite() && sp > 0.0 => (((l / sp).floor() as usize).saturating_add(1), sp),
// As AutoCAD 2024 fills a path by distance: floor(length / spacing) items on a closed path,
// so none lands on or near the first where the path closes, and one more, at the end, on
// an open one (measured). The 1e-9 lets a length that comes out a hair short still fit.
(_, Some(sp)) if sp.is_finite() && sp > 0.0 => {
let fit = (l / sp + 1e-9).floor() as usize;
(if c.closed { fit.max(1) } else { fit.saturating_add(1) }, sp)
}
(Some(n), _) => {
let n = n.max(1);
(n, if c.closed { l / n as f64 } else { l / (n.max(2) - 1) as f64 })
@@ -61,12 +67,25 @@ pub(crate) fn arraypath(
pub(super) fn run_arraypath(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let path = curves::handle_param(p, "path").ok_or_else(|| bad("arraypath", "`path` (handle) is required"))?;
let count = p.get("count").and_then(Value::as_u64).map(|n| usize::try_from(n).unwrap_or(usize::MAX));
let spacing = p.get("spacing").and_then(Value::as_f64);
let r = arraypath(s, &hs, path, count, spacing, bool_or(p, "align", true))?;
// As in the other arrays' JSON forms, a value that isn't a whole number of at least 1 (or a
// positive spacing) is refused, not ignored; missing or null is the default.
let count = crate::cmd::array::count_or("arraypath", p, "count", 6)?;
let spacing = crate::cmd::size_param("arraypath", p, "spacing", false)?;
let r = arraypath(s, &hs, path, Some(usize::try_from(count).unwrap_or(usize::MAX)), spacing, bool_or(p, "align", true))?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
/// The number of items typed at ARRAYPATH's prompt: a whole number from 1 to 32767, written in
/// plain decimals. AutoCAD 2024 takes 5, +5, 05, 5., 5.0, 5.00 and +5.0 there, and refuses 4.5,
/// 1e1, 8/2, 3', 0 and 32768 (measured).
pub(super) fn item_count(t: &str) -> Option<usize> {
let t = t.trim();
let digits = t.strip_prefix('+').unwrap_or(t);
let (whole, fraction) = digits.split_once('.').unwrap_or((digits, ""));
let plain = !whole.is_empty() && whole.bytes().all(|b| b.is_ascii_digit()) && fraction.bytes().all(|b| b == b'0');
whole.parse::<usize>().ok().filter(|n| plain && (1..=32_767).contains(n))
}
#[derive(Default)]
pub(in crate::cmd) struct PathArrayM {
sel: SelectPhase,
@@ -121,7 +140,7 @@ impl Interactive for PathArrayM {
}
(Some(path), inp @ (Input::Text(_) | Input::Enter)) => {
let n = match &inp {
Input::Text(t) => number(t).filter(|n| *n >= 1.0).ok_or_else(|| other("Requires a count of 1 or more."))? as usize,
Input::Text(t) => item_count(t).ok_or_else(|| other("Requires an integer between 1 and 32767."))?,
_ => 6,
};
arraypath(s, &self.objs, path, Some(n), None, true)?;
+99 -29
View File
@@ -1,7 +1,7 @@
use super::{
Accept, Chain, EntityKind, Handle, Input, Interactive, LwPolyline, MAX_GEN, PolyVertex, Prompt, Result, SelOutcome, SelectPhase, Session, Spline,
Step, Value, Vec2, as_lwpoly, bad, bool_or, curves, f64_or, f64_req, json, line, number, other, pedit_vertex, point_req, set_kind, str_param,
targets,
Accept, Chain, Entity, EntityKind, Handle, Input, Interactive, LwPolyline, MAX_GEN, PolyVertex, Prompt, Result, SelOutcome, SelectPhase, Session,
Spline, Step, Value, Vec2, Vec3, as_lwpoly, bad, bool_or, curves, f64_or, f64_req, json, line, number, other, pedit_vertex, point_req,
polyline_of, set_kind, set_polyline, str_param, targets,
};
/// Fit curve: a tangent-continuous pair of arcs (biarc) per segment through every vertex,
@@ -106,7 +106,21 @@ pub(crate) fn spline_vertices(vs: &[PolyVertex], closed: bool, segs: usize) -> V
}
/// Join connected lines/arcs/open polylines onto the ends of polyline `h` (kept in place).
pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f64) -> Result<usize> {
///
/// As AutoCAD 2024 joins (measured), none facing the other way: an arc or a polyline whose normal
/// points down Z where the polyline's points up, or the other way round; a line counts as facing
/// up. Multiple's Join (`same_height` false) takes them at any height (lines at Z 5 and Z 0 join).
///
/// PEDIT's own Join takes only objects in one plane with the polyline: the plane the polyline and
/// every line picked share, when they share one, else the polyline's own. So a sloped line joins
/// only when the polyline and all the lines picked lie in one plane (a vertical one for a sloped
/// line continuing a straight polyline in plan), and then no arc or polyline joins, as those lie
/// flat; otherwise only objects at the polyline's height join (a line, arc or polyline at Z 0
/// stays off one at Z 5). Ends meet within `fuzz` in plan and within 1e-6 in height, which `fuzz`
/// doesn't widen. After a sloped line the chain's end is at the line's far end, so the next object
/// meets it there; AutoCAD's polyline then lies in the lines' plane, CADCraft's keeps the source's
/// elevation and runs through the objects' points seen from above.
pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f64, same_height: bool) -> Result<usize> {
let e = curves::entity(s, h)?;
let mut base = as_lwpoly(&e.kind).ok_or_else(|| other("Select a polyline."))?;
if base.closed {
@@ -114,46 +128,88 @@ pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f6
}
let mut chain = Chain::of(&EntityKind::LwPolyline(base.clone())).unwrap_or_default();
let tol = fuzz.max(1e-6);
let mut pool: Vec<(Handle, Chain)> = Vec::new();
for o in others {
if *o == h {
// Which way an object faces, and its two ends' world heights.
let down = |e: &Entity| !matches!(e.kind, EntityKind::Line(_)) && e.common.extrusion.z < 0.0;
let heights = |e: &Entity| match &e.kind {
EntityKind::Line(l) => (l.a.z, l.b.z),
// An arc's centre is in world coordinates.
EntityKind::Arc(a) => (a.center.z, a.center.z),
// A polyline's elevation runs along its normal.
EntityKind::LwPolyline(p) => {
let z = if down(e) { -p.elevation } else { p.elevation };
(z, z)
}
_ => (0.0, 0.0),
};
// Two ends meet: in plan within the fuzz distance, and for PEDIT's own Join at the same height.
let at = |p: Vec2, ph: f64, q: Vec2, qh: f64| p.near(q, tol) && (!same_height || (ph - qh).abs() < 1e-6);
let picked: Vec<(Handle, Entity)> = others.iter().filter(|o| **o != h).filter_map(|o| Some((*o, curves::entity(s, *o).ok()?))).collect();
// The plane PEDIT's own Join works in (AutoCAD 2024, measured): the polyline's points, with a
// point off the chord of an arc segment, which lies flat, and the ends of every line picked.
let z0 = heights(&e).0;
let mut pts: Vec<Vec3> = base.vertices.iter().map(|v| Vec3::new(v.p.x, v.p.y, z0)).collect();
if let Some(w) = base.vertices.windows(2).find(|w| w[0].bulge.abs() > 1e-12) {
let (a, b) = (w[0].p, w[1].p);
let off = (a + b) * 0.5 + Vec2::new(a.y - b.y, b.x - a.x);
pts.push(Vec3::new(off.x, off.y, z0));
}
let lines: Vec<(Vec3, Vec3)> =
picked.iter().filter_map(|(_, oe)| if let EntityKind::Line(l) = &oe.kind { Some((l.a, l.b)) } else { None }).collect();
pts.extend(lines.iter().flat_map(|(a, b)| [*a, *b]));
let shared = coplanar(&pts);
// That plane is the polyline's own, flat, when every line is at its height.
let level = lines.iter().all(|(a, b)| (a.z - z0).abs() < 1e-6 && (b.z - z0).abs() < 1e-6);
let mut pool: Vec<(Handle, Chain, (f64, f64))> = Vec::new();
for (o, oe) in &picked {
if down(oe) != down(&e) {
continue;
}
let Ok(oe) = curves::entity(s, *o) else { continue };
let ok = matches!(&oe.kind, EntityKind::Line(_) | EntityKind::Arc(_)) || matches!(&oe.kind, EntityKind::LwPolyline(p) if !p.closed);
let line = matches!(oe.kind, EntityKind::Line(_));
let (ah, bh) = heights(oe);
// A sloped line lies in no flat plane, and an arc or a polyline in no other.
let off_plane = if shared && !level { !line } else { (ah - bh).abs() >= 1e-6 };
if same_height && off_plane {
continue;
}
let ok = line || matches!(&oe.kind, EntityKind::Arc(_)) || matches!(&oe.kind, EntityKind::LwPolyline(p) if !p.closed);
if ok && let Some(c) = Chain::of(&oe.kind) {
pool.push((*o, c));
pool.push((*o, c, (ah, bh)));
}
}
let (mut st_h, mut en_h) = heights(&e);
let mut joined = Vec::new();
while let (Some(st), Some(en)) = (chain.start(), chain.end()) {
let Some(i) = pool
.iter()
.position(|(_, c)| c.start().zip(c.end()).is_some_and(|(a, b)| a.near(en, tol) || b.near(en, tol) || a.near(st, tol) || b.near(st, tol)))
else {
let meets = |c: &Chain, (ah, bh): (f64, f64)| {
c.start().zip(c.end()).is_some_and(|(a, b)| at(a, ah, en, en_h) || at(b, bh, en, en_h) || at(a, ah, st, st_h) || at(b, bh, st, st_h))
};
let Some(i) = pool.iter().position(|(_, c, z)| meets(c, *z)) else {
break;
};
let (oh, c) = pool.remove(i);
let (oh, c, (ah, bh)) = pool.remove(i);
let (Some(a), Some(b)) = (c.start(), c.end()) else { continue };
if a.near(en, tol) {
if at(a, ah, en, en_h) {
chain.segs.extend(c.segs);
} else if b.near(en, tol) {
en_h = bh;
} else if at(b, bh, en, en_h) {
chain.segs.extend(c.reversed().segs);
} else if b.near(st, tol) {
en_h = ah;
} else if at(b, bh, st, st_h) {
let mut v = c.segs;
v.extend(chain.segs);
chain.segs = v;
st_h = ah;
} else {
let mut v = c.reversed().segs;
v.extend(chain.segs);
chain.segs = v;
st_h = bh;
}
joined.push(oh);
}
if joined.is_empty() {
return Ok(0);
}
chain.closed = chain.start().zip(chain.end()).is_some_and(|(a, b)| a.near(b, tol)) && chain.segs.len() > 1;
chain.closed = chain.start().zip(chain.end()).is_some_and(|(a, b)| at(a, st_h, b, en_h)) && chain.segs.len() > 1;
base.vertices = chain.vertices();
base.closed = chain.closed;
let d = s.doc_mut()?;
@@ -164,14 +220,29 @@ pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f6
Ok(joined.len())
}
/// Whether the points `pts` lie in one plane, to within 1e-6 (points in a line always do).
fn coplanar(pts: &[Vec3]) -> bool {
let Some(&p0) = pts.first() else { return true };
let far = |a: &&Vec3, b: &&Vec3| (**a - p0).len().total_cmp(&(**b - p0).len());
let Some(&p1) = pts.iter().max_by(far) else { return true };
let d = p1 - p0;
// The normal from the point farthest off the line p0 p1, for the least rounding.
let Some(n) = pts.iter().map(|p| d.cross(*p - p0)).max_by(|a, b| a.len().total_cmp(&b.len())) else { return true };
if n.len() <= 1e-6 * d.len() {
return true;
}
let n = n.normalized();
pts.iter().all(|p| n.dot(*p - p0).abs() < 1e-6)
}
pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> Result<Value> {
let e = curves::entity(s, h)?;
if curves::is_locked(s, h) {
return Err(other("The object is on a locked layer."));
}
let mut pl = match &e.kind {
EntityKind::LwPolyline(pl) => pl.clone(),
EntityKind::Line(_) | EntityKind::Arc(_) if bool_or(p, "convert", true) => as_lwpoly(&e.kind).ok_or_else(|| other("Cannot convert."))?,
let (mut pl, normal) = match &e.kind {
EntityKind::LwPolyline(pl) => (pl.clone(), e.common.extrusion),
EntityKind::Line(_) | EntityKind::Arc(_) if bool_or(p, "convert", true) => polyline_of(&e).ok_or_else(|| other("Cannot convert."))?,
_ => return Err(other("Object selected is not a polyline.")),
};
match opt {
@@ -197,14 +268,14 @@ pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> R
"reverse" | "r" => pl.vertices = curves::reverse_vertices(&pl.vertices, pl.closed),
"ltypegen" | "l" => pl.plinegen = bool_or(p, "on", !pl.plinegen),
"join" | "j" => {
set_kind(s, h, EntityKind::LwPolyline(pl))?;
set_polyline(s, h, pl, normal)?;
let others: Vec<Handle> = p
.get("handles2")
.or_else(|| p.get("join"))
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(curves::handle_value).collect())
.unwrap_or_default();
let n = pedit_join(s, h, &others, f64_or(p, "fuzz", 0.0))?;
let n = pedit_join(s, h, &others, f64_or(p, "fuzz", 0.0), true)?;
return Ok(json!({ "handle": h.hex(), "joined": n }));
}
"vertex" | "e" => {
@@ -254,7 +325,7 @@ pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> R
}
_ => return Err(bad("pedit", "unknown option")),
}
set_kind(s, h, EntityKind::LwPolyline(pl))?;
set_polyline(s, h, pl, normal)?;
Ok(json!({ "handle": h.hex() }))
}
@@ -468,10 +539,9 @@ impl Interactive for PeditM {
return Ok(Step::Done);
}
let h = self.h.ok_or_else(|| other("No object."))?;
let k = curves::entity(s, h)?.kind;
let pl = as_lwpoly(&k).ok_or_else(|| other("Cannot convert."))?;
let (pl, normal) = polyline_of(&curves::entity(s, h)?).ok_or_else(|| other("Cannot convert."))?;
self.original = Some(pl.vertices.clone());
set_kind(s, h, EntityKind::LwPolyline(pl))?;
set_polyline(s, h, pl, normal)?;
self.phase = PPhase::Main;
Ok(Step::Continue)
}
@@ -544,7 +614,7 @@ impl Interactive for PeditM {
SelOutcome::Done(hs) => {
let h = self.h.ok_or_else(|| other("No polyline."))?;
self.snapshot(s);
let n = pedit_join(s, h, &hs, 0.0)?;
let n = pedit_join(s, h, &hs, 0.0, true)?;
s.echo(format!("{n} segments added to polyline"));
s.set_selection(vec![h]);
self.phase = PPhase::Main;
+7 -7
View File
@@ -8,7 +8,7 @@ use serde_json::json;
use super::super::curves;
use super::super::machines::{SelOutcome, SelectPhase, number};
use super::pedit::{PPhase, PeditM, clear_widths, pedit_apply, pedit_join, yes_no};
use super::{as_lwpoly, other, set_kind};
use super::{other, polyline_of, set_kind, set_polyline};
use crate::{Accept, Input, Prompt, Result, Session, Step};
/// Most option steps Undo can take back.
@@ -78,13 +78,13 @@ impl PeditM {
let no = !yes_no(&i)?;
let mut kept = Vec::new();
for h in std::mem::take(&mut self.multi) {
let kind = curves::entity(s, h)?.kind;
match kind {
let e = curves::entity(s, h)?;
match e.kind {
EntityKind::LwPolyline(_) => kept.push(h),
_ if no => {}
k => {
if let Some(pl) = as_lwpoly(&k) {
set_kind(s, h, EntityKind::LwPolyline(pl))?;
_ => {
if let Some((pl, normal)) = polyline_of(&e) {
set_polyline(s, h, pl, normal)?;
kept.push(h);
}
}
@@ -219,7 +219,7 @@ impl PeditM {
let open = matches!(curves::entity(s, h)?.kind, EntityKind::LwPolyline(p) if !p.closed);
if open {
// A polyline that took on segments no longer goes back past the Join on Decurve.
if pedit_join(s, h, &rest, fuzz)? > 0 {
if pedit_join(s, h, &rest, fuzz, false)? > 0 {
self.morig.remove(&h);
}
rest.retain(|o| s.doc().is_ok_and(|d| d.entity(*o).is_some()));
+51 -25
View File
@@ -61,8 +61,11 @@ fn edit(sp: &Spline, opt: &str, p: &Value) -> Result<EntityKind> {
spline(sp.refit(&fit, sp.closed))
}
"polyline" => {
let precision = p.get("precision").and_then(Value::as_u64).unwrap_or(10).min(99) as usize;
Ok(EntityKind::LwPolyline(spline_to_poly(sp, precision)))
let precision = match p.get("precision") {
None | Some(Value::Null) => 10,
Some(v) => v.as_u64().filter(|n| *n <= 99).ok_or_else(|| bad("splinedit", "`precision` must be a whole number from 0 to 99"))?,
};
Ok(EntityKind::LwPolyline(spline_to_poly(sp, precision as usize)))
}
"move" => {
let (i, to) = (index(p)?, point_req("splinedit", p, "to")?);
@@ -96,7 +99,9 @@ fn spline_close(sp: &Spline) -> Spline {
return sp.clone();
}
let mut out = if sp.fit.len() >= 2 {
sp.refit(&sp.fit, true)
// The open ends' tangents don't carry over: the closed curve takes its own where it closes.
let opts = cadcraft_geom::FitOptions { start_tangent: None, end_tangent: None, ..sp.fit_opts };
Spline::fit_with_end_derivatives(&sp.fit, true, opts)
} else {
let mut c = sp.control.clone();
c.extend(sp.control.first().copied());
@@ -235,11 +240,11 @@ fn tolerance(sp: &Spline, tol: f64) -> Result<Spline> {
// ---------------- control points ----------------
/// The number of distinct control points: a periodic spline repeats its first `degree` at the
/// end, and a clamped closed one repeats its first at the end.
/// The number of distinct control points: control points that wrap round repeat their first
/// `degree` at the end, and a clamped closed spline repeats its first at the end.
fn distinct(sp: &Spline) -> usize {
let n = sp.control.len();
if sp.is_periodic() {
if sp.wraps() {
n.saturating_sub(sp.degree)
} else if sp.closed && n > 2 && sp.control.first().zip(sp.control.last()).is_some_and(|(a, b)| a.near(*b, 1e-12)) {
n - 1
@@ -311,7 +316,7 @@ fn delete_control(sp: &Spline, j: usize) -> Result<Spline> {
}
let mut s = without_fit(sp.clone());
let w = |s: &Spline, i: usize| s.weights.get(i).copied().unwrap_or(1.0);
if sp.is_periodic() {
if sp.wraps() {
if u <= p + 1 {
return Err(other(format!("A closed spline of degree {p} needs more than {} control points.", p + 1)));
}
@@ -379,22 +384,30 @@ fn join(s: &mut Session, h: Handle, sp: &Spline, others: &[Handle]) -> Result<Ve
}
/// A control point added by inserting a knot where the curve passes nearest `at`; the curve
/// keeps its shape. A periodic spline is clamped at its seam first.
/// keeps its shape. Control points that wrap round are clamped at the seam first.
fn add_control(sp: &Spline, at: Vec2) -> Result<Spline> {
let base = if sp.is_periodic() { sp.clamped().ok_or_else(|| other("Cannot add a control point to this spline."))? } else { sp.clone() };
let base = if sp.wraps() { sp.clamped().ok_or_else(|| other("Cannot add a control point to this spline."))? } else { sp.clone() };
let t = curves::spline_param_of(&base, at);
let mut out = base.insert_knot(t).ok_or_else(|| other("Cannot add a control point to this spline."))?;
out.closed = sp.closed;
Ok(out)
}
/// The highest order Elevate order takes: degree 25 is the most `Spline::elevated` builds, and
/// AutoCAD 2024's limit too.
const MAX_ORDER: u64 = 26;
/// AutoCAD 2024's message for an order it refuses: from the spline's own order to 26 (measured at
/// orders 4 and 5).
fn order_range(sp: &Spline) -> crate::EngineError {
other(format!("Requires an integer between {} and {MAX_ORDER}.", sp.degree as u64 + 1))
}
/// The same curve at a higher order (degree + 1), with more control points.
fn elevate(sp: &Spline, order: u64) -> Result<Spline> {
// Degree 25 is the most `Spline::elevated` builds.
let max = 26;
let current = sp.degree as u64 + 1;
if order < current || order > max {
return Err(other(format!("Requires an order between {current} and {max}.")));
if order < current || order > MAX_ORDER {
return Err(order_range(sp));
}
if order == current {
return Ok(sp.clone());
@@ -585,6 +598,22 @@ impl SplineditM {
}
Ok(())
}
/// Elevate order's "Enter new order": a whole number as typed. AutoCAD 2024 takes +5 and 05
/// and refuses 5.0, 5., 1e1, 4.5, 3, 27 and a point, all with the order range; Enter keeps
/// the order (measured).
fn input_order(&mut self, s: &mut Session, sp: &Spline, input: &Input) -> Result<()> {
if *input != Input::Enter {
let order = match input {
Input::Text(t) => t.trim().parse::<u64>().ok(),
_ => None,
}
.ok_or_else(|| order_range(sp))?;
self.apply(s, json!({ "option": "elevate", "order": order }))?;
}
self.sub = Sub::Vertex;
Ok(())
}
}
impl Interactive for SplineditM {
@@ -673,11 +702,15 @@ impl Interactive for SplineditM {
}
Sub::Join => self.input_join(s, h, &sp, &i)?,
Sub::Precision => {
// A whole number as typed: AutoCAD 2024 takes +5 and 05 and refuses 5.0, 5., 4.5,
// 1e1, 8/2, 100, -1 and a point (measured).
let precision = match &i {
Input::Text(t) => number(t).filter(|n| (0.0..=99.0).contains(n)).ok_or_else(|| other("Requires an integer between 0 and 99."))?,
_ => 10.0,
};
self.apply(s, json!({ "option": "polyline", "precision": precision.round() as u64 }))?;
Input::Text(t) => t.trim().parse::<u64>().ok().filter(|n| *n <= 99),
Input::Enter => Some(10),
_ => None,
}
.ok_or_else(|| other("Requires an integer between 0 and 99."))?;
self.apply(s, json!({ "option": "polyline", "precision": precision }))?;
s.set_selection(Vec::new());
return Ok(Step::Done);
}
@@ -784,14 +817,7 @@ impl Interactive for SplineditM {
None if enter => self.sub = Sub::Vertex,
None => {}
},
Sub::VertexOrder => {
if let Input::Text(t) = &i {
let order =
number(t).filter(|o| o.fract() == 0.0 && *o >= 1.0 && *o <= 1000.0).ok_or_else(|| other("Requires a whole number."))?;
self.apply(s, json!({ "option": "elevate", "order": order as u64 }))?;
}
self.sub = Sub::Vertex;
}
Sub::VertexOrder => self.input_order(s, &sp, &i)?,
Sub::VertexDelete => match point {
Some(p) => {
let u = distinct(&sp);
+212
View File
@@ -639,6 +639,32 @@ fn arraypath_json_and_command_line() {
assert!(matches!(last(&s), EntityKind::Line(l) if near(l.a.xy(), -5.0, 20.0) && near(l.b.xy(), -6.0, 20.0)));
assert!(s.execute("arraypath", &json!({"handles": [dot], "path": dot})).is_err());
// By spacing, AutoCAD 2024 fills a closed path with floor(length / spacing) items and an open
// one with one more, at the end (measured on a 100 square and on the same square open).
let square = [[0, 0], [100, 0], [100, 100], [0, 100]];
let r400 = 400.0 / std::f64::consts::TAU;
for (closed, spacing, items) in
[(true, 100, 4), (true, 30, 13), (true, 200, 2), (true, 400, 1), (true, 399, 1), (false, 100, 4), (false, 30, 11), (false, 300, 2)]
{
let mut s = Session::new();
let dot = h(&s.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap());
let path = h(&s.execute("pline", &json!({"points": square, "closed": closed})).unwrap());
let r = s.execute("arraypath", &json!({"handles": [dot], "path": path, "spacing": spacing})).unwrap();
assert_eq!(r["handles"].as_array().map(Vec::len), Some(items - 1), "closed {closed}, spacing {spacing}");
}
// A circle 400 round: 4 items at 100, none on the first (AutoCAD 2024, measured).
let mut s = Session::new();
let dot = h(&s.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap());
let path = h(&s.execute("circle", &json!({"center": [0, r400], "radius": r400})).unwrap());
let r = s.execute("arraypath", &json!({"handles": [dot], "path": path, "spacing": 100})).unwrap();
assert_eq!(r["handles"].as_array().map(Vec::len), Some(3));
// Three sides of 0.35 add up to a hair under 3 × 0.35; the item at the end still fits.
let mut s = Session::new();
let dot = h(&s.execute("circle", &json!({"center": [0, 0], "radius": 0.01})).unwrap());
let path = h(&s.execute("pline", &json!({"points": [[0, 0], [0.35, 0], [0.35, 0.35], [0, 0.35]]})).unwrap());
let r = s.execute("arraypath", &json!({"handles": [dot], "path": path, "spacing": 0.35})).unwrap();
assert_eq!(r["handles"].as_array().map(Vec::len), Some(3));
let mut s = Session::new();
s.execute("circle", &json!({"center": [0, 1], "radius": 0.25})).unwrap();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
@@ -649,6 +675,40 @@ fn arraypath_json_and_command_line() {
assert_eq!(s.doc().unwrap().model.len(), 4);
}
#[test]
fn arraypath_item_count_as_autocad_takes_it() {
// AutoCAD 2024 at "Enter number of items along path": a whole number from 1 to 32767 in plain
// decimals, 5. and 5.0 included; 4.5, 1e1, 8/2, 3', 0 and 32768 are refused.
let mut s = Session::new();
s.execute("circle", &json!({"center": [0, 1], "radius": 0.25})).unwrap();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
s.cmdline("arraypath 0.25,1").unwrap();
s.cmdline("").unwrap();
s.cmdline("5,0").unwrap();
let asked = s.prompt_text();
// Measured, then texts that aren't plain whole numbers (not measured).
for t in ["4.5", "1e1", "8/2", "3'", "0", "32768", "+", ".5", "5.0.0", "5.1"] {
s.cmdline(t).unwrap();
assert_eq!(s.log.last().map(String::as_str), Some("Requires an integer between 1 and 32767."), "{t}");
assert_eq!(s.prompt_text(), asked, "{t}");
}
s.cmdline("3").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
// The ends of the range, without drawing 32,767 copies.
assert_eq!((super::patharray::item_count("1"), super::patharray::item_count("32767")), (Some(1), Some(32_767)));
for (typed, items) in [("5", 5), ("5.", 5), ("5.0", 5), ("5.00", 5), ("05.0", 5), ("+5.0", 5), ("05", 5), ("+4", 4), ("1", 1)] {
let mut s = Session::new();
s.execute("circle", &json!({"center": [0, 1], "radius": 0.25})).unwrap();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
for t in ["arraypath 0.25,1", "", "5,0", typed] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none(), "{typed}: {}", s.prompt_text());
// The path and the items (the original is the first).
assert_eq!(s.doc().unwrap().model.len(), 1 + items, "{typed}");
}
}
#[test]
fn textedit_json_and_command_line() {
let mut s = Session::new();
@@ -777,3 +837,155 @@ fn offset_elliptical_arc_follows_picked_side() {
let outer = max_x(json!([20, 20]));
assert!((outer - 11.0).abs() < 0.05, "outer side went inward: max x = {outer}");
}
/// STRETCH against what AutoCAD 2024 stores for the same crossing window and displacement (5, 3)
/// (black-box: synthetic objects in accoreconsole, read back with `entget`): the ends of an arc
/// that are inside move and the arc keeps its height (bulge × chord / 2), as does a polyline arc
/// segment; the centre alone moves nothing; a spline's control points inside move.
#[test]
fn stretch_arcs_bulges_and_splines_match_autocad() {
enum Want {
Arc([f64; 2], f64, f64, f64),
Bulges(&'static [f64]),
Control(&'static [[f64; 2]]),
}
// ((seed command, params), crossing window, what AutoCAD stores)
let cases: Vec<((&str, Value), [[f64; 2]; 2], Want)> = vec![
// SX-ARC-1END: one end of the arc inside.
(
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 0.0, "end": 90.0})),
[[15.0, -5.0], [30.0, 5.0]],
Want::Arc([3.17984478246544, -2.20611061402141], 22.43262716319083, 0.2342130724507349, 1.713026264953702),
),
// SX2-ARC-ENDPT: the other end inside.
(
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 0.0, "end": 90.0})),
[[-5.0, 15.0], [5.0, 25.0]],
Want::Arc([1.476584509301813, 4.310815984327269], 19.01841360081773, 6.054532724492258, 1.384456456611818),
),
// SX2-ARC-BIG-END: an arc over 180 degrees, its end inside.
(
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 30.0, "end": 300.0})),
[[5.0, -25.0], [15.0, -12.0]],
Want::Arc([1.341732093243006, -0.7463649967436295], 19.25631435504786, 0.5920576993601167, 5.500876277544912),
),
// SX2-ARC-CEN: only the centre inside: unchanged.
(
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 0.0, "end": 90.0})),
[[-3.0, -3.0], [16.0, 16.0]],
Want::Arc([0.0, 0.0], 20.0, 0.0, std::f64::consts::FRAC_PI_2),
),
// SX-ARC-ALL: the whole arc inside: moved.
(
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 0.0, "end": 90.0})),
[[-5.0, -5.0], [30.0, 30.0]],
Want::Arc([5.0, 3.0], 20.0, 0.0, std::f64::consts::FRAC_PI_2),
),
// A full-sweep arc (start = end) inside the window: moved whole, though its chord is zero.
(
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 45.0, "end": 45.0})),
[[-25.0, -25.0], [25.0, 25.0]],
Want::Arc([5.0, 3.0], 20.0, std::f64::consts::FRAC_PI_4, std::f64::consts::FRAC_PI_4),
),
// SX-PLA-V1: the vertex starting an arc segment.
(
(
"pline",
json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [30.0, 0.0], "bulge": 0.5}, {"p": [45.0, 20.0], "bulge": 0.0}, {"p": [60.0, 20.0], "bulge": 0.0}], "closed": false}),
),
[[25.0, -5.0], [35.0, 5.0]],
Want::Bulges(&[0.0, 0.6337751582042422, 0.0, 0.0]),
),
// SX-PLA-V2: the vertex ending an arc segment.
(
(
"pline",
json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [30.0, 0.0], "bulge": 0.5}, {"p": [45.0, 20.0], "bulge": 0.0}, {"p": [60.0, 20.0], "bulge": 0.0}], "closed": false}),
),
[[40.0, 15.0], [50.0, 25.0]],
Want::Bulges(&[0.0, 0.4101116968279916, 0.0, 0.0]),
),
// SX2-PLA-NEG: a negative bulge over 180 degrees.
(
(
"pline",
json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [30.0, 0.0], "bulge": -1.5}, {"p": [45.0, 20.0], "bulge": 0.0}, {"p": [60.0, 20.0], "bulge": 0.0}], "closed": false}),
),
[[40.0, 15.0], [50.0, 25.0]],
Want::Bulges(&[0.0, -1.230335090483974, 0.0, 0.0]),
),
// SX3-SPL-CV-ONLY: a window holding a control point but missing the drawn curve selects
// nothing in AutoCAD ("0 found"), so the spline stays as it was.
(
("spline", json!({"control": [[0.0, 0.0], [10.0, 100.0], [20.0, 100.0], [30.0, 0.0]], "degree": 3})),
[[5.0, 95.0], [15.0, 105.0]],
Want::Control(&[[0.0, 0.0], [10.0, 100.0], [20.0, 100.0], [30.0, 0.0]]),
),
// SX3-SPL-CV-CROSS: the same control point in a window that also crosses the curve moves.
(
("spline", json!({"control": [[0.0, 0.0], [10.0, 100.0], [20.0, 100.0], [30.0, 0.0]], "degree": 3})),
[[5.0, 40.0], [15.0, 105.0]],
Want::Control(&[[0.0, 0.0], [15.0, 103.0], [20.0, 100.0], [30.0, 0.0]]),
),
// SX-SPL: two control points inside.
(
("spline", json!({"control": [[0.0, 0.0], [10.0, 10.0], [20.0, 0.0], [30.0, 10.0]], "degree": 3})),
[[15.0, -5.0], [35.0, 15.0]],
Want::Control(&[[0.0, 0.0], [10.0, 10.0], [25.0, 3.0], [35.0, 13.0]]),
),
];
let same = |a: f64, b: f64| (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0);
let same_angle = |a: f64, b: f64| {
let d = (a - b).rem_euclid(std::f64::consts::TAU);
d < 1e-9 || std::f64::consts::TAU - d < 1e-9
};
for ((seed, params), window, want) in cases {
let mut s = Session::new();
let hd = h(&s.execute(seed, &params).unwrap());
s.execute("stretch", &json!({"window": window, "delta": [5.0, 3.0]})).unwrap();
match (kind(&s, &hd), want) {
(EntityKind::Arc(a), Want::Arc(c, r, start, end)) => assert!(
same(a.center.x, c[0]) && same(a.center.y, c[1]) && same(a.radius, r) && same_angle(a.start, start) && same_angle(a.end, end),
"{window:?}: {a:?}"
),
(EntityKind::LwPolyline(p), Want::Bulges(want)) => {
let got: Vec<f64> = p.vertices.iter().map(|v| v.bulge).collect();
assert!(got.len() == want.len() && got.iter().zip(want).all(|(a, b)| same(*a, *b)), "{window:?}: {got:?} / {want:?}");
}
(EntityKind::Spline(sp), Want::Control(want)) => {
let ok = sp.control.len() == want.len() && sp.control.iter().zip(want).all(|(p, w)| same(p.x, w[0]) && same(p.y, w[1]));
assert!(ok, "{window:?}: {:?} / {want:?}", sp.control);
}
(k, _) => panic!("{window:?}: {k:?}"),
}
}
// A spline built from fit points: the fit points inside move and it is fitted through them
// again, keeping its fit data; all of them inside, it moves whole (AutoCAD 2024, `entget`
// after STRETCH of a spline stored with these fit points only).
let fit = [[200.0, 0.0], [210.0, 10.0], [220.0, 0.0], [230.0, 10.0]];
let fit_cases: [([[f64; 2]; 2], [f64; 2], [[f64; 2]; 4]); 3] = [
([[225.0, 5.0], [235.0, 15.0]], [5.0, 0.0], [[200.0, 0.0], [210.0, 10.0], [220.0, 0.0], [235.0, 10.0]]),
([[205.0, 5.0], [215.0, 15.0]], [0.0, 5.0], [[200.0, 0.0], [210.0, 15.0], [220.0, 0.0], [230.0, 10.0]]),
([[195.0, -5.0], [235.0, 15.0]], [5.0, 5.0], [[205.0, 5.0], [215.0, 15.0], [225.0, 5.0], [235.0, 15.0]]),
];
for (window, delta, want) in fit_cases {
let mut s = Session::new();
let hd = h(&s.execute("spline", &json!({ "fit": fit })).unwrap());
s.execute("stretch", &json!({ "window": window, "delta": delta })).unwrap();
let EntityKind::Spline(sp) = kind(&s, &hd) else { panic!("not a spline") };
let got: Vec<[f64; 2]> = sp.fit.iter().map(|p| [p.x, p.y]).collect();
assert!(got.len() == 4 && got.iter().zip(want).all(|(g, w)| same(g[0], w[0]) && same(g[1], w[1])), "{window:?}: {got:?}");
// The curve still runs through them.
let (lo, hi) = sp.domain();
for w in want {
let q = cadcraft_geom::Vec2::new(w[0], w[1]);
let near = (0..=4000).map(|i| sp.eval(lo + (hi - lo) * f64::from(i) / 4000.0).dist(q)).fold(f64::INFINITY, f64::min);
assert!(near < 1e-2, "{window:?}: {w:?} is {near} off the curve");
}
}
// A stretch that brings an arc segment's ends together leaves no arc to keep: the bulge goes.
let mut s = Session::new();
let p = pline(&mut s, json!([{"p": [0, 0], "bulge": 0.5}, [10, 0], [20, 0]]), false);
s.execute("stretch", &json!({"window": [[9, -1], [11, 1]], "delta": [-10, 0]})).unwrap();
assert_eq!(poly(&kind(&s, &p)).vertices.iter().map(|v| v.bulge).collect::<Vec<_>>(), [0.0, 0.0, 0.0]);
}
+87 -4
View File
@@ -50,6 +50,7 @@ pub const PROFILE_VARS: &[&str] = &[
"CURSORSIZE",
"PICKFIRST",
"PICKADD",
"COPYMODE",
"PICKDRAG",
"MAXARRAY",
"MEASUREINIT",
@@ -85,18 +86,31 @@ pub fn profile(s: &Session) -> Value {
Value::Object(m)
}
/// The profile variables the drawing keeps in its header rather than in the session's settings.
const DRAWING_VARS: &[&str] = &["SNAPUNIT", "GRIDUNIT"];
/// Set the profile variables named in `values` (an object; other keys are refused). All or
/// nothing: one bad name or value leaves every setting as it was.
/// nothing: one bad name or value leaves every setting, and the drawing, as they were.
pub fn apply(s: &mut Session, values: &Value) -> Result<()> {
let Some(obj) = values.as_object() else { return Err(bad("options", "expected an object of profile variables")) };
let before = s.settings.clone();
// When one of the values is a drawing variable, the drawing as it is: put back whole on a
// refusal, it is the same drawing again, so not marked as changed either.
let touches_drawing = obj.keys().any(|k| DRAWING_VARS.iter().any(|v| v.eq_ignore_ascii_case(k.trim())));
let drawing = if touches_drawing { s.state().ok().map(|st| st.doc.clone()) } else { None };
let put_back = |s: &mut Session| {
s.settings = before.clone();
if let (Some(doc), Ok(st)) = (&drawing, s.state_mut()) {
st.doc = doc.clone();
}
};
for (name, v) in obj {
if !is_profile_var(name) {
s.settings = before;
put_back(s);
return Err(bad("options", format!("{name} is not a profile setting")));
}
if let Err(e) = crate::sysvars::set(s, name, v) {
s.settings = before;
put_back(s);
return Err(bad("options", format!("invalid value for {}: {e}", name.to_ascii_uppercase())));
}
}
@@ -117,7 +131,8 @@ pub fn restore(s: &mut Session, saved: &Value) {
}
}
/// Put every profile variable back to its default.
/// Put every profile variable back to its default, except [`DRAWING_VARS`]: a reset doesn't change
/// the drawing.
pub fn reset(s: &mut Session) {
let d = Settings::default();
let st = &mut s.settings;
@@ -143,8 +158,24 @@ pub fn reset(s: &mut Session) {
st.cursorsize = d.cursorsize;
st.pickfirst = d.pickfirst;
st.pickadd = d.pickadd;
st.copymode = d.copymode;
st.pickdrag = d.pickdrag;
st.maxarray = d.maxarray;
st.dynprompt = d.dynprompt;
st.dyndigrip = d.dyndigrip;
st.dyndivis = d.dyndivis;
st.selectioneffect = d.selectioneffect;
st.selectionpreview = d.selectionpreview;
st.previeweffect = d.previeweffect;
st.previewfilter = d.previewfilter;
st.grips = d.grips;
st.gripobjlimit = d.gripobjlimit;
st.selectionarea = d.selectionarea;
st.windowareacolor = d.windowareacolor;
st.crossingareacolor = d.crossingareacolor;
st.selectionareaopacity = d.selectionareaopacity;
st.pickstyle = d.pickstyle;
st.measureinit = d.measureinit;
}
fn run_options(s: &mut Session, p: &Value) -> Result<Value> {
@@ -191,4 +222,56 @@ mod tests {
restore(&mut b, &saved);
assert_eq!(profile(&b), saved);
}
#[test]
fn a_refused_change_leaves_the_drawings_snap_and_grid_too() {
let mut s = Session::new();
let before = profile(&s);
let refused = [
json!({ "SNAPUNIT": [2, 3], "GRIDUNIT": [4, 5], "WINDOWAREACOLOR": 0 }),
json!({ "GRIDUNIT": [4, 5], "LUNITS": 2 }),
json!({ "WINDOWAREACOLOR": 0 }),
];
for bad_one in refused {
assert!(apply(&mut s, &bad_one).is_err(), "{bad_one}");
assert_eq!(profile(&s), before, "{bad_one}");
// The same drawing, so there is nothing new to save.
assert!(!s.state().unwrap().is_dirty(), "{bad_one}");
}
assert!(s.execute("options", &json!({ "reset": true, "SNAPUNIT": [2, 3], "WINDOWAREACOLOR": 0 })).is_err());
assert_eq!(profile(&s), before);
// The header entries come back exactly: a zero grid spacing (which reads as the snap
// spacing), and a snap spacing the drawing doesn't have. The refused value comes last, so
// both are written first (the keys are taken in name order).
let header = |s: &Session, n: &str| s.doc().unwrap().header.get(n).cloned();
s.doc_mut().unwrap().header.set("GRIDUNIT", cadcraft_doc::HVal::Point(cadcraft_geom::Vec3::new(0.0, 0.0, 0.0)));
s.doc_mut().unwrap().header.vars.remove("SNAPUNIT");
let (grid, snap) = (header(&s, "GRIDUNIT"), header(&s, "SNAPUNIT"));
assert!(apply(&mut s, &json!({ "GRIDUNIT": [4, 5], "SNAPUNIT": [2, 3], "WINDOWAREACOLOR": 0 })).is_err());
assert_eq!((header(&s, "GRIDUNIT"), header(&s, "SNAPUNIT")), (grid, snap));
}
#[test]
fn reset_puts_every_profile_var_back_except_the_drawings() {
let defaults = profile(&Session::new());
let mut s = Session::new();
for name in PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)) {
// A value the variable takes that isn't its default: 0 and 1 swapped, or a number one
// more or less, or an angle.
let was = &defaults[*name];
let n = was.as_f64().unwrap_or(0.0);
let tries = [json!(if n == 0.0 { 1 } else { 0 }), json!(n + 1.0), json!(n - 1.0), json!("15")];
let changed = tries.iter().any(|v| apply(&mut s, &json!({ *name: v })).is_ok() && profile(&s)[*name] != *was);
assert!(changed, "no other value found for {name} (default {was})");
}
assert!(PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)).all(|n| profile(&s)[*n] != defaults[*n]));
apply(&mut s, &json!({ "SNAPUNIT": [2, 3], "GRIDUNIT": [4, 5] })).unwrap();
reset(&mut s);
let after = profile(&s);
for name in PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)) {
assert_eq!(after[*name], defaults[*name], "{name}");
}
// The snap and grid spacing are the drawing's, and stay.
assert_eq!((after["SNAPUNIT"].clone(), after["GRIDUNIT"].clone()), (json!([2.0, 3.0]), json!([4.0, 5.0])));
}
}
+5 -5
View File
@@ -449,7 +449,7 @@ fn run_style(s: &mut Session, p: &Value) -> Result<Value> {
let d = s.doc_mut()?;
// As it was (none for a new style), so dimensions are redrawn only when it changes.
let before = d.text_style(&name).cloned();
let idx = match d.text_styles.iter().position(|t| t.name.eq_ignore_ascii_case(&name)) {
let idx = match d.text_styles.position_by_name(&name) {
Some(i) => i,
None => {
d.text_styles.push(cadcraft_doc::TextStyle { name: name.clone(), ..Default::default() });
@@ -554,7 +554,7 @@ fn run_style_rename(s: &mut Session, p: &Value) -> Result<Value> {
if d.text_style(&to).is_some() && !to.eq_ignore_ascii_case(&from) {
return Err(bad("style.rename", format!("a text style `{to}` already exists")));
}
let st = d.text_styles.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("style.rename", "no such style"))?;
let st = d.text_styles.by_name_mut(&from).ok_or_else(|| bad("style.rename", "no such style"))?;
st.name = to.clone();
// References follow the new name.
let fix = |n: &mut String| {
@@ -642,7 +642,7 @@ fn run_dimstyle(s: &mut Session, p: &Value) -> Result<Value> {
// As it was (none for a new style), so dimensions are redrawn only when it changes.
let before = d.dim_style(&name).cloned();
let base = d.dim_style(&d.header.str("DIMSTYLE", "Standard")).cloned().unwrap_or_default();
let idx = match d.dim_styles.iter().position(|t| t.name.eq_ignore_ascii_case(&name)) {
let idx = match d.dim_styles.position_by_name(&name) {
Some(i) => i,
None => {
d.dim_styles.push(cadcraft_doc::DimStyle { name: name.clone(), ..base });
@@ -792,7 +792,7 @@ fn run_dimstyle_rename(s: &mut Session, p: &Value) -> Result<Value> {
if d.dim_style(&to).is_some() && !to.eq_ignore_ascii_case(&from) {
return Err(bad("dimstyle.rename", format!("a dimension style `{to}` already exists")));
}
let st = d.dim_styles.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("dimstyle.rename", "no such dimension style"))?;
let st = d.dim_styles.by_name_mut(&from).ok_or_else(|| bad("dimstyle.rename", "no such dimension style"))?;
st.name = to.clone();
if d.header.str("DIMSTYLE", "Standard").eq_ignore_ascii_case(&from) {
d.header.set_str("DIMSTYLE", &to);
@@ -1015,7 +1015,7 @@ fn run_rename(s: &mut Session, p: &Value) -> Result<Value> {
if d.linetype(&to).is_some() && !to.eq_ignore_ascii_case(&from) {
return Err(bad("rename", format!("a linetype `{to}` already exists")));
}
let st = d.linetypes.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("rename", "no such linetype"))?;
let st = d.linetypes.by_name_mut(&from).ok_or_else(|| bad("rename", "no such linetype"))?;
st.name = to.clone();
// References follow the new name.
let fix = |n: &mut String| {
+1 -1
View File
@@ -59,7 +59,7 @@ fn put(d: &mut Drawing, lt: Linetype, reload: bool, out: &mut Loaded) {
break;
}
}
match d.linetypes.iter_mut().find(|l| l.name.eq_ignore_ascii_case(&lt.name)) {
match d.linetypes.by_name_mut(&lt.name) {
Some(old) if reload => {
out.reloaded.push(old.name.clone());
// The drawing keeps the name as it had it (objects refer to it).
+87 -12
View File
@@ -8,11 +8,13 @@ use super::cells::cell_of;
use super::{MAX_COLS, MAX_ROWS, anchors, edit, set_anchors, usize_param};
use crate::cmd::machines::SelectRun;
use crate::cmd::{CommandSpec, bad, bool_or, str_param};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
use crate::{Accept, DocState, Input, Interactive, Prompt, Result, Session, Step};
/// Largest linked file read (bytes).
#[cfg(not(target_arch = "wasm32"))]
const MAX_LINK_BYTES: usize = 8 << 20;
/// Most files remembered per drawing as linked by the user ([`DocState::chosen_links`]).
const MAX_CHOSEN_LINKS: usize = 1000;
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -26,7 +28,10 @@ pub fn specs() -> Vec<CommandSpec> {
.menu(&["Insert", "Data Link..."])
.params("{handle, path (.csv, .txt/.tsv tab-separated), startRow? (default: below the title), remove?: bool} → {rows, cols}"),
CommandSpec::new("datalinkupdate", "Update Data Links", run_update)
.params("{handles?} (default: every linked table) → {updated}")
.params(
"{handles?} (default: every linked table) → {updated, errors}; a link saved in the drawing is read only from the drawing's \
folder or below it, unless DATALINK linked that file since the drawing was opened",
)
.interactive(|_| Ok(Box::new(SelectRun::new("datalinkupdate", "DATALINKUPDATE")))),
]
}
@@ -224,13 +229,45 @@ fn separator(path: &str, text: &str) -> char {
if first.contains(';') && !first.contains(',') { ';' } else { ',' }
}
/// The file to read for a data link: a path the user just `chosen` as given, a path stored in the
/// drawing at `host` only through [`crate::doc_path::resolve`].
fn link_file(id: &str, path: &str, host: Option<&str>, chosen: bool) -> Result<std::path::PathBuf> {
/// The file to read for a data link of the drawing `st`: a path the user just `chosen` as given;
/// a path stored in the drawing through [`crate::doc_path::resolve`], and then only as the file
/// system finds it (`..` and links followed) in the drawing's `folder`
/// ([`crate::doc_path::drawing_folder`]) or below it, or when the user linked that same file since
/// the drawing was opened ([`DocState::chosen_links`]).
fn link_file(id: &str, path: &str, st: &DocState, folder: Option<&std::path::Path>, chosen: bool) -> Result<std::path::PathBuf> {
if chosen {
return Ok(std::path::PathBuf::from(path));
}
crate::doc_path::resolve(path, host.map(std::path::Path::new)).map_err(|r| bad(id, format!("{path}: not opened, {r}")))
let host = st.path.as_deref().map(std::path::Path::new);
let file = crate::doc_path::resolve(path, host).map_err(|r| bad(id, format!("{path}: not opened, {r}")))?;
if cfg!(target_arch = "wasm32") {
// Nothing is read there; [`read_link`] says so.
return Ok(file);
}
// The automation roots first: outside them nothing about the file is asked.
crate::file_access::check_read(&file).map_err(|e| bad(id, e))?;
let real = std::fs::canonicalize(&file).map_err(|e| bad(id, format!("{path}: {e}")))?;
// Whole components: `plans-old` is not in `plans`.
if folder.is_some_and(|f| real.starts_with(f)) || st.chosen_links.contains_key(&real) {
// Read where it was checked, not through the links again.
return Ok(real);
}
Err(bad(id, format!("{path}: not read, the file is outside the drawing's folder; link it with DATALINK to read it")))
}
/// Remember `real` (resolved), the file of a link the user just gave, as theirs to read for the
/// drawing `st`, as its latest choice. At [`MAX_CHOSEN_LINKS`] files a new one makes room by
/// dropping the file chosen longest ago.
fn remember_link(st: &mut DocState, real: std::path::PathBuf) {
let links = &mut st.chosen_links;
let latest = links.values().max().map_or(0, |n| n.saturating_add(1));
if links.len() >= MAX_CHOSEN_LINKS
&& !links.contains_key(&real)
&& let Some(oldest) = links.iter().min_by_key(|(_, n)| **n).map(|(p, _)| p.clone())
{
links.remove(&oldest);
}
links.insert(real, latest);
}
/// Read a linked file through the host (natively the file system; not on the web).
@@ -288,16 +325,20 @@ fn fill(t: &mut Table, start: usize, data: &[Vec<String>]) {
}
}
/// Re-read the linked file of table `h`; `chosen` says its path was just given by the user.
fn update(s: &mut Session, h: Handle, chosen: bool) -> Result<(usize, usize)> {
/// Re-read the linked file of table `h`; `chosen` says its path was just given by the user, else
/// it is read from the drawing's `folder` ([`crate::doc_path::drawing_folder`]) or a file the user
/// linked.
fn update(s: &mut Session, h: Handle, folder: Option<&std::path::Path>, chosen: bool) -> Result<(usize, usize)> {
let id = "datalinkupdate";
let link = match s.doc()?.entity(h).map(|e| &e.kind) {
Some(EntityKind::Table(t)) => t.data_link.clone().ok_or_else(|| bad(id, "the table has no data link"))?,
_ => return Err(bad(id, "object is not a table")),
};
let host = s.state()?.path.clone();
let file = link_file(id, &link.path, host.as_deref(), chosen)?;
let file = link_file(id, &link.path, s.state()?, folder, chosen)?;
let text = read_link(id, &file)?;
if chosen && let Ok(real) = std::fs::canonicalize(&file) {
remember_link(s.state_mut()?, real);
}
let data = parse_csv(&text, separator(&link.path, &text));
let mut size = (0, 0);
edit(s, &json!({ "handle": h.hex() }), id, |t| {
@@ -325,7 +366,7 @@ fn run_datalink(s: &mut Session, p: &Value) -> Result<Value> {
Ok(())
})?;
let h = r.get("handle").and_then(Value::as_str).and_then(Handle::parse_hex).ok_or_else(|| bad(id, "no table"))?;
let (rows, cols) = update(s, h, true)?;
let (rows, cols) = update(s, h, None, true)?;
Ok(json!({ "handle": h.hex(), "rows": rows, "cols": cols }))
}
@@ -351,8 +392,10 @@ fn run_update(s: &mut Session, p: &Value) -> Result<Value> {
};
let mut updated = 0;
let mut errors = Vec::new();
// Resolved once for every table, and only when there is one.
let folder = if hs.is_empty() { None } else { crate::doc_path::drawing_folder(s.state()?.path.as_deref().map(std::path::Path::new)) };
for h in hs {
match update(s, h, false) {
match update(s, h, folder.as_deref(), false) {
Ok(_) => updated += 1,
Err(e) => errors.push(e.to_string()),
}
@@ -379,6 +422,38 @@ mod tests {
}
}
/// Whether the drawing `st` remembers `file` as linked by the user.
fn remembered(st: &DocState, file: &std::path::Path) -> bool {
st.chosen_links.contains_key(file)
}
/// However many files the user links, the drawing remembers at most [`MAX_CHOSEN_LINKS`] of
/// them: the ones linked last, a file linked again counting as just linked.
#[test]
fn remembered_links_are_the_most_recent_ones() {
let mut st = DocState::new(cadcraft_doc::Drawing::new_metric(), "t", None);
let file = |i: usize| std::path::PathBuf::from(format!("/data/{i}.csv"));
for i in 0..MAX_CHOSEN_LINKS {
remember_link(&mut st, file(i));
}
// Linked again at the bound, the second file drops nothing and becomes the newest, so two
// new files make room by dropping the first and the third.
remember_link(&mut st, file(1));
assert_eq!(st.chosen_links.len(), MAX_CHOSEN_LINKS);
assert!(remembered(&st, &file(0)));
remember_link(&mut st, file(MAX_CHOSEN_LINKS));
remember_link(&mut st, file(MAX_CHOSEN_LINKS + 1));
assert!([1, MAX_CHOSEN_LINKS, MAX_CHOSEN_LINKS + 1].iter().all(|&i| remembered(&st, &file(i))));
assert!(!remembered(&st, &file(0)) && !remembered(&st, &file(2)));
// After many more, the ones linked last are the ones remembered.
let end = 2 * MAX_CHOSEN_LINKS + 10;
for i in MAX_CHOSEN_LINKS + 2..end {
remember_link(&mut st, file(i));
}
assert_eq!(st.chosen_links.len(), MAX_CHOSEN_LINKS, "the bound is reached, not a smaller one");
assert!((end - MAX_CHOSEN_LINKS..end).all(|i| remembered(&st, &file(i))));
}
#[test]
fn csv_parsing() {
assert_eq!(parse_csv("a,b\r\n\"c,d\",\"e\"\"f\"\n", ','), vec![vec!["a", "b"], vec!["c,d", "e\"f"]]);
+15
View File
@@ -5,6 +5,12 @@
//! itself is on, are opened (see `craft_docpath`). A refused path is handled like a missing file,
//! with the reason in its status. Paths the user gives a command (XATTACH, -XREF Path, DATALINK)
//! are their own choice and are used as given.
//!
//! A data link copies its file's text into the drawing, where the next save keeps it. So a data
//! link the drawing itself names is read only from the drawing's folder or a folder below it, once
//! `..` and links are followed ([`drawing_folder`]), unless the user linked that file with
//! DATALINK since the drawing was opened. Otherwise a drawing could copy any file it names into
//! itself for whoever made it.
use std::path::{Path, PathBuf};
@@ -21,6 +27,15 @@ pub fn resolve(stored: &str, document: Option<&Path>) -> Result<PathBuf, Refused
craft_docpath::resolve_absolute(stored.trim(), document.as_deref())
}
/// The folder of the drawing saved at `document` as the file system resolves it
/// ([`std::fs::canonicalize`]: absolute, with `..` and links followed), to compare files resolved
/// the same way with. `None` for a drawing without a file, and when its folder can't be resolved.
pub fn drawing_folder(document: Option<&Path>) -> Option<PathBuf> {
let document = document.filter(|d| !d.as_os_str().is_empty())?;
let folder = std::path::absolute(document).ok()?.parent()?.to_path_buf();
std::fs::canonicalize(folder).ok()
}
#[cfg(test)]
mod tests {
use super::*;
+6
View File
@@ -48,6 +48,11 @@ pub struct DocState {
/// The fonts missing on Windows that a save last named: the next save names them again only
/// when they change.
pub(crate) fonts_noted: String,
/// The files the user linked with DATALINK since the drawing was opened, as the file system
/// resolves them, each with when it was last chosen (a larger number is later):
/// DATALINKUPDATE reads these also outside the drawing's folder ([`crate::doc_path`]). Kept
/// with the open drawing only, never saved.
pub(crate) chosen_links: std::collections::HashMap<std::path::PathBuf, u64>,
}
static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
@@ -77,6 +82,7 @@ impl DocState {
ucs_tilted_noted: false,
erased: Default::default(),
fonts_noted: String::new(),
chosen_links: Default::default(),
}
}
/// The drawing has changes not saved to its file, or the Block Editor has changes not yet
@@ -202,6 +202,7 @@ pub const NO_FILES: &[&str] = &[
"dim",
"mleader",
"leader",
"qleader",
"dimstyle.update",
"dimoverride",
"dimreassociate",
+38 -5
View File
@@ -143,7 +143,8 @@ pub struct LispState {
/// the step is charged it without charging the enclosing callback a second time.
pub(crate) callback_work: u64,
/// The `callback_used` value the callback running now (and so every one it calls) must not
/// pass: the lowest of its own and its callers' allowances.
/// pass: the lowest of its own and its callers' allowances, and of what is left to an
/// expression typed at a prompt.
pub(crate) callback_ceiling: Option<u64>,
}
@@ -200,6 +201,9 @@ struct Run {
inputs: std::collections::VecDeque<Value>,
/// Run to the end without waiting (programmatic calls): `get…` without an input gets nil.
blocking: bool,
/// An expression typed at a command's prompt ([`Session::lisp_eval_answer`]): blocking, with
/// [`ANSWER_CAP`] steps instead of [`BLOCKING_CAP`].
answer: bool,
/// Steps taken, for the cap on blocking runs.
steps: u64,
/// The `*error*` handler is the one running.
@@ -215,6 +219,10 @@ struct Run {
const SLICE: u64 = 400_000;
/// Steps a blocking run (a programmatic call) may take before it is stopped.
const BLOCKING_CAP: u64 = 500_000_000;
/// Steps an expression typed at a command's prompt may take, the callbacks it runs included. It
/// runs blocking, since its value is the prompt's answer, so the interface draws no frame and
/// Esc doesn't reach it until it ends; a routine at `Command:` runs a slice per frame instead.
const ANSWER_CAP: u64 = 20_000_000;
impl Session {
/// The LISP environment of the active drawing.
@@ -272,12 +280,19 @@ impl Session {
inputs: Vec<Value>,
) -> crate::Result<Option<std::result::Result<Value, String>>> {
let forms = read::read_all(src).map_err(|e| crate::EngineError::Other(format!("; error: {}", e.msg)))?;
self.lisp_start(Machine::forms(forms), print, blocking, inputs, "LISP".into())
self.lisp_start(Machine::forms(forms), print, blocking, inputs, "LISP".into(), false)
}
/// Evaluate an expression typed at a command's prompt, whose value is the answer: it runs to
/// the end as a programmatic call does, within [`ANSWER_CAP`] steps.
pub(crate) fn lisp_eval_answer(&mut self, src: &str) -> crate::Result<Option<std::result::Result<Value, String>>> {
let forms = read::read_all(src).map_err(|e| crate::EngineError::Other(format!("; error: {}", e.msg)))?;
self.lisp_start(Machine::forms(forms), false, true, Vec::new(), "LISP".into(), true)
}
/// Call a LISP function (`c:` commands typed at the command line).
fn lisp_call(&mut self, f: Value, label: String) -> crate::Result<Option<std::result::Result<Value, String>>> {
self.lisp_start(Machine::calling(f, Vec::new()), false, false, Vec::new(), label)
self.lisp_start(Machine::calling(f, Vec::new()), false, false, Vec::new(), label, false)
}
fn lisp_start(
@@ -287,6 +302,7 @@ impl Session {
blocking: bool,
inputs: Vec<Value>,
label: String,
answer: bool,
) -> crate::Result<Option<std::result::Result<Value, String>>> {
if self.lisp.active {
return Err(crate::EngineError::Other("a LISP routine is already running".into()));
@@ -305,6 +321,7 @@ impl Session {
before,
inputs: inputs.into(),
blocking,
answer,
steps: 0,
handler: false,
string_bytes: 0,
@@ -368,6 +385,10 @@ impl Session {
// [`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);
// Set for every slice (callbacks run only inside one). An answer's callbacks
// (`vl-sort`'s comparator…) run inside one of its steps: they share what is left of
// its allowance instead of each taking a callback's own.
self.lisp.callback_ceiling = run.answer.then(|| self.lisp.callback_used.saturating_add(ANSWER_CAP.saturating_sub(run.steps)));
let outcome = {
let machine = &mut run.machine;
let mut ctx = Ctx { s: self, env: &mut env, depth: 0 };
@@ -395,9 +416,21 @@ impl Session {
// The work the slice did, which one step can take far past the slice. After a panic
// `used` is still the previous slice's; the run ends with the error anyway.
run.steps = run.steps.saturating_add(run.machine.used);
if run.blocking && run.steps > BLOCKING_CAP && matches!(outcome, Outcome::Wait(_)) {
// An answer that failed past its cap was stopped by the cap too: a callback that ran
// out of what was left ends here past the cap, since the step that called it counts.
let past_cap = if run.answer {
run.steps > ANSWER_CAP && matches!(outcome, Outcome::Wait(_) | Outcome::Error(_))
} else {
run.steps > BLOCKING_CAP && matches!(outcome, Outcome::Wait(_))
};
if run.blocking && past_cap {
let msg = if run.answer {
format!("expression at a prompt stopped after {ANSWER_CAP} steps; run long routines at Command:, where Esc stops them")
} else {
format!("routine stopped after {BLOCKING_CAP} steps")
};
self.lisp.run = Some(run);
self.lisp_error(LispError::quit(format!("routine stopped after {BLOCKING_CAP} steps")));
self.lisp_error(LispError::quit(msg));
return;
}
match outcome {
+3 -1
View File
@@ -205,6 +205,8 @@ pub(super) fn float(a: &[Value]) -> R {
Ok(Value::Real(num(&a[0])?))
}
/// The greatest common divisor. The one past 32 bits, 2147483648 (of -2147483648 and 0 or
/// itself), is a real, as the reader and `fix` give such a number, not the largest integer.
pub(super) fn gcd(a: &[Value]) -> R {
arity(a, 2, 2)?;
let (mut x, mut y) = (i64::from(int(&a[0])?).abs(), i64::from(int(&a[1])?).abs());
@@ -216,7 +218,7 @@ pub(super) fn gcd(a: &[Value]) -> R {
x = y;
y = t;
}
Ok(Value::Int(i32::try_from(x).unwrap_or(i32::MAX)))
Ok(i32::try_from(x).map_or(Value::Real(x as f64), Value::Int))
}
pub(super) fn logand(a: &[Value]) -> R {
+9 -2
View File
@@ -51,13 +51,20 @@ pub(super) fn itoa(a: &[Value]) -> R {
Ok(Value::str(&int(&a[0])?.to_string()))
}
/// C's `atoi`: leading blanks, a sign, digits; 0 when there are none.
/// C's `atoi`: leading blanks, a sign, digits; 0 when there are none. Digits past the 32-bit
/// range give a real, the number `atof` reads from them, as the reader gives one for such a
/// literal: neither wrapped nor clamped to an integer.
pub(super) fn atoi(a: &[Value]) -> R {
arity(a, 1, 1)?;
let s = string(&a[0])?;
let t = s.trim_start();
let end = t.char_indices().take_while(|(i, c)| c.is_ascii_digit() || (*i == 0 && (*c == '-' || *c == '+'))).count();
Ok(Value::Int(t.get(..end).and_then(|n| n.parse::<i64>().ok()).map(|n| n as i32).unwrap_or(0)))
let digits = t.get(..end).unwrap_or_default();
match digits.parse::<i32>() {
Ok(n) => Ok(Value::Int(n)),
Err(_) if digits.bytes().any(|b| b.is_ascii_digit()) => atof(&[Value::str(digits)]),
Err(_) => Ok(Value::Int(0)),
}
}
/// C's `atof`: the number token at the start; 0.0 when there is none.
+47
View File
@@ -1602,6 +1602,53 @@ fn a_lisp_value_at_a_prompt_is_not_evaluated_again() {
assert_eq!(r, Some(4.0));
}
/// #1926: an expression typed at a command's prompt runs to the end before the prompt takes its
/// value, so the interface waits for it: it gets a far smaller allowance than a programmatic run,
/// and the callbacks it runs share that allowance instead of each taking a callback's own.
#[test]
fn an_expression_at_a_prompt_has_a_short_allowance() {
let mut s = session();
let circles = |s: &Session| s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, cadcraft_doc::EntityKind::Circle(_))).count();
let last_error = |s: &Session, from: usize| s.log.get(from..).and_then(|l| l.iter().rev().find(|l| l.starts_with("; error:")).cloned());
let endless = "(while (< i 2000000000) (setq i (1+ i)))";
s.cmdline(&format!("circle 0,0 (progn (setq i 0) {endless} 5)")).unwrap();
let typed: i64 = ok(&mut s, "i").parse().unwrap();
let stopped = last_error(&s, 0);
assert!(typed > 0 && stopped.is_some(), "the loop ran and was stopped");
assert_eq!(circles(&s), 0, "the stopped expression gave no radius");
assert!(s.running.is_none(), "CIRCLE ends with the failed expression");
// The same loop run programmatically goes on to twice as far.
let further = format!("(setq i 0) (while (< i {}) (setq i (1+ i))) i", typed * 2);
assert_eq!(ok(&mut s, &further), (typed * 2).to_string());
// Half the loop, then a comparator's endless loop: the comparator gets what the expression
// has left, not a callback's own allowance, and the expression stops as the loop alone did.
let half = format!("(while (< i {}) (setq i (1+ i)))", typed / 2);
let from = s.log.len();
s.cmdline(&format!("circle 0,0 (progn (setq i 0) {half} (vl-sort '(1 2) '(lambda (a b) {endless} (< a b))) 5)")).unwrap();
let with_callback: i64 = ok(&mut s, "i").parse().unwrap();
assert!(with_callback > typed / 2 && with_callback < typed * 5 / 4, "{with_callback} against {typed}");
assert_eq!(last_error(&s, from), stopped);
assert_eq!(circles(&s), 0);
}
/// #1933: a whole number past 32 bits is a real, as the reader and `fix` make one, not a wrapped
/// or clamped integer: `atoi` gives the number its digits read as, `gcd` the true divisor.
#[test]
fn atoi_and_gcd_past_32_bits_give_reals() {
let mut s = session();
for digits in ["2147483648", "-2147483649", "99999999999", "99999999999999999999"] {
assert_eq!(ok(&mut s, &format!("(= (atoi \"{digits}\") (read \"{digits}\"))")), "T", "{digits}");
}
// Past every real too: the largest, as `atof` reads it.
let huge = "9".repeat(400);
assert_eq!(ok(&mut s, &format!("(= (atoi \"{huge}\") (atof \"{huge}\"))")), "T");
// Within the range, integers as before.
assert_eq!(ok(&mut s, "(list (atoi \" -2147483648x\") (atoi \"+2147483647\") (atoi \"-\"))"), "(-2147483648 2147483647 0)");
let past = "(abs (float -2147483648))";
assert_eq!(ok(&mut s, &format!("(= (gcd -2147483648 0) (gcd 0 -2147483648) (gcd -2147483648 -2147483648) {past})")), "T");
assert_eq!(ok(&mut s, "(list (gcd -2147483648 6) (gcd 2147483647 0))"), "(2 2147483647)");
}
#[test]
fn atof_out_of_range_exponent_reads_whole_token() {
let mut s = Session::new();
+1
View File
@@ -37,6 +37,7 @@ const NO_OR: &[&str] = &[
"Choose mode for selected object conversion",
"Create annotative block",
"Enter a configuration option",
"Enter a copy mode option",
"Enter a plotting preference",
"Enter an annotation option",
"Enter an option",
+3 -2
View File
@@ -89,11 +89,12 @@ impl Session {
if tt.starts_with('\'') {
return self.start(tt);
}
// A LISP expression typed at a command's prompt: its value is the answer.
// A LISP expression typed at a command's prompt: its value is the answer, so it runs to
// the end first, with a short allowance (the interface waits for it).
// Not at a free-text prompt: there the text is the answer (CAL takes "(3+4)*2").
if lisp && lisp_expression(tt) && !prompt.accept.text && self.lisp_prompt().is_none() && !self.lisp_groups_undo() {
let src = tt.strip_prefix('!').unwrap_or(tt).to_string();
let v = match self.lisp_eval(&src, false, true, Vec::new()) {
let v = match self.lisp_eval_answer(&src) {
Ok(Some(Ok(v))) => v,
Ok(_) => return Ok(()),
Err(e) => {
+3
View File
@@ -75,6 +75,8 @@ pub struct Settings {
/// FILEDIA: kept for routines that switch file dialogs off around a script; no command reads it yet.
pub filedia: bool,
pub pickadd: bool,
/// COPYMODE: COPY makes one copy and ends (true, 1), or copies until Enter (false, 0).
pub copymode: bool,
/// PICKDRAG: false = two-click windows (0), true = clicks or dragging (2).
/// Drag-only mode (1) is not supported yet.
pub pickdrag: bool,
@@ -180,6 +182,7 @@ impl Default for Settings {
cmdecho: true,
filedia: true,
pickadd: true,
copymode: false,
pickdrag: true,
pickstyle: 1,
gripsize: 5.0,
+3 -3
View File
@@ -161,8 +161,8 @@ impl SpatialIndex {
let infinite = chunks.iter().flat_map(|(off, c)| c.infinite.iter().map(move |i| off + i)).collect();
SpatialIndex {
store: store.clone(),
blocks: d.blocks.clone(),
dim_styles: d.dim_styles.clone(),
blocks: (*d.blocks).clone(),
dim_styles: d.dim_styles.to_vec(),
dimscale: d.header.f64("DIMSCALE", 1.0),
anno: anno_key(d),
hidden_layers: hidden_layers(d).map(str::to_owned).collect(),
@@ -178,7 +178,7 @@ impl SpatialIndex {
self.blocks.len() == d.blocks.len()
&& self.blocks.iter().zip(&d.blocks).all(|((ka, a), (kb, b))| ka == kb && Arc::ptr_eq(a, b))
&& self.dimscale.to_bits() == d.header.f64("DIMSCALE", 1.0).to_bits()
&& self.dim_styles == d.dim_styles
&& self.dim_styles == *d.dim_styles
&& self.anno == anno_key(d)
&& self.hidden_layers.iter().map(String::as_str).eq(hidden_layers(d))
}
+3
View File
@@ -59,6 +59,7 @@ const SESSION_VARS: &[&str] = &[
"CMDECHO",
"FILEDIA",
"PICKADD",
"COPYMODE",
"PICKDRAG",
"PICKSTYLE",
"GRIPSIZE",
@@ -140,6 +141,7 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
"CMDECHO" => json!(i32::from(st.cmdecho)),
"FILEDIA" => json!(i32::from(st.filedia)),
"PICKADD" => json!(i32::from(st.pickadd)),
"COPYMODE" => json!(i32::from(st.copymode)),
"PICKDRAG" => json!(i32::from(st.pickdrag) * 2),
"PICKSTYLE" => json!(st.pickstyle),
"GRIPSIZE" => json!(st.gripsize),
@@ -394,6 +396,7 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
"CMDECHO" => st.cmdecho = small(v, 1).ok_or_else(bad)? == 1,
"FILEDIA" => st.filedia = small(v, 1).ok_or_else(bad)? == 1,
"PICKADD" => st.pickadd = as_bool(v).ok_or_else(bad)?,
"COPYMODE" => st.copymode = small(v, 1).ok_or_else(bad)? == 1,
"PICKDRAG" => st.pickdrag = as_i(v).filter(|b| matches!(b, 0 | 2)).map(|b| b == 2).ok_or_else(bad)?,
"PICKSTYLE" => st.pickstyle = as_i(v).filter(|b| (0..=3).contains(b)).and_then(|b| u8::try_from(b).ok()).ok_or_else(bad)?,
"GRIPSIZE" => st.gripsize = as_f64(v).ok_or_else(bad)?.clamp(1.0, 255.0),
+2
View File
@@ -67,6 +67,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
("OFFSETDIST", Kind::AnyReal, Def::Real(-1.0)),
("OFFSETERASE", Kind::Choice(&[0, 1]), Def::Int(0)),
("OFFSETLAYER", Kind::Choice(&[0, 1]), Def::Int(0)),
// The width a new polyline starts at; PLINE's Width and Halfwidth answers set it.
("PLINEWID", Kind::Real { min: 0.0, strict: false }, Def::Real(0.0)),
("POLYSIDES", Kind::Int(3, 1024), Def::Int(4)),
("PROJMODE", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
("REVCLOUDARCLEN", Kind::Real { min: 0.0, strict: true }, Def::Units(0.5, 15.0)),
+56
View File
@@ -1309,6 +1309,62 @@ fn pline_width_answers_taper_the_next_segment() {
assert_eq!(widths(&p), (0.0, vec![(0.0, 0.0), (0.0, 0.0)]));
}
/// PLINE against what AutoCAD 2024 stores for the same typed input (black-box: synthetic input
/// in accoreconsole, read back with `entget` and GETVAR).
#[test]
fn pline_undo_mode_and_plinewid_match_autocad() {
// Undo after an arc segment returns to line mode, where `_L` is Length (a point gives the
// length, along the last segment).
let p = typed_pline(
"pline -0.702422643378533,-28.46727901968281 -27.912058384977463,-34.74188138168937 -22.546524604415925,32.44142803067136 _U \
25.831317263304115,13.510616645626207 _A -33.2372517304228,12.083585785350365 _U _L -22.546524604415925,32.44142803067136",
);
let want = [
(-0.7024226433785329, -28.4672790196828),
(-27.91205838497746, -34.74188138168937),
(25.83131726330411, 13.5106166456262),
(64.48701958199356, 48.21692560701169),
];
assert_eq!(p.vertices.len(), want.len(), "{p:?}");
for (v, (x, y)) in p.vertices.iter().zip(want) {
assert!(v.p.near(Vec2::new(x, y), 1e-9 * x.abs().max(y.abs())) && v.bulge == 0.0, "{p:?}");
}
// PLINEWID is the width a new polyline starts with…
let mut s = Session::new();
s.cmdline("(setvar \"PLINEWID\" 0.75)").unwrap();
s.cmdline("pline -21.06802233135781,9.943678105070298 -29.261665218975015,-28.460093326613574 7.898763272534772,6.73634194079888").unwrap();
s.cmdline("").unwrap();
assert!(matches!(&s.doc().unwrap().model.last().unwrap().kind, EntityKind::LwPolyline(p) if p.const_width == 0.75));
// …and the ending width of the last Width or Halfwidth answer (half-width 0.5: PLINEWID 1).
let mut s = Session::new();
s.cmdline("pline -9.151085154682761,12.9438035725412 _W 0.0934460985004879 1.547654372298795").unwrap();
assert_eq!(s.doc().unwrap().header.f64("PLINEWID", 0.0), 1.547654372298795);
s.cmdline("19.161590651864245,38.23079339857958 26.720225103092986,-9.028145532375504 _H 0.5 0.5 -24.7035288980598,-14.309723714209586").unwrap();
s.cmdline("").unwrap();
assert_eq!(s.doc().unwrap().header.f64("PLINEWID", 0.0), 1.0);
// PLINEWID is an ordinary system variable: 0 until set, typed at the command line or set
// with SETVAR, and that width is where the next polyline starts.
let mut s = Session::new();
let r = s.execute("getvar", &json!({"name": "PLINEWID"})).unwrap();
assert_eq!(r["value"].as_f64(), Some(0.0), "{r}");
s.cmdline("plinewid 0.5").unwrap();
assert_eq!(s.doc().unwrap().header.f64("PLINEWID", 0.0), 0.5);
s.cmdline("pline 0,0 10,0").unwrap();
s.cmdline("").unwrap();
assert!(matches!(&s.doc().unwrap().model.last().unwrap().kind, EntityKind::LwPolyline(p) if p.const_width == 0.5));
// The JSON form starts there too, unless it gives a width or its vertices give theirs.
let width = |s: &mut Session, p: serde_json::Value| {
s.execute("pline", &p).unwrap();
match &s.doc().unwrap().model.last().unwrap().kind {
EntityKind::LwPolyline(p) => p.const_width,
k => panic!("{k:?}"),
}
};
assert_eq!(width(&mut s, json!({"vertices": [[0, 0], [10, 0]]})), 0.5);
assert_eq!(width(&mut s, json!({"vertices": [[0, 0], [10, 0]], "width": 0})), 0.0);
assert_eq!(width(&mut s, json!({"vertices": [{"p": [0, 0], "startWidth": 1, "endWidth": 2}, [10, 0]]})), 0.0);
}
#[test]
fn press_and_drag_selection_window() {
let mut s = Session::new();
+2 -2
View File
@@ -198,7 +198,7 @@ pub fn set_current(d: &mut Drawing, space: &Space, frame: &UcsFrame, name: &str)
h.set_str("UCSNAME", name);
}
Space::Paper(layout) => {
if let Some(l) = d.layouts.iter_mut().find(|l| l.name.eq_ignore_ascii_case(layout)) {
if let Some(l) = d.layouts.by_name_mut(layout) {
l.ucs = (!(frame.is_world() && name.is_empty())).then(|| frame.record(name));
}
}
@@ -210,7 +210,7 @@ pub fn set_current(d: &mut Drawing, space: &Space, frame: &UcsFrame, name: &str)
fn previous_mut<'a>(d: &'a mut Drawing, space: &Space) -> Option<&'a mut Vec<Ucs>> {
match space {
Space::Model => Some(&mut d.ucs_previous),
Space::Paper(layout) => d.layouts.iter_mut().find(|l| l.name.eq_ignore_ascii_case(layout)).map(|l| &mut l.ucs_previous),
Space::Paper(layout) => d.layouts.by_name_mut(layout).map(|l| &mut l.ucs_previous),
}
}
+31
View File
@@ -229,3 +229,34 @@ fn json_arraypolar_rejects_bad_fill_angles() {
s.execute("arraypolar", &p).unwrap();
}
}
#[test]
fn json_arraypath_rejects_a_bad_count_or_spacing() {
// As arrayrect's and arraypolar's counts: not a whole number of at least 1 is refused, as is a
// spacing that isn't a positive number. Before, these fell back to the default 6 items.
let mut s = Session::new();
let h = s.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap()["handle"].clone();
let path = s.execute("line", &json!({"points": [[0, 0], [100, 0]]})).unwrap()["handles"][0].clone();
let before = s.doc().unwrap().model.iter().count();
for (key, bad) in [
("count", json!(0)),
("count", json!(-3)),
("count", json!(4.5)),
("count", json!("8")),
("spacing", json!(0)),
("spacing", json!(-5)),
("spacing", json!("10")),
] {
let p = json!({"handles": [h], "path": path, key: bad});
let e = s.execute("arraypath", &p).unwrap_err();
assert!(e.to_string().contains(&format!("`{key}`")), "{key} {bad}: {e}");
assert_eq!(s.doc().unwrap().model.iter().count(), before, "{key} {bad}");
}
// Missing or null is the default, 6 items: the original and 5 copies.
for p in [json!({"handles": [h], "path": path}), json!({"handles": [h], "path": path, "count": null, "spacing": null})] {
assert_eq!(s.execute("arraypath", &p).unwrap()["handles"].as_array().map(Vec::len), Some(5), "{p}");
}
// One item is the original alone; a spacing of 25 along 100 is 5 items.
assert_eq!(s.execute("arraypath", &json!({"handles": [h], "path": path, "count": 1})).unwrap()["handles"], json!([]));
assert_eq!(s.execute("arraypath", &json!({"handles": [h], "path": path, "spacing": 25})).unwrap()["handles"].as_array().map(Vec::len), Some(4));
}
+151
View File
@@ -0,0 +1,151 @@
//! The counts the ARRAY commands ask for take a whole number as typed, as AutoCAD 2024's do
//! (measured in its core console at ARRAYRECT's rows and columns, ARRAYPOLAR's items and rows,
//! and -ARRAY's rows and items): +3 and 03 are three, and 5.0, 1e1, 8/2 and 3' are refused and
//! asked for again.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{ArrayKind, EntityKind, Handle};
use serde_json::json;
/// Texts AutoCAD 2024 refuses at an array count.
const REFUSED: [&str; 6] = ["5.0", "4.", "1e1", "8/2", "3'", "4.5"];
fn typed(s: &mut Session, inputs: &[&str]) {
for t in inputs {
s.cmdline(t).unwrap();
}
}
/// Each refused text gets the count message, and the same prompt again.
fn refuses_and_asks_again(s: &mut Session) {
let asked = s.prompt_text();
for t in REFUSED {
s.cmdline(t).unwrap();
assert!(s.log.last().is_some_and(|l| l.starts_with("Requires an integer between 1 and")), "{t}: {:?}", s.log.last());
assert_eq!(s.prompt_text(), asked, "{t}");
}
}
fn lines(s: &Session) -> usize {
s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count()
}
fn with_line() -> Session {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[10, 0], [12, 0]] })).unwrap();
s
}
#[test]
fn arrayrect_columns_and_rows() {
let mut s = with_line();
typed(&mut s, &["arrayrect", "l", "", "cou"]);
assert!(s.prompt_text().contains("Enter the number of columns"), "{}", s.prompt_text());
refuses_and_asks_again(&mut s);
s.cmdline("+3").unwrap();
assert!(s.prompt_text().contains("Enter the number of rows"), "{}", s.prompt_text());
refuses_and_asks_again(&mut s);
typed(&mut s, &["03", "as", "n", "x"]);
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s), 9);
}
/// The bounds are CADCraft's, which this rule leaves as they were: a count runs from 1 to what
/// MAXARRAY allows for the array's other counts. With MAXARRAY 100 and three rows, 0 and 34 columns
/// are refused and 33 taken; then 4 rows are refused and 3 taken.
#[test]
fn a_count_runs_from_one_to_the_maxarray_limit() {
let mut s = with_line();
s.execute("setvar", &json!({ "name": "MAXARRAY", "value": 100 })).unwrap();
typed(&mut s, &["arrayrect", "l", "", "cou"]);
let refused = |s: &mut Session, texts: &[&str], max: u64| {
let asked = s.prompt_text();
for t in texts {
s.cmdline(t).unwrap();
let msg = format!("Requires an integer between 1 and {max} ");
assert!(s.log.last().is_some_and(|l| l.starts_with(&msg)), "{t}: {:?}", s.log.last());
assert_eq!(s.prompt_text(), asked, "{t}");
}
};
assert!(s.prompt_text().contains("Enter the number of columns"), "{}", s.prompt_text());
refused(&mut s, &["0", "34"], 33);
s.cmdline("33").unwrap();
assert!(s.prompt_text().contains("Enter the number of rows"), "{}", s.prompt_text());
refused(&mut s, &["0", "4"], 3);
typed(&mut s, &["3", "as", "n", "x"]);
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s), 99);
}
#[test]
fn arraypolar_items() {
let mut s = with_line();
typed(&mut s, &["arraypolar", "l", "", "0,0", "i"]);
assert!(s.prompt_text().contains("Enter number of items in array"), "{}", s.prompt_text());
refuses_and_asks_again(&mut s);
typed(&mut s, &["+5", "as", "n", "x"]);
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s), 5);
}
/// ARRAYEDIT's counts go through the same count parser as ARRAYRECT's, ARRAYPOLAR's and -ARRAY's
/// (`count()` in `crates/engine/src/cmd/array.rs`), so they refuse and take the same texts: here 5.0,
/// 5., 4.5, 1e1 and 8/2 are refused at a rectangular array's columns and rows and a polar array's
/// items, and +5, 05 and 5 are taken. No AutoCAD measurement of ARRAYEDIT is claimed.
#[test]
fn arrayedit_counts() {
let refused = ["5.0", "5.", "4.5", "1e1", "8/2"];
let edit = |s: &mut Session, h: Handle, option: &str, asked: &str, count: &str, after: &[&str]| {
s.set_selection(vec![h]);
typed(s, &["arrayedit", option]);
assert!(s.prompt_text().contains(asked), "{}", s.prompt_text());
let prompt = s.prompt_text();
for t in refused {
s.cmdline(t).unwrap();
assert!(s.log.last().is_some_and(|l| l.starts_with("Requires an integer between 1 and")), "{t}: {:?}", s.log.last());
assert_eq!(s.prompt_text(), prompt, "{t}");
}
s.cmdline(count).unwrap();
typed(s, after);
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
let d = s.doc().unwrap();
d.array_params(d.entity(h).unwrap()).unwrap().kind
};
let mut s = with_line();
let l = s.doc().unwrap().model.iter().next().unwrap().handle.hex();
let r = s.execute("arrayrect", &json!({ "handles": [l], "cols": 4, "rows": 3, "colSpacing": 5, "rowSpacing": 5 })).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
let ArrayKind::Rect(a) = edit(&mut s, h, "col", "Enter the number of columns", "+5", &["", "x"]) else { panic!("not rectangular") };
assert_eq!((a.cols, a.rows), (5, 3));
let ArrayKind::Rect(a) = edit(&mut s, h, "r", "Enter the number of rows", "05", &["", "", "x"]) else { panic!("not rectangular") };
assert_eq!((a.cols, a.rows), (5, 5));
let mut s = with_line();
let l = s.doc().unwrap().model.iter().next().unwrap().handle.hex();
let r = s.execute("arraypolar", &json!({ "handles": [l], "center": [0, -50], "count": 6 })).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
let ArrayKind::Polar(a) = edit(&mut s, h, "i", "Enter number of items in array", "5", &["x"]) else { panic!("not polar") };
assert_eq!(a.items, 5);
}
#[test]
fn classic_array_rows_columns_and_items() {
let mut s = with_line();
typed(&mut s, &["-array", "l", "", "r"]);
assert!(s.prompt_text().contains("Enter the number of rows (---)"), "{}", s.prompt_text());
refuses_and_asks_again(&mut s);
s.cmdline("03").unwrap();
assert!(s.prompt_text().contains("Enter the number of columns (|||)"), "{}", s.prompt_text());
refuses_and_asks_again(&mut s);
typed(&mut s, &["+2", "5", "5"]);
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s), 6);
let mut s = with_line();
typed(&mut s, &["-array", "l", "", "p", "0,0"]);
assert!(s.prompt_text().contains("Enter the number of items in the array"), "{}", s.prompt_text());
refuses_and_asks_again(&mut s);
typed(&mut s, &["+3", "360", "y"]);
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s), 3);
}
@@ -0,0 +1,98 @@
//! Attributes are matched to their block's definitions, and definitions to a reference's
//! attributes, by tag in one lookup each: BURST and ATTSYNC on a reference with many of both.
use std::sync::Arc;
use cadcraft_doc::{Attrib, EntityKind, Handle};
use cadcraft_engine::Session;
use serde_json::json;
/// Block B with definition T and a reference to it carrying T = "v"; with `n` > 0 the block gets
/// `n` more definitions and the reference's attribute is replaced by `n`, the tags `n` long ones
/// alike up to their last characters, no attribute's a definition's.
fn reference(n: usize) -> (Session, Handle) {
let mut s = Session::new();
s.execute("attdef", &json!({"tag": "T", "default": "d", "at": [0, 1], "height": 1.0})).unwrap();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
let hs: Vec<String> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
s.execute("block", &json!({"name": "B", "base": [0, 0], "keep": "delete", "handles": hs})).unwrap();
let r = s.execute("insert", &json!({"name": "B", "at": [0, 0], "attribs": {"T": "v"}})).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
if n > 0 {
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let d = s.doc_mut().unwrap();
let handles: Vec<Handle> = (0..n).map(|_| d.new_handle()).collect();
let blk = Arc::make_mut(d.blocks.get_mut("B").unwrap());
let def = blk.entities.iter().find(|e| matches!(e.kind, EntityKind::AttDef(_))).unwrap().as_ref().clone();
for (i, h) in handles.into_iter().enumerate() {
let mut e = def.clone();
e.handle = h;
if let EntityKind::AttDef(a) = &mut e.kind {
a.tag = tag('D', i);
}
blk.entities.push(e);
}
d.modify_entity(h, |e| {
if let EntityKind::Insert(ins) = &mut e.kind {
let one = ins.attribs[0].clone();
ins.attribs = (0..n).map(|i| Attrib { tag: tag('A', i), ..one.clone() }).collect();
}
})
.unwrap();
}
(s, h)
}
fn attribs(s: &Session, h: Handle) -> Vec<Attrib> {
let EntityKind::Insert(i) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") };
i.attribs.clone()
}
/// #1923: comparing each attribute with each definition (BURST: for its properties; ATTSYNC: for
/// the value each definition keeps) cost N x N comparisons of whole tags (many seconds here); one
/// lookup each costs milliseconds.
const N: usize = 4000;
#[test]
fn burst_matches_many_attributes_without_comparing_every_pair() {
let (mut s, h) = reference(N);
let t = std::time::Instant::now();
s.execute("burst", &json!({"handles": [h.hex()]})).unwrap();
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Text(_))).count(), N);
}
#[test]
fn attsync_matches_many_definitions_without_comparing_every_pair() {
let (mut s, h) = reference(N);
let t = std::time::Instant::now();
s.execute("attsync", &json!({"name": "B"})).unwrap();
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
// An attribute for each definition (T and the N others), with its default value: the
// reference carried none of their tags.
let a = attribs(&s, h);
assert_eq!(a.len(), N + 1);
assert!(a.iter().all(|a| a.text.value == "d"));
}
#[test]
fn attsync_keeps_the_value_of_the_first_attribute_of_a_tag() {
// A reference carrying two attributes of one tag (in different case, as a file can hold
// them) keeps the first one's value for the definition of that tag.
let (mut s, h) = reference(0);
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let EntityKind::Insert(ins) = &mut e.kind {
let mut second = ins.attribs[0].clone();
second.tag = "t".into();
second.text.value = "second".into();
ins.attribs[0].text.value = "first".into();
ins.attribs.push(second);
}
})
.unwrap();
s.execute("attsync", &json!({"name": "B"})).unwrap();
let a = attribs(&s, h);
assert_eq!(a.iter().map(|a| (a.tag.as_str(), a.text.value.as_str())).collect::<Vec<_>>(), [("T", "first")]);
}
+258
View File
@@ -0,0 +1,258 @@
//! COPY at the command line as AutoCAD 2024 runs it (accoreconsole, a line from (0, 0) to (1, 0)
//! copied with `(command "_.COPY" line "" ...)`, then the start point of every line):
//!
//! - COPYMODE 1 makes one copy and ends; Multiple copies until Exit or Enter, and Undo takes back
//! the last placement, a whole array at once;
//! - Enter at the first second point copies by the base point taken as a displacement;
//! - Array asks for a number of items, the original included (2 to 32767), and puts them the
//! second point apart, or spread up to it with Fit; Enter there leaves them at the base.
use cadcraft_engine::Session;
use cadcraft_engine::doc::EntityKind;
use serde_json::json;
/// A session with one line from (0, 0) to (1, 0) and COPYMODE set to `mode`.
fn with_line(mode: i64) -> Session {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[0, 0], [1, 0]] })).unwrap();
s.execute("setvar", &json!({ "name": "COPYMODE", "value": mode })).unwrap();
s
}
/// The start point of every line, sorted.
fn starts(s: &Session) -> Vec<(f64, f64)> {
let mut v: Vec<(f64, f64)> =
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.x, l.a.y)) } else { None }).collect();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v
}
fn copymode(s: &mut Session) -> serde_json::Value {
s.execute("getvar", &json!({ "name": "COPYMODE" })).unwrap()["value"].clone()
}
/// Types COPY, selects everything, then each of `inputs`.
fn copy(s: &mut Session, inputs: &[&str]) {
for t in ["COPY", "all", ""].iter().chain(inputs) {
s.cmdline(t).unwrap();
}
}
#[test]
fn copymode_1_makes_one_copy_and_ends() {
let mut s = with_line(1);
copy(&mut s, &["0,0"]);
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Array] <use first point as displacement>:");
s.cmdline("10,0").unwrap();
assert!(s.current_prompt().is_none(), "COPY ended");
assert_eq!(starts(&s), [(0.0, 0.0), (10.0, 0.0)]);
assert_eq!(copymode(&mut s), json!(1));
}
#[test]
fn the_base_point_prompt_offers_mode_and_multiple() {
let mut s = with_line(1);
copy(&mut s, &[]);
assert_eq!(s.current_prompt().unwrap().display(), "Specify base point or [Displacement/mOde/Multiple] <Displacement>:");
// Multiple, this once: the option goes and COPYMODE stays 1.
s.cmdline("M").unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Specify base point or [Displacement/mOde] <Displacement>:");
for t in ["0,0", "10,0", "20,0"] {
s.cmdline(t).unwrap();
}
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Array/Exit/Undo] <Exit>:");
s.cmdline("E").unwrap();
assert!(s.current_prompt().is_none());
assert_eq!(starts(&s), [(0.0, 0.0), (10.0, 0.0), (20.0, 0.0)]);
assert_eq!(copymode(&mut s), json!(1));
// Multiple, then mOde with Enter: the mode shown (Single, COPYMODE 1) is the mode COPY runs in.
let mut s = with_line(1);
copy(&mut s, &["M", "O"]);
assert_eq!(s.current_prompt().unwrap().display(), "Enter a copy mode option [Single/Multiple] <Single>:");
for t in ["", "0,0", "5,0"] {
s.cmdline(t).unwrap();
}
assert!(s.current_prompt().is_none(), "one copy");
assert_eq!(starts(&s), [(0.0, 0.0), (5.0, 0.0)]);
// mOde sets COPYMODE.
let mut s = with_line(0);
copy(&mut s, &["O"]);
assert_eq!(s.current_prompt().unwrap().display(), "Enter a copy mode option [Single/Multiple] <Multiple>:");
s.cmdline("S").unwrap();
assert_eq!(copymode(&mut s), json!(1));
for t in ["0,0", "5,0"] {
s.cmdline(t).unwrap();
}
assert!(s.current_prompt().is_none(), "one copy, now single");
assert_eq!(starts(&s), [(0.0, 0.0), (5.0, 0.0)]);
}
#[test]
fn copymode_0_copies_until_enter_and_undo_takes_back_the_last() {
let mut s = with_line(0);
copy(&mut s, &["0,0", "10,0", "20,0", "U", "30,0", ""]);
assert!(s.current_prompt().is_none());
assert_eq!(starts(&s), [(0.0, 0.0), (10.0, 0.0), (30.0, 0.0)]);
// Undoing the only copy goes back to the first prompt.
let mut s = with_line(0);
copy(&mut s, &["0,0", "10,0", "U"]);
assert!(s.log.iter().any(|l| l == "Command has been completely undone."), "{:?}", s.log);
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Array] <use first point as displacement>:");
s.cmdline("30,0").unwrap();
s.cmdline("").unwrap();
assert_eq!(starts(&s), [(0.0, 0.0), (30.0, 0.0)]);
// An array is one placement: Undo takes all its items back.
let mut s = with_line(0);
copy(&mut s, &["0,0", "10,0", "A", "3", "0,5", "U", "40,0", ""]);
assert_eq!(starts(&s), [(0.0, 0.0), (10.0, 0.0), (40.0, 0.0)]);
// An array after a copy, and more after it.
let mut s = with_line(0);
copy(&mut s, &["3,4", "10,4", "A", "2", "20,4", ""]);
assert_eq!(starts(&s), [(0.0, 0.0), (7.0, 0.0), (17.0, 0.0)]);
}
#[test]
fn enter_at_the_first_second_point_copies_by_the_base_point() {
for mode in [0, 1] {
let mut s = with_line(mode);
copy(&mut s, &["3,4", ""]);
assert!(s.current_prompt().is_none(), "COPYMODE {mode}");
assert_eq!(starts(&s), [(0.0, 0.0), (3.0, 4.0)], "COPYMODE {mode}");
}
// Displacement, and Enter at the base point (its default), make one copy too.
for inputs in [["D", "5,6"], ["", "7,8"]] {
let mut s = with_line(0);
copy(&mut s, &inputs);
assert!(s.current_prompt().is_none(), "{inputs:?}");
assert_eq!(starts(&s).len(), 2, "{inputs:?}");
}
}
#[test]
fn array_puts_the_items_a_second_point_apart_or_fits_them() {
// (inputs after the base point (0, 0), AutoCAD's lines)
let cases: [(&[&str], &[(f64, f64)]); 5] = [
(&["A", "4", "10,5"], &[(0.0, 0.0), (10.0, 5.0), (20.0, 10.0), (30.0, 15.0)]),
(&["A", "4", "F", "30,0"], &[(0.0, 0.0), (10.0, 0.0), (20.0, 0.0), (30.0, 0.0)]),
// Fit, then Array again: back to the spacing.
(&["A", "3", "F", "A", "10,0"], &[(0.0, 0.0), (10.0, 0.0), (20.0, 0.0)]),
// The base point again, or Enter: every item at the base.
(&["A", "3", "0,0"], &[(0.0, 0.0); 3]),
(&["A", "3", ""], &[(0.0, 0.0); 3]),
];
for (inputs, want) in cases {
let mut s = with_line(1);
copy(&mut s, &["0,0"]);
for t in inputs {
s.cmdline(t).unwrap();
}
assert!(s.current_prompt().is_none(), "{inputs:?}");
assert_eq!(starts(&s), want, "{inputs:?}");
}
// Enter at the array's point with the base at (3, 4): still on the original, the base
// isn't taken as a displacement there.
let mut s = with_line(1);
copy(&mut s, &["3,4", "A", "3", ""]);
assert_eq!(starts(&s), [(0.0, 0.0); 3]);
let mut s = with_line(1);
copy(&mut s, &["0,0", "A", "4"]);
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Fit]:");
s.cmdline("F").unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Array]:");
}
#[test]
fn array_takes_2_to_32767_items() {
let mut s = with_line(1);
copy(&mut s, &["0,0", "A"]);
assert_eq!(s.current_prompt().unwrap().display(), "Enter number of items to array:");
// A point from LISP is refused too (AutoCAD 2024 with '(1 2): the same message).
for bad in ["1", "0", "2.5", "32768", "-3", "1'", "8/2", "x", "4.0", "1e1", "3\"", "(list 1 2)"] {
let logged = s.log.len();
s.cmdline(bad).unwrap();
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
assert_eq!(said, ["Requires an integer between 2 and 32767."], "{bad}");
assert_eq!(s.current_prompt().unwrap().display(), "Enter number of items to array:", "{bad}");
}
s.cmdline("32767").unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Fit]:");
// A sign or a leading zero is still a whole number, and so is the LISP real 3.0 (AutoCAD 2024:
// three items each).
for three in ["+3", "03", "(+ 1.5 1.5)"] {
let mut s = with_line(1);
copy(&mut s, &["0,0", "A", three, "5,0"]);
assert_eq!(starts(&s), [(0.0, 0.0), (5.0, 0.0), (10.0, 0.0)], "{three}");
}
// Enter at the number ends COPY with nothing copied.
let mut s = with_line(1);
copy(&mut s, &["0,0", "A", ""]);
assert!(s.current_prompt().is_none());
assert_eq!(starts(&s), [(0.0, 0.0)]);
}
#[test]
fn maxarray_doesnt_limit_the_items() {
// AutoCAD 2024 with MAXARRAY 100000: four lines and 26000 items made 104000 lines (measured).
// Here MAXARRAY is 100 (its least): two lines and 60 items, and 101 lines and 2 items, go past
// it and are still made.
let mut s = with_line(1);
s.execute("line", &json!({ "points": [[0, 5], [1, 5]] })).unwrap();
s.execute("setvar", &json!({ "name": "MAXARRAY", "value": 100 })).unwrap();
copy(&mut s, &["0,0", "A", "60", "10,0"]);
assert!(s.current_prompt().is_none());
assert_eq!(starts(&s).len(), 120);
let mut s = with_line(1);
s.execute("setvar", &json!({ "name": "MAXARRAY", "value": 100 })).unwrap();
for y in 1..=100 {
s.execute("line", &json!({ "points": [[0, y], [1, y]] })).unwrap();
}
copy(&mut s, &["0,0", "A", "2", "10,0"]);
assert!(s.current_prompt().is_none());
assert_eq!(starts(&s).len(), 202);
}
#[test]
fn the_copies_stay_within_ten_million() {
// Not AutoCAD's limit, ARRAY's: 400 lines times 25000 more items is exactly 10 million copies
// and is taken; one item more is refused before anything is made.
let mut s = with_line(1);
for y in 1..400 {
s.execute("line", &json!({ "points": [[0, y], [1, y]] })).unwrap();
}
copy(&mut s, &["0,0", "A", "25002"]);
assert_eq!(
s.log.last().map(String::as_str),
Some("The array would create 10000400 objects; the limit is 10000000. Use fewer items or select fewer objects.")
);
assert_eq!(s.current_prompt().unwrap().display(), "Enter number of items to array:");
assert_eq!(starts(&s).len(), 400);
s.cmdline("25001").unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Fit]:");
}
#[test]
fn copymode_is_a_profile_variable() {
// OPTIONS reports it, a saved profile brings it back, reset puts it back to 0, and typing its
// name asks for it as for any variable.
let mut s = with_line(1);
assert_eq!(s.execute("options", &json!({})).unwrap()["COPYMODE"], json!(1));
let saved = cadcraft_engine::cmd::options::profile(&s);
let mut t = Session::new();
cadcraft_engine::cmd::options::restore(&mut t, &saved);
assert_eq!(copymode(&mut t), json!(1));
s.execute("options", &json!({ "reset": true })).unwrap();
assert_eq!(copymode(&mut s), json!(0));
s.cmdline("COPYMODE").unwrap();
s.cmdline("1").unwrap();
assert_eq!(copymode(&mut s), json!(1));
}
#[test]
fn copymode_takes_0_or_1() {
let mut s = Session::new();
assert_eq!(copymode(&mut s), json!(0));
for bad in [json!(2), json!(-1), json!("x")] {
assert!(s.execute("setvar", &json!({ "name": "COPYMODE", "value": bad })).is_err(), "{bad}");
}
assert_eq!(copymode(&mut s), json!(0));
}
+102
View File
@@ -129,3 +129,105 @@ fn insert_options_match_autocad() {
s.cmdline("(command \"_.-INSERT\" \"B7\" \"_B\" '(612350.678 2398770.432) '(612365.678 2398775.432) 1 \"\" 0)").unwrap();
assert_eq!(last_insert(&s), (115.0, 55.0, 1.0, 1.0, 1.0, 0.0));
}
/// A session with block B1, a line from (0, 0) to (10, 0) based at the origin.
fn with_b1() -> Session {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
s.execute("block", &json!({ "name": "B1", "base": [0, 0], "keep": "delete", "handles": ["100"] })).unwrap();
s
}
/// Points at the scale and rotation prompts, as AutoCAD 2024 takes them (accoreconsole, unitless;
/// INSERT measured at Scale, Rotate and XYZ's Z, MINSERT at every one): at the Scale, X, Y, Z and
/// Rotate presets a point is the first of two, "Specify second point:" gives their distance or
/// direction, and Enter there keeps the default; at XYZ's Z a point gives its distance from the
/// insertion point.
#[test]
fn points_at_the_scale_and_rotation_prompts() {
let cases = [
("\"_S\" '(3.0 4.0) '(6.0 8.0) '(10.0 0.0) 0", (10.0, 0.0, 5.0, 5.0, 5.0, 0.0)),
("\"_X\" '(3.0 4.0) '(6.0 8.0) '(10.0 0.0) 0", (10.0, 0.0, 5.0, 1.0, 1.0, 0.0)),
("\"_Z\" '(3.0 4.0) '(6.0 8.0) '(10.0 0.0) 0", (10.0, 0.0, 1.0, 1.0, 5.0, 0.0)),
("\"_R\" '(3.0 4.0) '(3.0 8.0) '(10.0 0.0) 1 \"\"", (10.0, 0.0, 1.0, 1.0, 1.0, 90.0)),
// Enter at the second point keeps the preset's default.
("\"_S\" '(3.0 4.0) \"\" '(10.0 0.0) 0", (10.0, 0.0, 1.0, 1.0, 1.0, 0.0)),
("\"_X\" '(3.0 4.0) \"\" '(10.0 0.0) 0", (10.0, 0.0, 1.0, 1.0, 1.0, 0.0)),
("\"_R\" '(3.0 4.0) \"\" '(10.0 0.0) 1 \"\"", (10.0, 0.0, 1.0, 1.0, 1.0, 0.0)),
// <<45 typed at the Rotate preset is still the angle 45, not an override for a point.
("\"_R\" \"<<45\" '(10.0 0.0) 1 \"\"", (10.0, 0.0, 1.0, 1.0, 1.0, 45.0)),
// The same point twice is no turn.
("\"_R\" '(3.0 4.0) '(3.0 4.0) '(10.0 0.0) 1 \"\"", (10.0, 0.0, 1.0, 1.0, 1.0, 0.0)),
];
for (args, want) in cases {
let mut s = with_b1();
s.cmdline(&format!("(command \"_.-INSERT\" \"B1\" {args})")).unwrap();
assert!(s.running.is_none(), "{args}: {}", s.prompt_text());
assert_eq!(last_insert(&s), want, "{args}");
}
// Typed at the command line too: the prompt asks for the second point.
let mut s = with_b1();
s.cmdline("-insert B1 s 3,4").unwrap();
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Specify second point:"));
s.cmdline("6,8 10,0 0").unwrap();
assert_eq!(last_insert(&s), (10.0, 0.0, 5.0, 5.0, 5.0, 0.0));
// XYZ's Z: (3, 4) is √65 from the insertion point (10, 0).
let mut s = with_b1();
s.cmdline("(command \"_.-INSERT\" \"B1\" '(10.0 0.0) \"_XYZ\" 2 3 '(3.0 4.0) 0)").unwrap();
let (.., z, _) = last_insert(&s);
assert!((z - 65f64.sqrt()).abs() < 1e-9, "{z}");
}
/// What the scale and rotation prompts refuse, with AutoCAD 2024's messages (accoreconsole,
/// measured), and the prompt asked again ("" for the same one): a refusal at "Specify second point:"
/// asks the first one.
#[test]
fn what_the_scale_and_rotation_prompts_refuse() {
const TWO: &str = "Requires numeric distance or two points.";
const NONZERO: &str = "Value must be nonzero.";
const NUMERIC: &str = "Requires numeric value.";
const SCALE: &str = "Specify scale factor for XYZ axes <1>:";
const Y: &str = "Enter Y scale factor <use X scale factor>:";
const Z: &str = "Specify Z scale factor or <use X scale factor>:";
let cases = [
("-insert B1 s", "x", TWO, SCALE),
("-insert B1 s", "0", NONZERO, SCALE),
("-insert B1 s 3,4", "5", TWO, SCALE),
("-insert B1 s 3,4", "3,4", NONZERO, SCALE),
("-insert B1 x", "x", TWO, "Specify X scale factor <1>:"),
("-insert B1 x", "0", NONZERO, "Specify X scale factor <1>:"),
("-insert B1 x 3,4", "5", TWO, "Specify X scale factor <1>:"),
("-insert B1 x 3,4", "3,4", NONZERO, "Specify X scale factor <1>:"),
("-insert B1 r", "x", "Requires valid numeric angle or two points.", "Specify rotation angle <0>:"),
// A point from LISP: typed text at this prompt is read as an angle, as before.
("-insert B1 r|(list 3 4)", "5", "Requires valid numeric angle or two points.", "Specify rotation angle <0>:"),
("-insert B1 10,0", "0", NONZERO, ""),
("-insert B1 10,0 2", "(list 3 4)", NUMERIC, Y),
("-insert B1 10,0 2", "x", NUMERIC, Y),
("-insert B1 10,0 2", "0", NONZERO, Y),
("-insert B1 10,0 xyz 2 3", "x", "Requires numeric distance or second point.", Z),
("-insert B1 10,0 xyz 2 3", "0", NONZERO, Z),
// XYZ's Z at the insertion point itself: no distance.
("-insert B1 10,0 xyz 2 3", "10,0", NONZERO, Z),
// Exploded, after the insertion point, the scale is a positive number only.
("-insert *B1 10,0", "(list 3 4)", NUMERIC, ""),
("-insert *B1 10,0", "x", NUMERIC, ""),
("-insert *B1 10,0", "0", "Value must be positive and nonzero.", ""),
("-insert *B1 10,0", "-2", "Value must be positive and nonzero.", ""),
];
for (typed, bad, message, again) in cases {
let mut s = with_b1();
// Separate inputs are split at `|`.
for t in typed.split('|') {
s.cmdline(t).unwrap();
}
let before = s.current_prompt().map(|p| p.display());
let logged = s.log.len();
s.cmdline(bad).unwrap();
let said: Vec<&str> =
s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires") || l.starts_with("Value must")).collect();
assert_eq!(said, [message], "{typed} then {bad}");
let again = if again.is_empty() { before.clone() } else { Some(again.to_string()) };
assert_eq!(s.current_prompt().map(|p| p.display()), again, "{typed} then {bad}");
}
}
File diff suppressed because it is too large Load Diff
+6
View File
@@ -4,6 +4,7 @@ mod annotate_options;
mod annotative;
mod arc_ctrl_direction;
mod array_commands;
mod array_counts;
mod array_key_point;
mod array_live;
mod assoc_array;
@@ -12,6 +13,7 @@ mod attdisp_attsync;
mod attedit_prompts;
mod attrib_modes;
mod attrib_props;
mod attribute_tag_matching;
mod attribute_tools;
mod attribute_value_baseline;
mod block_description;
@@ -33,6 +35,7 @@ mod compare_export;
mod constraint_geometry;
mod constraint_infer;
mod copy_count;
mod copy_modes;
mod count;
mod dash_block;
mod dash_units;
@@ -84,6 +87,7 @@ mod insert_enter;
mod insert_prompts;
mod isometric;
mod join_close;
mod join_on_source;
mod json_param_validation;
mod kept_dimension_snaps;
mod layer_cmdline;
@@ -122,6 +126,7 @@ mod oops_command;
mod options_profile;
mod overkill;
mod parallel_display_list;
mod pedit_heights;
mod pedit_multiple;
mod pedit_splinedit;
mod pick_text;
@@ -143,6 +148,7 @@ mod purge_mlinestyles;
mod purge_prompts;
mod qdim;
mod qdim_modes;
mod qleader;
mod query_entities;
mod quickcalc;
mod recent_commands;
+86 -2
View File
@@ -117,6 +117,73 @@ fn the_prompts_follow_autocad_2024() {
assert_eq!(grid(&i), (3, 2, 20.0, 15.0));
}
#[test]
fn the_column_spacing_takes_two_points() {
// AutoCAD 2024 at "Specify distance between columns (|||):": a point asks "Specify second
// point:", and the two points' distance is the spacing, 0 included; x and Enter there, and
// Enter or 5 at the second point, get "Requires numeric distance or two points." (measured).
let to_spacing = |s: &mut Session| {
let l = handle(&s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap());
s.execute("-block", &json!({"name": "B", "base": [0, 0], "handles": [l]})).unwrap();
for input in ["minsert", "B", "10,0", "1", "", "0", "2", "2", "10"] {
s.cmdline(input).unwrap();
}
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Specify distance between columns (|||):"));
};
for (second, spacing) in [("6,8", 5.0), ("3,4", 0.0)] {
let mut s = Session::new();
to_spacing(&mut s);
s.cmdline("3,4").unwrap();
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Specify second point:"));
s.cmdline(second).unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let [i] = inserts(&s).try_into().unwrap();
assert_eq!(grid(&i), (2, 2, spacing, 10.0), "{second}");
}
for bad in [&["x"][..], &[""], &["3,4", ""], &["3,4", "5"]] {
let mut s = Session::new();
to_spacing(&mut s);
let logged = s.log.len();
for input in bad {
s.cmdline(input).unwrap();
}
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
assert_eq!(said, ["Requires numeric distance or two points."], "{bad:?}");
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Specify distance between columns (|||):"), "{bad:?}");
}
}
#[test]
fn counts_take_a_whole_number_as_typed() {
// AutoCAD 2024 at "Enter number of rows (---)": +3 and 03 are three rows; 5.0, 5., 1e1, 8/2,
// 3', 4.5, 0 and a point from LISP are refused and asked again (measured; at the columns 5.0
// and +3 too).
let mut s = Session::new();
let l = handle(&s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap());
s.execute("-block", &json!({"name": "B", "base": [0, 0], "handles": [l]})).unwrap();
for input in ["minsert", "B", "0,0", "1", "", "0"] {
s.cmdline(input).unwrap();
}
for row_or_column in ["+3", "03"] {
let asked = s.prompt_text();
for bad in ["5.0", "5.", "1e1", "8/2", "3'", "4.5", "0", "(list 1 2)"] {
let logged = s.log.len();
s.cmdline(bad).unwrap();
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
assert_eq!(said, ["Requires an integer between 1 and 32767."], "{bad}");
assert_eq!(s.prompt_text(), asked, "{bad}");
}
s.cmdline(row_or_column).unwrap();
}
for input in ["10", "20"] {
s.cmdline(input).unwrap();
}
assert!(s.running.is_none(), "{}", s.prompt_text());
let [i] = inserts(&s).try_into().unwrap();
// (columns, rows, column spacing, row spacing)
assert_eq!(grid(&i), (3, 3, 20.0, 10.0));
}
#[test]
fn counts_run_from_1_to_32767() {
// AutoCAD 2024: "Requires an integer between 1 and 32767."
@@ -205,14 +272,31 @@ fn the_json_form_makes_the_same_grid() {
json!({"name": "B", "at": [0, 0], "rows": 0}),
json!({"name": "B", "at": [0, 0], "columns": 32768}),
json!({"name": "B", "at": [0, 0], "rows": 2.5}),
// A whole number written as a float is refused, as by the array commands' JSON forms.
json!({"name": "B", "at": [0, 0], "rows": 2.0}),
json!({"name": "B", "at": [0, 0], "columns": 1e2}),
json!({"name": "B", "at": [0, 0], "rows": "2"}),
json!({"name": "B", "at": [0, 0], "rows": -2}),
// A distance that is not a number is refused, not taken as 0.
json!({"name": "B", "at": [0, 0], "rows": 2, "rowSpacing": "15"}),
json!({"name": "B", "at": [0, 0], "columns": 2, "columnSpacing": true}),
] {
assert!(s.execute("minsert", &bad).is_err(), "{bad}");
}
// A whole number written as 2.0 is a count; `explode` is INSERT's and leaves the grid made.
let r = s.execute("minsert", &json!({"name": "B", "at": [0, 200], "rows": 2.0, "rowSpacing": 15, "explode": true})).unwrap();
// Nothing was made by the refused calls.
assert_eq!(inserts(&s).len(), 2);
// `explode` is INSERT's and leaves the grid made; 32767 is the largest count.
let r = s.execute("minsert", &json!({"name": "B", "at": [0, 200], "rows": 2, "rowSpacing": 15, "explode": true})).unwrap();
assert!(r["handle"].is_string(), "{r}");
assert_eq!(inserts(&s).last().map(grid), Some((1, 2, 0.0, 15.0)));
// A null count is 1 and a null distance 0, as missing ones are: each count on its own, then
// both distances with two rows and two columns (one row or column keeps no distance anyway).
s.execute("minsert", &json!({"name": "B", "at": [0, 250], "rows": null, "columns": 2, "columnSpacing": 20})).unwrap();
assert_eq!(inserts(&s).last().map(grid), Some((2, 1, 20.0, 0.0)));
s.execute("minsert", &json!({"name": "B", "at": [0, 270], "rows": 2, "columns": null, "rowSpacing": 15})).unwrap();
assert_eq!(inserts(&s).last().map(grid), Some((1, 2, 0.0, 15.0)));
s.execute("minsert", &json!({"name": "B", "at": [0, 290], "rows": 2, "columns": 2, "rowSpacing": null, "columnSpacing": null})).unwrap();
assert_eq!(inserts(&s).last().map(grid), Some((2, 2, 0.0, 0.0)));
s.execute("minsert", &json!({"name": "B", "at": [0, 300], "columns": 32767, "columnSpacing": 1})).unwrap();
assert_eq!(inserts(&s).last().map(grid), Some((32767, 1, 1.0, 0.0)));
}
+365
View File
@@ -0,0 +1,365 @@
//! PEDIT on lines, arcs and polylines away from Z 0, as AutoCAD 2024 runs it (accoreconsole,
//! `entget` of the polyline made, on self-built drawings). A mirrored object here is one whose
//! normal is 0,0,-1, kept in world coordinates as the DXF reader keeps it.
use cadcraft_doc::{Entity, EntityKind, Handle, LwPolyline};
use cadcraft_engine::Session;
use cadcraft_geom::Vec3;
use serde_json::{Value, json};
fn handle(v: &Value) -> Handle {
Handle::parse_hex(v["handle"].as_str().or_else(|| v["handles"][0].as_str()).unwrap()).unwrap()
}
fn entity(s: &Session, h: Handle) -> Entity {
(**s.doc().unwrap().entity(h).unwrap()).clone()
}
fn edit(s: &mut Session, h: Handle, f: impl FnOnce(&mut Entity)) {
s.doc_mut().unwrap().modify_entity(h, f).unwrap();
}
/// A line from `a` to `b`.
fn line(s: &mut Session, a: [f64; 3], b: [f64; 3]) -> Handle {
let h = handle(&s.execute("line", &json!({ "points": [[a[0], a[1]], [b[0], b[1]]] })).unwrap());
edit(s, h, |e| {
if let EntityKind::Line(l) = &mut e.kind {
(l.a.z, l.b.z) = (a[2], b[2]);
}
});
h
}
/// An arc round `c` (world) from `a1` to `a2` degrees, counterclockwise in plan.
fn arc(s: &mut Session, c: [f64; 3], r: f64, a1: f64, a2: f64) -> Handle {
let h = handle(&s.execute("arc", &json!({ "center": [c[0], c[1]], "radius": r, "start": a1, "end": a2 })).unwrap());
edit(s, h, |e| {
if let EntityKind::Arc(a) = &mut e.kind {
a.center.z = c[2];
}
});
h
}
/// An open polyline through `points` at `elevation`.
fn pline(s: &mut Session, points: Value, elevation: f64) -> Handle {
let h = handle(&s.execute("pline", &json!({ "points": points })).unwrap());
edit(s, h, |e| {
if let EntityKind::LwPolyline(p) = &mut e.kind {
p.elevation = elevation;
}
});
h
}
fn face_down(s: &mut Session, h: Handle) {
edit(s, h, |e| e.common.extrusion = Vec3::new(0.0, 0.0, -1.0));
}
fn polyline(e: &Entity) -> LwPolyline {
let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline: {e:?}") };
p.clone()
}
/// PEDIT's JSON form with nothing to change, which only turns a line or an arc into a polyline.
fn convert(s: &mut Session, h: Handle) -> Entity {
s.execute("pedit", &json!({ "handle": h.hex(), "option": "ltypegen", "on": false })).unwrap();
entity(s, h)
}
#[test]
fn a_line_or_an_arc_becomes_a_polyline_at_its_height() {
// AutoCAD 2024: a line at Z 5 and an arc whose centre is at Z 5 give elevation 5 facing up;
// a thickness of 2 stays, a line's and an arc's; a line facing down still gives a polyline
// facing up.
let mut s = Session::new();
let l = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
edit(&mut s, l, |e| e.common.thickness = 2.0);
let e = convert(&mut s, l);
assert_eq!((polyline(&e).elevation, e.common.extrusion, e.common.thickness), (5.0, Vec3::Z, 2.0));
let a = arc(&mut s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0);
edit(&mut s, a, |e| e.common.thickness = 2.0);
let e = convert(&mut s, a);
let p = polyline(&e);
assert_eq!((p.elevation, e.common.extrusion, e.common.thickness), (5.0, Vec3::Z, 2.0));
assert!((p.vertices[0].bulge - std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{p:?}");
// Below Z 0 too (AutoCAD 2024: 38 = -5 for the arc's centre at Z -5).
let a = arc(&mut s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
let e = convert(&mut s, a);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (-5.0, Vec3::Z));
let l = line(&mut s, [0.0, 20.0, 5.0], [10.0, 20.0, 5.0]);
face_down(&mut s, l);
let e = convert(&mut s, l);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (5.0, Vec3::Z));
// A mirrored arc keeps its normal (AutoCAD 2024: 210 0,0,-1, elevation 5 for the arc at world
// Z -5) and runs as it does in its own coordinates: from world (15,5) to (10,0), bulge
// -0.414214 in plan (0.414214 in its own coordinates).
let a = arc(&mut s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
face_down(&mut s, a);
let e = convert(&mut s, a);
let p = polyline(&e);
assert_eq!((p.elevation, e.common.extrusion), (5.0, Vec3::new(0.0, 0.0, -1.0)));
let v: Vec<(f64, f64)> = p.vertices.iter().map(|v| (v.p.x, v.p.y)).collect();
assert!((v[0].0 - 15.0).abs() < 1e-9 && (v[0].1 - 5.0).abs() < 1e-9 && (v[1].0 - 10.0).abs() < 1e-9 && v[1].1.abs() < 1e-9, "{v:?}");
assert!((p.vertices[0].bulge + std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{p:?}");
// The elevation runs along the normal the other way too: a mirrored arc at world Z 5 gives -5,
// and one 2 thick at world Z -5 keeps the thickness (AutoCAD 2024: 38 = -5; 38 = 5, 39 = 2).
let a = arc(&mut s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0);
face_down(&mut s, a);
let e = convert(&mut s, a);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (-5.0, Vec3::new(0.0, 0.0, -1.0)));
let a = arc(&mut s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
face_down(&mut s, a);
edit(&mut s, a, |e| e.common.thickness = 2.0);
let e = convert(&mut s, a);
assert_eq!((polyline(&e).elevation, e.common.extrusion, e.common.thickness), (5.0, Vec3::new(0.0, 0.0, -1.0), 2.0));
// A sloped line still comes out at elevation 0, facing up: AutoCAD 2024 makes a polyline in the
// line's vertical plane (normal 0,1,0), which a CADCraft polyline can't be.
let l = line(&mut s, [0.0, 40.0, 0.0], [10.0, 40.0, 5.0]);
let e = convert(&mut s, l);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (0.0, Vec3::Z));
// A refused option leaves a line as it was, its normal included.
let l = line(&mut s, [0.0, 60.0, 5.0], [10.0, 60.0, 5.0]);
face_down(&mut s, l);
let before = entity(&s, l);
let r = s.execute("pedit", &json!({ "handle": l.hex(), "option": "vertex", "index": 0, "action": "break" }));
assert!(r.is_err(), "{r:?}");
assert_eq!(entity(&s, l), before);
}
/// PEDIT Join from the first object onto the second; whether the second was taken.
fn joins(s: &mut Session, first: Handle, second: Handle) -> bool {
let r = s.execute("pedit", &json!({ "handle": first.hex(), "option": "join", "join": [second.hex()] })).unwrap();
let taken = r["joined"] == json!(1);
assert_eq!(taken, s.doc().unwrap().entity(second).is_none(), "{r}");
taken
}
#[test]
fn join_takes_only_objects_at_the_polylines_height_facing_its_way() {
// AutoCAD 2024, from a line at Z 5 ending at (10,0): "1 segments added to polyline" or "0".
let next: [(&str, bool, fn(&mut Session) -> Handle); 6] = [
("a line at Z 5", true, |s| line(s, [10.0, 0.0, 5.0], [10.0, 5.0, 5.0])),
("a line at Z 0", false, |s| line(s, [10.0, 0.0, 0.0], [10.0, 5.0, 0.0])),
("an arc at Z 5", true, |s| arc(s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0)),
("an arc at Z 0", false, |s| arc(s, [10.0, 5.0, 0.0], 5.0, 270.0, 0.0)),
("a mirrored line at Z 5", true, |s| {
let h = line(s, [10.0, 0.0, 5.0], [10.0, 5.0, 5.0]);
face_down(s, h);
h
}),
("a mirrored arc at Z 5", false, |s| {
let h = arc(s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0);
face_down(s, h);
h
}),
];
for (what, want, make) in next {
let mut s = Session::new();
let base = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let other = make(&mut s);
assert_eq!(joins(&mut s, base, other), want, "{what}");
let p = polyline(&entity(&s, base));
assert_eq!((p.elevation, p.vertices.len()), (5.0, if want { 3 } else { 2 }), "{what}");
if want && what.contains("arc") {
// AutoCAD 2024: bulge 0.414214 on the arc's segment.
assert!((p.vertices[1].bulge - std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{what}: {p:?}");
}
}
// From a mirrored polyline at elevation 5 (world Z -5, from (0,0) to (10,0)): no line at its
// world height, but a mirrored arc there and another mirrored polyline at elevation 5; and a
// polyline at elevation 5 takes no polyline at 0.
let mirrored: [(&str, bool, fn(&mut Session) -> Handle); 3] = [
("a line at Z -5", false, |s| line(s, [10.0, 0.0, -5.0], [10.0, 5.0, -5.0])),
("a mirrored arc at Z -5", true, |s| {
let h = arc(s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
face_down(s, h);
h
}),
("a mirrored polyline at elevation 5", true, |s| {
let h = pline(s, json!([[10, 0], [10, 5]]), 5.0);
face_down(s, h);
h
}),
];
for (what, want, make) in mirrored {
let mut s = Session::new();
let base = pline(&mut s, json!([[0, 0], [10, 0]]), 5.0);
face_down(&mut s, base);
let other = make(&mut s);
assert_eq!(joins(&mut s, base, other), want, "{what}");
// AutoCAD 2024: the polyline keeps elevation 5 and normal 0,0,-1; the arc's segment has
// bulge -0.414214 in the polyline's own coordinates, 0.414214 seen from above.
let e = entity(&s, base);
let p = polyline(&e);
assert_eq!((p.elevation, e.common.extrusion, p.vertices.len()), (5.0, Vec3::new(0.0, 0.0, -1.0), if want { 3 } else { 2 }), "{what}");
if want && what.contains("arc") {
assert!((p.vertices[1].bulge - std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{what}: {p:?}");
}
}
let mut s = Session::new();
let base = pline(&mut s, json!([[0, 0], [10, 0]]), 5.0);
let other = pline(&mut s, json!([[10, 0], [10, 5]]), 0.0);
assert!(!joins(&mut s, base, other), "a polyline at elevation 0");
}
#[test]
fn multiple_join_takes_objects_at_any_height_but_not_facing_the_other_way() {
// AutoCAD 2024: PEDIT Multiple, a line at Z 5 and one at Z 0 meeting it in plan, convert and
// Join with no fuzz: "1 segments added to polyline", one polyline at elevation 5.
let mut s = Session::new();
line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
line(&mut s, [10.0, 0.0, 0.0], [10.0, 5.0, 0.0]);
s.cmdline("pedit m 5,0 10,2.5").unwrap();
s.cmdline("").unwrap();
s.cmdline("y j 0").unwrap();
s.cmdline("").unwrap();
let objects: Vec<Entity> = s.doc().unwrap().model.iter().map(|e| (**e).clone()).collect();
assert_eq!(objects.len(), 1, "{objects:?}");
let p = polyline(&objects[0]);
assert_eq!((p.elevation, p.vertices.len()), (5.0, 3));
// A line at Z 0 to (10,0) and a mirrored arc from there to (15,5), picked in either order:
// both become polylines, the arc's facing down, and Join takes neither ("0 segments added").
for arc_first in [false, true] {
let mut s = Session::new();
line(&mut s, [0.0, 0.0, 0.0], [10.0, 0.0, 0.0]);
let a = arc(&mut s, [10.0, 5.0, 0.0], 5.0, 270.0, 0.0);
face_down(&mut s, a);
// The arc picked on it, at 315 degrees.
s.cmdline(if arc_first { "pedit m 13.5355339,1.4644661 5,0" } else { "pedit m 5,0 13.5355339,1.4644661" }).unwrap();
s.cmdline("").unwrap();
s.cmdline("y j 0").unwrap();
s.cmdline("").unwrap();
let objects: Vec<Entity> = s.doc().unwrap().model.iter().map(|e| (**e).clone()).collect();
assert_eq!(objects.len(), 2, "arc first {arc_first}: {objects:?}");
assert!(objects.iter().all(|e| matches!(e.kind, EntityKind::LwPolyline(_))), "{objects:?}");
// AutoCAD 2024: the arc's polyline at elevation 0 with normal 0,0,-1, the line's facing up.
let (arcs, lines): (Vec<&Entity>, Vec<&Entity>) = objects.iter().partition(|e| e.common.extrusion.z < 0.0);
assert_eq!((arcs.len(), lines.len()), (1, 1), "{objects:?}");
let p = polyline(arcs[0]);
assert!(p.elevation == 0.0 && p.vertices[0].bulge != 0.0 && lines[0].common.extrusion == Vec3::Z, "{objects:?}");
}
}
#[test]
fn join_continues_from_a_sloped_lines_far_end_height() {
// AutoCAD 2024: from a line at Z 5, a sloped line down to Z 0 and a line on at Z 0 both join
// ("2 segments added"), at the polyline's end and at its start alike, the sloped line drawn
// either way. AutoCAD makes that polyline in the lines' vertical plane; a CADCraft polyline
// stays at the source's elevation.
for (base, sloped, next) in [
([[0.0, 0.0, 5.0], [10.0, 0.0, 5.0]], [[10.0, 0.0, 5.0], [20.0, 0.0, 0.0]], [[20.0, 0.0, 0.0], [30.0, 0.0, 0.0]]),
([[0.0, 0.0, 5.0], [10.0, 0.0, 5.0]], [[20.0, 0.0, 0.0], [10.0, 0.0, 5.0]], [[20.0, 0.0, 0.0], [30.0, 0.0, 0.0]]),
([[10.0, 0.0, 5.0], [20.0, 0.0, 5.0]], [[0.0, 0.0, 0.0], [10.0, 0.0, 5.0]], [[-10.0, 0.0, 0.0], [0.0, 0.0, 0.0]]),
([[10.0, 0.0, 5.0], [20.0, 0.0, 5.0]], [[10.0, 0.0, 5.0], [0.0, 0.0, 0.0]], [[-10.0, 0.0, 0.0], [0.0, 0.0, 0.0]]),
] {
let mut s = Session::new();
let h = line(&mut s, base[0], base[1]);
let a = line(&mut s, sloped[0], sloped[1]);
let b = line(&mut s, next[0], next[1]);
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [a.hex(), b.hex()] })).unwrap();
assert_eq!(r["joined"], json!(2), "{base:?}: {r}");
assert_eq!(polyline(&entity(&s, h)).vertices.len(), 4);
}
}
#[test]
fn a_chain_closes_only_at_one_height() {
// AutoCAD 2024: three sides of a triangle at Z 5 join into a closed polyline; with its last
// side at Z 0, that side stays a line and the polyline stays open ("1 segments added").
for (last_z, joined, closed) in [(5.0, 2, true), (0.0, 1, false)] {
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let a = line(&mut s, [10.0, 0.0, 5.0], [10.0, 10.0, 5.0]);
let b = line(&mut s, [10.0, 10.0, last_z], [0.0, 0.0, last_z]);
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [a.hex(), b.hex()] })).unwrap();
assert_eq!(r["joined"], json!(joined), "last side at {last_z}: {r}");
assert_eq!(polyline(&entity(&s, h)).closed, closed, "last side at {last_z}");
}
// A line at Z 5 and a sloped line back over it to Z 0: the ends meet in plan at Z 5 and at Z 0,
// and the polyline stays open (AutoCAD 2024: "1 segments added", 70 = 0).
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let back = line(&mut s, [10.0, 0.0, 5.0], [0.0, 0.0, 0.0]);
assert!(joins(&mut s, h, back));
let p = polyline(&entity(&s, h));
assert_eq!((p.vertices.len(), p.closed), (3, false));
}
#[test]
fn join_takes_a_sloped_line_only_in_one_plane_with_the_polyline_and_every_line_picked() {
// AutoCAD 2024 joins only objects in one plane with the polyline: the plane the polyline and
// every line picked share, when they share one, else the polyline's own, flat, where no sloped
// line lies. From a line at Z 5, (0,0) to (10,0):
let cases: [(&str, &[[[f64; 3]; 2]], usize); 4] = [
// a sloped line at right angles in plan, a tilted plane: "1 segments added";
("at an angle", &[[[10.0, 0.0, 5.0], [10.0, 10.0, 0.0]]], 1),
// a triangle at Z 5 whose last side slopes from (10,10,5) to (0,0,0): that side stays a line;
("a triangle's sloped side", &[[[10.0, 0.0, 5.0], [10.0, 10.0, 5.0]], [[10.0, 10.0, 5.0], [0.0, 0.0, 0.0]]], 1),
// a corner at Z 5, then a sloped line on in plan: the sloped line stays a line;
("after a corner", &[[[10.0, 0.0, 5.0], [10.0, 10.0, 5.0]], [[10.0, 10.0, 5.0], [10.0, 20.0, 0.0]]], 1),
// a sloped line on in plan, then a line at Z 0 from its foot turning off their vertical
// plane: the three share no plane, and neither joins ("0 segments added").
("then a turn", &[[[10.0, 0.0, 5.0], [20.0, 0.0, 0.0]], [[20.0, 0.0, 0.0], [20.0, 10.0, 0.0]]], 0),
];
for (what, lines, joined) in cases {
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let picked: Vec<String> = lines.iter().map(|[a, b]| line(&mut s, *a, *b).hex()).collect();
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": picked })).unwrap();
assert_eq!(r["joined"], json!(joined), "{what}: {r}");
let left = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
assert_eq!(left, lines.len() - joined, "{what}");
}
// A sloped line on in plan, then an arc at Z 0 from its foot: the line joins, the arc, which
// lies flat, doesn't ("1 segments added").
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let l = line(&mut s, [10.0, 0.0, 5.0], [20.0, 0.0, 0.0]);
let a = arc(&mut s, [20.0, 5.0, 0.0], 5.0, 270.0, 0.0);
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [l.hex(), a.hex()] })).unwrap();
assert_eq!(r["joined"], json!(1), "{r}");
assert!(s.doc().unwrap().entity(l).is_none() && s.doc().unwrap().entity(a).is_some());
}
#[test]
fn join_meets_within_the_fuzz_in_plan_and_1e_6_in_height() {
// The JSON form's fuzz bridges a gap in plan only: a line 0.3 off the end joins with fuzz 0.5
// at the polyline's height, to within 1e-6, and not 0.001 above it.
for (z, want) in [(5.0, true), (5.0 + 1e-9, true), (5.001, false)] {
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let o = line(&mut s, [10.3, 0.0, z], [10.3, 5.0, z]);
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [o.hex()], "fuzz": 0.5 })).unwrap();
assert_eq!(r["joined"] == json!(1), want, "Z {z}: {r}");
}
// Multiple's Join takes the line 0.001 above too, as it takes one at any height.
let mut s = Session::new();
line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
line(&mut s, [10.3, 0.0, 5.001], [10.3, 5.0, 5.001]);
s.cmdline("pedit m 5,0 10.3,2.5").unwrap();
s.cmdline("").unwrap();
s.cmdline("y j 0.5").unwrap();
s.cmdline("").unwrap();
assert_eq!(s.doc().unwrap().model.iter().count(), 1);
}
#[test]
fn the_command_line_converts_and_joins_the_same_way() {
// PEDIT typed: a mirrored line at Z 5 becomes a polyline at elevation 5 facing up, and Join
// leaves a line at Z 0 off it ("0 segments added to polyline").
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
face_down(&mut s, h);
let other = line(&mut s, [10.0, 0.0, 0.0], [10.0, 5.0, 0.0]);
s.cmdline("pedit 5,0 y").unwrap();
let e = entity(&s, h);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (5.0, Vec3::Z));
let n = s.log.len();
s.cmdline("j 10,2.5").unwrap();
s.cmdline("").unwrap();
assert!(s.log[n..].iter().any(|l| l.contains("0 segments added to polyline")), "{:?}", &s.log[n..]);
assert!(s.doc().unwrap().entity(other).is_some());
s.cmdline("").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
}
+138 -2
View File
@@ -151,6 +151,19 @@ fn fit_spline(s: &mut Session) -> String {
h(&s.execute("spline", &json!({ "fit": [[0, 0], [2, 2], [4, 0], [6, 2]] })).unwrap())
}
#[test]
fn close_gives_a_closed_fit_its_own_tangent() {
// SPLINEDIT Close refits the fit points closed: the open ends' tangents don't carry over, the
// closed curve takes its own where it closes, as SPLINE ... Close builds it.
let mut s = Session::new();
let fit = json!([[0, 0], [4, 0], [6, 3], [1, 4]]);
let sp = h(&s.execute("spline", &json!({ "fit": fit, "startTangent": [0, 1] })).unwrap());
s.execute("splinedit", &json!({ "handle": sp, "option": "close" })).unwrap();
let closed = spline(&s, &sp);
let own = h(&s.execute("spline", &json!({ "fit": fit, "closed": true })).unwrap());
assert_eq!(closed, spline(&s, &own));
}
#[test]
fn fit_data_options_at_the_command_line() {
let mut s = Session::new();
@@ -281,9 +294,10 @@ fn control_edits_drop_fit_data_and_keep_closed_splines_closed() {
let x = spline(&s, &sp);
assert!(x.fit.is_empty() && x.control[1] == Vec2::new(1.0, 5.0));
let c = h(&s.execute("spline", &json!({ "fit": [[0, 0], [4, 0], [4, 4], [0, 4], [-2, 2]], "closed": true })).unwrap());
// Control points that wrap round (uniform knots): the first `degree` repeat at the end.
let c = h(&s.execute("spline", &json!({ "fit": [[0, 0], [4, 0], [4, 4], [0, 4], [-2, 2]], "closed": true, "knots": "uniform" })).unwrap());
let before = spline(&s, &c);
assert!(before.is_periodic());
assert!(before.wraps() && before.is_periodic());
let u = before.control.len() - before.degree;
s.execute("splinedit", &json!({ "handle": c, "option": "vertexmove", "index": 0, "to": [-1, -1] })).unwrap();
let x = spline(&s, &c);
@@ -297,6 +311,23 @@ fn control_edits_drop_fit_data_and_keep_closed_splines_closed() {
let (lo, hi) = x.domain();
assert!(x.eval(lo).near(x.eval(hi), 1e-9), "still closed");
assert!(s.execute("splinedit", &json!({ "handle": c, "option": "vertexdelete", "index": 99 })).is_err());
// Clamped (chord-length knots, as AutoCAD 2024 builds a closed fit spline): only the first
// control point repeats, at the end. Moving it leaves a corner where the curve closes.
let c = h(&s.execute("spline", &json!({ "fit": [[0, 0], [4, 0], [4, 4], [0, 4], [-2, 2]], "closed": true })).unwrap());
let before = spline(&s, &c);
assert!(before.is_periodic() && !before.wraps());
let last = before.control.len() - 1;
s.execute("splinedit", &json!({ "handle": c, "option": "vertexmove", "index": 0, "to": [-1, -1] })).unwrap();
let x = spline(&s, &c);
assert_eq!((x.control[0], x.control[last]), (Vec2::new(-1.0, -1.0), Vec2::new(-1.0, -1.0)), "both ends move");
assert!(x.closed && !x.is_periodic(), "a corner where it closes");
s.execute("splinedit", &json!({ "handle": c, "option": "vertexdelete", "index": 2 })).unwrap();
let x = spline(&s, &c);
assert!(x.is_valid() && x.closed && x.control.len() == before.control.len() - 1);
let (lo, hi) = x.domain();
assert!(x.eval(lo).near(x.eval(hi), 1e-9), "still closed");
assert!(s.execute("splinedit", &json!({ "handle": c, "option": "vertexdelete", "index": 0 })).is_err(), "the start point stays");
}
/// Largest distance from samples of `a` to the curve `b` (a shape comparison).
@@ -369,3 +400,108 @@ fn edit_vertex_add_and_elevate_order_keep_the_shape() {
}
assert!(s.execute("splinedit", &json!({ "handle": c, "option": "vertexadd" })).is_err());
}
#[test]
fn elevate_order_takes_a_whole_number_as_typed() {
// AutoCAD 2024 at "Enter new order <4>:" on a cubic: +5, 05 and the LISP real 5.0 make it order
// 5, and 4 keeps it; 5.0, 5., 1e1, 4.5, 3, 27 and a point from LISP get "Requires an integer
// between 4 and 26." and the prompt again. At order 5 the range starts at 5 (measured).
let control = json!({ "control": [[0, 0], [2, 3], [4, 0], [6, 3], [8, 0]] });
let refused = |s: &mut Session, bad: &str, message: &str| {
let asked = s.prompt_text();
let logged = s.log.len();
s.cmdline(bad).unwrap();
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
assert_eq!(said, [message], "{bad}");
assert_eq!(s.prompt_text(), asked, "{bad}");
};
for typed in ["+5", "05", "(+ 2.5 2.5)"] {
let mut s = Session::new();
let sp = h(&s.execute("spline", &control).unwrap());
s.cmdline("splinedit 0,0 e e").unwrap();
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter new order <4>:"));
for bad in ["5.0", "5.", "1e1", "4.5", "3", "27", "(list 1 2)"] {
refused(&mut s, bad, "Requires an integer between 4 and 26.");
}
assert_eq!(spline(&s, &sp).degree, 3);
s.cmdline(typed).unwrap();
assert_eq!(spline(&s, &sp).degree, 4, "{typed}");
assert!(s.prompt_text().contains("vertex editing option"), "{}", s.prompt_text());
// Now order 5: 4 is below it, 5 keeps it.
s.cmdline("e").unwrap();
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter new order <5>:"));
refused(&mut s, "4", "Requires an integer between 5 and 26.");
s.cmdline("5").unwrap();
assert_eq!(spline(&s, &sp).degree, 4, "{typed}");
assert!(s.prompt_text().contains("vertex editing option"), "{typed}: {}", s.prompt_text());
}
// 26 is the highest order (AutoCAD 2024: taken, degree 25).
let mut s = Session::new();
let sp = h(&s.execute("spline", &control).unwrap());
s.cmdline("splinedit 0,0 e e 26").unwrap();
assert_eq!(spline(&s, &sp).degree, 25);
// 4 keeps a cubic as it is, and so does Enter.
for keep in ["4", ""] {
let mut s = Session::new();
let sp = h(&s.execute("spline", &control).unwrap());
let before = spline(&s, &sp);
s.cmdline("splinedit 0,0 e e").unwrap();
s.cmdline(keep).unwrap();
assert!(s.prompt_text().contains("vertex editing option"), "{keep:?}: {}", s.prompt_text());
assert_eq!(spline(&s, &sp).control, before.control, "{keep:?}");
}
}
#[test]
fn the_polyline_precision_is_a_whole_number_as_typed() {
// AutoCAD 2024 at "Specify a precision <10>:": +5, 05, 0, 99 and the LISP real 5.0 are taken;
// 5.0, 5., 4.5, 1e1, 8/2, 100, -1, a point and the real 4.6 from LISP are refused and asked
// again (measured).
let control = json!({ "control": [[0, 0], [2, 3], [4, 0], [6, 3], [8, 0]] });
for (typed, precision) in [("+5", 5), ("05", 5), ("0", 0), ("99", 99), ("", 10), ("(+ 2.5 2.5)", 5)] {
// The same spline converted through the JSON form, for the vertices to expect.
let mut s = Session::new();
let sp = h(&s.execute("spline", &control).unwrap());
s.execute("splinedit", &json!({ "handle": sp, "option": "polyline", "precision": precision })).unwrap();
let EntityKind::LwPolyline(want) = kind(&s, &sp) else { panic!("converted") };
let mut s = Session::new();
let sp = h(&s.execute("spline", &control).unwrap());
s.cmdline("splinedit 0,0 p").unwrap();
let asked = s.prompt_text();
for bad in ["5.0", "5.", "4.5", "1e1", "8/2", "100", "-1", "(list 1 2)", "(+ 2.3 2.3)"] {
let logged = s.log.len();
s.cmdline(bad).unwrap();
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
assert_eq!(said, ["Requires an integer between 0 and 99."], "{bad}");
assert_eq!(s.prompt_text(), asked, "{bad}");
}
s.cmdline(typed).unwrap();
assert!(s.running.is_none(), "{typed:?}: {}", s.prompt_text());
let EntityKind::LwPolyline(got) = kind(&s, &sp) else { panic!("{typed:?} converted") };
assert_eq!(pts(&got), pts(&want), "{typed:?}");
}
}
#[test]
fn the_json_polyline_precision_is_a_whole_number_from_0_to_99() {
let mut s = Session::new();
let sp = h(&s.execute("spline", &json!({ "control": [[0, 0], [2, 3], [4, 0], [6, 3], [8, 0]] })).unwrap());
for bad in [json!(100), json!(-1), json!(4.5), json!(5.0), json!("5")] {
assert!(s.execute("splinedit", &json!({ "handle": sp, "option": "polyline", "precision": bad })).is_err(), "{bad}");
assert!(matches!(kind(&s, &sp), EntityKind::Spline(_)), "{bad}");
}
s.execute("splinedit", &json!({ "handle": sp, "option": "polyline", "precision": 99 })).unwrap();
assert!(matches!(kind(&s, &sp), EntityKind::LwPolyline(_)));
// Without a precision, or with null, it is 10, the prompt's default.
let [a, b, c] = [json!({ "precision": 10 }), json!({}), json!({ "precision": null })].map(|mut p| {
let sp = h(&s.execute("spline", &json!({ "control": [[0, 0], [2, 3], [4, 0], [6, 3], [8, 0]] })).unwrap());
p["handle"] = json!(sp);
p["option"] = json!("polyline");
s.execute("splinedit", &p).unwrap();
let EntityKind::LwPolyline(poly) = kind(&s, &sp) else { panic!("converted") };
pts(&poly)
});
assert_eq!(a, b);
assert_eq!(a, c);
}
+253
View File
@@ -0,0 +1,253 @@
//! QLEADER at the command line as AutoCAD 2024 runs it with its default settings (accoreconsole,
//! `(command "_.QLEADER" ...)` on a metric drawing, then `entget` of the LEADER and the MTEXT):
//! up to three points, a text width, lines of text; the text sits DIMGAP past the leader's end
//! with the middle of its first line level with it on the right, of its last line on the left.
use cadcraft_engine::doc::EntityKind;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::{Input, Session};
use serde_json::json;
/// What QLEADER drew: the leader's vertices, and the text's insertion point, height, width,
/// attachment and contents (rounded to 1e-9).
type Drawn = (Vec<(f64, f64)>, Option<((f64, f64), f64, f64, u8, String)>);
fn drawn(s: &Session) -> Drawn {
let r = |v: f64| (v * 1e9).round() / 1e9;
let d = s.doc().unwrap();
let leader = d
.model
.iter()
.find_map(|e| if let EntityKind::Leader(l) = &e.kind { Some(l.vertices.iter().map(|p| (r(p.x), r(p.y))).collect()) } else { None });
let text = d.model.iter().find_map(|e| match &e.kind {
EntityKind::MText(m) => Some(((r(m.insert.x), r(m.insert.y)), r(m.height), r(m.width), m.attach, m.contents.clone())),
_ => None,
});
(leader.unwrap_or_default(), text)
}
/// A drawing with the measured scripts' dimension settings: DIMTAD 1, DIMGAP 0.625, DIMASZ 2.5,
/// DIMSCALE 1 and DIMTXT 2.5.
fn session() -> Session {
let mut s = Session::new();
for (name, v) in [("DIMTAD", 1.0), ("DIMGAP", 0.625), ("DIMASZ", 2.5), ("DIMSCALE", 1.0), ("DIMTXT", 2.5)] {
s.execute("setvar", &json!({ "name": name, "value": v })).unwrap();
}
s
}
/// Types QLEADER then each of `inputs`, and checks it ended.
fn qleader(s: &mut Session, inputs: &[&str]) {
s.cmdline("QLEADER").unwrap();
for t in inputs {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none(), "{inputs:?}: {}", s.prompt_text());
}
#[test]
fn qleader_places_the_text_as_autocad_does() {
// (inputs, AutoCAD's leader vertices, text insertion point, width, attachment, contents)
type Case<'a> = (&'a [&'a str], &'a [(f64, f64)], (f64, f64), f64, u8, &'a str);
let cases: [Case; 8] = [
// Three points, the last segment level: no hook line.
(&["0,0", "20,15", "40,15", "0", "ABC", ""], &[(0.0, 0.0), (20.0, 15.0), (40.0, 15.0)], (40.625, 16.25), 0.0, 1, "ABC"),
// Two points: a hook line DIMASZ (2.5) long into the end.
(&["0,0", "20,15", "", "0", "ABC", ""], &[(0.0, 0.0), (17.5, 15.0), (20.0, 15.0)], (20.625, 16.25), 0.0, 1, "ABC"),
(
&["0,0", "20,15", "35,30", "20", "AB", "CD", ""],
&[(0.0, 0.0), (20.0, 15.0), (32.5, 30.0), (35.0, 30.0)],
(35.625, 31.25),
20.0,
1,
"AB\\PCD",
),
// Running left: the middle of the last line level with the end.
(&["0,0", "-20,15", "-40,15", "0", "AB", "CD", ""], &[(0.0, 0.0), (-20.0, 15.0), (-40.0, 15.0)], (-40.625, 13.75), 0.0, 9, "AB\\PCD"),
(&["0,0", "-20,15", "-40,15", "0", "A", "B", "C", ""], &[(0.0, 0.0), (-20.0, 15.0), (-40.0, 15.0)], (-40.625, 13.75), 0.0, 9, "A\\PB\\PC"),
// A short leader running left: the hook line comes from past the start.
(&["0.5,0.25", "0.48,0.265", "", "0", "ABC", ""], &[(0.5, 0.25), (2.98, 0.265), (0.48, 0.265)], (-0.145, -0.985), 0.0, 9, "ABC"),
// Straight up: it counts as running right.
(&["0,0", "0,20", "", "0", "ABC", ""], &[(0.0, 0.0), (-2.5, 20.0), (0.0, 20.0)], (0.625, 21.25), 0.0, 1, "ABC"),
// Survey coordinates, running left.
(
&["612345.678,2398765.432", "612325.678,2398780.432", "612305.678,2398780.432", "0", "ABC", ""],
&[(612345.678, 2398765.432), (612325.678, 2398780.432), (612305.678, 2398780.432)],
(612305.053, 2398779.182),
0.0,
9,
"ABC",
),
];
for (inputs, leader, at, width, attach, text) in cases {
let mut s = session();
qleader(&mut s, inputs);
assert_eq!(drawn(&s), (leader.to_vec(), Some((at, 2.5, width, attach, text.to_string()))), "{inputs:?}");
}
}
#[test]
fn qleader_scales_with_dimscale_and_ignores_dimtad() {
// DIMGAP 2 and DIMSCALE 2: text 5 high, 4 past the end; the hook line 5 long.
let mut s = session();
s.execute("setvar", &json!({ "name": "DIMGAP", "value": 2.0 })).unwrap();
s.execute("setvar", &json!({ "name": "DIMSCALE", "value": 2.0 })).unwrap();
qleader(&mut s, &["0,0", "20,15", "35,30", "0", "ABC", ""]);
let want = vec![(0.0, 0.0), (20.0, 15.0), (30.0, 30.0), (35.0, 30.0)];
assert_eq!(drawn(&s), (want, Some(((39.0, 32.5), 5.0, 0.0, 1, "ABC".to_string()))));
// DIMTAD 0 or 1, the same place.
for tad in [0, 1] {
let mut s = session();
s.execute("setvar", &json!({ "name": "DIMTAD", "value": tad })).unwrap();
qleader(&mut s, &["0,0", "20,15", "40,15", "0", "ABC", ""]);
assert_eq!(drawn(&s).1, Some(((40.625, 16.25), 2.5, 0.0, 1, "ABC".to_string())), "DIMTAD {tad}");
}
}
#[test]
fn qleader_prompts_and_its_width() {
let mut s = session();
let mut asked = Vec::new();
s.cmdline("QLEADER").unwrap();
for t in ["0,0", "20,15", "40,15", "50,15", "ABC", ""] {
asked.push(s.current_prompt().unwrap().display());
s.cmdline(t).unwrap();
}
assert_eq!(
asked,
[
"Specify first leader point, or [Settings] <Settings>:",
"Specify next point:",
"Specify next point:",
"Specify text width <0>:",
"Enter first line of annotation text <Mtext>:",
"Enter next line of annotation text:",
]
);
// A point gives the width as its distance from the end, so Dynamic Input shows a distance.
assert_eq!(drawn(&s).1.map(|t| t.2), Some(10.0));
let mut s = session();
s.cmdline("QLEADER").unwrap();
for t in ["0,0", "20,15", "40,15"] {
s.cmdline(t).unwrap();
}
assert!(s.current_prompt().unwrap().distance);
// Text that isn't a distance is refused and asked again; Enter is no width.
let _ = s.cmdline("abc");
assert!(s.log.iter().any(|l| l.contains("Requires numeric distance or two points.")), "{:?}", s.log);
assert_eq!(s.current_prompt().unwrap().display(), "Specify text width <0>:");
for t in ["", "ABC", ""] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none());
assert_eq!(drawn(&s).1.map(|t| t.2), Some(0.0));
// A point so far off that its distance overflows is refused like bad text.
let mut s = session();
s.cmdline("QLEADER").unwrap();
for p in [Vec2::new(0.0, 0.0), Vec2::new(1e308, 0.0)] {
s.input(Input::Point(p)).unwrap();
}
s.cmdline("").unwrap();
let _ = s.input(Input::Point(Vec2::new(-1e308, 0.0)));
assert!(s.log.iter().any(|l| l.contains("Requires numeric distance or two points.")), "{:?}", s.log);
assert_eq!(s.current_prompt().unwrap().display(), "Specify text width <0>:");
// A negative width is none. A width isn't remembered: AutoCAD 2024 offers 0 again after 20.
for width in ["-5", "20"] {
let mut s = session();
qleader(&mut s, &["0,0", "20,15", "40,15", width, "ABC", ""]);
assert_eq!(drawn(&s).1.map(|t| t.2), Some(width.parse::<f64>().unwrap().max(0.0)));
s.cmdline("QLEADER").unwrap();
for t in ["0,0", "20,15", "40,15"] {
s.cmdline(t).unwrap();
}
assert_eq!(s.current_prompt().unwrap().display(), "Specify text width <0>:", "{width}");
}
}
#[test]
fn a_click_at_the_text_prompts_is_no_line_of_text() {
let mut s = session();
s.cmdline("QLEADER").unwrap();
for t in ["0,0", "20,15", "40,15", "0"] {
s.cmdline(t).unwrap();
}
s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Enter first line of annotation text <Mtext>:");
s.cmdline("AB").unwrap();
s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Enter next line of annotation text:");
s.cmdline("CD").unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none());
assert_eq!(drawn(&s).1.map(|t| t.4), Some("AB\\PCD".to_string()));
}
#[test]
fn qleader_without_text_or_points() {
// Enter at the first line: the leader alone.
let mut s = session();
qleader(&mut s, &["0,0", "20,15", "40,15", "0", ""]);
assert_eq!(drawn(&s), (vec![(0.0, 0.0), (20.0, 15.0), (40.0, 15.0)], None));
// Sloped, without text: no hook line either (AutoCAD 2024: two vertices).
let mut s = session();
qleader(&mut s, &["0,0", "20,15", "", "0", ""]);
assert_eq!(drawn(&s), (vec![(0.0, 0.0), (20.0, 15.0)], None));
// Enter after one point: nothing.
let mut s = session();
qleader(&mut s, &["0,0", ""]);
assert_eq!(s.doc().unwrap().model.iter().count(), 0);
// Settings, typed or by Enter: no dialog yet, the first point is asked again.
for settings in ["S", ""] {
let mut s = session();
s.cmdline("QLEADER").unwrap();
s.cmdline(settings).unwrap();
assert!(s.log.iter().any(|l| l == "The QLEADER Settings dialog is not available yet."), "{settings:?}: {:?}", s.log);
assert_eq!(s.current_prompt().unwrap().display(), "Specify first leader point, or [Settings] <Settings>:", "{settings:?}");
}
// LE starts it too.
let mut s = session();
s.cmdline("LE").unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Specify first leader point, or [Settings] <Settings>:");
}
#[test]
fn qleader_by_json() {
let mut s = session();
let r = s.execute("qleader", &json!({ "points": [[0, 0], [20, 15], [35, 30]], "width": 20, "text": "AB\r\nCD" })).unwrap();
assert_eq!(r["handles"].as_array().map(Vec::len), Some(2));
let want = vec![(0.0, 0.0), (20.0, 15.0), (32.5, 30.0), (35.0, 30.0)];
assert_eq!(drawn(&s), (want, Some(((35.625, 31.25), 2.5, 20.0, 1, "AB\\PCD".to_string()))));
// Text with nothing on its lines is no text: the leader alone, without a hook line.
for text in ["", "\n", "\r\n\r\n"] {
let mut s = session();
let r = s.execute("qleader", &json!({ "points": [[0, 0], [20, 15]], "width": 0, "text": text })).unwrap();
assert_eq!(r["handles"].as_array().map(Vec::len), Some(1), "{text:?}");
assert_eq!(drawn(&s), (vec![(0.0, 0.0), (20.0, 15.0)], None), "{text:?}");
}
// Empty lines at the end are dropped: running left, the text sits as the command line puts it.
let mut s = session();
s.execute("qleader", &json!({ "points": [[0, 0], [-20, 15], [-40, 15]], "text": "AB\n\n" })).unwrap();
assert_eq!(drawn(&s).1, Some(((-40.625, 13.75), 2.5, 0.0, 9, "AB".to_string())));
// 2 or 3 points, a width of 0 or more, text as a string.
for bad in [
json!({ "points": [[0, 0]] }),
json!({ "points": [[0, 0], [1, 1], [2, 1], [3, 1]] }),
json!({ "points": [[0, 0], [1, 1]], "width": -1 }),
json!({ "points": [[0, 0], [1, 1]], "width": "x" }),
json!({ "points": [[0, 0], [1, 1]], "text": 5 }),
json!({ "points": [[0, 0], [1, 1]], "text": ["AB", "CD"] }),
] {
let before = s.doc().unwrap().model.iter().count();
assert!(s.execute("qleader", &bad).is_err(), "{bad}");
assert_eq!(s.doc().unwrap().model.iter().count(), before, "{bad}");
}
// A point that can't be read is named as such, not as missing points.
for (bad, says) in [
(json!({}), "`points` is required"),
(json!({ "points": null }), "`points` is required"),
(json!({ "points": [[0, 0], ["x", 1]] }), "`points` must be a list of [x, y] points"),
] {
let e = s.execute("qleader", &bad).unwrap_err().to_string();
assert!(e.contains(says), "{bad}: {e}");
}
}
+5 -3
View File
@@ -43,12 +43,14 @@ fn insertion_snaps_to_a_multileader_text() {
#[test]
fn geometric_center_of_a_closed_spline() {
let mut s = Session::new();
// A closed fit spline symmetric about (5,5): its centroid is the centre.
// A closed fit spline through the corners of a square: the centroid of its area, as AutoCAD
// 2024 gives it (MASSPROP of its region; the curve is not symmetric, its tangent where it
// closes comes from the first points).
s.execute("spline", &json!({"fit": [[0, 5], [5, 0], [10, 5], [5, 10]], "closed": true})).unwrap();
let c = Vec2::new(5.0, 5.0);
let c = Vec2::new(5.02693946, 5.04916453);
let hit = snap::osnap(s.doc().unwrap(), &Space::Model, c + Vec2::new(0.05, 0.0), 0.5, mode::GCEN, None, false).expect("a geometric center");
assert_eq!(hit.mode, mode::GCEN);
assert!(hit.point.dist(c) < 1e-3, "{:?}", hit.point);
assert!(hit.point.dist(c) < 1e-5, "{:?}", hit.point);
// An open spline has none.
let mut s = Session::new();
s.execute("spline", &json!({"fit": [[0, 5], [5, 0], [10, 5], [5, 10]]})).unwrap();
+47 -1
View File
@@ -21,6 +21,29 @@ fn logged(s: &Session, text: &str) -> bool {
const FIT: &str = "0,0 1,0.2 5,3 6,3.1 9,0";
#[test]
fn a_click_on_the_last_point_adds_no_fit_point() {
// AutoCAD 2024's SPLINE leaves a click on the point before out (measured with
// accoreconsole): no repeated fit point, so no kink.
let mut s = Session::new();
s.cmdline("spline 0,0 5,0 5,0 10,5").unwrap();
s.cmdline("").unwrap();
assert_eq!(last_spline(&s).fit, vec![Vec2::ZERO, Vec2::new(5.0, 0.0), Vec2::new(10.0, 5.0)]);
// Nor does the preview add one with the cursor on the last point: it shows the curve a
// click there would leave, not a corner.
let mut s = Session::new();
s.cmdline("spline 0,0 5,0 10,5").unwrap();
let shown: Vec<Vec<Vec2>> = s
.preview(Vec2::new(10.0, 5.0))
.into_iter()
.filter_map(|e| match e.kind {
EntityKind::Spline(sp) => Some(sp.fit),
_ => None,
})
.collect();
assert_eq!(shown, vec![vec![Vec2::ZERO, Vec2::new(5.0, 0.0), Vec2::new(10.0, 5.0)]]);
}
#[test]
fn knots_option_sets_the_parametrisation_and_is_remembered() {
let mut s = Session::new();
@@ -130,7 +153,9 @@ fn object_option_converts_polylines() {
assert_eq!(doc.model.iter().count(), 1, "converted in place");
let EntityKind::Spline(sp) = last(&s) else { panic!("not converted") };
assert_eq!(sp.fit.len(), n);
assert!(sp.eval(0.0).near(Vec2::ZERO, 1e-9) && sp.eval(1.0).near(Vec2::new(30.0, 10.0), 1e-9));
// Chord-length knots run over the length of the fit points, not 0..1.
let (lo, hi) = sp.domain();
assert!(sp.eval(lo).near(Vec2::ZERO, 1e-9) && sp.eval(hi).near(Vec2::new(30.0, 10.0), 1e-9));
// JSON form: a closed polyline becomes a closed spline; arcs are refused.
let sq = s.execute("pline", &json!({"vertices": [[0, 20], [10, 20], [10, 30], [0, 30]], "closed": true})).unwrap()["handle"].clone();
@@ -172,6 +197,27 @@ fn json_form_takes_the_fit_options() {
assert_eq!(sp.fit_opts.end_tangent, Some(-Vec2::Y));
}
#[test]
fn reverse_keeps_a_closed_spline_seam() {
// As AutoCAD 2024's REVERSE (accoreconsole, `entget`): the curve and its fit points still start
// at (0,0), the other fit points turn round, and so does the tangent where it closes; a
// fit-point grip or SPLINEDIT edit then rebuilds the same reversed curve.
let mut s = Session::new();
s.cmdline("spline 0,0 4,0 6,3 1,4 c").unwrap();
let before = last_spline(&s);
let h = s.doc().unwrap().model.iter().last().map(|e| e.handle.hex()).unwrap();
s.execute("reverse", &json!({ "handle": h })).unwrap();
let sp = last_spline(&s);
let fit = [Vec2::ZERO, Vec2::new(1.0, 4.0), Vec2::new(6.0, 3.0), Vec2::new(4.0, 0.0)];
assert_eq!(sp.fit, fit);
assert_eq!(sp.fit_opts.start_tangent, before.fit_opts.start_tangent.map(|t| -t));
let (lo, hi) = sp.domain();
assert!(sp.eval(lo).near(Vec2::ZERO, 1e-12) && sp.eval(hi).near(Vec2::ZERO, 1e-12));
s.execute("splinedit", &json!({ "handle": h, "option": "move", "index": 2, "to": [6, 3] })).unwrap();
let again = last_spline(&s);
assert!(again.control.iter().zip(&sp.control).all(|(a, b)| a.near(*b, 1e-9)), "{:?} vs {:?}", again.control, sp.control);
}
#[test]
fn cv_method_keeps_cv_on_enter_and_can_switch_back_to_fit() {
for entry in ["spline.cv", "spline m cv"] {
@@ -23,6 +23,7 @@ fn install() {
});
set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
}
/// A proxy entity of class 500 (WIDGETX) in `owner`, with a string stream of `strings` bytes.
@@ -117,6 +118,60 @@ fn legacy_visualstyles_warn_only_for_2007_dwg() {
}
}
/// A linetype with more dash elements than a DWG counts is saved with its first 255, and each
/// way of writing a DWG says so in one note (#1923, F-05); a DXF keeps it whole and says nothing.
#[test]
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
fn a_dwg_save_notes_the_linetypes_it_cuts() {
use cadcraft_engine::doc::{Common, DashElement, EntityKind, Line, Linetype, Space};
use cadcraft_engine::geom::Vec3;
install();
cadcraft_io::dwg_worker::allow_in_process();
let dir = TempDir::new("ltype-notes");
let linetype = |name: &str, n: usize| Linetype {
name: name.into(),
description: String::new(),
pattern: (0..n).map(|i| DashElement::dash(if i % 2 == 0 { 1.0 } else { -0.5 })).collect(),
};
let mut d = Drawing::new_metric();
d.linetypes.extend([linetype("LONG", 256), linetype("FITS", 255)]);
// Lines drawn with it in model space and on a sheet, so WBLOCK and LAYOUT SAVEAS keep it.
let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) });
let common = Common { linetype: "LONG".into(), ..Common::default() };
let model_line = d.add(&Space::Model, common.clone(), line.clone()).unwrap();
d.add(&Space::Paper("Layout1".into()), common, line).unwrap();
let mut s = Session::empty();
s.open_drawing(d, "ltypes.dxf", None);
let one_note = |r: &Value| matches!(r["warnings"].as_array().map(Vec::as_slice), Some([note]) if note.as_str().is_some_and(|t| t.contains("1 linetype") && t.contains("255")));
let notes_since = |s: &Session, n: usize| s.log[n..].iter().filter(|l| l.contains("dash elements")).count();
let dwg = dir.path_str("out.dwg");
let writes = [
("saveas", json!({ "path": dwg })),
("document.bytes", json!({ "format": "dwg" })),
("export", json!({ "format": "dwg" })),
("wblock", json!({ "path": dir.path_str("all.dwg"), "name": "*" })),
("layout.saveas", json!({ "name": "Layout1", "path": dir.path_str("sheet.dwg") })),
("-wblock", json!({ "path": dir.path_str("line.dwg"), "handles": [model_line.0] })),
];
for (cmd, p) in writes {
let n = s.log.len();
let r = s.execute(cmd, &p).unwrap();
assert!(one_note(&r), "{cmd}: {r}");
assert_eq!(notes_since(&s, n), 1, "{cmd}: {:?}", &s.log[n..]);
}
// -WBLOCK at the command line says it too (a DWG file has no precision prompt).
let n = s.log.len();
let path = dir.path_str("typed.dwg").replace('\\', "/");
s.cmdline(&format!("(command \"_.-WBLOCK\" \"{path}\" \"*\")")).unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(notes_since(&s, n), 1, "{:?}", &s.log[n..]);
let back = cadcraft_io::read(&std::fs::read(&dwg).unwrap(), "out.dwg").unwrap();
assert_eq!(back.linetype("LONG").map(|l| l.pattern.len()), Some(255));
let n = s.log.len();
let r = s.execute("saveas", &json!({ "path": dir.path_str("out.dxf") })).unwrap();
assert!(r.get("warnings").is_none() && !s.log[n..].iter().any(|l| l.contains("dash elements")), "{r} {:?}", &s.log[n..]);
}
#[test]
fn a_proxy_no_version_writes_is_not_reported() {
install();
+139
View File
@@ -171,3 +171,142 @@ fn data_links_saved_in_a_drawing_are_read_beside_it_or_on_this_computer_only() {
assert!(errors.iter().all(|e| e.contains("another computer")), "{errors:?}");
let _ = std::fs::remove_dir_all(&base);
}
/// Read and write drawings through `cadcraft-io`, as the app does.
fn use_file_io() {
cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks {
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: None,
});
}
/// A new table, `i` rows of tables down, whose data link names `path` as a drawing file stores it.
fn linked_table(s: &mut Session, i: usize, path: &str) {
let r = s.execute("table", &json!({ "at": [0, 10.0 * i as f64], "cols": 2, "rows": 1 })).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let EntityKind::Table(t) = &mut e.kind {
t.data_link = Some(cadcraft_engine::doc::DataLink { path: path.to_string(), start_row: 0 });
}
})
.unwrap();
}
/// The text of every cell of every table in model space.
fn table_texts(s: &Session) -> String {
let mut out = String::new();
for e in s.doc().unwrap().model.iter() {
if let EntityKind::Table(t) = &e.kind {
for cell in t.cells.iter().flatten() {
out.push_str(&cell.text);
out.push('\n');
}
}
}
out
}
/// A drawing's own data link can't copy a file from outside its folder into it: not by `..`, not
/// by an absolute path, not through a folder whose name only starts the same, not through a link
/// inside the folder that leads out. Links within the folder, also by `..` back into it, still
/// update.
#[test]
fn a_saved_data_link_reads_no_file_outside_the_drawings_folder() {
use_file_io();
let base = std::env::temp_dir().join(format!("cadcraft-datalink-outside-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let (dir, private, sibling) = (base.join("plans"), base.join("private"), base.join("plans-old"));
for d in [dir.join("sub"), private.clone(), sibling.clone()] {
std::fs::create_dir_all(d).unwrap();
}
let secret = "not-for-the-drawing";
std::fs::write(private.join("secret.csv"), format!("{secret},1\n")).unwrap();
std::fs::write(sibling.join("secret.csv"), format!("{secret},2\n")).unwrap();
std::fs::write(dir.join("parts.csv"), "bolt,4\n").unwrap();
std::fs::write(dir.join("sub").join("more.csv"), "nut,8\n").unwrap();
let path = |p: std::path::PathBuf| p.to_str().unwrap().to_string();
let inside = ["parts.csv".to_string(), "sub/more.csv".to_string(), "../plans/parts.csv".to_string(), path(dir.join("parts.csv"))];
let mut outside = vec!["../private/secret.csv".to_string(), path(private.join("secret.csv")), path(sibling.join("secret.csv"))];
#[cfg(unix)]
let linked = std::os::unix::fs::symlink(private.join("secret.csv"), dir.join("link.csv")).is_ok();
// Windows lets only some accounts make symbolic links.
#[cfg(windows)]
let linked = std::os::windows::fs::symlink_file(private.join("secret.csv"), dir.join("link.csv")).is_ok();
if linked {
outside.push("link.csv".to_string());
} else {
eprintln!("symbolic links can't be made here: the link case is not checked");
}
let mut s = Session::new();
for (i, link) in inside.iter().chain(&outside).enumerate() {
linked_table(&mut s, i, link);
}
let host = dir.join("host.dxf");
s.execute("saveas", &json!({ "path": path(host.clone()) })).unwrap();
let mut s = Session::new();
s.execute("open", &json!({ "path": path(host) })).unwrap();
let r = s.execute("datalinkupdate", &json!({})).unwrap();
assert_eq!(r["updated"], inside.len(), "only the files in the drawing's folder: {r}");
let errors: Vec<&str> = r["errors"].as_array().unwrap().iter().filter_map(|e| e.as_str()).collect();
assert_eq!(errors.len(), outside.len(), "{errors:?}");
assert!(errors.iter().all(|e| e.contains("outside the drawing's folder")), "{errors:?}");
let texts = table_texts(&s);
assert!(texts.contains("bolt") && texts.contains("nut"), "the files inside are read: {texts}");
assert!(!texts.contains(secret), "{texts}");
// So the next save carries nothing of them either.
let after = dir.join("after.dxf");
s.execute("saveas", &json!({ "path": path(after.clone()) })).unwrap();
assert!(!std::fs::read_to_string(&after).unwrap().contains(secret));
let _ = std::fs::remove_dir_all(&base);
}
/// A file outside the drawing's folder that the user links with DATALINK keeps updating while
/// the drawing stays open; once it is opened again, the drawing alone can't read it until the
/// user links it again.
#[test]
fn a_file_the_user_links_outside_the_folder_updates_until_the_drawing_is_opened_again() {
use_file_io();
let base = std::env::temp_dir().join(format!("cadcraft-datalink-chosen-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let (dir, data) = (base.join("plans"), base.join("data"));
std::fs::create_dir_all(&dir).unwrap();
std::fs::create_dir_all(&data).unwrap();
let bom = data.join("bom.csv");
let bom_path = bom.to_str().unwrap();
let host = dir.join("host.dxf");
let host_path = host.to_str().unwrap();
let mut s = Session::new();
let r = s.execute("table", &json!({ "at": [0, 0], "cols": 2, "rows": 1 })).unwrap();
let h = r["handle"].as_str().unwrap().to_string();
s.execute("saveas", &json!({ "path": host_path })).unwrap();
std::fs::write(&bom, "bolt,rev-a\n").unwrap();
s.execute("datalink", &json!({ "handle": h, "path": bom_path })).unwrap();
std::fs::write(&bom, "bolt,rev-b\n").unwrap();
let r = s.execute("datalinkupdate", &json!({})).unwrap();
assert_eq!(r["updated"], 1, "{r}");
assert!(table_texts(&s).contains("rev-b"));
s.execute("saveas", &json!({ "path": host_path })).unwrap();
let mut s = Session::new();
s.execute("open", &json!({ "path": host_path })).unwrap();
std::fs::write(&bom, "bolt,rev-c\n").unwrap();
let r = s.execute("datalinkupdate", &json!({})).unwrap();
assert_eq!(r["updated"], 0, "{r}");
assert!(r["errors"][0].as_str().unwrap().contains("outside the drawing's folder"), "{r}");
assert!(!table_texts(&s).contains("rev-c"));
// Linked again by the user, it reads and keeps updating.
s.execute("datalink", &json!({ "handle": h, "path": bom_path })).unwrap();
assert!(table_texts(&s).contains("rev-c"));
std::fs::write(&bom, "bolt,rev-d\n").unwrap();
let r = s.execute("datalinkupdate", &json!({})).unwrap();
assert_eq!(r["updated"], 1, "{r}");
assert!(table_texts(&s).contains("rev-d"));
let _ = std::fs::remove_dir_all(&base);
}
+8
View File
@@ -64,6 +64,14 @@ mod tests {
let _ = crate::ttf::fallback_for('\u{65E5}');
}
#[test]
fn lookups_cached_per_thread_see_a_font_registered_later() {
// Asked before it exists (cached as missing), then registered: found.
assert!(crate::ttf::find("CADCraft Late Test").is_none());
crate::ttf::register_static("cadcraftlatetest-regular", &TINY_SFNT);
assert!(crate::ttf::find("CADCraft Late Test").is_some());
}
#[test]
fn no_barred_family_is_embedded() {
// AGENTS.md: no Adobe fonts. Noto Sans CJK is Source Han Sans; `build.rs` skips them.

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